part of change_phone;

class ChangePhoneController 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 (phoneInput.text.length == 11 && 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> changePhone() async {
    final result = await MineAPI.changePhone(phone:phoneInput.text, code: codeInput.text,);
    return result;
  }


}