package com.ytpm.lemonios.config.interceptor;

import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
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;

@Slf4j
@Component
public class HttpInterceptor implements HandlerInterceptor {

    @Value("${spring.application.name-zh:}")
    private String applicationNameZh;

    @Override
    public boolean preHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response,
                             @NonNull Object obj) {
        // 获取客户端IP地址
        String clientIp = getClientIp(request);
        String requestURI = request.getRequestURI();
        log.info("{}收到来自客户端[{}]的用户请求:{}", applicationNameZh, clientIp, requestURI);
        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(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response,
                           @NonNull 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()));

    }
}