package com.sckw.log.TraceLog.interceptor;

import com.sckw.core.model.constant.StringConstant;
import com.sckw.core.utils.StringUtils;
import com.sckw.core.utils.UUIDUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author lfdc
 * @version 1.0.0
 * @ClassName MDCInterceptor.java
 * @Description MDC拦截器
 * @createTime 2021年09月09日 09:25:00
 */
@Slf4j
@Component
public class MDCInterceptor implements HandlerInterceptor {

    @Value("${spring.application.name}")
    private String shortName;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String traceId = request.getHeader(StringConstant.TRACE_ID);
        if (StringUtils.isNotBlank(traceId)) {
            //添加MDC值
            MDC.put(StringConstant.TRACE_ID, traceId);
        } else {
            //添加MDC值
            MDC.put(StringConstant.TRACE_ID, UUIDUtils.get32UUID() + StringConstant.RUNG + shortName);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //删除MDC值
        MDC.remove(StringConstant.TRACE_ID);
    }
}
