import 'package:fis_i18n/i18n.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_ui/interface/interactive_container.dart';
import 'package:flutter/cupertino.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/router/index.dart';
import 'package:flyinsono/architecture/utils/keyboard.dart';
import 'package:flyinsono/pages/components/select.dart';
import 'package:flyinsono/pages/organization/org_personnel/controllers/org_structure_controller.dart';
import 'package:flyinsono/pages/organization/org_personnel/controllers/org_user_controller.dart';
import 'package:flyinsono/pages/organization/org_personnel/widgets/edit_rank_dialog.dart';
import 'package:flyinsono/pages/organization/org_personnel/widgets/org_member.dart';
import 'package:flyinsono/pages/organization/org_personnel/widgets/select_build.dart';
import 'package:get/get.dart';
import 'index.dart';

class OrgPesonnelController extends FControllerBase
    with EnterPressListenOnControllerMixin {
  OrgPesonnelController() {
    orgUserController = OrgUserPesonnelController(this);
    orgStructureController = OrgStructurePesonnelController(this);
  }

  ///用户相关控制器
  late OrgUserPesonnelController orgUserController;

  ///组织架构相关控制器
  late OrgStructurePesonnelController orgStructureController;

  /// 所有组织
  List<OrgNameModel> allOrgList = [];

  /// 所有岗位身份列表
  List<OrgNameModel> allProfessionalList = [];

  /// 所有职称列表
  List<OrgNameModel> allRanks = [];

  /// 组织架构
  String? organizationName;

  /// 组织架构code
  String? organizationCode;

  /// 岗位身份
  Map position = {};

  /// 职称名称
  String? professionalName;

  /// 职称Code
  String? professionalCode;

  /// 用户信息
  UserEditInfo? userEditInfo = UserEditInfo();

  /// 选中的列表
  List<int> selectedIdxs = [];

  /// 回车是否失焦
  bool _isFocus = false;

  /// 筛选姓名或者手机号的
  late FSelectController<OrgNameModel> searchInputController =
      FSelectController<OrgNameModel>(
    initialValue: [],
  );

  final state = OrgPesonnelState();
  final searchFocusNode = FocusNode();

  /// 姓名手机号筛选
  void searchSelect() {
    loadUserListInfo();
  }

  /// 组织架构筛选
  ///
  /// [obj] 组织架构筛选对象
  void orgStructureFiltering(PublicChoice obj) {
    state.organizationCode = obj.code;
    state.organizationQueryType = obj.type;
    loadUserListInfo();
  }

  /// 岗位身份筛选
  ///
  /// [obj] 岗位身份筛选对象
  void postScreening(PublicChoice obj) {
    state.positionCode = obj.code;
    loadUserListInfo();
  }

  /// 职称筛选
  ///
  /// [obj] 职称筛选对象
  void titleScreening(PublicChoice obj) {
    state.rankCode = obj.code;
    loadUserListInfo();
  }

  /// 组织架构新增和编辑
  ///
  /// [orgStruture] 编辑传入的值
  void openOrgStrutureDialog(PublicChoice? orgStruture) {
    orgStructureController.openOrgStrutureDialog(orgStruture);
  }

  /// 职称的新增还是编辑
  ///
  /// [orgStruture] 职称对象
  void editRankDialog(PublicChoice? orgStruture) {
    professionalName = orgStruture?.name;
    professionalCode = orgStruture?.code;
    router.dialog(
      () => EditRankDialogPage(
        isEdit: orgStruture != null ? true : false,
        onOkTap: (val) => isEditRank(val),
      ),
    );
  }

  /// 是否编辑还是新增组织架构
  void isEditRank(bool edit) {
    if (edit) {
      updateProfessional();
    } else {
      addProfessional();
    }
  }

  /// 用户删除确认框
  void makeSureDelete() {
    orgUserController.makeSureDelete();
  }

  /// 打开用户编辑
  ///
  /// [userCode] 用户编码
  void openUserEditDialog(String userCode) async {
    orgUserController.openUserEditDialog(userCode);
  }

  ///设置所选用户Id
  void getSelectedIdxs(List<int> selectedIdxs) {
    List<String> selectList = [];
    for (var i in selectedIdxs) {
      selectList.add(state.tableDataSource[i].userCode!);
    }
    state.selectedIdxs = selectList;
  }

  /// 获取用户详情code匹配name 回显
  void getEditUserInfo(rowData) {
    orgUserController.getEditUserInfo(rowData);
  }

  /// 手机机构部门的跳转页面
  void getCompanyPersonnelList() async {
    var companyPersonnel = await SelectBuild.open(
      i18nBook.organization.selectDepartmentTip.t,
      state.companyPersonnelList
          .where(
            (element) => element.type == '1',
          )
          .toList(),
    );
    state.companyCode = companyPersonnel![1];
  }

  /// 手机岗位身份称的跳转页面
  void getPositionList() async {
    var position = await SelectBuild.open(
      i18nBook.organization.selectWorkPostIdentify.t,
      state.positionList
          .where(
            (element) => element.name != i18nBook.common.all.t,
          )
          .toList(),
    );
    state.positionListCode = position![1];
  }

  /// 手机端职称的跳转页面
  void getProfessional() async {
    var professional = await SelectBuild.open(
      i18nBook.organization.workTitleSelectionTip.t,
      state.professionalList
          .where(
            (element) => element.type == '1',
          )
          .toList(),
    );
    state.professionalListCode = professional![1];
  }

  /// 单独删除框
  void deleteUserAlert(selectedIdxs, FInteractiveContainer businessParent) {
    orgUserController.deleteUserAlert(selectedIdxs, businessParent);
  }

  /// 删除多个
  void deleteUserListAlert(selectedIdxs, FInteractiveContainer businessParent) {
    FConfirmAlert.show(
      context: Get.context!,
      title: i18nBook.organization.messgaeConfirm.t,
      subTitle: i18nBook.organization.removeMembersConfirm
          .translate([selectedIdxs.length]),
      onConfirm: () {
        deleteUserPhoneList(selectedIdxs);
        deleteList = [];
        state.batchOperation = false;
        state.selectedIdxs = deleteList;
      },
      onCancel: () {
        deleteList = [];
        state.batchOperation = false;
        state.selectedIdxs = deleteList;
      },
      confrimLabel: i18nBook.common.confirm.t,
      cancelLabel: i18nBook.common.cancel.t,
      businessParent: businessParent,
    );
  }

  Future<void> deleteConfirmBox(
    organizationCodes,
    deleteFun,
    subTitle,
    FInteractiveContainer businessParent,
  ) async {
    FConfirmAlert.show(
      businessParent: businessParent,
      context: Get.context!,
      title: i18nBook.common.tip.t,
      subTitle: subTitle,
      confrimLabel: i18nBook.common.confirm.t,
      cancelLabel: i18nBook.common.cancel.t,
      onConfirm: () async {
        await busyHandle(
          () async {
            await deleteFun();
          },
          text: i18nBook.remedical.deleting.t,
        );
      },
    );
  }

  /// 删除组织架构
  ///
  /// [organizationCodes] 组织编码
  Future<void> deleteUserTab(
    organizationCodes,
    FInteractiveContainer businessParent,
  ) async {
    deleteConfirmBox(
      organizationCodes,
      () => orgStructureController.deleteUserTab(organizationCodes),
      i18nBook.organization.deleteOrganizationConfirm.t,
      businessParent,
    );
  }

  /// 删除职称
  ///
  /// [rankCode] 职称编码
  Future<void> deleteProfessional(
    String rankCode,
    FInteractiveContainer businessParent,
  ) async {
    deleteConfirmBox(
      rankCode,
      () => orgStructureController.deleteProfessional(rankCode),
      i18nBook.organization.deleteProfessionalConfirm.t,
      businessParent,
    );
  }

  /// 查询用户下级机构列表
  Future<void> searchOrganizationList() async {
    await orgStructureController.searchOrganizationList();
  }

  /// 查询所有岗位身份
  Future<void> searchAllPositions() async {
    orgUserController.searchAllPositions();
  }

  /// 查询所有职称
  Future<void> searchAllRanks() async {
    orgUserController.searchAllRanks();
  }

  /// 新增岗位身份
  Future<void> addPositions() async {
    orgStructureController.addPositions();
  }

  /// 更新岗位身份
  Future<void> updatePositions() async {
    orgStructureController.updatePositions();
  }

  /// 新增职称
  Future<void> addProfessional() async {
    await orgStructureController.addProfessional();
  }

  /// 更新职称
  Future<void> updateProfessional() async {
    await orgStructureController.updateProfessional();
  }

  /// 更新用户信息
  Future<void> updateUser(String userCode) async {
    orgUserController.updateUser(userCode);
  }

  /// 手机端更新用户
  /// 更新用户信息
  Future<void> updateUserOrganizationInfoAsync(String? userCode) async {
    orgUserController.updateUserOrganizationInfoAsync(userCode);
  }

  /// 删除
  Future<void> deleteUserPhoneList(selectedIdxs) async {
    orgUserController.deleteUserPhoneList(selectedIdxs);
  }

  ///回车搜索
  @override
  Future<void> onEnterPressed() async {
    if (kIsMobile) return;
    print("enter");
    if (_isFocus) searchSelect();
  }

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    // 初始化
    _initSelect();

    super.onInit();
  }

  @override
  void dispose() {
    searchFocusNode.dispose();
    super.dispose();
  }

  @override
  Future<void> onLoad() async {
    await Future.wait([
      searchOrganizationList(),
      loadUserListInfo(),
      searchAllRanks(),
      searchAllPositions(),
      orgStructureController.loadData(),
    ]);
  }

  /// 加载用户信息
  Future<void> loadUserListInfo() async {
    orgUserController.loadUserListInfo();
  }

  // 输入框初始化
  void _initSelect() {
    searchFocusNode.addListener(() {
      if (searchFocusNode.hasFocus) {
        _isFocus = true;
      } else {
        Future.delayed(Duration(microseconds: 200), () => _isFocus = false);
      }
    });
  }
}
