import 'dart:async';

import 'package:cs_resources/generated/l10n.dart';
import 'package:domain/repository/auth_repository.dart';
import 'package:domain/repository/profile_repository.dart';
import 'package:flutter/material.dart';
import 'package:plugin_basic/constants/app_constant.dart';
import 'package:plugin_basic/dialog/verify_code_dialog.dart';
import 'package:plugin_basic/provider/user_config/user_config_service.dart';
import 'package:plugin_platform/engine/dialog/dialog_engine.dart';
import 'package:plugin_platform/engine/notify/notify_engine.dart';
import 'package:plugin_platform/engine/toast/toast_engine.dart';
import 'package:plugin_platform/http/dio/dio_cancelable_mixin.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 'change_mobile_state.dart';

part 'change_mobile_view_model.g.dart';

@riverpod
class ChangeMobileViewModel extends _$ChangeMobileViewModel with DioCancelableMixin {
  late final ProfileRepository _profileRepository;
  late final AuthRepository _authRepository;

  @override
  ChangeMobileState build() {
    _profileRepository = ref.read(profileRepositoryProvider);
    _authRepository = ref.read(authRepositoryProvider);

    final state = ChangeMobileState();
    initListener(state);

    registerCancellation(callback: () {
      onDispose(state);
    });

    return state;
  }

  /// 提交表单修改电话号码
  void submitChangeMobile() async {
    state = state.copyWith(oldCodeErrorText: null, newCodeErrorText: null);

    final FocusNode newMobileFocusNode = state.formData['new']!['focusNode'];
    final FocusNode newCodeFocusNode = state.formData['new_code']!['focusNode'];

    final TextEditingController newMobileController = state.formData['new']!['controller'];
    final TextEditingController newCodeController = state.formData['new_code']!['controller'];

    newMobileFocusNode.unfocus();
    newCodeFocusNode.unfocus();

    final newMobile = newMobileController.text;
    final newCode = newCodeController.text;

    Log.d('当前待提交的 newMobile:$newMobile newCode:$newCode');

    if (Utils.isEmpty(newMobile)) {
      ToastEngine.show("Enter New Mobile Phone");
      return;
    }

    if (Utils.isEmpty(newCode)) {
      state = state.copyWith(newCodeErrorText: "New mobile phone verification code cannot be empty!");
      return;
    }

    //执行密码登录
    final result = await _profileRepository.changeMobilePhone(
      smsCode: newCode,
      countryCode: state.newCountryCode,
      phone: newMobile,
      cancelToken: cancelToken,
    );

    if (result.isSuccess) {
      //提示成功
      NotifyEngine.showSuccess(S.current.successful);
      //清除用户登录信息
      UserConfigService.getInstance().handleLogoutParams();
      //去登录页面
      ComponentServiceManager().authService.startAndPopAllLoginPage();
    } else {
      ToastEngine.show(result.errorMsg ?? "UnKnow Error");
    }
  }

  //展示发送验证码弹窗
  void showVerifyCodedDialog() {
    final TextEditingController phoneController = state.formData['new']!['controller'];
    final phone = phoneController.text;
    if (Utils.isEmpty(phone)) {
      ToastEngine.show("Mobile Phone Error");
      return;
    }

    //短信验证码之前的图片验证码弹窗
    DialogEngine.show(
      onDismiss: () {},
      widget: VerifyCodeDialog(
        confirmAction: (key, code) {
          //发送短信验证码
          _sendSMS("${state.newCountryCode}$phone", key, code);
        },
      ),
    );
  }

  /// 调用接口发送短信验证码
  void _sendSMS(String fullPhone, String? key, String? code) async {
    final result = await _authRepository.sendSMS(
      countryCode: Utils.getMobileCode(fullPhone ?? ""),
      phone: Utils.getRealMobile(fullPhone ?? ""),
      captchaKey: key,
      captchaValue: code,
      cancelToken: cancelToken,
    );

    if (result.isSuccess) {
      NotifyEngine.showSuccess(S.current.send_sms_successful);
      _startCountDown();
    } else {
      ToastEngine.show(result.errorMsg ?? "UnKnow Error");
    }
  }

  Timer? newCountdownTimer;

  /// 开启倒计时 - New
  void _startCountDown() {
    //60秒倒计时
    state = state.copyWith(isNewCounting: true, newCountdownTime: 60);

    //每秒的倒计时
    newCountdownTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      int time = state.newCountdownTime;
      Log.d('Old倒计时-->$time');
      if (time > 0) {
        time--;
        state = state.copyWith(isNewCounting: true, newCountdownTime: time);
      } else {
        state = state.copyWith(isNewCounting: false, newCountdownTime: 0);
        newCountdownTimer?.cancel(); // 取消计时器
      }
    });
  }

  //初始化监听
  void initListener(ChangeMobileState initState) {
    final String? phone = UserConfigService.getState().user?.information?.phone;
    final TextEditingController phoneController = initState.formData['old']!['controller'];
    phoneController.text = phone ?? "-";

    final FocusNode newCodeFocusNode = initState.formData['new_code']!['focusNode'];

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

  //销毁资源
  void onDispose(ChangeMobileState initState) {
    final FocusNode newCodeFocusNode = initState.formData['new_code']!['focusNode'];
    newCodeFocusNode.dispose();

    newCountdownTimer?.cancel();

    Log.d("ChangeMobileViewModel 销毁 onDispose");
  }

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

}
