package com.microservices.common.security.feign;

import com.microservices.common.core.constant.SecurityConstants;
import com.microservices.common.core.utils.ServletUtils;
import com.microservices.common.core.utils.StringUtils;
import com.microservices.common.core.utils.ip.IpUtils;
import com.microservices.common.security.utils.SecurityUtils;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * feign 请求拦截器
 *
 * @author microservices
 */
@Component
public class FeignRequestInterceptor implements RequestInterceptor
{
    @Override
    public void apply(RequestTemplate requestTemplate)
    {
        HttpServletRequest httpServletRequest = ServletUtils.getRequest();
        Map<String, String> headers = null;
        if (StringUtils.isNotNull(httpServletRequest))
        {
            headers = ServletUtils.getHeaders(httpServletRequest);
            // 配置客户端IP
            requestTemplate.header("X-Forwarded-For", IpUtils.getIpAddr());
        }
        // 传递用户信息请求头，防止丢失
        setHeader(requestTemplate
                , headers
                , SecurityConstants.DETAILS_USER_ID
                , String.valueOf(SecurityUtils.getUserId()));
        setHeader(requestTemplate
                , headers
                , SecurityConstants.USER_KEY
                , SecurityUtils.getUserKey());
        setHeader(requestTemplate
                , headers
                , SecurityConstants.DETAILS_USERNAME
                , SecurityUtils.getUsername());
        setHeader(requestTemplate
                , headers
                , SecurityConstants.AUTHORIZATION_HEADER
                , null);
        setHeader(requestTemplate
                , headers
                , SecurityConstants.DEPT_ID
                , String.valueOf(SecurityUtils.getDeptId()));
    }

    private void setHeader(RequestTemplate requestTemplate, Map<String, String> headers, String key, String cacheValue) {
        if (headers != null) {
            String headerValue = headers.get(key);
            if (StringUtils.isNotEmpty(headerValue)) {
                requestTemplate.header(key, headerValue);
            } else if (StringUtils.isNotEmpty(cacheValue)) {
                requestTemplate.header(key, cacheValue);
            }
        } else if (StringUtils.isNotEmpty(cacheValue)) {
            requestTemplate.header(key, cacheValue);
        }
    }
}