import 'package:base_app/common/common.dart';
import 'package:base_app/data/protocol/user_model.dart';
import 'package:base_app/data/repository/user_repository.dart';
import 'package:common_utils/common_utils.dart';
import 'package:flustars/flustars.dart';

/// 登录工具类
class LoginUtils {
  /// 判断用户是否已登录
  static Future<bool> isLogin() async {
    // 1. 先判断token是否在
    bool hasToken =
        ObjectUtil.isNotEmpty(SpUtil.getString(BaseConstant.keyAppToken));
    if (hasToken) {
      // 2.用token去获取用户信息，有信息认为已登录，否则为未登录
      UserRepository userRepository = new UserRepository();
      UserModel user = await userRepository.getUserInfo();
      if (user == null) {
        // 未登录的尝试自动登录，返回自动登录结果
        return await autoLogin();
      } else {
        return true;
      }
    } else {
      return hasToken;
    }
  }

  // 自动登录
  static Future<bool> autoLogin() async {
    // 取用户名和密码自动登录
    String username = SpUtil.getString(BaseConstant.keyAccount);
    String password = SpUtil.getString(BaseConstant.keyPassword);
    UserRepository userRepository = new UserRepository();
    LoginReq req = new LoginReq(username, password);
    try {
      UserModel model = await userRepository.login(req);
      if (model != null) {
        return true;
      } else {
        return false;
      }
    } catch (error) {
      return false;
    }
  }
}
