package com.wisewoods.base.app;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPStaticUtils;
import com.wisewoods.base.bean.BaseEvent;
import com.wisewoods.base.bean.LoginUser;
import com.wisewoods.base.utils.$;

import org.greenrobot.eventbus.EventBus;

/**
 * 用户管理类
 * Created by Administrator on 2019/3/28 10:15.
 */
public class UserManager {

    private static LoginUser.UserBean userInfo;

    public static void initUser(LoginUser user) {
        if (userInfo != null) {
            int roleIndex = userInfo.roleIndex;
            user.user.roleIndex = roleIndex;
        }
        userInfo = user.user;
        SPStaticUtils.put("uid", user.user.userId + "", true);
        SPStaticUtils.put("userInfo", GsonUtils.toJson(user.user), true);
    }

    public static void logout() {
        userInfo = null;

        SPStaticUtils.remove("uid");
        SPStaticUtils.remove("jwtToken");
        SPStaticUtils.remove("userInfo");

        EventBus.getDefault().post(new BaseEvent.LogoutEvent());
    }

    public static String getUid() {
        if (getUser() != null) {
            return getUser().userId + "";
        }
        return "";
    }


    public static String getInterlocutorsUid() {
        if (getUser() != null) {
            return "user_" + getUser().userId + "";
        }
        return "";
    }

    public static String getEduUid() {
        if (getUser() != null) {
            return "teacher_" + getUser().userId + "";
        }
        return "";
    }

    public static String getWorkid() {
        if (getUser() != null) {
            return "work_" + getUser().userId + "";
        }
        return "";
    }

    public static String getAvatar() {
        if (getUser() != null) {
            return getUser().avatar;
        }
        return "";
    }

    public static String getDeptName() {
        if (getUser() != null) {
            if (getUser().dept != null) {
                return getUser().dept.deptName;
            }
        }
        return "";
    }

    public static LoginUser.UserBean getUser() {
        if (userInfo == null) {
            LogUtils.e("内存用户不存在，查询sp数据是否存在");
            if ($.spNoNull("userInfo")) {
                String userJson = $.getSp("userInfo");
                LoginUser.UserBean user = GsonUtils.fromJson(userJson, LoginUser.UserBean.class);
                userInfo = user;
                return user;
            }
            LogUtils.e("用户未登陆");
            $.toast("用户未登陆");
            logout();
            return new LoginUser.UserBean();
        }

        return userInfo;
    }


}
