import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_smartscan_plugin/id_card_recognition.dart';
import 'package:get/get.dart';
import 'package:vitalapp/architecture/defines.dart';
import 'package:vitalapp/architecture/utils/common_util.dart';
import 'package:vitalapp/architecture/utils/json_rpc_ex_interceptor.dart';
import 'package:vitalapp/architecture/utils/prompt_box.dart';
import 'package:vitalapp/global.dart';
// import 'package:vitalapp/architecture/utils/prompt_box.dart';
import 'package:vitalapp/managers/interfaces/account.dart';
import 'package:vitalapp/managers/interfaces/device.dart';
import 'package:vitalapp/managers/interfaces/diagnosis.dart';
import 'package:vitalapp/managers/interfaces/doctor.dart';
import 'package:vitalapp/managers/interfaces/organization.dart';
import 'package:vitalapp/managers/interfaces/patient.dart';
import 'package:vitalapp/managers/interfaces/system_setting.dart';
import 'package:vitalapp/managers/interfaces/upgrade.dart';
import 'package:vitalapp/pages/upgrade/controller.dart';
import 'package:vitalapp/pages/upgrade/widget/simple_app_upgrade.dart';
import 'package:vitalapp/store/store.dart';
import 'package:fis_common/logger/logger.dart';
import 'state.dart';

class LoginController extends FControllerBase {
  final state = LoginState();

  void onSubmit() async {
    if (!kIsOnline) {
      PromptBox.toast("登录失败，请检查网络连接");
      return;
    }

    setBusy('正在登录');
    // busy = true;
    try {
      final code = await Get.find<IAccountManager>()
          .login(state.account, state.password, state.isAutoLogin);
      if (code == 0) {
        await _syncAfterLogin();
        // PromptBox.toast("登录成功");
        busy = false;
        Get.offAllNamed("/");
        loadIdCardRecognition();

        /// 主页不确定 先跳检测页面
        // Get.offAllNamed('/medical', id: 1001);
      } else {
        busy = false;
        final exMsg = JsonRpcExInterceptor.translateErrorCode(code);
        PromptBox.toast(exMsg);
      }
    } catch (e) {
      logger.e("LoginController login error", e);
      busy = false;
      PromptBox.error("登录异常");
    }
  }

  void loadIdCardRecognition() async {
    ///模型路径
    ModelDataInformation modelDataInfo = ModelDataInformation(
        ocrv4DetInfer: 'assets/valid_models/ch_PP-OCRv4_det_infer.onnx',
        ocrv4RecInfer: 'assets/valid_models/ch_PP-OCRv4_rec_infer.onnx',
        ppocrKeysV1: 'assets/valid_models/ppocr_keys_v1.txt',
        ppocrMobileClsTrain:
            'assets/valid_models/ch_ppocr_mobile_v2.0_cls_train.onnx');
    var result = await CommonUtil.idCardRecognition.initiate(modelDataInfo);
    logger.e("LoginController loadIdCardRecognition result：$result");
  }

  @override
  void onInit() {
    _loadHisState();
    super.onInit();
  }

  @override
  void onReady() {
    super.onReady();
    _checkUpdate().then((value) {
      if (value) {
        return;
      }
      if (state.isAutoLogin && Store.user.isLogOn) {
        // 先进行退出登录
        Store.user.handleLogOut();
        // 勾选了“自动登录”且之前是已登录状态下，尝试自动登录
        onSubmit();
      }
    });
  }

  /// 自动登录状态切换
  void onAutoLoginChanged(bool val) {
    state.isAutoLogin = val;
  }

  Future<bool> _checkUpdate() async {
    if (!kIsOnline) {
      return false;
    }
    final result = await Get.find<IUpgradeManager>().checkNewVersionArrival();
    if (result != null && result.isNeedUpdate) {
      final completer = Completer<bool>();
      Get.dialog(
        GetBuilder<AppUpgradeController>(
          builder: (_) => AppUpgradeWidget(
            model: result,
            onCanceled: () {
              completer.complete(false);
            },
            onInstallReady: () {
              completer.complete(true);
            },
          ),
          init: AppUpgradeController(),
        ),
        barrierDismissible: false,
        barrierColor: Colors.black.withOpacity(.4),
      );
      return completer.future;
    } else {
      return false;
    }
  }

  Future<void> _syncAfterLogin() async {
    await Get.find<IDoctorManager>().syncInfo();
    await Future.wait([
      // 更新应用级配置
      Get.find<ISystemSettingManager>().getSettings(true),
      // 更新机构相关配置
      Get.find<IOrganizationManager>().syncConfigurations(),
      //更新本地离线居民数据userCode等于空的数据
      Get.find<IPatientManager>().resettingUsercodeIsEmptyData(),
      //更新本地离线测试数据userCode等于空的数据
      Get.find<IDiagnosisManager>().resettingUsercodeIsEmptyData(),
      // 上报设备
      Get.find<IDeviceManager>().reportTablet(),
    ]);
  }

  void _loadHisState() {
    state.isAutoLogin = Store.user.isAutoLogin;
    if (Store.user.account != null) {
      state.account = Store.user.account!;
    }
    if (Store.user.isAutoLogin) {
      state.password = Store.user.password ?? '';
    }
  }
}
