
package com.config;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

@Configuration
public class RestTemplateConfig {

    private static final Logger log = LoggerFactory.getLogger(RestTemplateConfig.class);

    @Bean
    public RestTemplate restTemplate() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(30000); // 30秒连接超时
        factory.setReadTimeout(60000);    // 60秒读取超时

        RestTemplate restTemplate = new RestTemplate(factory);

        // 添加自定义日志拦截器，控制日志输出
        List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
        interceptors.add(new LoggingInterceptor());
        restTemplate.setInterceptors(interceptors);

        return restTemplate;
    }

    /**
     * 自定义日志拦截器，控制请求/响应日志
     */
    public static class LoggingInterceptor implements ClientHttpRequestInterceptor {

        @Override
        public org.springframework.http.client.ClientHttpResponse intercept(
                org.springframework.http.HttpRequest request,
                byte[] body,
                org.springframework.http.client.ClientHttpRequestExecution execution)
                throws java.io.IOException {

            // 记录请求信息
            log.debug("请求URL: {}", request.getURI());
            log.debug("请求方法: {}", request.getMethod());
            log.debug("请求头: {}", request.getHeaders());

            // 记录请求体（限制长度）
            if (log.isDebugEnabled() && body != null) {
                String requestBody = new String(body, "UTF-8");
                int printLength = Math.min(200, requestBody.length());
                log.debug("请求体 (前{}字符): {}", printLength, requestBody.substring(0, printLength));
            }

            // 执行请求
            org.springframework.http.client.ClientHttpResponse response = execution.execute(request, body);

            // 记录响应信息
            log.debug("响应状态码: {}", response.getStatusCode());
            log.debug("响应头: {}", response.getHeaders());

            // 注意：这里不要直接读取响应体，否则会导致后续无法读取
            // 使用BufferingClientHttpResponseWrapper包装响应

            return response;
        }
    }
}