import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:making_school_asignment_app/common/mixins/request_tool_mixin.dart';
import 'package:making_school_asignment_app/common/store/user_store.dart';
import 'package:making_school_asignment_app/common/utils/app_upgrade/model/UpdateAppEvent.dart';
import 'package:making_school_asignment_app/common/utils/app_upgrade/upgradeLogic.dart';
import 'package:making_school_asignment_app/common/utils/storage.dart';
import 'package:making_school_asignment_app/common/utils/toast_utils.dart';
import 'package:making_school_asignment_app/common/utils/utils.dart';
import 'package:making_school_asignment_app/page/login_page/children/sys_protocol.dart';
import 'package:making_school_asignment_app/routes/app_pages.dart';
import 'package:making_school_asignment_app/common/store/app_storage_key.dart';

import 'login_state.dart';

class LoginLogic extends GetxController with RequestToolMixin {
  final LoginState state = LoginState();

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

    /* state.userNameController = TextEditingController()
      ..addListener(userNameListener);
    state.passwordController = TextEditingController();*/

    String account = StorageService.to.read(AppStorageKey.account.value) ?? '';
    String pwd = StorageService.to.read(AppStorageKey.pwd.value) ?? '';
    if (account != '' && pwd != '') {
      state.userNameController.text = account;
      state.passwordController.text = pwd;
      state.keepPwd.value = true;
    }
    // state.userNameController.text = "AppleTester";
    // state.passwordController.text = "AppleTester123!";
    
    // state.userNameController.text = "SZJY200504252";
    // state.passwordController.text = "504252";

    state.pwdFocus = FocusNode();
    state.theFocus = FocusNode();
    getShowUserAdditionalFeatures(); //
  }

  void userNameListener() {
    String userName = state.userNameController.text;
    int useNameLength = userName.length;
    bool hasNameValNew = useNameLength > 0;
    if (hasNameValNew != state.hasNameVal) state.hasNameVal = hasNameValNew;
    const isProd = bool.fromEnvironment('dart.vm.product');
    if (!isProd && useNameLength == 11) {
      state.passwordController.text = userName.substring(useNameLength - 6);
    }
  }

  void showPassword() {
    state.isShowPwd.value = !state.isShowPwd.value;
  }

  /// 前往登录
  void toLogin(BuildContext context, UpgradeLogic upgradeLogic) async {
    if (!state.canLogin.value) return;
    Utils.hideKeyboard();
    state.canLogin.value = false;

    void toMsg(msg, [bool error = true]) {
      if (error) {
        WidgetsBinding.instance.addPostFrameCallback((_) => ToastUtils.showError(msg));
      } else {
        WidgetsBinding.instance.addPostFrameCallback((_) => ToastUtils.showInfo(msg));
      }
      state.canLogin.value = true;
    }

    String userName = state.userNameController.text.trim();
    String userPwd = state.passwordController.text.trim();
    if (userName == '') return toMsg('请填写用户账号');
    if (userPwd == '') return toMsg('请填写密码再试');
    if (!state.readAgreement.value) {
      var consent = await assistedReadingProtocol(context); // 辅助阅读协议阅读引导
      if (!consent) return toMsg('请阅读用户协议、隐私协议');
      state.readAgreement.value = true;
    }

    EasyLoading.show(status: 'loading...');

    try {
      /// 检查升级APP
      if (userName != 'AppleTester' && const bool.fromEnvironment('dart.vm.product')) {
        UpdateAppEvent? updateAppEvent = await upgradeLogic.getUpdateAppEvent();
        var upgrade = updateAppEvent?.upgrade ?? false;
        if (upgrade) {
          upgradeLogic.getAppUpgrade(Get.context ?? context);
          return toMsg('请在升级APP后再次登陆', false);
        }
      }
      await getClient().toLogin(userName, userPwd);
      String? nameidentifier = UserStore.to.userInfo.value?.nameidentifier;
      if (nameidentifier == null) {
        throw Exception('用户信息无效，请重试');
      }
      var data = await getClient().getUser(nameidentifier);
      if (data == null) {
        throw Exception('用户信息获取失败');
      }
      UserStore.to.setUserDetailInfo(data);

      if (state.keepPwd.value) {
        StorageService.to.write(AppStorageKey.account.value, userName);
        StorageService.to.write(AppStorageKey.pwd.value, userPwd);
      }

      Get.offAllNamed(Routes.startPage);
    } catch (e) {
      print('进来异常');
      UserStore.to.erase();
      StorageService.to.erase();
      if (e is Exception) {
        try {
          if (e is DioException && e.response?.data != null) {
            Map? msg = e.response?.data['error'];
            if (msg != null && msg["message"] != null) {
              return toMsg(msg["message"]);
            }
          }
          toMsg(e.toString().split(":")[1]);
          return;
          // ignore: empty_catches
        } catch (e) {}
      }
      toMsg('登录失败，请重试');
    } finally {
      state.canLogin.value = true;
      EasyLoading.dismiss();
    }
  }

  @override
  void onClose() {
    state.userNameController
      ..removeListener(userNameListener)
      ..dispose();
    state.passwordController.dispose();
    state.pwdFocus.dispose();
    state.theFocus.dispose();
    super.onClose();
  }

  /// 是否展示用户附加功能
  Future<void> getShowUserAdditionalFeatures() async {
    // state.showUserAdditionalFeatures.value = ;
  }
}
