package com.czg.config;

import cn.hutool.core.util.IdUtil;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author GYJoker
 */
@Configuration
public class CorsFilter implements Filter {

    @Value("${spring.application.name:unknown-service}")
    private String applicationName;
    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
            throws IOException, ServletException {
        // traceId
        Map<String, String> copyOfContextMap = MDC.getCopyOfContextMap();
        if(copyOfContextMap == null){
            copyOfContextMap = new HashMap<>();
        }
        copyOfContextMap.put("traceId",applicationName + IdUtil.fastSimpleUUID());
        MDC.setContextMap(copyOfContextMap);
        HttpServletResponse response = (HttpServletResponse) resp;
        HttpServletRequest reqs = (HttpServletRequest) req;
        String curOrigin = reqs.getHeader("Origin");
        response.setHeader("Access-Control-Allow-Origin", curOrigin == null ? "true" : curOrigin);
        response.setHeader("Access-Control-Allow-Methods", "*");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "token,Origin, X-Requested-With, Content-Type, Accept,shopId");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        try {
            // 原有 MDC 设置逻辑...
            chain.doFilter(req, resp);
        } finally {
            // 清理当前线程的 traceId
            MDC.remove("traceId");
        }
    }
}
