import 'package:cpt_auth/modules/forgot_verify/forgot_verify_page.dart';
import 'package:flutter/material.dart';
import 'package:plugin_platform/engine/toast/toast_engine.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:shared/utils/util.dart';

import 'forgot_input_state.dart';

part 'forgot_input_view_model.g.dart';

@riverpod
class ForgotInputViewModel extends _$ForgotInputViewModel {
  @override
  ForgotInputState build() {
    final state = ForgotInputState();
    initListener(state);
    ref.onDispose(() {
      onDispose(state);
    });
    return state;
  }

  //提交忘记密码表单，发送验证码
  void submitInput() {
    state = state.copyWith(emailErrorText: null, phoneErrorText: null);

    final FocusNode emailFocusNode = state.formData['email']!['focusNode'];
    final FocusNode phoneFocusNode = state.formData['phone']!['focusNode'];
    final TextEditingController emailController = state.formData['email']!['controller'];
    final TextEditingController phoneController = state.formData['phone']!['controller'];

    emailFocusNode.unfocus();
    phoneFocusNode.unfocus();

    final email = emailController.text;
    final phone = phoneController.text;

    Log.d('当前待提交的 邮箱:${email} 电话:${phone} 最终的电话：${state.countryCode}$phone');

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

    ForgotVerifyPage.startInstance(phone: "${state.countryCode}$phone");
  }

  //初始化监听
  void initListener(ForgotInputState initState) {
    final FocusNode emailFocusNode = initState.formData['email']!['focusNode'];
    final FocusNode phoneFocusNode = initState.formData['phone']!['focusNode'];

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

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

  //销毁资源
  void onDispose(ForgotInputState initState) {
    final FocusNode emailFocusNode = initState.formData['email']!['focusNode'];
    final FocusNode phoneFocusNode = initState.formData['phone']!['focusNode'];
    emailFocusNode.dispose();
    phoneFocusNode.dispose();
    Log.d("ForgotInputViewModel 销毁 onDispose");
  }

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

}
