package com.kym.common.filter;

import cn.hutool.core.lang.UUID;
import com.kym.common.utils.IPUtils;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.FilterConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

import java.io.IOException;


/**
 * 权限过滤器
 *
 * @author yaop
 */
public class RequestLogFilter implements Filter {

    private Logger logger = LoggerFactory.getLogger(RequestLogFilter.class);

    private String IP = "ip";
    private String SEQ = "seq";
    private  final String Timestamp = "ts";


    @Override
    public void init(FilterConfig filterConfig) {
        logger.info("RequestLogFilter init...");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setHeader("Access-Control-Allow-Origin", "*");
        // 解决预请求（发送2次请求），此问题也可在 nginx 中作相似设置解决。
        response.setHeader("Access-Control-Allow-Headers", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        //options请求是由浏览器发起确认是否访问可达，无数据传输
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            filterChain.doFilter(request, response);
            return;
        }
        String ip = IPUtils.getIpAddr(request);
        String seq = UUID.fastUUID().toString(true);
        MDC.put(IP, ip);
        MDC.put(SEQ, seq);
        long start = System.currentTimeMillis();

        logger.info("request>>>uri:{}", request.getRequestURI());
        try {
            filterChain.doFilter(request, response);
        } finally {
            logger.info("request<<<uri:{},cost:{}", request.getRequestURI(),(System.currentTimeMillis()-start));
            MDC.remove(IP);
            MDC.remove(SEQ);
        }
    }


    @Override
    public void destroy() {
        logger.info("RequestLogFilter destroy()...");
    }

}
