package com.bcxin.identify.util.baidu.v3;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.CompletableFuture;

/**
 * http 工具类
 */
public class HttpUtil {
    private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class.toString());

    public static String post(String requestUrl, String accessToken, String params)
            throws Exception {
        String contentType = "application/x-www-form-urlencoded";
        return HttpUtil.post(requestUrl, accessToken, contentType, params);
    }

    public static String post(String requestUrl, String accessToken, String contentType, String params)
            throws Exception {
        String encoding = "UTF-8";
        if (requestUrl.contains("nlp")) {
            encoding = "GBK";
        }
        return HttpUtil.post(requestUrl, accessToken, contentType, params, encoding);
    }

    public static String post(String requestUrl, String accessToken, String contentType, String params, String encoding)
            throws Exception {
        String url = requestUrl + "?access_token=" + accessToken;
        return HttpUtil.postGeneralUrl(url, contentType, params, encoding);
    }

    private static final CloseableHttpClient httpclient;
    static {
        // 创建连接池管理器
        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
        // 设置最大连接数
        connManager.setMaxTotal(500); // 总连接数
        connManager.setDefaultMaxPerRoute(80); // 每个路由的最大连接数

        // 设置请求配置
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(10000) // 连接超时时间（毫秒）
                .setSocketTimeout(10000) // 读取超时时间（毫秒）
                .build();

        // 创建 HttpClient 实例
        httpclient = HttpClients.custom()
                .setConnectionManager(connManager)
                .setDefaultRequestConfig(requestConfig)
                .build();
    }


    public static String postGeneralUrl(String generalUrl, String contentType, String params, String encoding) {
        String responseBody = "";
        try {
            HttpPost httpPost = new HttpPost(generalUrl);
            httpPost.addHeader("Content-Type", contentType);
            httpPost.addHeader("Connection", "Keep-Alive");
            HttpEntity entity = new StringEntity(params, encoding);
            httpPost.setEntity(entity);

            HttpResponse response = httpclient.execute(httpPost);
            responseBody = EntityUtils.toString(response.getEntity());
        } catch (Exception ex) {
            logger.error("do.postGeneralUrl 异常:{};param={}", generalUrl, params, ex);
        }

        return responseBody;
    }

    public static String doGet(String requestUrl) {
        String responseBody = "";
        try {
            HttpGet httpGet = new HttpGet(requestUrl);
            HttpResponse response = httpclient.execute(httpGet);
            responseBody = EntityUtils.toString(response.getEntity());
        } catch (Exception ex) {
            logger.error("doGet发生异常:{}", requestUrl, ex);
        }

        return responseBody;
    }
}
