import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../../../config/translations/strings_enum.dart';
import '../../../controllers/api_controller.dart';
import '../../../dialog/loading/loading_dialog.dart';

class ForgotpwdController extends GetxController {
  final _apiController = Get.find<ApiController>();
  final usernameController = TextEditingController();
  final passwordController = TextEditingController();
  final usernameFocusNode = FocusNode();
  final passwordFocusNode = FocusNode();
  final _isChangePassword = false.obs;
  bool get isChangePassword => _isChangePassword.value;
  set isChangePassword(bool value) {
    _isChangePassword.value = value;
  }

  @override
  void onInit() {
    super.onInit();
  }

  @override
  void onClose() {
    usernameController.dispose();
    passwordController.dispose();
    usernameFocusNode.dispose();
    passwordFocusNode.dispose();
    super.onClose();
  }

  void checkLogin() {
    final username = usernameController.text;
    final password = passwordController.text;
    if (validatorInputValue(username) &&
        validatorInputValue(password) &&
        username == password) {
      isChangePassword = true;
    } else {
      isChangePassword = false;
    }
  }

  //6-20 characters (letters or numbers)
  bool validatorInputValue(String value) {
    // 只允许字母和数字并且是6-20位
    return value.length >= 6 &&
        value.length <= 20 &&
        RegExp(r'^[a-zA-Z0-9]+$').hasMatch(value);
  }

  bool validatorConfirmInputValue(String value) {
    // 只允许字母和数字并且是6-20位
    return value == usernameController.text;
  }

  // 处理修改密码
  Future<void> handleChangePassword() async {
    if (!isChangePassword) {
      return;
    }
    await LoadingDialog.show(
      context: Get.context!,
      loadingText: Strings.changingPassword.tr,
      successText: Strings.changePasswordSuccessful.tr,
      onRequest: () async {
        // 执行你的异步请求
        await _apiController.changePassword({
          "newPassword": passwordController.text,
        });
      },
      onSuccess: () {
        // 成功后的操作
        Get.back();
      },
    );
  }
}
