package top.baogutang.common.config;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

/**
 * @description:
 * @author: nikooh
 * @date: 2023/06/15 : 12:25
 */
@Slf4j
@Component
@Order(1)
public class MdcRequestIdFilter extends OncePerRequestFilter {

    public static final String REQUEST_ID_KEY = "X-Request-Id";
    public static final String CLIENT_IP_KEY = "clientIp";

    // 静态资源后缀列表
    private static final String[] STATIC_RESOURCES = {
            "css", "js", "jpg", "jpeg", "png", "gif", "ico", "svg", "woff", "ttf", "eot", "map", "gz", "rar", "zip", "7z", "pdf",
            "doc", "docx", "xls", "xlsx", "ppt", "pptx", "txt", "mp3", "mp4", "avi", "wmv", "flv", "swf", "exe", "dll", "ico", "psd", "ai",
            "eps", "svg", "ttf", "woff", "woff2", "eot", "otf", "otc", "ttc", "ttf", "woff", "woff2", "eot", "otf", "json"
    };

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 判断是否为静态资源请求
        String uri = request.getRequestURI();
        if (isStaticResource(uri)) {
            // 静态资源请求直接放行，不处理
            filterChain.doFilter(request, response);
            return;
        }

        try {
            // 获取真实客户端IP
            String clientIp = getClientIp(request);
            MDC.put(CLIENT_IP_KEY, clientIp);
            String traceId = request.getHeader(REQUEST_ID_KEY);
            if (traceId == null) {
                traceId = UUID.randomUUID().toString().replace("-", "");
                log.info("request uri:{} requestId为空,自动生成 {}, client ip: {}", uri, traceId, clientIp);
                request.setAttribute(REQUEST_ID_KEY, traceId);
            }
            MDC.put(REQUEST_ID_KEY, traceId);
            filterChain.doFilter(request, response);
        } finally {
            MDC.remove(REQUEST_ID_KEY);
            MDC.remove(CLIENT_IP_KEY);
        }

    }

    /**
     * 判断是否为静态资源请求
     */
    private boolean isStaticResource(String uri) {
        if (uri == null || uri.isEmpty()) {
            return false;
        }

        String lowerUri = uri.toLowerCase();
        for (String suffix : STATIC_RESOURCES) {
            if (lowerUri.endsWith(suffix) || lowerUri.contains("." + suffix)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取客户端真实IP地址
     * 优先从代理请求头中获取，如果没有则使用remoteAddr
     */
    private String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
            // X-Forwarded-For可能包含多个IP，取第一个
            if (ip.indexOf(",") > 0) {
                ip = ip.substring(0, ip.indexOf(","));
            }
            return ip.trim();
        }

        ip = request.getHeader("X-Real-IP");
        if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
            return ip.trim();
        }

        ip = request.getHeader("Proxy-Client-IP");
        if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
            return ip.trim();
        }

        ip = request.getHeader("WL-Proxy-Client-IP");
        if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
            return ip.trim();
        }

        // 如果所有代理头都没有，使用remoteAddr
        return request.getRemoteAddr();
    }
}
