import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:wgshare/common/mixins/request_tool_mixin.dart';
import 'package:wgshare/common/store/app_storage_key.dart';
import 'package:wgshare/utils/storage.dart';

import '../../routes/app_routes.dart';
import '../models/user_info_entity.dart';


class UserStore extends GetxController with RequestToolMixin {
  static UserStore get to => Get.find();

  /// 是否登录
  String? token;

  /// 刷新用的token
  String? refreshToken;

  /// 登录类型
  String? loginType;

  /// 用户信息
  Rx<UserInfoEntity?> userInfoEntity = Rx(null);

  UserStore init() {
    loginType = StorageService.to.read(AppStorageKey.loginType.value);
    token = StorageService.to.read(AppStorageKey.token.value);
    refreshToken = StorageService.to.read(AppStorageKey.refreshToken.value);
    try {
      var userDetail = StorageService.to.read(AppStorageKey.userInfo.value);
      if (userDetail != null) {
        userInfoEntity.value = UserInfoEntity.fromJson(userDetail);
      }
    } catch (err) {
      StorageService.to.remove(AppStorageKey.userInfo.value);
    }
    if ((token?.isNotEmpty ?? false) && userInfoEntity.value != null) {

    } else {
      Get.offAllNamed(Routes.loginPage);
    }
    return this;
  }

  /// 保存token
  void setToken(String token) {
    this.token = token;
    StorageService.to.write(AppStorageKey.token.value, token);
  }

  /// 保存refreshToken
  void setRefreshToken(String refreshToken) {
    this.refreshToken = refreshToken;
    StorageService.to.write(AppStorageKey.refreshToken.value, refreshToken);
  }

  /// 保存登录类型
  void setLoginType(String loginType) {
    this.loginType = loginType;
    StorageService.to.write(AppStorageKey.loginType.value, loginType);
  }

  /// 保存用户信息
  void setUserDetailInfo(UserInfoEntity info) {
    userInfoEntity.value = info;
    StorageService.to.write(AppStorageKey.userInfo.value, info);
  }

  /// 清除数据
  void erase() {
    userInfoEntity.value = null;
    token = null;
    refreshToken = null;
    loginType = null;

    StorageService.to.write(AppStorageKey.userInfo.value, null);
    StorageService.to.write(AppStorageKey.token.value, null);
    StorageService.to.write(AppStorageKey.refreshToken.value, null);
    StorageService.to.write(AppStorageKey.loginType.value, null);
    // StorageService.to.erase();
  }

  // 用户信息更新
  Future<UserInfoEntity?> updateUserInfo() async {
    // BaseStructureResult<UserInfoDetail> res = await getClient().getUser();
    // var data = res.data;
    // if (res.success && data != null) {
    //   setUserDetailInfo(data);
    //   return data;
    // }
    // return null;
  }
}
