import 'package:flustars/flustars.dart' as FlutterStars;
import 'package:liftmanager/internal/account/model/user_entity.dart';

import 'common.dart';

class User {
  static final User singleton = User._internal();

  factory User() {
    return singleton;
  }

  UserEntity userEntity;

  List<AppMenus> userAuth;

  User._internal();

  ///保存当前用户
  setCurrentUser(UserEntity res, {type: "normal"}) async {
    if (type == "normal") {
      FlutterStars.SpUtil.putString(Constant.accessToken, res.token);
      FlutterStars.SpUtil.putString(Constant.userId, res.userId);
      FlutterStars.SpUtil.putString(
          Constant.companyId, res.maintenanceCompany?.id);
      FlutterStars.SpUtil.putString(Constant.companyRole, res.role?.code);
      FlutterStars.SpUtil.putObject(Constant.user, res);
      FlutterStars.SpUtil.putString('username', res.name);
      FlutterStars.SpUtil.putString('avatarUrl', res.avatarUrl);
      FlutterStars.SpUtil.putInt('userLevel', res.userLevel);
      FlutterStars.SpUtil.putInt('expertFlag', res.expertFlag);
      FlutterStars.SpUtil.putInt('expertLevel', res.expertLevel);
      // FlutterStars.SpUtil.putInt('expertFlag', res);
      FlutterStars.SpUtil.putString('userLevelName', res.userLevelName);
      FlutterStars.SpUtil.putObjectList(Constant.userAuth, res.appMenus);
    } else if (type == "upDataAppMenus") {
      FlutterStars.SpUtil.putInt('expertFlag', res.expertFlag);
      FlutterStars.SpUtil.putObjectList(Constant.userAuth, res.appMenus);
    }

    // FlutterStars.SpUtil.putObjectList(Constant.userAuth, res.appMenus);

    // userEntity = FlutterStars.SpUtil.getObj(
    //     Constant.user, (v) => UserEntity.fromJsonMap(v));
  }

  Future<String> getCompanyRole() async {
    return FlutterStars.SpUtil.getString(Constant.companyRole);
  }

  ///获取当前用户
  Future<UserEntity> getCurrentUser() async {
    if (userEntity == null) {
      userEntity = FlutterStars.SpUtil.getObj(
          Constant.user, (v) => UserEntity.fromJsonMap(v));
    }
    return userEntity;
  }

  ///清除用户信息
  clearUser() {
    FlutterStars.SpUtil.remove(Constant.accessToken);
    FlutterStars.SpUtil.remove(Constant.userId);
    FlutterStars.SpUtil.remove(Constant.companyId);
    FlutterStars.SpUtil.remove(Constant.companyRole);
    FlutterStars.SpUtil.remove(Constant.user);
  }

  // 保存用户权限
  List<AppMenus> getUserAuth() {
    print("getUserAuth");
    userAuth = FlutterStars.SpUtil.getObjList(
        Constant.userAuth, (v) => AppMenus.fromJsonMap(v));
    print("获取用户权限");
    print(userAuth);
    return userAuth;
  }
}
