import 'dart:convert';

import 'package:get/get.dart';
import 'package:news_getx/config/storage.dart';
import 'package:news_getx/data/model/user.dart';
import 'package:news_getx/data/provider/user.dart';
import 'package:news_getx/data/services/storage.dart';

class UserService extends GetxService {
  static UserService get to => Get.find();

  // 是否登录
  var _isLogin = false.obs;

  String token = "";

  // 用户 profile
  var _profile = UserLoginResponse().obs;

  bool get isLogin => _isLogin.value; // 令牌 token
  UserLoginResponse get profile => _profile.value;
  bool get hasToken => token.isNotEmpty;

  @override
  void onInit() {
    super.onInit();
    token = StorageService.to.getString(StorageUserTokenKey);
    var profileOffline = StorageService.to.getString(StorageUserProfileKey);
    if (profileOffline.isNotEmpty) {
      _profile(UserLoginResponse.fromJson(jsonDecode(profileOffline)));
      _isLogin.value = true;
    }
  }

  // 保存 token
  Future<void> setToken(String value) async {
    await StorageService.to.setString(StorageUserTokenKey, value);
    token = value;
  }

  // 获取 profile
  Future<void> getProfile() async {
    if (token.isEmpty) return;
    UserLoginResponse result = await UserAPI.profile();
    _profile(result);
    _isLogin.value = true;
    StorageService.to.setString(StorageUserProfileKey, jsonEncode(result));
  }

  // 保存 profile
  Future<void> saveProfile(UserLoginResponse profile) async {
    _isLogin.value = true;
    await StorageService.to.setString(StorageUserProfileKey, jsonEncode(profile));
  }

  // 注销
  Future<void> onLogout() async {
    if (_isLogin.value) await UserAPI.logout();
    await StorageService.to.remove(StorageUserTokenKey);
    _isLogin.value = false;
    token = '';
  }
}
