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

class DepartmentSelectLogic extends GetxController {
  /// 搜索关键字
  String key = '';

  /// 树节点
  var nodes = <TreeNode>[];

  List<String> selectedNos = <String>[];
  List<String> forbidNos = <String>[];
  var isSingle = false;

  @override
  void onInit() {
    _requestDepartmentTree();
    selectedNos = Get.arguments['selectedNos'] ?? [];
    forbidNos = Get.arguments['forbidNos'] ?? [];
    isSingle = Get.arguments['isSingle'] ?? false;
    super.onInit();
  }

  void _requestDepartmentTree() {
    fetchList(
      Method.get,
      url: HttpApi.listDepartmentTree,
      queryParameters: {
        'companyNo': SpUtil.getString(SPKey.companyNo),
      },
      onSuccess: (response) {
        nodes = TreeNode.formatNodes(
          response,
          'childDepartmentList',
          formatData,
        );
        update();
      },
      onError: (code, msg) {
        ToastUtil.showToast(msg);
      },
    );
  }

  void search() {
    update();
  }

  void setKey(String? value) {
    key = value ?? '';
    update();
  }

  confirm() {
    var selectedList = <dynamic>[];
    for (var item in nodes) {
      selectedList.addAll(item.getCheckedData());
    }
    Get.back(result: selectedList);
  }

  TreeNode formatData(item) {
    bool forbid = forbidNos.contains(item['departmentNo']);
    String departmentNo = item['departmentNo'];
    return TreeNode()
      ..isForbid = forbid
      ..isChecked = selectedNos.contains(departmentNo) || forbid
      ..expand = departmentNo == SpUtil.getString(SPKey.companyNo)
      ..canExpand = true
      ..canCheck = item['departmentPno'] != null
      ..title = item['departmentName']
      ..data = item;
  }
}
