package com.ytpm.picking.config.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

@Component
public class HttpInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object obj) throws Exception {
        // 获取客户端IP地址
        String clientIp = getClientIp(request);
        System.out.println("找茬挑战王接收客户端" + clientIp + "发起用户请求");
        // 可以在这里添加更多的逻辑，比如记录日志等
        return true;
    }

    private String getClientIp(HttpServletRequest request) {
        String xfHeader = request.getHeader("X-Forwarded-For");
        if (xfHeader == null) {
            return request.getRemoteAddr();
        }
        return xfHeader.split(",")[0]; // 可能会有多个IP，这里取第一个逗号前的IP
    }
    /**
     * 请求处理之后调用；在视图渲染之前，controller处理之后。
     */
    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object obj, ModelAndView mv)
            throws Exception {
        response.setDateHeader("Expires", 0);
        response.setHeader("Buffer", "True");
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Expires", "0");
        response.setHeader("ETag", String.valueOf(System.currentTimeMillis()));
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Date", String.valueOf(new Date()));
        response.setHeader("Last-Modified", String.valueOf(new Date()));

    }
}