import 'package:fis_common/extensions/string.dart';
import 'package:fis_common/logger/logger.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/services/index.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.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_info/state.dart';
import 'package:flyinsono/pages/organization/org_info/widget/select_organization.dart';
import 'package:flyinsono/pages/user/user_profile/user_profile_base_controller.dart';
import 'package:flyinsono/pages/user/user_profile/widgets/mobile_update_user_Info.dart';
import 'package:flyinsono/rpc.dart';
import 'package:get/get.dart';

class UserProfileController extends UserProfileBaseController {
  ///create focusnode
  final nameFocusNode = FocusNode();

  final hospitalFocusNode = FocusNode();
  final departmentFocusNode = FocusNode();

  UserProfileController();

  ///获取医院信息
  Future<List<OrgModel>> fetchHospital(String name,
      [bool isLoadMore = false]) async {
    try {
      final hospitals = await rpc.organization.searchOrganizationsAsync(
        SearchOrganizationsRequest(
          keyword: name,
          parentCode: "",
          pageIndex: state.pageIndex,
          pageSize: 50,
          token: Store.user.token,
          organizationType: OrganizationTypeEnum.Corporation,
        ),
      );
      if (isLoadMore) {
        hospitalModelsCache.addAll(hospitals);
      } else if (state.pageIndex == 1) {
        hospitalModelsCache = hospitals;
      }
      final List<OrgModel> orgModels = [];
      hospitalModelsCache.forEach((element) {
        orgModels.add(OrgModel(
            name: element.organizationName ?? '',
            code: element.organizationCode ?? ''));
      });
      return hospitals
          .map((element) => OrgModel(
              name: element.organizationName ?? '',
              code: element.organizationCode ?? ''))
          .toList();
    } catch (e) {
      logger.e("UserProfile: fetch hospital list fail", e);
    }
    return [];
  }

  ///在 [onDelete] 方法之前调用。 [onClose] 可能用于
  ///处理控制器使用的资源。就像 closing events 一样，
  ///或在控制器销毁之前的流。
  ///或者处置可能造成一些内存泄漏的对象，
  ///像 TextEditingControllers、AnimationControllers。
  ///将一些数据保存在磁盘上也可能很有用。
  @override
  void onClose() {
    super.onClose();
    // 1 stop & close 关闭对象
    // 2 save 持久化数据
    nameFocusNode.dispose();
    hospitalFocusNode.dispose();
    departmentFocusNode.dispose();
  }

  //手机跳转到更改手机号页面
  Future<void> openChangePhoneorEmail(bool isPhone) async {
    try {
      final result = await Get.to(
        () => UpdateUserTextInfo(
          title: isPhone
              ? i18nBook.user.changePhone.t
              : i18nBook.user.changeEmail.t,
          hintText: isPhone
              ? i18nBook.errorCodes.errorCode5004.t
              : i18nBook.auth.enterEmail.t,
          value: isPhone ? state.phone : state.email,
          changeType: isPhone ? ChangeType.Phone : ChangeType.Email,
        ),
      );
      if (result != null) {
        final newValue = result.toString();
        if (isPhone) {
          state.phone = newValue;
        } else {
          state.email = newValue;
        }
      }
    } catch (e) {
      logger.e("msg", e);
    }
  }

  ///手机端修改部门
  Future<void> openSelectDep() async {
    try {
      if (state.orgShortCode.isEmpty) {
        PromptBox.toast(i18nBook.auth.pleaseSetHospitalCodeFirst.t);
        return;
      }
      final List<OrgModel> orgModels = [];
      var departments = await rpc.organization.searchOrganizationsAsync(
        SearchOrganizationsRequest(
          token: Store.user.token,
          keyword: "",
          parentShortCode: state.orgShortCode,
          organizationType: OrganizationTypeEnum.Department,
        ),
      );
      departments.forEach((element) => {
            orgModels.add(OrgModel(
                name: element.organizationName!, code: element.shortCode!))
          });

      if (orgModels.length > 0) {
        final orgResult = await SelectOrganization.open(orgModels,
            title: i18nBook.organization.selectDepartmentTip.t);
        if (orgResult != null && orgResult.isNotEmpty) {
          state.depShortCode = orgResult[0];
          state.department = orgResult[1];
        }
      } else {
        PromptBox.toast(i18nBook.user.noDepartmentInfo.t);
      }
    } catch (e) {
      logger.e("UserProfile: select dep fail", e);
    }
  }

  //手机跳转到更改名字页面
  Future<void> openSelectName() async {
    final result = await Get.to(
      () => UpdateUserTextInfo(
        title: i18nBook.user.changeName.t,
        value: state.fullName,
        changeType: ChangeType.Name,
      ),
    );
    if (result != null) {
      final newName = result.toString();
      state.fullName = newName;
    }
  }

  ///手机端修改机构
  Future<void> openSelectOrg() async {
    try {
      final result = await Get.to(
        () => UpdateUserTextInfo(
          title: i18nBook.auth.hospitalCode.t,
          value: state.orgShortCode,
          hintText: i18nBook.auth.pleaseSetHospitalCode.t,
          changeType: ChangeType.OrgShortCode,
        ),
      );
      if (result == null) {
        return;
      }
      final orgShortCode = result.toString();
      state.orgShortCode = orgShortCode;
      state.depShortCode = "";
      state.department = "";
      state.orgName = '';
      setDepartment();
    } catch (e) {
      logger.e("UserProfile: select org fail", e);
    }
  }

  //手机端提交
  void submit() async {
    try {
      if (!_chechUserInfos()) {
        return;
      }
      var updateResult = await rpc.user.alterUserInfoAsync(
        AlterUserInfoRequest(
          token: Store.user.token,
          phone: state.phone,
          email: state.email,
          fullName: state.fullName,
          shortCode: state.depShortCode.isNotNullOrEmpty
              ? state.depShortCode
              : state.orgShortCode,
          languageCode: i18nBook.locale.languageCode,
        ),
      );
      if (updateResult) {
        PromptBox.success(i18nBook.user.saveSuccess.t);
        router.back();
      } else {
        PromptBox.error(i18nBook.user.saveFailed.t);
      }
    } catch (e) {
      logger.e('UserProfileController submit ex:', e);
    }
  }

  /// 客户端提交完善账号信息
  submitUserInfo() async {
    try {
      final name = state.fullName;
      if (state.email.isNotEmpty && !state.email.isEmail) {
        PromptBox.toast(i18nBook.profileComplete.emailFormatValidation.t);
        return;
      }
      if (state.phone.isNotEmpty) {
        if (i18nBook.isCurrentChinese) {
          if (!state.phone.isChineseMobileNumber) {
            PromptBox.toast(i18nBook.errorCodes.errorCode6000.t);
            return;
          }
        } else {
          if (!state.phone.isNumberPhone) {
            PromptBox.toast(i18nBook.errorCodes.errorCode6000.t);
            return;
          }
        }
      }
      var updateResult = await rpc.user.alterUserInfoAsync(
        AlterUserInfoRequest(
          token: Store.user.token,
          phone: state.phone,
          email: state.email,
          nickName: state.nickName,
          fullName: name,
          shortCode: state.depShortCode.isNotNullOrEmpty
              ? state.depShortCode
              : state.orgShortCode,
          languageCode: i18nBook.locale.languageCode,
        ),
      );

      if (updateResult) {
        PromptBox.success(i18nBook.user.saveSuccess.t);
        router.back();
      } else {
        PromptBox.error(i18nBook.user.saveFailed.t);
      }
    } catch (e) {
      logger.e("UserProfile: submit fail", e);
    }
  }

  ///检查用户信息
  ///返回结果 ： 是否检查通过
  bool _chechUserInfos() {
    userInfoCache.fullName = state.fullName;
    userInfoCache.email = state.email;
    userInfoCache.phone = state.phone;
    userInfoCache.displayName = state.displayName;
    if (userInfoCache.phone!.isNotEmpty) {
      if (i18nBook.isCurrentChinese) {
        if (!userInfoCache.phone!.isChineseMobileNumber) {
          PromptBox.toast(i18nBook.profileComplete.phoneFormatValidation.t);
          return false;
        }
      } else {
        if (!userInfoCache.phone!.isNumberPhone) {
          PromptBox.toast(i18nBook.profileComplete.phoneFormatValidation.t);
          return false;
        }
      }
    }
    if (userInfoCache.email!.isNotEmpty) {
      if (!userInfoCache.email!.isEmail) {
        PromptBox.toast(i18nBook.profileComplete.emailFormatValidation.t);
        return false;
      }
    }
    return true;
  }
}
