package cn.freemud.interceptor;

import cn.freemud.utils.AppLogUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

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

@Configuration
public class FeignInterceptor implements RequestInterceptor {

    @Value("${forward.feign.headers:x-forwarded-for, x-real-ip}")
    private Set<String> needHeaders;

    @Override
    public void apply(RequestTemplate requestTemplate) {
        HttpServletRequest httpServletRequest = this.getHttpServletRequest();
        if (Objects.nonNull(httpServletRequest)) {
            Map<String, String> headers = getHeaders(httpServletRequest);
            for (String headerName : headers.keySet()) {
                requestTemplate.header(headerName, getHeaders(getHttpServletRequest()).get(headerName));
            }
        }
    }

    private HttpServletRequest getHttpServletRequest() {
        try {
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (Objects.isNull(requestAttributes)) {
                return null;
            }
            return requestAttributes.getRequest();
        } catch (Exception e) {
            AppLogUtil.errorLog("FeignInterceptor error {}", "", "", e);
            return null;
        }
    }

    private Map<String, String> getHeaders(HttpServletRequest request) {
        Map<String, String> map = new LinkedHashMap<>();
        Enumeration<String> enumeration = request.getHeaderNames();
        while (enumeration.hasMoreElements()) {
            String key = enumeration.nextElement();
            if (needThisHeader(key)) {
                String value = request.getHeader(key);
                map.put(key, value);
            }
        }
//        AppLogUtil.printLog("clientIp for feign client info:" + JSON.toJSONString(map), "", "");
        return map;
    }

    private boolean needThisHeader(String headerName) {
        // TODO:过滤哪些header需要传递，千万不能把所有的header传下去
        return needHeaders.contains(headerName);
    }
}
