import 'package:flutter/foundation.dart';
import 'package:flyinsono/architecture/router/index.dart';
import 'package:flyinsono/architecture/services/modules/config_language.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/architecture/utils/dongle_data.dart';
import 'package:flyinsono/architecture/utils/prompt_box.dart';
import 'package:flyinsono/js_platform/listener.dart';
import 'package:flyinsono/lab/manager/interfaces/login.dart';
import 'package:flyinsono/pages/setting/server_setting/bindings.dart';
import 'package:flyinsono/pages/setting/server_setting/view.dart';
import 'package:flyinsono/rpc.dart';
import 'package:get/get.dart';
import 'package:fis_jsonrpc/services/index.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:fis_common/logger/logger.dart';
import 'package:fis_common/helpers/encrypt.dart';
import 'package:fis_common/index.dart';
import 'index.dart';

class LabLoginController extends GetxController {
  LabLoginController();

  // int tabHashCode;
  int _callServerTimes = 0;

  final state = LabLoginState();
  final login = Get.find<ILogInManager>();

  /// 语言包初始化
  final languageService = Get.find<LanguageService>();
  static const String labLoginId = "lab_login";

  /// 当前平台
  Platform get platform => FPlatform.isAndroid
      ? Platform.Android
      : FPlatform.isIOS
          ? Platform.Ios
          : Platform.Windows;

  /// 当前设备
  LoginSource get loginSource => kIsMobile
      ? LoginSource.Mobile
      : FPlatform.isPureWeb
          ? LoginSource.Web
          : (FPlatform.isMacOS || FPlatform.isWindows)
              ? LoginSource.PC
              : LoginSource.Pad;

  void commonLoginAsync() async {
    if (state.password.isEmpty) {
      PromptBox.toast('请输入密码');
      return;
    }
    bool isLocalLabStation = false;
    if (FPlatform.isWindows) {
      isLocalLabStation = await rpc.platform.getIsLabStation();
    }
    if (isLocalLabStation) {
      bool calServerResult = await callServer();
      if (!calServerResult) {
        PromptBox.toast('服务正在初始化，请稍后再试。');
        return;
      }
    }
    print(Store.user.isLogin);
    var result = await login.commonLoginAsync(
      username: state.username.trim(),
      password: FEncryptHelper.symmetryEncrypt(state.password),
      platform: platform,
      loginSource: loginSource,
    );
    print(result?.toJson());

    /// 密码输错之后 错误提示
    if (result?.lockRemainingTimes != null) {
      await passwordRetryPrompt(result?.lockRemainingTimes! ?? 0);
    }
    logger.i(
        "User - [${state.username}] logon! Session Token: ${result?.token}.");
    if (result != null) {
      if (result.token != null && result.token!.isNotEmpty) {
        Store.user.setToken(result.token!);
        await handleSignIn(result);

        /// 三月之后的密码过期 选择是否重设密码
        if (result.passwordExpired) {
          await passwordFailureReset();
        } else {
          _successfulLoginNavigation();
        }
      }
    }

    // if (result) {
    //   Get.offNamed(LabRouteNames.Main);
    // }
    // 导航到主页
  }

  Future<bool> callServer() async {
    try {
      await rpc.vinnoServer.echoAsync();
      return true;
    } catch (e) {
      logger.i('call server times:${_callServerTimes}');
      if (kDebugMode) {
        print('call server times:${_callServerTimes}');
      }
    }
    return false;
  }

  /// 登录成功的跳转
  void _successfulLoginNavigation() {
    router.offAll(RouteNames.Lab.Main);
  }

  void dongleLoginAsync() async {
    var dongleData = await rpc.platform.getDongleData();
    logger.i("dongleLoginAsync-  User - dongleData: $dongleData.");
    var splitItems = dongleData.split(';');
    if (splitItems.length < 6) {
      PromptBox.toast(i18nBook.homePage.dongleLoginError.t);
      return;
    }
    if (splitItems[1] != "Vinno" || splitItems[2] != "vLab") {
      PromptBox.toast(i18nBook.homePage.dongleLoginError.t);
      return;
    }
    DongleData.anyCode = splitItems[0];
    DongleData.labDongle = splitItems[3];
    DongleData.anyAccount = splitItems[4];

    var result = await login.dongleCommonLoginAsync(
      anyAccount: DongleData.anyAccount,
      anyCode: DongleData.anyCode,
      labDongle: DongleData.labDongle,
      loginSource: loginSource,
    );
    logger.i(
        "User - [${state.username}] logon! Session Token: ${result?.token}.");
    if (result != null) {
      // PromptBox.toast(
      //     "anyAccount:${DongleData.anyAccount},licenseId:${result.licenseId}");
      if (result.licenseId != DongleData.anyAccount) {
        ///更新anyAccount
        splitItems[4] = result.licenseId ?? splitItems[4];
        var dongleWriteData = splitItems.join(';');
        await rpc.platform.writeDongleData(dongleWriteData);
      }

      if (result.token != null && result.token!.isNotEmpty) {
        Store.user.setToken(result.token!);
        await handleSignIn(result);
        _successfulLoginNavigation(); //登陆成功跳转
      }
    }
  }

  /// 密码重试机制
  Future<void> passwordRetryPrompt(int lockRemainingTimes) async {
    return PromptBox.toast(
      i18nBook.auth.remainingTimes.translate(
        [lockRemainingTimes],
      ),
    );
  }

  /// 密码失效机制 修改密码
  Future<void> passwordFailureReset() async {
    JsListener businessParent = JsListener();
    FConfirmAlert.show(
      context: Get.context!,
      title: i18nBook.auth.theCurrentPasswordHasExpired.t,
      subTitle: i18nBook.auth.confirmEnterOrResetPassword.t,
      businessParent: businessParent,
      confrimLabel: i18nBook.auth.resetPassword.t,
      cancelLabel: i18nBook.auth.confirmEnter.t,
      onConfirm: () async {
        // await router.dialog(
        //   () => ChangePasswordPage(),
        //   binding: UserCenterBinding(),
        // );
        // Store.user.handelLogOut();
        // passwordController.text = "";
      },
      onCancel: () {
        // _successfulLoginNavigation();
      },
    );
  }

  /// 处理登录
  Future<void> handleSignIn(LoginResult result) async {
    try {
      final userInfo = await rpc.user.getUserInfoAsync(GetUserInfoRequest(
        token: result.token,
      ));
      Store.user.avatar = userInfo.headImageUrl ?? "";
      Store.user.setBatchExportRight(userInfo.isBatchExportDiagnoseData);
      Store.user.handleUserSyncUpdate(userInfo);
      state.userCode = userInfo.userCode!;
      await _saveSignInState(result).then((value) {
        languageService.init();
      });
    } catch (e) {
      logger.e("handleSignIn failed.", e);
    }
  }

  /// 网络设置
  Future<void> onNetworkSettingClick() async {
    await router.dialog(
      () => ServerSettingPage(),
      binding: ServerSettingBinding(),
    );
  }

  /// 保存登录状态
  Future<void> _saveSignInState(LoginResult info) async {
    final isAutoLogin = state.isAutoLogin && !state.isCodeSignIn;
    await Store.user.handleLogOn(
      token: info.token!,
      code: state.userCode,
      isAutoLogin: isAutoLogin,
      isAgreeClause: state.isAgreeClause,
      password: state.password,
      account: state.username,
    );
    Store.user.handleAfterLogOn();
  }

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    super.onInit();
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    super.onReady();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    super.onClose();
  }

  /// dispose 释放内存
  @override
  void dispose() {
    super.dispose();
  }
}
