import 'package:fis_common/logger/logger.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/architecture/utils/prompt_box.dart';
import 'package:flyinsono/managers/interfaces/user_info.dart';
import 'package:flyinsono/pages/main/profile_complete/state.dart';
import 'package:flyinsono/pages/organization/org_info/state.dart';
import 'package:flyinsono/pages/user/user_profile/state.dart';
import 'package:flyinsono/rpc.dart';
import 'package:get/get.dart';
import 'package:get/get_navigation/src/root/parse_route.dart';

///用户基类Controller
class UserProfileBaseController extends FControllerBase {
  final state = UserProfileState();
  final orgShortCodeController = TextEditingController();

  ///姓名输入框controller
  late final nameController = TextEditingController();

  ///手机号输入框controller
  late final phoneController = TextEditingController();

  ///邮箱输入框controller
  late final emailController = TextEditingController();

  /// 响应式成员变量
  late UserDTO userInfoCache;

  /// 默认全部机构
  late List<OrganizationDTO> hospitalAllModelsCache = [];

  late List<OrganizationDTO> hospitalModelsCache = [];

  final userinfoManager = Get.find<IUserInfoManager>();

  ///重置state
  void clear() {
    state.userCode = '';
    state.userName = '';
    state.phone = '';
    state.email = '';
    state.nickName = '';
    state.department = '';
  }

  // 初始化用户相关数据
  Future<void> loadData() async {
    try {
      busy = true;
      final userInfo = await rpc.user.getUserInfoAsync(
        GetUserInfoRequest(token: Store.user.token),
      );
      Store.user.handleUserSyncUpdate(userInfo);

      if (userInfo.fullName != null) {
        state.fullName = userInfo.fullName!;
      }

      if (userInfo.userCode != null) {
        state.userCode = userInfo.userCode!;
      }
      if (userInfo.userName != null) {
        state.userName = userInfo.userName!;
      }
      if (userInfo.displayName != null) {
        state.displayName = userInfo.displayName!;
      }
      state.phone = userInfo.phone ?? "";

      state.orgShortCode = userInfo.rootOrganizationShortCode ?? '';
      orgShortCodeController.text = state.orgShortCode;
      state.email = userInfo.email ?? "";
      state.nickName = userInfo.nickName ?? userInfo.displayName!;
      state.displayName = userInfo.displayName!;
      //organizationCode是部门Code
      state.depShortCode = userInfo.departmentShortCode ?? "";
      nameController.text = state.fullName;
      emailController.text = state.email;
      phoneController.text = state.phone;
      userInfoCache = userInfo;
      busy = false;
      await loadHospitalData(userInfo);
    } catch (e) {
      PromptBox.toast(i18nBook.user.getUserInfoFailed.t);
      clear();
    }
    busy = false;
  }

  ///加载医院相关信息
  Future<void> loadHospitalData(UserDTO userInfo) async {
    try {
      final request = SearchOrganizationsRequest(
        token: Store.user.token,
        keyword: "",
        parentCode: "",
        organizationType: OrganizationTypeEnum.Corporation,
      );
      hospitalModelsCache =
          await rpc.organization.searchOrganizationsAsync(request);
      state.hospitalCode = null;
      if (userInfo.rootOrganizationCode!.isNotEmpty) {
        final hosInfo = await rpc.organization.getOrganizationByCodeAsync(
          GetOrganizationByCodeRequest(
            organizationCode: userInfo.rootOrganizationCode,
            token: Store.user.token,
          ),
        );
        state.hospitalCode = hosInfo.organizationCode!;
        await setDepartment();
        if (userInfo.departmentShortCode != null &&
            state.depOptions.any((element) =>
                element.code == userInfoCache.departmentShortCode)) {
          state.depShortCode = userInfoCache.departmentShortCode ?? '';
          state.department = state.depOptions
              .firstWhere(
                  (element) => element.code == userInfo.departmentShortCode)
              .name;
        }
      }
      loadRoleInfo(userInfo);
    } catch (e) {
      logger.e("UserProfile: load hospital data fail", e);
    }
  }

  ///加载角色信息
  loadRoleData(String roleCode) async {
    try {
      if (roleCode.isEmpty) {
        return;
      }
      var result = await rpc.role.findDefaultRolesAsync(
        FindDefaultRolesRequest(
          token: Store.user.token,
          organizationCode: userInfoCache.organizationCode!,
        ),
      );
      final role =
          result.firstWhere((element) => element.roleCode == roleCode).roleName;
      if (role!.isNotEmpty) {
        state.postIdentity = role;
      }
    } catch (e) {
      logger.e("UserProfile: load role data fail", e);
    }
  }

  //医院信息加载完成后再加载角色和职称
  loadRoleInfo(UserDTO userInfo) {
    if (userInfo.roleCodes != null && userInfo.roleCodes!.length > 0) {
      final roleCode = userInfo.roleCodes!.first;
      if (roleCode.isNotEmpty) {
        loadRoleData(state.postIdentity);
      }
    }

    if (userInfo.rankCodes != null && userInfo.rankCodes!.length > 0) {
      var titleCode = userInfo.rankCodes!.first;
      if (titleCode.isNotEmpty) {
        loadTitleData(titleCode);
      }
    }
  }

  ///加载职称
  void loadTitleData(String titleCode) async {
    try {
      var result = await rpc.rank.getAllRanksAsync(
        GetRanksRequest(
          token: Store.user.token,
          organizationCodes: [userInfoCache.organizationCode!],
          rankCodes: userInfoCache.rankCodes ?? [],
        ),
      );
      if (result.length > 0) {
        var title = result
            .firstWhere((element) => element.rankCode == titleCode)
            .rankName;
        if (title!.isNotEmpty) {
          state.isTitleReadOnly = true;
          state.title = title;
        }
      }
    } catch (e) {
      logger.e("UserProfile: load ranks data fail", e);
    }
  }

  ///在 onInit() 之后调用 1 帧。这是进入的理想场所
  ///导航事件，例如 snackbar、对话框或新route，或
  ///async 异步请求。
  @override
  void onReady() {
    super.onReady();
    loadData();
  }

  ///设置部门
  Future<void> setDepartment() async {
    try {
      List<OrgModel> models = [];
      List<RoleModel> roleModels = [];

      var departments = await rpc.organization.searchOrganizationsAsync(
        SearchOrganizationsRequest(
          keyword: "",
          token: Store.user.token,
          parentShortCode: state.orgShortCode,
          organizationType: OrganizationTypeEnum.Department,
        ),
      );

      departments.forEach(
        (element) {
          models.add(
            OrgModel(
              name: element.organizationName!,
              code: element.shortCode!,
            ),
          );
          roleModels.add(
            RoleModel(
              name: element.organizationName!,
              code: element.shortCode!,
            ),
          );
        },
      );

      state.depOptions = models;
      state.depShortCode = '';
      var orginfos = await userinfoManager.queryOrganizationsByShortCodeAsync(
        shortCode: state.orgShortCode,
      );
      state.orgName = orginfos.organizationName ?? '';
    } catch (e) {
      logger.e("UserProfile: set department fail", e);
    }
    busy = false;
  }
}
