package com.pj.current.satoken;

import cn.dev33.satoken.SaManager;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpLogic;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.pj.current.dto.APPLoginUserInfo;
import com.pj.utils.cache.RedisUtil;
import org.springframework.stereotype.Component;

@Component
public class StpAPPUserUtil {
    /**
     * 账号类型标识
     */
    public static final String TYPE = "app";

    /**
     * 底层的 StpLogic 对象
     */
    public static StpLogic stpLogic = new StpLogic(TYPE);

    /**
     * 获取当前 StpLogic 的账号类型
     * @return See Note
     */
    public static String getLoginType(){
        return stpLogic.getLoginType();
    }

    /**
     * 重置 StpLogic 对象
     * @param stpLogic /
     */
    public static void setStpLogic(StpLogic stpLogic) {
        StpUtil.stpLogic = stpLogic;
        // 防止自定义 stpLogic 被覆盖
        SaManager.putStpLogic(stpLogic);
    }
    public static void login(Object id) {
        stpLogic.login(id);
    }
    public static SaTokenInfo getTokenInfo(){
       return stpLogic.getTokenInfo();
    }
    public static boolean isLogin() {
        return stpLogic.isLogin();
    }
    /**
     * 缓存登录用户信息
     * @param info
     */
    public static void cacheAPPLoginInfo(APPLoginUserInfo info){
        String loginId= stpLogic.getLoginIdAsString();
        RedisUtil.set("app:"+loginId, JSONUtil.toJsonStr(info));
    }

    /**
     * 获取登录信息
     * @return
     */
    public static APPLoginUserInfo getAPPLoginInfo(){
        String key="app:"+stpLogic.getLoginIdAsString();
        String info=RedisUtil.get(key);
        return StrUtil.isEmpty(info)?new APPLoginUserInfo():JSONUtil.toBean(info,APPLoginUserInfo.class);
    }

    /**
     * 退出登录
     */
    public static void logout() {
        stpLogic.logout(stpLogic.getLoginIdAsString());
    }


}
