package com.org.hktshop.base;

import com.org.hktshop.constant.CommonConstant;
import com.org.hktshop.entity.user.HktUser;
import com.org.hktshop.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Component
public class UserContext {

    @Autowired
    protected RedisUtil redisUtil;

    /**
     * 获取登录用户信息 * * @return
     */
    public HktUser getUserInfo() {
        String userToken = getUserToken();
        if (!StringUtils.isEmpty(userToken)) {
            HktUser hktUser = (HktUser) redisUtil.get(CommonConstant.HKT_SHOP_USER + userToken);
            return hktUser;
        }
        return null;
    }

    public String getUserToken() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader(CommonConstant.ACCESS_TOKEN);
        return token;
    }

    public HttpServletRequest getRequest() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        return request;
    }
}
