import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:news_getx/data/model/user.dart';
import 'package:news_getx/data/repository/user_repository.dart';
import 'package:news_getx/data/services/user.dart';
import 'package:news_getx/modules/widgets/toast.dart';
import 'package:news_getx/routes/app_pages.dart';
import 'package:news_getx/utils/security.dart';
import 'package:news_getx/utils/validator.dart';

class SignInController extends GetxController {
  final UserRepository repository;

  // email的控制器
  final TextEditingController emailController = TextEditingController();

  // 密码的控制器
  final TextEditingController passwordController = TextEditingController();

  SignInController({required this.repository});

  // 跳转 注册界面
  handleNavSignUp() {
    Get.toNamed(AppRoutes.Signup);
  }

  // 忘记密码
  handleForgotPassword() {
    toastInfo(msg: "忘记密码");
  }

  // 执行登录操作
  handleSignIn() async {
    if (!isEmail(emailController.text)) {
      toastInfo(msg: "请输入正确的邮箱");
      return;
    }

    if (!checkStringLength(passwordController.text, 6)) {
      toastInfo(msg: '密码不能小于6位');
      return;
    }

    UserLoginRequest request = UserLoginRequest(
      email: emailController.text,
      password: cryptoSha256(passwordController.text),
    );

    UserLoginResponse response = await repository.login(request);
    // 设置令牌和用户信息
    UserService.to.saveProfile(response);
    UserService.to.setToken(response.accessToken!);

    Get.offAndToNamed(AppRoutes.Application);
  }

  @override
  void dispose() {
    emailController.dispose();
    passwordController.dispose();
    super.dispose();
  }
}
