import 'dart:async';

import 'package:fis_common/index.dart';
import 'package:fis_common/logger/logger.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:fis_measure/utils/prompt_box.dart';
import 'package:fis_ui/values.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/config/config.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/router/index.dart';
import 'package:flyinsono/architecture/utils/keyboard.dart';
import 'package:flyinsono/managers/interfaces/vboxcontrol.dart';
import 'package:flyinsono/pages/auth/retrieve_password/controller.dart';
import 'package:flyinsono/pages/auth/sign_in/controller.dart';
import 'package:flyinsono/pages/auth/sign_up/controller.dart';
import 'package:flyinsono/rpc.dart';
import 'package:get/get.dart';

import 'state.dart';

///授权页面控制器
class AuthBoardController extends GetxController
    with EnterPressListenOnControllerMixin {
  /// 注册页面的路由名
  static final _registeredNames = [
    RouteNames.Auth.SignIn,
    RouteNames.Auth.SignUp,
    RouteNames.Auth.RetrievePwd,
  ];

  /// 响应式成员变量
  final state = AuthBoardState();

  /// 配置
  static ConfigService get config => ConfigService.ins;

  /// 当前文案
  BuildContext? currentContext;
  Timer? _timer;
  AuthBoardController();

  /// 根据路由切换页面
  ///
  /// [name] 路由name
  void changePageByName(String name, {Map<String, String>? parameters}) {
    final index = _registeredNames.indexOf(name);
    if (index < 0) return;

    changePage(index, parameters: parameters);
  }

  /// 根据索引切换页面
  ///
  /// [index] 索引值
  void changePage(int index, {Map<String, String>? parameters}) {
    if (index == state.currentIndex) return;

    state.currentIndex = index;
    router.replace(
      _registeredNames[index],
      id: NavIds.AUTH_BOARD,
      parameters: parameters,
    );
  }

  /// 处理路由切换
  Route? onGenerateRoute(RouteSettings settings) {
    return router.onGenerateRoute(
      settings,
      registeredNames: _registeredNames,
      id: NavIds.AUTH_BOARD,
    );
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  @override
  void onClose() {
    _timer?.cancel();
    Get.delete<SignInController>();
    Get.delete<SignUpController>();
    Get.delete<RetrievePasswordController>();
    currentContext = null;
    super.onClose();
  }

  @override
  void onEnterPressed() {
    if (kIsMobile) return;
    logger.i("Enter is pressed");
    final routeName = router.getCurrentNameByNavId(NavIds.AUTH_BOARD);
    if (routeName == null || routeName == RouteNames.Auth.SignIn) {
      Get.find<SignInController>().onSignInSubmit();
    } else if (routeName == RouteNames.Auth.SignUp) {
      Get.find<SignUpController>().onSubmit();
    } else if (routeName == RouteNames.Auth.RetrievePwd) {
      Get.find<RetrievePasswordController>().onSubmit();
    }
  }

  Future<void> onSwitchQRLogin() async {
    if (!state.isSwitchAuthBody) {
      await startWaitLogin();
    } else {
      _timer?.cancel();
    }
    state.isSwitchAuthBody = !state.isSwitchAuthBody;
  }

  Future<GetScanCodeResult?> _getScanCode() async {
    try {
      var result = await rpc.login.getScanCodeAsync(GetScanCodeRequest(
        platform: FPlatform.isWindows
            ? Platform.Windows
            : FPlatform.isAndroid
                ? Platform.Android
                : Platform.Ios,
        scanLoginSource:
            FPlatform.isPureWeb ? ScanLoginSource.Web : ScanLoginSource.PC,
      ));
      return result;
    } catch (e) {
      PromptBox.toast(i18nBook.common.networkException.t);
      logger.e('AuthBoardController getScanCode', e);
      state.expiredQRCode = true;
    }
    return null;
  }

  //检查是否扫码成功
  Future<CheckConfirmScanStateResult> _checkConfirmScanStateAsync() async {
    return await rpc.login
        .checkConfirmScanStateAsync(CheckConfirmScanStateRequest(
      scanCode: state.qrCode,
    ));
  }

  Future<void> startWaitLogin() async {
    var getScanCodeResult = await _getScanCode();
    if (getScanCodeResult == null) {
      return;
    }
    state.expiredQRCode = false;
    state.qrCode = getScanCodeResult.scanCode ?? '';
    try {
      _timer = Timer.periodic(Duration(seconds: 2), (timer) async {
        var checkResult = await _checkConfirmScanStateAsync();
        switch (checkResult.checkConfirmScanState) {
          case CheckConfirmScanState.Wait:
            break;
          case CheckConfirmScanState.Success:
            _timer?.cancel();
            try {
              var loginController = Get.find<SignInController>();
              await loginController.handleSignIn(checkResult.loginResult!);
              if (CartSystemPlatform.isCartSystemVersion) {
                var vBoxManager = Get.find<IVBoxControlManager>();
                vBoxManager.canShowHardwareDetector = true;
              }
              router.offAll(RouteNames.Home.Home);
            } catch (e) {
              logger.e('AuthBoardController onSwitchQRLogin ex:', e);
            }
            break;
          case CheckConfirmScanState.Expire:
            state.expiredQRCode = true;
            _timer?.cancel();
            break;
        }
      });
    } catch (e) {
      logger.e('AuthBoardController startWaitQRLogin ex:', e);
    }

    ///设置二维码超时
    Future.delayed(Duration(seconds: 120), () {
      if (_timer != null && _timer!.isActive) {
        state.expiredQRCode = true;
        _timer?.cancel();
      }
    });
  }
}
