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';
import '../../../routes/app_pages.dart';

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

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

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

  void onBackPressed() {
    // 判断软键盘是否弹出
    if (usernameFocusNode.hasFocus || passwordFocusNode.hasFocus) {
      FocusManager.instance.primaryFocus?.unfocus();
      // 延迟100毫秒后关闭页面
      Future.delayed(const Duration(milliseconds: 250), () {
        Get.back();
      });
    } else {
      Get.back();
    }
  }

  void checkLogin() {
    final username = usernameController.text;
    final password = passwordController.text;
    if (validatorInputValue(username) && validatorInputValue(password)) {
      isLogin = true;
    } else {
      isLogin = 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);
  }

  // 处理登录
  Future<void> handleSignUp() async {
    if (!isLogin) {
      return;
    }
    // 取消输入框焦点，关闭软键盘，防止 LoadingDialog 关闭后软键盘再次弹出
    FocusManager.instance.primaryFocus?.unfocus();

    final params = {
      "account": usernameController.text.trim(),
      "password": passwordController.text,
    };
    await LoadingDialog.show(
      context: Get.context!,
      loadingText: Strings.loggingIn.tr,
      successText: Strings.loginSuccessful.tr,
      onRequest: () async {
        // 执行你的异步请求
        await _apiController.login(params);
      },
      onSuccess: () {
        // 成功后的操作
        Get.offAllNamed(Routes.HOME);
      },
    );
  }
}
