import 'package:fis_common/logger/logger.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:flyinsono/architecture/router/router.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/architecture/utils/prompt_box.dart';
import 'package:flyinsono/pages/organization/org_personnel/controller.dart';
import 'package:flyinsono/pages/organization/org_personnel/state.dart';
import 'package:flyinsono/pages/organization/org_personnel/view.dart';
import 'package:flyinsono/pages/organization/org_personnel/widgets/org_struture_dialog.dart';
import 'package:flyinsono/rpc.dart';
import 'package:get/get.dart';

class OrgStructurePesonnelController {
  late OrgPesonnelController controller;
  late OrgPesonnelState state;
  OrgStructurePesonnelController(OrgPesonnelController controller) {
    this.controller = controller;
    this.state = controller.state;
  }

  /// 加载机构名称
  Future<void> loadData() async {
    try {
      var result = await rpc.organization.getOrganizationByCodeAsync(
        GetOrganizationByCodeRequest(
          organizationCode: Store.user.rootOrganizationCode,
          token: Store.user.token,
        ),
      );
      state.organizationName = result.organizationName;
    } catch (ex) {
      PromptBox.toast(i18nBook.organization.loadOrgInfoFailedTip.t);
      printError(info: ex.toString());
    }
  }

  /// 组织架构新增和编辑
  ///
  /// [orgStruture] 编辑传入的值
  void openOrgStrutureDialog(PublicChoice? orgStruture) {
    controller.organizationName = orgStruture?.name;
    controller.organizationCode = orgStruture?.code;
    router.dialog(
      () => OrgStrutureDialogPage(
        isEdit: orgStruture != null ? true : false,
        onOkTap: (val) => isOrgStruture(val),
      ),
    );
  }

  /// 是否编辑还是新增组织架构
  ///
  /// [edit] 是否编辑
  void isOrgStruture(bool edit) {
    if (edit) {
      updateOrganization();
    } else {
      addOrganizations();
    }
  }

  /// 更新机构 部门
  Future<void> updateOrganization() async {
    try {
      if (controller.organizationName == null ||
          controller.organizationName!.isEmpty) {
        PromptBox.toast(i18nBook.organization.departmentNamePlaceholder.t);
        return;
      }

      final result = await rpc.organization.updateOrganizationNameAsync(
        UpdateOrganizationNameRequest(
          token: Store.user.token,
          organizationName: controller.organizationName,
          organizationCode: controller.organizationCode,
        ),
      );
      if (result) {
        searchOrganizationList();
        router.back();
        controller.organizationName = null;
        controller.organizationCode = null;
      }
    } catch (e) {
      logger.e("[UserCenterload]UserInfo error", e);
    }
  }

  /// 新增岗位身份
  Future<void> addPositions() async {
    try {
      final position = controller.position;
      if (position['positionName'] == null ||
          position['fitDepartmentCode'] == null) {
        PromptBox.toast(i18nBook.organization.FillInCompletely.t);
        return;
      }
      final List<PositionItemDTO> positionItem = [
        PositionItemDTO(
          organizationCode: state.rootOrganizationCode,
          positionName: position['positionName'],
          fitDepartmentCode: position['fitDepartmentCode'],
        )
      ];
      final result = await rpc.position.addPositionsAsync(
        AddPositionsRequest(
          token: Store.user.token,
          positions: positionItem,
        ),
      );
      if (result) {
        controller.searchAllPositions();
        PromptBox.toast(i18nBook.user.operationSuccess.t);
        router.back();
        controller.organizationName = null;
      }
    } catch (e) {
      logger.e("[UserCenterload]UserInfo error", e);
    }
  }

  /// 更新岗位身份
  Future<void> updatePositions() async {
    try {
      final position = controller.position;
      if (position['positionName'] == null ||
          position['fitDepartmentCode'] == null) {
        PromptBox.toast(i18nBook.organization.FillInCompletely.t);
        return;
      }
      final result = await rpc.position.updatePositionNameAsync(
        UpdatePositionNameRequest(
          token: Store.user.token,
          positionCode: position['positionCode'],
          positionName: position['positionName'],
          fitDepartmentCode: position['fitDepartmentCode'],
        ),
      );
      if (result) {
        controller.searchAllPositions();
        router.back();
        controller.position = {};
      }
    } catch (e) {
      logger.e("[UserCenterload]UserInfo error", e);
    }
  }

  /// 新增职称
  Future<void> addProfessional() async {
    try {
      var professionalName = controller.professionalName;
      if (professionalName == null) {
        PromptBox.toast(i18nBook.organization.titleNamePlaceholder.t);
        return;
      }
      List<RankItemDTO> rankInfo = [
        RankItemDTO(
          rankName: professionalName,
          organizationCode: state.rootOrganizationCode,
        )
      ];
      final result = await rpc.rank.addRanksAsync(
        AddRanksRequest(token: Store.user.token, rankInfos: rankInfo),
      );
      if (result) {
        controller.searchAllRanks();
        PromptBox.toast(i18nBook.user.operationSuccess.t);
        router.back();
        professionalName = null;
      }
    } catch (e) {
      logger.e('msg', e);
    }
  }

  /// 更新职称
  Future<void> updateProfessional() async {
    try {
      var professionalName = controller.professionalName;
      if (professionalName == null) {
        PromptBox.toast(i18nBook.organization.titleNamePlaceholder.t);
        return;
      }
      final result = await rpc.rank.updateRankNameAsync(
        UpdateRankNameRequest(
          token: Store.user.token,
          rankName: professionalName,
          rankCode: controller.professionalCode,
        ),
      );
      if (result) {
        controller.searchAllRanks();
        controller.loadUserListInfo();
        router.back();
        professionalName = null;
      }
    } catch (e) {
      logger.e('msg', e);
    }
  }

  /// 删除职称
  ///
  /// [rankCode] 职称编码
  Future<void> deleteProfessional(String rankCode) async {
    try {
      List<String> rankCodesList = [rankCode];
      final result = await rpc.rank.removeRanksAsync(
        RemoveRanksRequest(
          token: Store.user.token,
          rankCodes: rankCodesList,
        ),
      );
      if (result) {
        controller.searchAllRanks();
      }
    } catch (e) {
      logger.e('msg', e);
    }
  }

  /// 新增机构 部门
  Future<void> addOrganizations() async {
    try {
      if (controller.organizationName == null) {
        PromptBox.toast(i18nBook.organization.departmentNamePlaceholder.t);
        return;
      }
      final List<OrganizationItemDTO> organizationInfos = [
        OrganizationItemDTO(
          parentCode: state.rootOrganizationCode,
          organizationName: controller.organizationName,
        )
      ];
      final result = await rpc.organization.addOrganizationsAsync(
        AddOrganizationsRequest(
          token: Store.user.token,
          organizationInfos: organizationInfos,
          languageCode: i18nBook.locale.toCodeString('-'),
        ),
      );
      if (result) {
        searchOrganizationList();
        PromptBox.toast(i18nBook.user.operationSuccess.t);
        router.back();
        state.organizationQueryType = '2';
        controller.organizationName = null;
      }
    } catch (e) {
      logger.e("[UserCenterload]UserInfo error", e);
    }
  }

  /// 查询用户下级机构列表
  Future<void> searchOrganizationList() async {
    try {
      /// 后端没这些状态，前端默认状态
      final List<PublicChoice> companyPersonnelList = [
        PublicChoice(
          name: i18nBook.common.distributed.t,
          code: state.rootOrganizationCode,
          type: '2',
          isHover: false,
          isActive: true,
        ),
        PublicChoice(
          name: i18nBook.common.unDistributed.t,
          code: state.rootOrganizationCode,
          type: '0',
          isHover: false,
          isActive: false,
        ),
      ];
      final List<OrgNameModel> model = [];
      final result = await rpc.organization.searchOrganizationsAsync(
        SearchOrganizationsRequest(
          organizationType: OrganizationTypeEnum.Department,
          parentCode: state.rootOrganizationCode == ""
              ? "-1"
              : state.rootOrganizationCode,
          token: Store.user.token,
        ),
      );
      result.forEach(
        (e) => {
          companyPersonnelList.add(
            PublicChoice(
              name: e.organizationName!,
              code: e.organizationCode!,
              type: '1',
              isHover: false,
              isActive: false,
            ),
          ),
          model.add(
            OrgNameModel(
              code: e.organizationCode ?? '',
              name: e.organizationName ?? '',
            ),
          )
        },
      );
      controller.allOrgList = model;
      state.companyPersonnelList = companyPersonnelList;
      controller.loadUserListInfo();
    } catch (e) {
      logger.e('OrgStructurePesonnelController searchOrganizationList ex:', e);
    }
  }

  /// 删除组织架构
  ///
  /// [organizationCodes] 组织编码
  Future<void> deleteUserTab(organizationCodes) async {
    try {
      List<String> organizationCodesList = [organizationCodes];
      final result = await rpc.organization.removeOrganizationsAsync(
        RemoveOrganizationsRequest(
          token: Store.user.token,
          organizationCodes: organizationCodesList,
        ),
      );
      if (result) {
        state.organizationQueryType = '2';
        searchOrganizationList();
        state.organizationCode = '';
      } else {}
    } catch (e) {
      logger.e('msg', e);
    }
  }
}
