import 'dart:async';

import 'package:fis_common/helpers/color.dart';
import 'package:fis_common/logger/logger.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_ui/interface/interactive_container.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/router/desktop/names.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/managers/interfaces/user_info.dart';
import 'package:flyinsono/pages/user/role_authentication/bindings.dart';
import 'package:flyinsono/pages/user/role_authentication/types.dart';
import 'package:flyinsono/pages/user/role_authentication/view.dart';
import 'package:flyinsono/pages/user/user_center/state.dart';
import 'package:flyinsono/pages/user/user_device/controller.dart';
import 'package:flyinsono/pages/user/user_id_auth_apply/bindings.dart';
import 'package:flyinsono/pages/user/user_id_auth_apply/view.dart';
import 'package:flyinsono/pages/user/user_profile/bindings.dart';
import 'package:flyinsono/pages/user/user_profile/view.dart';
import 'package:flyinsono/rpc.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:get/get_instance/src/extension_instance.dart';
import 'package:get/get_navigation/get_navigation.dart';

class UserCenterBaseController extends FControllerBase {
  final state = UserCenterState();
  late Timer? _timer;

  @override
  Future<void> onLoad() async {
    await loadData();
  }

  /// 加载数据
  Future<void> loadData() async {
    await loadUserInfo();
    _timer = null;
    if (state.idRolePassed || state.isGeneralUserRole) {
      loadIdRoleDisplay(state.roleCode);
    } else {
      checkIdentityApplyState();
    }
  }

  ///组织设备
  Future<void> orgDevice() async {
    try {
      Future.delayed(Duration(milliseconds: 300), () {
        final controller = Get.find<DeviceController>();
        controller.state.isOrgDevice = true;
      });
    } catch (e) {
      logger.e('to userDevice ex:', e);
    }
    await router.to(
      RouteNames.Org.Device,
      id: kIsMobile ? null : NavIds.HOME,
      parameters: {
        'isOrgdevice': 'true',
      },
    );
  }

  ///跳转报告模板页面
  Future<void> userReporTemplate({bool isOrg: false}) async {
    final routeName =
        isOrg ? RouteNames.Org.ReportTemplate : RouteNames.User.ReportTemplate;
    await router.to(
      routeName,
      id: kIsMobile ? null : NavIds.HOME,
      parameters: {
        "isOrg": isOrg.toString(),
      },
    );
  }

  /// 加载用户信息
  Future<void> loadUserInfo() async {
    try {
      var manager = Get.find<IUserInfoManager>();
      final result = await manager.getUserInfoAsync();
      state.avatar = result.headImageUrl ?? "";
      state.userName = result.userName ?? "";
      state.nickName = result.nickName ?? "";
      state.fullName = result.fullName ?? "";
      state.displayName = result.displayName!;
      state.avatar = result.headImageUrl ?? "";

      if (result.roleCodes != null &&
          result.roleCodes!.isNotEmpty &&
          result.roleCodes!.first.isNotEmpty) {
        // 有认证角色，状态-》已认证
        state.roleCode = result.roleCodes!.first;
        state.applyState = ApplyStateEnum.Passed;
      } else {
        // 重置状态
        state.roleCode = '';
        state.roleName = i18nBook.user.notAuthenticated.t;
        state.applyState = ApplyStateEnum.NotApply;
      }
      if (result.fieldList != null && result.fieldList!.length > 0) {
        state.labels = result.fieldList!;
      }
    } catch (e) {
      logger.e("[UserCenterload]UserInfo error", e);
    }
  }

  ///用户设备
  Future<void> userDevice() async {
    try {
      await router.to(
        RouteNames.User.Device,
        id: kIsMobile ? null : NavIds.HOME,
        parameters: {"isOrgdevice": 'false'},
      );
    } catch (e) {
      logger.e('to userDevice ex:', e);
    }
  }

  /// 根据申请状态跳转身份申请页面
  void gotoIdRoleApply(FInteractiveContainer businessParent) async {
    if (_timer != null) {
      return;
    }
    _timer = Timer(
      Duration(milliseconds: 1000),
      () {
        _timer = null;
      },
    );
    if (state.fullName.isEmpty) {
      return FConfirmAlert.show(
        businessParent: businessParent,
        context: Get.context!,
        title: i18nBook.user.notCompleteInfo.t,
        subTitle: i18nBook.user.completeInfoBeforeApply.t,
        confrimLabel: i18nBook.user.toCompleteInfo.t,
        cancelLabel: i18nBook.common.cancel.t,
        onConfirm: editProfile,
      );
    }
    // 个人信息已认证可前往身份申请
    try {
      final checked = await checkIdentityApplyState();
      if (!checked) return;

      if (state.applyState == ApplyStateEnum.NotApply) {
        // 未申请，选择角色
        await loadRoles();
        router.dialog(
          () => RoleAuthenticationPage(),
          binding: RoleAuthenticationBinding(),
          dismissible: false,
        );
      } else {
        if (state.applyState == ApplyStateEnum.Refused) {
          await loadRoles();
        }
        // 已申请，查看状态
        if (kIsMobile) {
          await router.to(RouteNames.User.RoleApply);
        } else {
          await router.dialog(
            () => UserIdAuthApplyPage(),
            binding: UserIdAuthApplyBinding(),
          );
        }
      }
    } catch (e) {
      logger.e("[UserCenter] check id_role apply state error", e);
    }
  }

  /// 编辑个人信息
  void editProfile() async {
    // AppRoutePages.USER_PROFILE.binding!.dependencies();
    if (kIsMobile) {
      await router.to(RouteNames.User.Profile);
    } else {
      await router.dialog(
        () => UserProfilePage(),
        binding: UserProfileBinding(),
      );
    }
    Future.delayed(
      Duration(milliseconds: 300), // 重新加载用户信息
      loadUserInfo,
    );
  }

  /// 加载角色集合
  Future<void> loadRoles() async {
    final roles = await rpc.role.findAuthenticationRolesAsync(
      FindAuthenticationRolesRequest(
        token: Store.user.token,
        language: i18nBook.locale.toCodeString('-'),
      ),
    );

    state.roles = roles.map(
      (x) {
        final descList = x.description!.split('\n');
        return UserRole(
          roleCode: x.roleCode!,
          startColor: FColorHelper.hex2Color(
              (x.colorStart == null || x.colorStart!.isEmpty)
                  ? "FFFFFF"
                  : x.colorStart,
              hasTag: false)!,
          endColor: FColorHelper.hex2Color(
              (x.colorEnd == null || x.colorEnd!.isEmpty)
                  ? "FFFFFF"
                  : x.colorEnd,
              hasTag: false)!,
          icon: FIcon(FIcons.account, color: Color(0xffc3a873), size: 44),
          iconUrl: x.iConUrl ?? '',
          roleName: x.roleName ?? '',
          descriptionLines: descList,
          fieldShowType: x.fieldShowType,
        );
      },
    ).toList();
  }

  /// 检查身份申请状态
  Future<bool> checkIdentityApplyState() async {
    try {
      final reslut = await rpc.identityApply.getLastIdentityApplyAsync(
        GetLastIdentityApplyRequest(token: Store.user.token),
      );
      state.applyState = ApplyStateEnum.values[reslut.applyState.index];
      if (state.idRolePassed) {
        loadIdRoleDisplay(reslut.applyRoleCode!);
      }
      return true;
    } on JsonRpcException catch (e) {
      if (e.code == 1001) {
        // 没有申请记录
        state.applyState = ApplyStateEnum.NotApply; // TODO: fix code
        return true;
      }
    } catch (e) {
      logger.e("[UserCenter] check identity apply state error", e);
      PromptBox.toast(i18nBook.user.loadApplyInfoFailed.t);
    }
    return false;
  }

  ///加载角色Style
  Future<void> loadIdRoleDisplay(String roleCode) async {
    try {
      if (roleCode.isEmpty) {
        return;
      }
      final roleInfo = await rpc.role.getRoleByCodeAsync(
        GetRoleByCodeRequest(
          token: Store.user.token,
          roleCode: roleCode,
          language: i18nBook.locale.toCodeString('-'),
        ),
      );
      state.vipColor = FColorHelper.hex2Color(
          (roleInfo.colorEnd == null || roleInfo.colorEnd!.isEmpty)
              ? "1b0207"
              : roleInfo.colorEnd,
          hasTag: false)!;
      state.roleName = roleInfo.roleName ?? i18nBook.user.hasAuthenticated.t;
    } catch (e) {
      state.vipColor = Colors.white;
      logger.e("[UserCenter] load identity vip color error", e);
    }
  }
}
