package com.tiesheng.core.config.token;

import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.jwt.JWT;
import com.tiesheng.core.config.token.bean.TokenBean;
import com.tiesheng.core.util.servlet.ServletKit;
import com.tiesheng.util.exception.ApiException;
import com.tiesheng.util.pojos.ApiResp;

/**
 * @author hao
 */
public class TokenParse {


    /**
     * 获取登陆信息
     *
     * @param token
     * @return
     */
    public static TokenBean get(String token) {
        try {

            TokenValidConfig tokenValidConfig = SpringUtil.getBean(TokenValidConfig.class);
            TokenBean tokenBean = tokenValidConfig.getTokenBean(token);
            if (tokenBean == null) {
                JWT decode = JWT.of(token);
                String id = decode.getPayload("id").toString();
                String environmentType = decode.getPayload("environmentType").toString();
                String service = decode.getPayload("service").toString();
                String extra = decode.getPayload("extra").toString();
                tokenBean = new TokenBean(id, environmentType, service);
                tokenBean.setExtra(extra);
            }
            return tokenBean;
        } catch (Exception e) {
            throw new ApiException(ApiResp.respNeedLogin("请重新登录"));
        }
    }

    /**
     * 获取登录信息
     *
     * @return
     */
    public static TokenBean get() {
        String headerToken = ServletUtil.getHeader(ServletKit.getRequest(), "token", "utf-8");
        return get(headerToken);
    }

    /**
     * 获取用户id
     *
     * @return
     */
    public static TokenBean getWithoutThr() {
        TokenBean tokenBean = null;
        try {
            tokenBean = get();
        } catch (Exception ignored) {
        }
        return tokenBean;
    }

}
