package com.fkzy.warn.common.filter;

import org.slf4j.MDC;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 跨域过滤器
 *
 * @author yuyantian
 * @data 2021/9/7 14:30
 */
@Order(0)
@Component
public class CrossDomainFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }
    private final AtomicInteger traceIdCounter = new AtomicInteger(10000);

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
        FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Headers",
            "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,userId,openId,authorization,Content-Disposition");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "0");
        response.addHeader("Access-Control-Allow-Credentials", "true");
        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("contentType", "application/json; charset=utf-8");
        response.setCharacterEncoding("utf-8");
        try {
            // logback 文件日志 traceId, 让同一请求下的日志 traceId 相同
            MDC.put("traceId", String.valueOf(traceIdCounter.getAndIncrement()));
            filterChain.doFilter(request, response);
        } finally {
            MDC.remove("traceId");
        }
    }

    @Override
    public void destroy() {

    }
}
