import 'package:account_center/api/base_model.dart';
import 'package:account_center/common/sp/sp_util.dart';
import 'package:flutter_clx_base/flutter_clx_base.dart';

import 'staff_select_state.dart';

class StaffSelectLogic extends GetxController {
  final StaffSelectState state = StaffSelectState();

  List<dynamic> listSelected = [];
  List<dynamic> forbidNo = [];

  /// 人员名称 搜索关键字
  String searchKey = '';

  /// 是否是职位选择
  bool isPosition = false;

  bool isSingle = false;

  @override
  void onInit() {
    forbidNo = Get.arguments?['forbidNo'] ?? <dynamic>[];
    isPosition = Get.arguments?['isPosition'] ?? false;
    isSingle = Get.arguments?['isSingle'] ?? false;
    var selected = Get.arguments?['listSelected'] ?? <dynamic>[];
    listSelected.addAll(selected);
    super.onInit();
  }

  /// 请求数据
  void getItemList(int page, int pageSize, success, error) {
    fetchList(Method.post, url: HttpApi.listCompanyUsers, params: {
      'page': page,
      'pageSize': pageSize,
      'companyNo': getCompanyNo(),
      'searchKey': searchKey
    }, onSuccess: (response) {
      success(response);
    }, onError: (code, msg) {
      error(code, msg);
    });
  }

  bool isForbid(staff) {
    return forbidNo.contains(staff['userNo']);
  }

  bool isChecked(staff) {
    return listSelected
            .firstWhereOrNull((data) => staff['userNo'] == data['userNo']) !=
        null;
  }

  /// 搜索
  void search(key) {
    state.userListController.callRefresh();
  }

  /// 搜索框字符变化
  void searchKeyChange(String value) {
    searchKey = value;
    state.userListController.callRefresh();
  }

  void completed() {
    Get.back(result: listSelected);
  }

  void itemTap(staff, bool checked, bool isForbid) {
    if (isForbid) {
      return;
    }
    if (maxPositionNum(staff)) {
      ToastUtil.showToast('该账号已拥有5个职位，不能再添加了');
      return;
    }
    if (isSingle) {
      listSelected.clear();
    }
    if (checked == true) {
      listSelected.add(staff);
    } else {
      listSelected.removeWhere((data) {
        return staff['userNo'] == data['userNo'];
      });
    }
    update();
  }

  bool maxPositionNum(staff) {
    return isPosition &&
        (staff['departmentAndPositionVos'] as List?)?.length == 5;
  }
}
