import 'dart:async';
import 'package:flutter/material.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'package:ln_jq_app/common/model/base_model.dart';

class LoginController extends GetxController with BaseControllerMixin {
  @override
  String get builderId => 'login';

  LoginController();

  // 控制输入框的 TextEditingController
  final TextEditingController phoneController = TextEditingController();
  final TextEditingController codeController = TextEditingController();

  final TextEditingController stationIdController = TextEditingController();
  final TextEditingController passwordController = TextEditingController();


  // --- 倒计时逻辑 ---
  final RxInt countdown = 0.obs;
  Timer? _timer;

  void startCountdown() async {
    if (phoneController.text.isEmpty || !phoneController.text.isPhoneNumber) {
      showToast("请输入正确的手机号");
      return;
    }

    if (countdown.value > 0) return;

    // 调用发送验证码接口
    var responseData = await HttpService.to.post(
      'appointment/login/sendCode',
      data: {"mobile": phoneController.text},
    );

    if (responseData == null) {
      showToast('验证码发送失败，请稍后重试');
      return;
    }

    try {
      var result = BaseModel.fromJson(responseData.data);

      if (result.code != 0) {
        showToast(result.error);
        dismissLoading();
        return;
      }

      showToast("验证码已发送");

      countdown.value = 60;
      _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
        if (countdown.value > 0) {
          countdown.value--;
        } else {
          _timer?.cancel();
        }
      });
    } catch (e) {
      showToast('验证码服务异常，请稍后重试');
    }
  }

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

  @override
  void onClose() {
    _timer?.cancel();
    phoneController.dispose();
    codeController.dispose();

    stationIdController.dispose();
    passwordController.dispose();
    super.onClose();
  }
}
