part of forget_pwd;

class ForgetPwdController extends GetxController {
  // 账号
  final TextEditingController phoneInput = TextEditingController();
  // 验证码
  final TextEditingController codeInput = TextEditingController();
  // 定时器
  late Timer _timer;
  // 按钮是否可用
  bool _enable = false;
  bool get enable => _enable;
  // 倒计时60秒
  int _countDown = 60;
  int get countDown => _countDown;
  bool _isCounting = false;

  bool get isCounting => _isCounting;

  /// 开启定时器
  void start() {
    _isCounting = true;
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (_countDown > 1) {
        _countDown--;
      } else {
        stop();
      }
      update();
    });
  }

  /// 停止计时器
  void stop() {
    if (_timer != null) {
      _timer.cancel();
      _isCounting = false;
    }
    _countDown = 60;
  }

  /// 是否可点击
  void setCanClick() {
    if (ValidatorTool.isValidPhoneNumber(phoneInput.text) &&
        codeInput.text.length == 6) {
      _enable = true;
    } else {
      _enable = false;
    }
    update();
  }

  @override
  void onInit() {
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      // 定时器回调
    });

    /// 测试账号
    // if (kDebugMode) {
    //   phoneInput.text = '13521054068';
    //   codeInput.text = '123456';
    // }
    super.onInit();
  }

  @override
  void onClose() {
    phoneInput.dispose();
    codeInput.dispose();
    _timer.cancel();
    _isCounting = false;
    super.onClose();
  }

  /// 发送验证码
  void sendCode() async {
    final result =
        await AccountAPI.sendCode(phone: phoneInput.text, type: 'login');
    if (result) {
      Toast.show('发送成功');
      start();
    } else {
      Toast.show('发送失败');
    }
  }

  /// 验证验证码
  Future<bool> checkCode() async {
    final result = await AccountAPI.checkCode(
        phone: phoneInput.text, code: codeInput.text);
    return result;
  }
}
