import 'package:fis_common/logger/logger.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:fis_ui/interface/interactive_container.dart';
import 'package:fis_ui/usual/alert.dart';
import 'package:flyinsono/architecture/router/router.dart';
import 'package:flyinsono/architecture/services/modules/config_language.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/make_sure_delete_dialog.dart';
import 'package:flyinsono/pages/organization/org_personnel/widgets/user_edit_dialog.dart';
import 'package:flyinsono/rpc.dart';
import 'package:get/get.dart';

class OrgUserPesonnelController {
  late OrgPesonnelController controller;
  late OrgPesonnelState state;
  final languageService = Get.find<LanguageService>();
  OrgUserPesonnelController(OrgPesonnelController controller) {
    this.controller = controller;
    this.state = controller.state;
  }

  /// 单独删除框
  void deleteUserAlert(selectedIdxs, FInteractiveContainer businessParent) {
    FConfirmAlert.show(
      context: Get.context!,
      title: i18nBook.organization.messgaeConfirm.t,
      subTitle: i18nBook.organization.removeMemberConfirm.t,
      onConfirm: () {
        deleteUserPhoneList(selectedIdxs);
      },
      businessParent: businessParent,
    );
  }

  /// 数据删除
  Future<void> deleteUserList() async {
    try {
      router.back();
      controller.setBusy(i18nBook.organization.removing.t);
      final result = await rpc.user.removeUsersFromOrganizationAsync(
        RemoveUsersFromOrganizationRequest(
          token: Store.user.token,
          userCodes: state.selectedIdxs,
        ),
      );
      if (result) {
        PromptBox.toast(i18nBook.user.deleteSuccess.t);
        controller.busy = false;
        state.selectedIdxs = [];
        loadUserListInfo();
      }
    } catch (e) {
      router.back();
    }
    controller.busy = false;
  }

  /// 移除用户
  Future<void> deleteUserPhoneList(selectedIdxs) async {
    try {
      final result = await rpc.user.removeUsersFromOrganizationAsync(
        RemoveUsersFromOrganizationRequest(
          token: Store.user.token,
          userCodes: selectedIdxs,
        ),
      );
      if (result) {
        loadUserListInfo();
      }
    } catch (e) {
      logger.e('msg', e);
    }
  }

  /// 获取用户详情code匹配name 回显
  void getEditUserInfo(rowData) {
    try {
      final userEditInfo = controller.userEditInfo;
      userEditInfo?.organizationCode =
          rowData.organizationCode != Store.user.rootOrganizationCode
              ? rowData.organizationCode
              : null;
      userEditInfo?.positionCodes =
          rowData.positionCodes.length != 0 ? rowData.positionCodes[0] : null;
      userEditInfo?.rankCodes =
          rowData.rankCodes.length != 0 ? rowData.rankCodes[0] : null;
    } catch (e) {
      logger.e('getEditUserInfo', e);
    }
  }

  ///跟据UserCode获取用户信息
  Future<UserDTO?> getUserByCodeAsync(String userCode) async {
    try {
      final result = await rpc.user.getUserByCodeAsync(
        GetUserByCodeRequest(
          token: Store.user.token,
          userCode: userCode,
        ),
      );
      result.fullName = result.fullName ?? '';
      result.phone = result.phone ?? '';
      return result;
    } catch (e) {
      logger.e("getUserByCodeAsync - call `checkUpdate` error.", e);
    }
    return null;
  }

  /// 加载用户信息
  Future<void> loadUserListInfo() async {
    try {
      state.tableLoading = true;
      final result = await rpc.user.getUserListAsync(
        GetUserListRequest(
          token: Store.user.token,
          exceptSelf: true,
          language: i18nBook.locale.toCodeString('-'),
          organizationCode: state.organizationCode == ''
              ? state.rootOrganizationCode
              : state.organizationCode,
          // 全部和待分配的枚举
          organizationQueryType: (state.organizationQueryType == '' ||
                  state.organizationQueryType == '2')
              ? OrganizationQueryTypeEnum.AllDep
              : state.organizationQueryType == '1'
                  ? OrganizationQueryTypeEnum.Single
                  : OrganizationQueryTypeEnum.Wait,
          rankCode: state.rankCode,
          positionCode: state.positionCode,
          keyword: state.searchText,
          // queryType: state.searchType,
        ),
      );
      state.tableDataSource = _convertUsers(result);
      state.tableLoading = false;
    } catch (e) {
      logger.e("error", e);
    }
  }

  /// 用户删除确认框
  void makeSureDelete() {
    if (state.selectedIdxs.length == 0) {
      PromptBox.toast(i18nBook.organization.SelectUserToRemove.t);
    } else {
      router.dialog(
        () => MakeSureDeleteDialogPage(
          onOkTap: () => deleteUserList(),
        ),
      );
    }
  }

  /// 打开用户编辑
  ///
  /// [userCode] 用户编码
  void openUserEditDialog(String userCode) async {
    UserDTO? rowData = await getUserByCodeAsync(userCode);
    if (rowData != null) {
      rowData.fullName = rowData.fullName ?? '';
      rowData.phone = rowData.phone ?? '';
    }
    router.dialog(
      () => UserEditDialogPage(
        rowData: rowData,
        onOkTap: (userCode) => updateUser(userCode),
      ),
    );
  }

  /// 查询所有岗位身份
  Future<void> searchAllPositions() async {
    try {
      final List<PublicChoice> positionList = [
        PublicChoice(
          name: i18nBook.common.all.t,
          code: '',
          type: '2',
          isHover: false,
          isActive: true,
        ),
      ];
      final List<OrgNameModel> model = [];

      final result = await rpc.position.getPositionsAsync(
        GetPositionsRequest(
          token: Store.user.token,
        ),
      );
      result.forEach(
        (e) => {
          positionList.add(
            PublicChoice(
              name: languageService.findLanguageValueByCode(
                'common',
                e.positionCode ?? '',
              ),
              code: e.positionCode!,
              type: '2',
              isHover: false,
              isActive: false,
              organizationCode: e.organizationCode,
              fitDepartmentCode: e.fitDepartmentCode,
            ),
          ),
          model.add(
            OrgNameModel(
              code: e.positionCode ?? '',
              name: languageService.findLanguageValueByCode(
                'common',
                e.positionCode ?? '',
              ),
            ),
          )
        },
      );
      state.positionList = positionList;
      controller.allProfessionalList = model;
    } catch (e) {
      logger.e('msg', e);
    }
  }

  /// 查询所有职称
  Future<void> searchAllRanks() async {
    try {
      final List<PublicChoice> professionalList = [
        PublicChoice(
          name: i18nBook.common.all.t,
          code: '',
          type: '2',
          isHover: false,
          isActive: true,
        ),
      ];
      final List<OrgNameModel> model = [];
      final result = await rpc.rank.getAllRanksAsync(
        GetRanksRequest(
          token: Store.user.token,
          organizationCodes: [
            state.rootOrganizationCode == "" ? "-1" : state.rootOrganizationCode
          ],
        ),
      );
      result.forEach(
        (e) => {
          professionalList.add(
            PublicChoice(
              name: e.rankName!,
              code: e.rankCode!,
              type: '1',
              isHover: false,
              isActive: false,
            ),
          ),
          model.add(
            OrgNameModel(
              code: e.rankCode!,
              name: e.rankName!,
            ),
          )
        },
      );
      state.professionalList = professionalList;
      controller.allRanks = model;
    } catch (e) {
      print(e);
      logger.e('OrgPesonnelController searchAllRanks ex', e);
    }
  }

  /// 更新用户信息
  Future<void> updateUser(String userCode) async {
    try {
      final userEditInfo = controller.userEditInfo;
      userEditInfo!.userCode = userCode;
      final result = await rpc.user.setUserOrganizationInfoAsync(
        SetUserOrganizationInfoRequest(
          token: Store.user.token,
          userCode: userEditInfo.userCode ?? '',
          rankCodes: [
            if (userEditInfo.rankCodes != null) userEditInfo.rankCodes!
          ],
          positionCodes: [
            if (userEditInfo.positionCodes != null) userEditInfo.positionCodes!
          ],
          organizationCode: userEditInfo.organizationCode ?? '',
        ),
      );
      if (result) {
        loadUserListInfo();
        router.back();
        controller.professionalName = null;
      }
    } catch (e) {
      logger.e('msg', e);
    }
  }

  /// 手机端更新用户
  /// 更新用户信息
  Future<void> updateUserOrganizationInfoAsync(String? userCode) async {
    try {
      final result = await rpc.user.setUserOrganizationInfoAsync(
        SetUserOrganizationInfoRequest(
          token: Store.user.token,
          userCode: userCode ?? '',
          rankCodes: [
            if (state.professionalListCode != null) state.professionalListCode
          ],
          positionCodes: [
            if (state.positionListCode != null) state.positionListCode
          ],
          organizationCode: state.companyCode ?? '',
        ),
      );
      if (result) {
        controller.loadUserListInfo();
        Get.back();
      }
    } catch (e) {
      logger.e('msg', e);
    }
  }

  List<UserExtendDTO> _convertUsers(List<UserExtendDTO> users) {
    List<UserExtendDTO> result = [];
    for (var user in users) {
      user.fullName = user.fullName ?? '';
      user.phone = user.phone ?? '';
      result.add(user);
    }
    return result;
  }
}
