import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:vitalapp/architecture/defines.dart';
// import 'package:vitalapp/architecture/utils/prompt_box.dart';
import 'package:vitalapp/managers/interfaces/account.dart';
import 'package:vitalapp/managers/interfaces/doctor.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 {
    setBusy('登录中');
    // busy = true;
    try {
      final result = await Get.find<IAccountManager>()
          .login(state.account, state.password, state.isAutoLogin);
      if (result) {
        await Get.find<IDoctorManager>().syncInfo();
        // PromptBox.toast("登录成功");
        busy = false;
        Get.offAllNamed("/");

        /// 主页不确定 先跳检测页面
        // Get.offAllNamed('/medical', id: 1001);

        return;
      }
    } catch (e) {
      logger.e("LoginController login error", e);
    } finally {
      // busy = false;
    }
    // PromptBox.error("登录失败");
  }

  @override
  void onInit() {
    if (Store.user.account != null) {
      state.account = Store.user.account!;
    }
    state.isAutoLogin = Store.user.isAutoLogin;
    if (Store.user.isAutoLogin) {
      state.password = Store.user.password ?? '';
    }
    _checkUpdate();
    super.onInit();
  }

  /// 记住密码状态切换
  void onRememberPasswordChanged(bool val) {
    state.isAutoLogin = val;
  }

  @override
  void onClose() {
    _doDispose();
    super.onClose();
  }

  Future<void> _checkUpdate() async {
    final result = await Get.find<IUpgradeManager>().checkNewVersionArrival();
    if (result != null && result.isNeedUpdate) {
      final AppUpgradeController appUpgradeController =
          Get.put(AppUpgradeController());
      Get.dialog(
        GetBuilder<AppUpgradeController>(
          builder: (_) => AppUpgradeWidget(model: result),
          init: appUpgradeController,
        ),
        barrierDismissible: false,
        barrierColor: Colors.black.withOpacity(.4),
      );
    }
  }

  void _doDispose() {}
}
