import 'package:food_health/api/dto/login_dto.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../data/local/storage.dart';

class AppStore with ChangeNotifier {
  ///用户信息
  UserInfo? userInfo;

  ///token
  String token = '';

  //初始化
  Future<void> init() async {
    token = await getToken();
    var userInfoStorage = await Storage.get('userInfo');
    if (userInfoStorage != null) {
      userInfo = UserInfo.fromJson(await Storage.get('userInfo'));
    }

    notifyListeners();
  }

  ///设置用户数据
  Future<void> setInfo(LoginDto data) async {
    token = data.accessToken!;
    userInfo = data.userInfo;

    await Storage.set('userInfo', userInfo?.toJson());
    await Storage.set('token', token);
  }

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

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