import 'package:app/data/local/storage.dart';
import 'package:app/request/api/user_api.dart';
import 'package:app/request/dto/user/user_info_dto.dart';
import 'package:flutter/cupertino.dart';

class UserStore extends ChangeNotifier {
  UserInfoDto? userInfo;
  String token = "";

  Future<void> init() async {
    token = await getToken();
    await setUserInfo();
    notifyListeners();
  }

  ///获取用户数据
  Future<void> setUserInfo() async {
    if (token.isNotEmpty) {
      userInfo = await getUserInfoApi();
      await Storage.set("user_info", userInfo!.toJson());
    }
  }

  ///设置token
  Future<void> setToken(String value) async {
    token = value;
    await Storage.set('token', token);
  }

  ///获取token
  static Future<String> getToken() async {
    return await Storage.get("token") ?? '';
  }

  ///退出登录
  Future<void> logout() async {
    await logoutApi();
    await Storage.remove('token');
    await Storage.remove('user_info');
    userInfo = null;
    token = '';
    notifyListeners();
  }

  ///强制退出（不调用接口、不通知 UI）
  static Future<void> forceLogout() async {
    await Storage.remove('token');
    await Storage.remove('user_info');
  }
}
