package com.cool.store.context;

import com.alibaba.fastjson.JSON;
import com.cool.store.enums.ErrorCodeEnum;
import com.cool.store.exception.ServiceException;
import org.apache.commons.lang3.StringUtils;

import java.util.Optional;

/**
 * 当前登录用户信息
 */
public class CurrentUserHolder {

    private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();

    public static LoginUserInfo getUser() {
        String userStr = contextHolder.get();
        if (StringUtils.isNotBlank(userStr)) {
            return JSON.parseObject(userStr, LoginUserInfo.class);
        }
        return new LoginUserInfo();
    }

    public static void setUser(String user) {
        contextHolder.set(user);
    }

    public static void removeUser(){
        contextHolder.remove();
    }

    /**
     * 仅登录态可获取
     * @return
     */
    public static String getUserId(){
        LoginUserInfo user = getUser();
        return Optional.ofNullable(user).map(o->o.getUserId()).orElseThrow(()->new ServiceException(ErrorCodeEnum.ACCESS_TOKEN_INVALID));
    }

    /**
     * 仅登录态可获取
     * @return
     */
//    public static String getRoleId(){
//        LoginUserInfo user = getUser();
//        return Optional.ofNullable(user).map(LoginUserInfo::getSysRole).map(SysRoleDO::getRoleId).orElse(null);
//    }
}


