import 'dart:async';

import 'package:fis_common/helpers/encrypt.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/material.dart';
import 'package:flutter/services.dart';
import 'package:flyinsono/architecture/router/index.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/index.dart';
import 'package:flyinsono/pages/user/user_center/base_controller.dart';
import 'package:flyinsono/pages/user/user_center/widgets/change_password_Page.dart';
import 'package:flyinsono/pages/user/user_center/widgets/signature_panel.dart';
import 'package:flyinsono/rpc.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';

class UserCenterController extends UserCenterBaseController {
  TextEditingController oldPasswordInputController = TextEditingController();
  TextEditingController newPasswordInputController = TextEditingController();
  TextEditingController newPasswordAgainInputController =
      TextEditingController();
  final int countDown = 60;
  Timer? _timer;
  String password = '';
  VerificationTypeEnum verificationType = VerificationTypeEnum.Password;
  UserCenterController();

  /// 关于杏聆荟
  Future<void> aboutFlyinsono() async {
    final routeName = RouteNames.User.Setting;
    await router.to(
      routeName,
      id: kIsMobile ? null : NavIds.HOME,
    );
  }

  ///修改密码页面
  Future<void> changePassword() async {
    if (kIsMobile) {
      await router.to(
        RouteNames.User.ChangePasswordPage,
      );
    } else {
      await router.dialog(
        () => ChangePasswordPage(),
        binding: UserCenterBinding(),
      );

      state.disableSubmit = true;
    }
    state.verifyCode = '';
    state.oldPassword = '';
    state.newPassword = '';
    state.newPasswordAgain = '';
  }

  ///检查是否需要禁用提交
  void checkDisableSubmit() {
    var isPhoneEmpty = Store.user.phone == null || Store.user.phone!.isEmpty;
    var isEmailEmpty = Store.user.email == null || Store.user.email!.isEmpty;

    if (isPhoneEmpty && isEmailEmpty) {
      if (state.oldPassword.length > 5 &&
          state.newPassword.length > 5 &&
          state.newPasswordAgain.length > 5) {
        state.disableSubmit = false;
      } else if (!state.disableSubmit) {
        state.disableSubmit = true;
      }
    } else {
      if (state.verifyCode.length > 3 &&
          state.newPassword.length > 5 &&
          state.newPasswordAgain.length > 5) {
        state.disableSubmit = false;
      } else if (!state.disableSubmit) {
        state.disableSubmit = true;
      }
    }
  }

  @override
  void onClose() {
    _timer?.cancel();
    _timer = null;
    _doDispose();
    super.onClose();
  }

  Future<void> onScanData(String code) async {
    await router.replace(
      RouteNames.User.ScanQRLogin,
      parameters: {
        'scanData': code,
      },
    );
  }

  /// 打开电子签名的弹窗
  Future<void> openSignature() async {
    await Get.dialog(
      SignaturePanel(),
    );
  }

  ///组织架构
  void orgComPany() async {
    await router.to(
      RouteNames.Org.Personnel,
      id: kIsMobile ? null : NavIds.HOME,
    );
  }

  /// 机构信息
  void orgInfo() async {
    if (kIsMobile) {
      await router.to(RouteNames.Org.Info);
    } else {
      await router.dialog(() => OrgInfoPage(), binding: OrgInfoBinding());
    }
  }

  ///验证密码是否规范
  bool pwdCharCombinChecked(String newPassword) {
    if (newPassword.contains(' ')) {
      PromptBox.toast(i18nBook.auth.toast4PwdBlankError.t);
      return false;
    }
    int pwdMatchNum = 0;
    // 验证包含符号 - 非字母数字
    if (RegExp(r'[^\da-zA-Z\s]').hasMatch(newPassword)) pwdMatchNum++;
    // 验证包含字母
    if (RegExp(r'[a-zA-Z]').hasMatch(newPassword)) pwdMatchNum++;
    // 验证包含数字
    if (RegExp(r'\d').hasMatch(newPassword)) pwdMatchNum++;
    if (pwdMatchNum > 1) {
      return true;
    } else {
      PromptBox.toast(i18nBook.auth.toast4PwdCharCombinError.t);
      return false;
    }
  }

  ///发送验证码（手机/邮箱）
  Future<void> sendVerificationCode() async {
    try {
      setBusy(i18nBook.auth.sendingVerificationCode.t);
      final isPhoneNotEmpty =
          Store.user.phone != null && Store.user.phone!.isNotEmpty;
      var result = false;
      if (isPhoneNotEmpty) {
        result = await rpc.login.sendSMSVerificationCodeAsync(
          SendSMSVerificationCodeRequest(
            userPhone: Store.user.phone,
          ),
        );
      } else {
        result = await rpc.login.sendEmailVerificationCodeAsync(
          SendEmailVerificationCodeRequest(
            emailAddress: Store.user.email,
            languageCode: i18nBook.locale.toCodeString('-'),
          ),
        );
      }
      if (result) {
        _onSent();
      } else {
        PromptBox.toast(i18nBook.auth.toast4VerifyCodeSendFail.t);
      }
    } catch (ex) {
      logger.e("sendVerificationCode ex:", ex);
    }
    busy = false;
  }

  /// 设置签名
  Future<void> setCommonSettingsAsync(String signatureValue) async {
    try {
      final result = await rpc.user.setCommonSettingsAsync(
        CommonSettingsRequest(
          token: Store.user.token,
          value: signatureValue,
          settingType: CommonSettingsEnum.Signature,
        ),
      );
      if (result) {
        var manager = Get.find<IUserInfoManager>();
        await manager.getUserInfoAsync();
        PromptBox.toast(i18nBook.user.saveSuccess.t);
      }
    } catch (e) {
      printError(info: e.toString());
      logger.e("setCommonSettingsAsync ex:", e);
    }
  }

  /// 身份验证
  Future<void> commonUserLogOff() async {
    try {
      final isPhoneNotEmpty =
          Store.user.phone != null && Store.user.phone!.isNotEmpty;
      final isEmailNotEmpty =
          Store.user.email != null && Store.user.email!.isNotEmpty;
      final isPasswordNotEmpty =
          Store.user.password != null && Store.user.password!.isNotEmpty;
      var pas = password;
      if (isPhoneNotEmpty) {
        verificationType = VerificationTypeEnum.PhoneVerificationCode;
      } else if (isEmailNotEmpty) {
        verificationType = VerificationTypeEnum.EmailVerificationCode;
      } else if (isPasswordNotEmpty) {
        verificationType = VerificationTypeEnum.Password;
        pas = FEncryptHelper.symmetryEncrypt(password);
      }
      final result = await rpc.user.commonUserLogOffAsync(
        CommonLogOffRequest(
          token: Store.user.token,
          anyCode: pas,
          verificationType: verificationType,
        ),
      );
      if (result) {
        PromptBox.toast(i18nBook.common.cancellationSuccess.t);
        Future.delayed(Duration(milliseconds: 2000), () async {
          Store.app.setBusy(i18nBook.homePage.loginingOut.t);
          await Store.user.handelLogOut();
          Store.app.cancelBusy();
          router.offAll(RouteNames.Auth.AuthBoard);
        });
      }
    } catch (e) {
      printError(info: e.toString());
      logger.e("commonUserLogOff ex:", e);
    }
  }

  ///更新头像
  Future<void> updateAvatar() async {
    try {
      if (state.avatar.isEmpty) {
        printError(info: 'avatart is empty');
        return;
      }
      final result = await rpc.user.alterPersonInfoAsync(AlterPersonInfoRequest(
        token: Store.user.token,
        headImageUrl: state.avatar,
      ));
      if (result) {
        Store.user.avatar = state.avatar;
        PromptBox.toast(i18nBook.user.avatarUploadSuccess.t);
      } else {
        PromptBox.toast(i18nBook.user.avatarUploadFailed.t);
      }
    } catch (e) {
      printError(info: e.toString());
    }
  }

  ///更改密码
  Future<void> updatePassword() async {
    try {
      bool checkResult = _checkPassword();
      if (!checkResult) {
        return;
      }
      final isPhoneNotEmpty =
          Store.user.phone != null && Store.user.phone!.isNotEmpty;
      final isEmailNotEmpty =
          Store.user.email != null && Store.user.email!.isNotEmpty;
      final isPasswordNotEmpty =
          Store.user.password != null && Store.user.password!.isNotEmpty;
      bool result = false;
      if (isPhoneNotEmpty || isEmailNotEmpty) {
        result = await _modifyPassword();
      } else if (isPasswordNotEmpty) {
        var accout = '';
        accout = Store.user.account ?? '';
        result = await rpc.login.modifyPasswordAsync(ModifyPasswordRequest(
          token: Store.user.token,
          anyAccount: accout,
          password: FEncryptHelper.symmetryEncrypt(state.oldPassword),
          newPassword: FEncryptHelper.symmetryEncrypt(state.newPassword),
        ));
      }
      if (result) {
        PromptBox.toast(i18nBook.user.modifySuccess.t);
        router.back();
      }
    } catch (e) {
      printError(info: e.toString());
      logger.e("updatePassword ex:", e);
    }
  }

  /// 上传电子签名
  Future<void> uploadSignatureImage() async {
    try {
      Uint8List? signatureImageBytes = await Get.dialog(
        SignaturePanel(),
      );
      if (signatureImageBytes == null) return;
      XFile xFile = XFile.fromData(
        signatureImageBytes,
        name: 'signatureImage' + '.jpg',
      );

      final url = await rpc.storage.upload(xFile);

      if (url != null || url != '') {
        setCommonSettingsAsync(url ?? '');
      }
    } catch (ex) {}
  }

  ///设置页面
  Future<void> userSetting() async {
    await router.to(
      RouteNames.User.Setting,
      id: kIsMobile ? null : NavIds.HOME,
    );
  }

  /// 词条部分
  Future<void> vocabularyEntry(bool isOrgVocabularyEntry) async {
    Future.delayed(Duration(milliseconds: 100), () {
      final controller = Get.find<VocabularyEntryController>();
      if (isOrgVocabularyEntry) {
        controller.isOrg = true;
      }
    });

    final routeName =
        isOrgVocabularyEntry ? RouteNames.Org.Entry : RouteNames.User.Entry;
    await router.to(
      routeName,
      id: kIsMobile ? null : NavIds.HOME,
    );
  }

  ///校验密码是否合规
  bool _checkPassword() {
    final isPhoneNotEmpty =
        Store.user.phone != null && Store.user.phone!.isNotEmpty;
    final isEmailNotEmpty =
        Store.user.email != null && Store.user.email!.isNotEmpty;
    if (state.newPassword.isEmpty) {
      PromptBox.toast(i18nBook.user.newPassowrdCannotBeNull.t);
      return false;
    } else if (state.newPassword != state.newPasswordAgain) {
      PromptBox.toast(i18nBook.user.twoPasswordNotSame.t);
      return false;
    } else if (state.newPassword == state.oldPassword) {
      PromptBox.toast(i18nBook.user.newPassowrdCannotBeSame.t);
      return false;
    } else if (!pwdCharCombinChecked(state.newPassword)) {
      return false;
    }
    if (isPhoneNotEmpty || isEmailNotEmpty) {
      if (state.verifyCode.isEmpty) {
        PromptBox.toast(i18nBook.user.verifyCodeCannotBeNull.t);
        return false;
      }
    }
    return true;
  }

  void _doDispose() {
    oldPasswordInputController.dispose();
    newPasswordAgainInputController.dispose();
    newPasswordInputController.dispose();
  }

  ///跟据手机号修改密码
  Future<bool> _modifyPassword() async {
    final isPhoneNotEmpty =
        Store.user.phone != null && Store.user.phone!.isNotEmpty;
    var accout = '';
    if (isPhoneNotEmpty) {
      accout = Store.user.phone ?? '';
    } else {
      accout = Store.user.email ?? '';
    }
    return await rpc.login.modifyPasswordAsync(
      ModifyPasswordRequest(
        token: Store.user.token,
        anyAccount: accout,
        anyCode: state.verifyCode,
        newPassword: FEncryptHelper.symmetryEncrypt(state.newPassword),
      ),
    );
  }

  ///验证码发送完成
  void _onSent() {
    PromptBox.toast(i18nBook.user.hasSent.t);
    state.isFetching = true;
    state.seconds = countDown;
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      state.seconds = state.seconds - 1;
      if (state.seconds == 0) {
        timer.cancel();
        state.isFetching = false;
      }
    });
  }
}
