import 'package:get/get.dart'; import 'package:get/get_core/src/get_main.dart'; import 'package:injectable/injectable.dart'; import 'package:location/base/base_controller.dart'; import 'package:location/data/consts/error_code.dart'; import 'package:location/handler/error_handler.dart'; import 'package:location/resource/string.gen.dart'; import 'package:location/utils/http_handler.dart'; import 'package:location/utils/toast_util.dart'; import '../../data/repositories/account_repository.dart'; @injectable class LoginController extends BaseController { final RxString _phone = ''.obs; final RxString _code = ''.obs; String get phone => _phone.value; String get code => _code.value; final int _countDownTime = 60; final RxnInt _countDown = RxnInt(); int? get countDown => _countDown.value; final RxBool _isAgreePrivacy = false.obs; bool get isAgreePrivacy => _isAgreePrivacy.value; final AccountRepository accountRepository; LoginController(this.accountRepository); @override void onReady() { super.onReady(); } void onPhoneChanged(String value) { _phone.value = value; } void onCodeChanged(String value) { _code.value = value; } void onBackClick() { Get.back(); } void onSendVerificationCode() { if (_countDown.value != null) { return; } if (!RegExp(r'^1\d{10}$').hasMatch(phone)) { ToastUtil.show(StringName.loginPrintPhoneVerification); return; } if (!isAgreePrivacy) { ToastUtil.show(StringName.loginAgreePrivacy); return; } accountRepository.loginSendCode(phone).then((value) { _countDown.value = _countDownTime; _startCountDown(); }).catchError((error) { if (error is RequestCodeTooOftenException) { ToastUtil.show(StringName.loginRequestCodeFrequentlyToast); return; } if (error is ServerErrorException) { ToastUtil.show(error.message); } else { ToastUtil.show(StringName.loginVerificationCodeRequestFailedToast); } }); } void _startCountDown() { Future.delayed(Duration(seconds: 1), () { int? time = _countDown.value; if (time != null) { _countDown.value = time - 1; if (time > 0) { _startCountDown(); } else { _countDown.value = null; } } }); } void onPrivacyClick() { _isAgreePrivacy.value = !_isAgreePrivacy.value; } @override void onClose() { super.onClose(); _countDown.value = null; } void onLoginClick() { if (!RegExp(r'^1\d{10}$').hasMatch(phone)) { ToastUtil.show(StringName.loginPrintPhoneVerification); return; } if (!isAgreePrivacy) { ToastUtil.show(StringName.loginAgreePrivacy); return; } if (code.isEmpty) { ToastUtil.show(StringName.loginPrintVerificationCode); return; } accountRepository.loginUserLogin(phone, code).then((data) { Get.back(); ToastUtil.show(StringName.loginSuccess); }).catchError((error) { if (error is LoginTooOftenException) { ToastUtil.show(StringName.loginTooOftenToast); return; } if (error is ServerErrorException) { if (error.code == ErrorCode.verificationCodeError) { ToastUtil.show(StringName.loginVerificationCodeErrorToast); } else { ToastUtil.show(error.message); } } else { ToastUtil.show(StringName.loginFailedToast); } }); } }