package org.springblade.openfeign.interceptor;

import javax.servlet.http.HttpServletRequest;


import org.springblade.common.openfeign.OpenFeignConstants;
import org.springblade.openfeign.properties.OpenFeignProperties;
import org.springblade.openfeign.util.RequestHeaderHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import cn.hutool.core.util.StrUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;

/**
 * feign 请求拦截器
 *
 * @author wookvn
 */
@Component
public class FeignRequestInterceptor implements RequestInterceptor {

    @Autowired
    private OpenFeignProperties openFeignProperties;

    @Override
    public void apply(RequestTemplate requestTemplate) {
        String token = null;
        String appId = null;
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        //当多线程情况下，requestAttributes可能为null
        if (requestAttributes != null) {
            HttpServletRequest request = requestAttributes.getRequest();
            token = request.getHeader(openFeignProperties.getTokenHeaderName());
            appId = request.getHeader(openFeignProperties.getAppIdHeaderName());
        }
        /**
         * 多线程环境中，需要客户端调用{@link RequestHeaderHolder#set()}主动设置token值
         */
        token = StrUtil.isBlank(token) ? RequestHeaderHolder.get() : token;
        appId = StrUtil.isBlank(appId) ? RequestHeaderHolder.get() : appId;
        requestTemplate.header(openFeignProperties.getTokenHeaderName(), token);
        requestTemplate.header(openFeignProperties.getAppIdHeaderName(), appId);
        // 配置请求的HEADER
        requestTemplate.header(OpenFeignConstants.HEADER_SYMBOL, OpenFeignConstants.HEADER_SYMBOL_VAL);
        requestTemplate.header(OpenFeignConstants.HEADER_TS, System.currentTimeMillis() + "");
    }
}