import 'package:fis_common/helpers/color.dart';
import 'package:fis_common/logger/logger.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/services/index.dart';
import 'package:fis_ui/index.dart';
import 'package:flutter/cupertino.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/router/index.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/architecture/temp_cache.dart';
import 'package:flyinsono/architecture/utils/keyboard.dart';
import 'package:flyinsono/architecture/utils/prompt_box.dart';
import 'package:flyinsono/pages/user/role_authentication/view.dart';
import 'package:flyinsono/rpc.dart';

import 'index.dart';

class UserIdAuthApplyController extends FControllerBase
    with EnterPressListenOnControllerMixin {
  ///用户标签输入框Controller
  final labelInputController = TextEditingController();

  ///用户标签focus node.
  final labelFocus = FocusNode();

  final state = UserIdAuthApplyState();

  ///角色信息
  final roleInfo = ApplyRoleInfo();

  ///当前是否获取焦点
  bool _isFocus = false;

  ///获取角色标签
  /// 不做过滤，直接返回所有标签
  Future<List<String>> fetchLabels(String key) async {
    return state.labels;
  }

  /// 加载申请数据
  Future<bool> loadApplyData() async {
    try {
      final model = await rpc.identityApply.getLastIdentityApplyAsync(
        GetLastIdentityApplyRequest(token: Store.user.token),
      );
      if (!TempCache.inIdentityReselecting || state.applyCode.isEmpty) {
        state.applyCode = model.applyRoleCode!;
      }
      state.applyState = model.applyState;
      state.refuseNote = model.applyNote ?? "";
      final identityCards = model.identityCard ?? [];
      if (identityCards.length > 0) {
        state.idCardFront = identityCards[0];
        state.idCardBack = identityCards[1];
      }
      final licenseCard = model.licenseCard ?? [];
      if (licenseCard.length > 0) {
        state.doctorCard = licenseCard.first;
      }
      if (model.fieldList != null && model.fieldList!.length > 0) {
        state.selectedLables = model.fieldList!;
      }
      return true;
    } catch (e) {
      logger.e("[UserIdAuthApply] load apply data error", e);
      state.applyState = ApplyStateEnum.Applying; // disable edit
    }
    return false;
  }

  /// 加载数据
  Future<bool> loadData(String? code) async {
    if (code == null || code.isEmpty) {
      final resault = await loadApplyData();
      if (!resault) return resault;
    } else {
      state.applyCode = code;
      if (TempCache.inIdentityReselecting) {
        // 重选修改
        final result = await loadApplyData();
        if (!result) {
          return result;
        }
        // 重置缓存状态
        TempCache.inIdentityReselecting = false;
      } else {
        // 新申请
        state.applyState = ApplyStateEnum.NotApply;
      }
      state.inEditing = true;
    }

    final result = await loadRoleInfo();
    return result;
  }

  /// 加载角色信息
  Future<bool> loadRoleInfo() async {
    try {
      final result = await rpc.role.getRoleByCodeAsync(
        GetRoleByCodeRequest(
          token: Store.user.token,
          roleCode: state.applyCode,
          language: i18nBook.locale.toCodeString('-'),
        ),
      );
      final descriptionArray = result.description!.split('\n');
      roleInfo.name = result.roleName!;
      roleInfo.iconUrl = result.iConUrl!;
      roleInfo.startColor = FColorHelper.hex2Color(
          (result.colorStart == null || result.colorStart!.isEmpty)
              ? "FFFFFF"
              : result.colorStart,
          hasTag: false)!;
      roleInfo.endColor = FColorHelper.hex2Color(
          (result.colorEnd == null || result.colorEnd!.isEmpty)
              ? "FFFFFF"
              : result.colorEnd,
          hasTag: false)!;
      roleInfo.descriptionArray = descriptionArray;
      roleInfo.qualification = result.roleQualification;
      roleInfo.fieldShowType = result.fieldShowType;
      state.isNeedShowLabel = result.fieldShowType == RoleShowTypeEnum.ISShow;
      if (result.fieldList != null) {
        state.labels = result.fieldList!;
      }
      return true;
    } catch (e) {
      logger.e("[UserIdAuthApply] load role info error", e);
      print(e);
    }
    return false;
  }

  ///添加标签
  ///如果不设置label，则添加当前输入框中的内容
  bool onAddLabel([String? label]) {
    final labelToAdd = (label ?? state.label).trim();
    if (!state.selectedLables.contains(labelToAdd)) {
      if (labelToAdd.isEmpty) {
        PromptBox.toast(i18nBook.user.skilledAreaNullTip.t);
        return true;
      }
      state.selectedLables.add(labelToAdd);
      state.label = '';
      labelInputController.text = '';
      return true;
    } else {
      PromptBox.toast(i18nBook.user.tagAlready.t);
      return false;
    }
  }

  /// 键盘按下回车
  @override
  void onEnterPressed() {
    if (kIsMobile) return;
    if (_isFocus) onAddLabel();
  }

  @override
  void onReady() {
    super.onReady();
    final parameters = router.getParams();
    final code = parameters?['code'];
    state.loading = true;
    loadData(code).then((_) {
      state.loading = false;
    });
    labelFocus.addListener(() {
      if (labelFocus.hasFocus) {
        _isFocus = true;
      } else {
        Future.delayed(Duration(microseconds: 10), () => _isFocus = false);
      }
    });
  }

  ///重新选择角色认证
  Future<void> reselectRole() async {
    TempCache.inIdentityReselecting = true;
    if (kIsMobile) {
      final newCode = await router.to(RouteNames.User.RoleAuth);
      if (newCode != null && newCode.isNotEmpty) {
        state.applyCode = newCode;
        await loadRoleInfo();
        state.inEditing = true;
      }
      // 重置缓存状态
      TempCache.inIdentityReselecting = false;
    } else {
      router.back();
      Future.microtask(() {
        router.dialog(
          () => RoleAuthenticationPage(),
          id: NavIds.HOME,
        );
      });
    }
  }

  ///选中下拉选择器中的角色标签
  Future<void> setRoleLable(String key) async {
    try {
      onAddLabel(key);
      labelFocus.unfocus();
    } catch (e) {
      print(e.toString());
      logger.e('setRoleLable ex:', e);
    }
  }

  /// 提交申请
  Future<bool> submitApply() async {
    try {
      List<String> ids =
          roleInfo.isNeedIdCard ? [state.idCardFront, state.idCardBack] : [];
      List<String> identityCard =
          roleInfo.isNeedDocCard ? [state.doctorCard] : [];
      final result = await rpc.identityApply.applyForAsync(
        ApplyForRequest(
          token: Store.user.token,
          applyRoleCode: state.applyCode,
          identityCard: ids,
          licenseCard: identityCard,
          fieldList: state.selectedLables,
        ),
      );
      return result;
    } catch (e) {
      logger.e("[UserIdAuthApply] submit error", e);
    }
    return false;
  }

  ///提交申请
  Future<void> submitFormApply() async {
    final validMsg = validate();
    if (validMsg != null) {
      PromptBox.toast(validMsg);
      return;
    }
    final result = await this.submitApply();
    if (result) {
      PromptBox.toast(i18nBook.user.applymentSubmitted.t);
      if (kIsMobile) {
        router.back(result: result);
      } else {
        router.back();
        Future.microtask(() {
          router.back();
        });
      }
    } else {
      PromptBox.toast(i18nBook.user.applymentSubmittedFailed.t);
    }
  }

  ///验证用户信息
  String? validate() {
    if (roleInfo.isNeedIdCard) {
      if (state.idCardFront.isEmpty && state.idCardBack.isEmpty) {
        return i18nBook.user.uploadIdCardImage.t;
      }
      if (state.idCardFront.isEmpty) {
        return i18nBook.user.UploadIdCardFrontImage.t;
      }
      if (state.idCardBack.isEmpty) {
        return i18nBook.user.uploadIdCardReverseSideVerification.t;
      }
    }
    if (roleInfo.isNeedDocCard) {
      if (state.doctorCard.isEmpty) {
        return i18nBook.user.uplaodDoctorLicenseImage.t;
      }
    }
    return null;
  }
}
