part of store;

class UserStore extends GetxController {
  // 获取 UserStore 实例
  static UserStore get to => Get.find();

  // 是否登录
  bool _isLogin = false;
  // token
  String _token = '';
  // 获取token
  String get token => _token;
  // 刷新token
  String _accessToken = '';
  // 获取刷新token
  String get accessToken => _accessToken;
  // 是否登录
  bool get isLogin => _isLogin;
  // 是否有token
  bool get hasToken => _token.isNotEmpty;
  // 用户信息模型
  UserModel _info = UserModel();
  // 获取用户信息模型
  UserModel get info => _info;

  // 是否需要登录
  final ValueNotifier<bool> _needLogin = ValueNotifier<bool>(false);

  ValueNotifier<bool> get needLogin => _needLogin;

  @override
  void onInit() {
    super.onInit();
    _token = StorageService.to.getString(kLocalToken);
  }

  /// 登录
  Future<void> login(UserModel value) async {
    _token = value.token ?? '';
    _accessToken = value.accessToken ?? '';
    await StorageService.to.setString(kLocalToken, _token);
    await StorageService.to
        .setString(kLocalAccessToken, value.accessToken ?? '');
    await StorageService.to
        .setString(kLocalUserInfo, jsonEncode(value.toJson()));
    _needLogin.value = false;
    _info = value;
    _isLogin = true;
    update();
  }

  /// 设置token
  Future<void> setToken(String value) async {
    await StorageService.to.setString(kLocalToken, value);
    _token = value;
  }
  /// 设置刷新token
  Future<void> setAccessToken(String value) async {
    await StorageService.to.setString(kLocalAccessToken, value);
    _accessToken = value;
  }

  /// 设置用户信息
  Future<void> setInfo(UserModel value) async {
    await StorageService.to
        .setString(kLocalUserInfo, jsonEncode(value.toJson()));
    _needLogin.value = false;
    _info = value;
  }

  /// 登出
  Future<void> logout() async {
    await StorageService.to.remove(kLocalToken);
    await StorageService.to.remove(kLocalAccessToken);
    await StorageService.to.remove(kLocalUserInfo);
    _token = '';
    _isLogin = false;
    _needLogin.value = true;
  }

  Future<void> profile() async {
    if (!hasToken) return;
    _isLogin = true;
    update();
  }
}
