import 'package:account_center/api/base_model.dart';
import 'package:account_center/common/sp/sp_key.dart';
import 'package:account_center/page/enterprise/organization_structure/widget/view_department.dart';
import 'package:account_center/page/staff_manager/member_manage_event.dart';
import 'package:account_center/routes/route_config.dart';
import 'package:flutter_clx_base/flutter_clx_base.dart';

class MemberManageMainLogic extends GetxController {
  late String companyNo;

  /// 当前部门
  dynamic department;

  /// 是否是公司根部
  var isRoot = true;

  /// 父级部门们展示标题
  List<dynamic> parents = [];

  /// 部门
  List<dynamic> departments = [];

  /// 人员
  List<dynamic> users = [];

  int noDepartmentUserCount = 0;

  @override
  void onInit() {
    companyNo = SpUtil.getString(SPKey.companyNo) ?? '';
    _organizationTitle(Get.arguments);
    requestData();
    MemberManageEvent.controllers.add(this);
    super.onInit();
  }

  @override
  void onClose() {
    MemberManageEvent.controllers.remove(this);
    super.onClose();
  }

  void _organizationTitle(Map<dynamic, dynamic> argument) {
    parents = argument['parents'] ?? [];
    if (parents.isNotEmpty) {
      department = parents.last;
      isRoot = false;
    } else {
      parents = [
        {
          'companyName': SpUtil.getString(SPKey.companyName),
          'departmentNo': companyNo,
          'departmentName': SpUtil.getString(SPKey.companyName)
        }
      ];
      isRoot = true;
      _requestNoDepartmentUsers();
    }
  }

  void createDepartment() {
    Get.toNamed(RouteConfig.createDepartment, arguments: {
      'companyNo': companyNo,
      'parentDept': isRoot
          ? {
              'departmentNo': companyNo,
              'departmentName': SpUtil.getString(SPKey.companyName),
            }
          : department,
    })?.then((value) {
      if (value?['changeDepartment'] == true) {
        /// 编辑部门是更改父部门，需要回到首页
        if (isRoot) {
          requestData();
        } else {
          Get.back(
            result: {
              'departmentNo': SpUtil.getString(SPKey.companyNo),
            },
          );
        }
      } else {
        MemberManageEvent.refreshData();
      }
    });
  }

  void addPeople() {
    Get.toNamed(RouteConfig.staffAddPage);
  }

  void refreshData() {
    requestData();
    if (isRoot) {
      _requestNoDepartmentUsers();
    }
  }

  void requestData() {
    fetch(
      Method.get,
      url: HttpApi.listDeptUsersAndChildDept,
      queryParameters: {
        'departmentNo': isRoot ? companyNo : department['departmentNo']
      },
      onSuccess: (response) {
        departments = response['childDeptList'] ?? [];
        users = response['users'] ?? [];
        update();
      },
    );
  }

  void clickDepartment(element) {
    Get.toNamed(RouteConfig.memberManagerMainPage,
            arguments: {
              'companyNo': companyNo,
              'parents': [...parents, element]
            },
            preventDuplicates: false)
        ?.then((value) {
      var departmentNo = value?['departmentNo'];
      if (departmentNo != null &&
          departmentNo != department?['departmentNo'] &&
          !isRoot) {
        Get.back(result: value);
      } else {
        MemberManageEvent.refreshData();
      }
    });
  }

  void toUserDetail(element) {
    Get.toNamed(RouteConfig.staffDetailPage, arguments: {
      'userNo': element['userNo'],
      'companyNo': companyNo,
    })?.then((value) {
      refreshData();
    });
  }

  /// 未分配部门人数
  void _requestNoDepartmentUsers() {
    fetch(
      Method.get,
      url: HttpApi.getNoDeptUsersCount,
      queryParameters: {'companyNo': companyNo},
      onSuccess: (response) {
        noDepartmentUserCount = response['count'] ?? 0;
        update();
      },
    );
  }

  void toNoDepartmentUserList() {
    Get.toNamed(
      RouteConfig.noDeptUserPage,
    )?.then((value) {
      refreshData();
    });
  }

  void viewDepartment() {
    Get.to(ViewDepartmentPage(
      departmentNo: department['departmentNo'],
      parentDept: parents.getElement(parents.length - 2),
    ))?.then((value) {
      if (value?['isDelete'] == true) {
        Get.back();
        MemberManageEvent.refreshData();
      } else if (value?['changeDepartment'] == true) {
        /// 编辑部门是更改父部门，需要回到首页
        if (isRoot) {
          requestData();
        } else {
          Get.back(
            result: {
              'departmentNo': SpUtil.getString(SPKey.companyNo),
            },
          );
        }
      } else {
        MemberManageEvent.refreshData();
        _requestDepartmentDetail();
      }
    });
  }

  void _requestDepartmentDetail() {
    fetch(Method.get, url: HttpApi.departmentDetail, queryParameters: {
      'departmentNo': department['departmentNo'],
    }, onSuccess: (response) {
      parents.last['departmentName'] = response?['departmentName'];
      update();
    });
  }

  void changeDepartment() {
    Get.toNamed(RouteConfig.changeDepartmentPage, arguments: {'data': users})
        ?.then((value) {
      refreshData();
    });
  }
}
