import 'package:cpt_auth/modules/sign_up/sign_up_page.dart';
import 'package:cs_resources/generated/l10n.dart';
import 'package:domain/repository/auth_repository.dart';
import 'package:flutter/material.dart';
import 'package:plugin_basic/constants/app_constant.dart';
import 'package:plugin_basic/modules/global_web_page.dart';
import 'package:plugin_basic/provider/user_config/user_config_service.dart';
import 'package:plugin_platform/engine/notify/notify_engine.dart';
import 'package:plugin_platform/engine/toast/toast_engine.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:router/componentRouter/component_service_manager.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:shared/utils/util.dart';

import '../forgot_input/forgot_input_page.dart';
import 'auth_login_state.dart';

part 'auth_login_view_model.g.dart';

@riverpod
class AuthLoginViewModel extends _$AuthLoginViewModel {
  late final AuthRepository authRepository;

  @override
  LoginState build() {
    authRepository = ref.read(authRepositoryProvider);
    final state = LoginState();
    initListener(state);
    ref.onDispose(() {
      onDispose(state);
    });
    return state;
  }

  //切换是否隐藏密码
  void switchPwdVisibility() {
    state = state.copyWith(pwdVisibility: !state.pwdVisibility);
  }

  //执行用户的登录
  void doLogin() async {
    state = state.copyWith(accountErrorText: null, passwordErrorText: null);

    final FocusNode accountFocusNode = state.formData['account']!['focusNode'];
    final FocusNode passwordFocusNode = state.formData['password']!['focusNode'];
    final TextEditingController accountController = state.formData['account']!['controller'];
    final TextEditingController passwordController = state.formData['password']!['controller'];

    accountFocusNode.unfocus();
    passwordFocusNode.unfocus();

    final account = accountController.text;
    final password = passwordController.text;

    Log.d('当前待提交的 账号:$account password:$password');

    if (Utils.isEmpty(account)) {
      state = state.copyWith(accountErrorText: "Phone cannot be empty!");
      return;
    }

    if (Utils.isEmpty(password)) {
      state = state.copyWith(passwordErrorText: "Password cannot be empty!");
      return;
    }

    final result = await authRepository.authLogin("${state.countryCode}$account", password);

    //请求成功去首页
    if (result.isSuccess) {
      UserConfigService.getInstance().setToken(token: result.data?.token, userName: result.data?.name);
      ComponentServiceManager().mainService.startMainPage();
    } else {
      ToastEngine.show(result.errorMsg ?? "UnKnow Error");
    }
  }

  //去用户协议页面
  void gotoTermsPage(BuildContext context) {
    GlobalWebPage.startInstance(context: context, title: S.current.terms_of_service, url: 'https://24ifm.com/terms-and-conditions');
  }

  //去忘记密码页面
  void gotoForgotPage() {
    ForgotInputPage.startInstance();
  }

  //去注册页面
  void gotoSignUpPage() {
    SignUpPage.startInstance();
  }

  //切换同意按钮
  void switchAgreeTerms() {
    state = state.copyWith(isAgreeTerms: !state.isAgreeTerms);
  }

  //初始化监听
  void initListener(LoginState initState) {
    final FocusNode accountFocusNode = initState.formData['account']!['focusNode'];
    final FocusNode passwordFocusNode = initState.formData['password']!['focusNode'];
    final TextEditingController accountController = initState.formData['account']!['controller'];
    final TextEditingController passwordController = initState.formData['password']!['controller'];

    accountFocusNode.addListener(() {
      // 获取焦点的时候清空错误文本
      if (accountFocusNode.hasFocus) {
        state = state.copyWith(accountErrorText: null);
      }
    });

    passwordFocusNode.addListener(() {
      // 获取焦点的时候清空错误文本
      if (passwordFocusNode.hasFocus) {
        state = state.copyWith(passwordErrorText: null);
      }
    });

    //文本框的监听输入
    accountController.addListener(() {
      _updateButtonState(accountController, passwordController);
    });

    passwordController.addListener(() {
      _updateButtonState(accountController, passwordController);
    });
  }

  //当 Account 和 Password 都有值才能按钮可用
  void _updateButtonState(TextEditingController accountController, TextEditingController passwordController) {
    state = state.copyWith(isLoginBtnEnable: accountController.text.isNotEmpty && passwordController.text.isNotEmpty);
  }

  //销毁资源
  void onDispose(LoginState initState) {
    final FocusNode accountFocusNode = initState.formData['account']!['focusNode'];
    final FocusNode passwordFocusNode = initState.formData['password']!['focusNode'];
    final TextEditingController accountController = initState.formData['account']!['controller'];
    final TextEditingController passwordController = initState.formData['password']!['controller'];
    accountFocusNode.dispose();
    passwordFocusNode.dispose();
    accountController.dispose();
    passwordController.dispose();
    Log.d("LoginViewModel 销毁 onDispose");
  }

  //保存当前选择的国家区号
  void saveCountryCode(String? countryCode) {
    state = state.copyWith(countryCode: countryCode);
    Log.d("saveCountryCode:${state.countryCode}");
  }
}
