package hw.tagApi.common.config;

import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.impl.conn.SystemDefaultRoutePlanner;
import org.apache.http.impl.conn.DefaultProxyRoutePlanner;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.conn.routing.HttpRoutePlanner;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.ProxySelector;

/**
 * HttpClient配置类
 *
 * @author Yinq
 * @date 2025-04-15
 */
@Configuration
public class HttpClientConfig {

    @Value("${http.client.connect-timeout:30000}")
    private int connectTimeout;

    @Value("${http.client.socket-timeout:30000}")
    private int socketTimeout;

    @Value("${http.client.connection-request-timeout:30000}")
    private int connectionRequestTimeout;

    @Value("${http.client.max-total:200}")
    private int maxTotal;

    @Value("${http.client.default-max-per-route:20}")
    private int defaultMaxPerRoute;

    @Value("${http.client.proxy-host:}")
    private String proxyHost;

    @Value("${http.client.proxy-port:0}")
    private int proxyPort;

    /**
     * 配置HttpClient
     */
    @Bean
    public CloseableHttpClient httpClient() {
        // 创建连接池管理器
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
        connectionManager.setMaxTotal(maxTotal);
        connectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute);

        // 配置请求参数
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(connectTimeout)
                .setSocketTimeout(socketTimeout)
                .setConnectionRequestTimeout(connectionRequestTimeout)
                .build();

        // 配置代理（如果需要）
        HttpRoutePlanner routePlanner = null;
        if (proxyHost != null && !proxyHost.isEmpty() && proxyPort > 0) {
            HttpHost proxy = new HttpHost(proxyHost, proxyPort);
            routePlanner = new DefaultProxyRoutePlanner(proxy);
        } else {
            routePlanner = new SystemDefaultRoutePlanner(ProxySelector.getDefault());
        }

        // 创建HttpClient
        return HttpClients.custom()
                .setConnectionManager(connectionManager)
                .setDefaultRequestConfig(requestConfig)
                .setRoutePlanner(routePlanner)
                .build();
    }
} 