package com.dcit.authority.utils;

import com.alibaba.fastjson.JSONObject;
import com.dcit.authority.dto.JwtDTO;
import com.dcit.authority.dto.SysUserBasicInfoDTO;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

/**
 * 获取用户信息
 */
@Component
public class GetUserInfoUtil implements ApplicationContextAware {

    private static ApplicationContext context = null;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    public synchronized static Object getBean(String beanName) {
        return context.getBean(beanName);
    }

    public static SysUserBasicInfoDTO getUserInfo(ServletRequest servletRequest){
        String jwt = ((HttpServletRequest)servletRequest).getHeader(JsonWebTokenUtil.TOKEN_HEADRE_KEY);
        JwtDTO jwtDTO = JsonWebTokenUtil.parseJwt(jwt, JsonWebTokenUtil.SECRET_KEY);
        RedisTemplate redisTemplate = (RedisTemplate) getBean("redisTemplate");
        SysUserBasicInfoDTO refreshJwt = (SysUserBasicInfoDTO) redisTemplate.opsForValue().get(jwtDTO.getAccount());
        return refreshJwt;
    }
}
