package com.fs.app.interceptor;

import com.alibaba.fastjson2.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * 请求日志拦截器
 * 打印所有请求的URL和参数
 */
@Component
public class RequestLogInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(RequestLogInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求信息
        String method = request.getMethod();
        String uri = request.getRequestURI();
        String queryString = request.getQueryString();

        // 获取所有请求参数
        Map<String, String[]> parameterMap = request.getParameterMap();
        Map<String, Object> params = new HashMap<>();
        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
            String[] values = entry.getValue();
            if (values.length == 1) {
                params.put(entry.getKey(), values[0]);
            } else {
                params.put(entry.getKey(), values);
            }
        }

        // 获取请求头（可选）
        Map<String, String> headers = new HashMap<>();
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            // 只记录常用的请求头，避免日志过长
            if (headerName.equalsIgnoreCase("Content-Type")
                || headerName.equalsIgnoreCase("Authorization")
                || headerName.equalsIgnoreCase("User-Agent")) {
                headers.put(headerName, request.getHeader(headerName));
            }
        }

        // 打印请求日志
        StringBuilder logMsg = new StringBuilder();
        logMsg.append("\n========== 请求开始 ==========\n");
        logMsg.append("请求方式: ").append(method).append("\n");
        logMsg.append("请求URL: ").append(uri);
        if (queryString != null && !queryString.isEmpty()) {
            logMsg.append("?").append(queryString);
        }
        logMsg.append("\n");

        if (!params.isEmpty()) {
            logMsg.append("请求参数: ").append(JSON.toJSONString(params)).append("\n");
        }

        if (!headers.isEmpty()) {
            logMsg.append("请求头: ").append(JSON.toJSONString(headers)).append("\n");
        }

        logMsg.append("客户端IP: ").append(getClientIp(request)).append("\n");
        logMsg.append("========== 请求结束 ==========");

        logger.info(logMsg.toString());

        return true;
    }

    /**
     * 获取客户端真实IP地址
     */
    private String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        // 对于多级代理，取第一个IP
        if (ip != null && ip.contains(",")) {
            ip = ip.split(",")[0].trim();
        }
        return ip;
    }
}
