package com.tzld.piaoquan.growth.common.config;

import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class HttpClientConfig {


    /**
     * 链接建立的超时时间 ms
     */
    private static final int CONNECTION_TIMEOUT = 5000;
    /**
     * 响应超时时间 ms
     */
    private static final int SOCKET_TIMEOUT = 120000;

    /**
     * 每个路由的最大连接数
     */
    private static final int MAX_PER_ROUTE = 100;

    /**
     * 最大连接数
     */
    private static final int MAX_TOTAL = 500;

    /**
     * 重试次数，默认0
     */
    private static final int RETRY_COUNT = 3;

    /**
     * 从connection pool中获得一个connection的超时时间 ms
     */
    private static final int CONNECTION_WAIT_TIMEOUT = 5000;


    @Bean(name = "httpClient")
    public CloseableHttpClient httpClient() {

        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(CONNECTION_TIMEOUT)
                .setSocketTimeout(SOCKET_TIMEOUT)
                .setConnectionRequestTimeout(CONNECTION_WAIT_TIMEOUT)
                .build();

        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
        connectionManager.setMaxTotal(MAX_TOTAL); // 设置最大连接数
        connectionManager.setDefaultMaxPerRoute(MAX_PER_ROUTE); // 每个路由的最大连接数

        return HttpClientBuilder.create()
                .setDefaultRequestConfig(requestConfig)
                .setConnectionManager(connectionManager)
                .setRetryHandler(new DefaultHttpRequestRetryHandler(RETRY_COUNT, false))
                .build();
    }

    @Bean(name = "proxyHttpClient")
    public CloseableHttpClient proxyHttpClient() {
        HttpHost proxy = new HttpHost("121.43.155.197", 8888, "http");
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(CONNECTION_TIMEOUT)
                .setSocketTimeout(SOCKET_TIMEOUT)
                .setConnectionRequestTimeout(CONNECTION_WAIT_TIMEOUT)
                .build();

        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
        connectionManager.setMaxTotal(MAX_TOTAL); // 设置最大连接数
        connectionManager.setDefaultMaxPerRoute(MAX_PER_ROUTE); // 每个路由的最大连接数

        return HttpClientBuilder.create()
                .setProxy(proxy)
                .setDefaultRequestConfig(requestConfig)
                .setConnectionManager(connectionManager)
                .setRetryHandler(new DefaultHttpRequestRetryHandler(RETRY_COUNT, false))
                .build();
    }
}
