import 'package:account_center/api/base_model.dart';
import 'package:account_center/common/sp/sp_key.dart';
import 'package:flutter_clx_base/flutter_clx_base.dart';
import 'package:flutter_clx_base/widget/my_refresh_list_public.dart';

import 'position_select_state.dart';

class PositionSelectLogic extends GetxController {
  final PositionSelectState state = PositionSelectState();

  /// 搜索关键字
  String? key;

  var controller = MyListController();

  List<dynamic> selectData = [];

  @override
  void onInit() {
    state.forbidNo = Get.arguments['forbidNo'] ?? <String>[];
    var data = Get.arguments?['selectData'] ?? [];
    selectData.addAll(data);
    super.onInit();
  }

  void search(value) {
    key = value;
    controller.callRefresh();
  }

  setKey(String value) {
    key = value;
    controller.callRefresh();
  }

  /// 选择
  check(role, bool checked) {
    role['checked'] = checked;
    if (checked) {
      selectData.add(role);
    } else {
      selectData.removeWhere(
        (element) => element['positionNo'] == role['positionNo'],
      );
    }
    update();
  }

  /// 完成
  finish() {
    Get.back(result: selectData);
  }

  /// 请求数据
  void requestData(int page, int pageSize, Function(List p1) success,
      Function(int p1, String p2) error) {
    fetch(Method.post, url: HttpApi.listCompanyPositions, params: {
      'page': page,
      'pageSize': pageSize,
      'companyNo': SpUtil.getString(SPKey.companyNo),
      'positionName': key,
    }, onSuccess: (response) {
      if (page == 1) {
        state.noData = response.isEmpty;
        update();
      }
      for (var element in response['records'] ?? []) {
        element['checked'] = selectData.firstWhereOrNull(
              (data) => data['positionNo'] == element['positionNo'],
            ) !=
            null;
      }
      success(response['records'] ?? []);
    }, onError: (code, msg) {
      error(code, msg);
    });
  }
}
