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/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/routes/app_pages.dart';

import 'login_state.dart';

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

  @override
  void onReady() {
    // TODO: implement onReady
    super.onReady();
  }

  @override
  void onInit() {
    super.onInit();
    state.userNameController = TextEditingController(text: 'longyunfei')..addListener(userNameListener);
    state.passwordController = TextEditingController(text: '123@abc');
    state.pwdFocus = FocusNode();
    state.theFocus = FocusNode();
  }

  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() async {
    if (!state.canLogin.value) return;

    state.canLogin.value = false;

    void toMsg(msg) {
      ToastUtils.showError(msg);
      state.canLogin.value = true;
    }

    Utils.hideKeyboard();

    String userName = state.userNameController.text.trim();
    String userPwd = state.passwordController.text.trim();
    if (userName == '') return toMsg('请填写用户账号');
    if (userPwd == '') return toMsg('请填写密码再试');
    if (!state.readAgreement.value) return toMsg('请阅读用户协议');

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

    try {
      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);
      EasyLoading.dismiss();
      Get.offAllNamed(Routes.startPage);
      // if (resultData.code != 200 || userData?.accessToken == null || userData?.accessToken == '') {
      //   return toMsg(resultData.message ?? '登录失败，请重试');
      // }

      // UserStore.to.setToken(userData!.accessToken);
      // state.canLogin.value = true;

      // BaseStructureResult<UserInfo> userRes = await UserApi.getUserInfo();
      // print('99999999999');
      // print(userRes.data!.userName);
      // if (userRes.code != 200 || userRes.data == null) {
      //   throw Exception('登录失败，请重试');
      // } else {
      //   UserStore.to.setUserInfo(userRes.data!);
      //   Get.offAllNamed(Routes.home);
      // }

      /* fastData.setUser(userRes.data!).then((value) {
        // 记住密码
        if (keepPwd) {
          fastData.setUserPwdAndAccount({'pwd': userPwd, 'account': userName});
        }
        // 更新
        ref.read(userProvider.notifier).initUserInfo();
        ref.read(userTokenProvider.notifier).initToken();

        // 跳转登录页
        Get.toNamed(Routes.login);
        // RouterManager.router.navigateTo(context, RouterManager.root, clearStack: true, transition: getTransition());
      });*/
    } catch (e) {
      print('进来异常');
      EasyLoading.dismiss();
      UserStore.to.erase();
      StorageService.to.erase();
      if (e is Exception) {
        try {
          toMsg(e.toString().split(":")[1]);
          return;
          // ignore: empty_catches
        } catch (e) {}
      }
      toMsg('登录失败，请重试');
    } finally {
      state.canLogin.value = true;
    }
  }

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