import 'dart:async';

import 'package:cpt_auth/modules/sing_up_success/sign_up_success_page.dart';
import 'package:cs_resources/generated/l10n.dart';
import 'package:domain/repository/auth_repository.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:riverpod_annotation/riverpod_annotation.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:shared/utils/util.dart';

import 'sign_up_verify_state.dart';

part 'sign_up_verify_view_model.g.dart';

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

  @override
  SignUpVerifyState build() {
    authRepository = ref.read(authRepositoryProvider);

    final state = SignUpVerifyState();
    ref.onDispose(() {
      onDispose(state);
    });
    return state;
  }

  //校验SMS短信验证码，并完成用户注册
  void verifySignUpInput({
    required String firstName,
    required String lastName,
    required String email,
    required String fullPhone,
    required String password,
    required String confirmPassword,
    required String? smsCode,
  }) async {
    if (Utils.isEmpty(smsCode)) {
      ToastEngine.show('Enter SMS Code');
      return;
    }

    final result = await authRepository.userRegister(
      firstName: firstName,
      lastName: lastName,
      email: email,
      countryCode: Utils.getMobileCode(fullPhone),
      phone: Utils.getRealMobile(fullPhone),
      password: password,
      confirmPassword: confirmPassword,
      smsCode: smsCode,
    );

    if (result.isSuccess) {
      NotifyEngine.showSuccess(S.current.successful);
      //存入Token
      UserConfigService.getInstance().setToken(token: result.data?.token, userName: result.data?.name);
      //去成功页面
      SignUpSuccessPage.startInstance();
    } else {
      ToastEngine.show(result.errorMsg ?? "UnKnow Error");
    }
  }

  //销毁资源
  void onDispose(SignUpVerifyState initState) {
    state.controller.dispose();
    state.focusNode.dispose();
    countdownTimer?.cancel();
  }

  //展示验证码的弹窗
  showVerifyCodedDialog(String fullPhone) {
    DialogEngine.show(
      onDismiss: () {},
      widget: VerifyCodeDialog(
        confirmAction: (key, code) {
          //发送短信验证码
          sendSMS(fullPhone, 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,
    );

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

  Timer? countdownTimer;

  /// 开启倒计时
  void _startCountDown() {
    //60秒倒计时
    state = state.copyWith(isCounting: true, countdownTime: 60);

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