package com.sckw.log.TraceLog.interceptor;


import com.sckw.core.model.constant.StringConstant;
import com.sckw.core.utils.UUIDUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author lfdc
 * @version 1.0.0
 * @ClassName RestTemplateTraceIdInterceptor.java
 * @Description RestTemplate拦截器
 * @createTime 2021年09月09日 12:29:00
 */
@Slf4j
@Component
public class RestTemplateTraceIdInterceptor implements ClientHttpRequestInterceptor {

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

    @Override
    public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes, ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {
        String traceId = MDC.get(StringConstant.TRACE_ID);
        if (StringUtils.isNotBlank(traceId)) {
            httpRequest.getHeaders().add(StringConstant.TRACE_ID, traceId + StringConstant.RUNG + UUIDUtils.get32UUID().substring(10));
        } else {
            //添加MDC值
            String traceId1 = UUIDUtils.get32UUID() + StringConstant.RUNG + shortName + StringConstant.RUNG + UUIDUtils.get32UUID().substring(10);
            MDC.put(StringConstant.TRACE_ID, traceId1);
            httpRequest.getHeaders().add(StringConstant.TRACE_ID, traceId1);
        }
        return clientHttpRequestExecution.execute(httpRequest, bytes);
    }
}
