package com.usky.cdi.service.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Slf4j
public class HttpClientUtils {
    // 使用静态连接池，避免每次请求都创建和关闭连接
    private static final CloseableHttpClient HTTP_CLIENT = HttpClients.custom()
            .setDefaultRequestConfig(RequestConfig.custom()
                    .setConnectTimeout(5000)  // 连接超时时间
                    .setSocketTimeout(5000)   // 读取超时时间
                    .setConnectionRequestTimeout(5000)  // 请求超时时间
                    .build())
            .build();

    public static String doGet(String url, Map<String, String> param) {
        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();

            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);

            // 执行请求
            response = HTTP_CLIENT.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            log.error("HTTP请求异常: {}", e.getMessage(), e);
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    public static String doGet(String url) {
        return doGet(url, null);
    }

    public static String doPost(String url, Map<String, String> param) {
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建参数列表
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key)));
                }
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
                httpPost.setEntity(entity);
            }
            // 执行http请求
            response = HTTP_CLIENT.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return resultString;
    }

    public static String doPost(String url) {
        return doPost(url, null);
    }

    public static String doPostJson(String url, String json) {
        final String requestId = UUID.randomUUID().toString();
        final long start = System.currentTimeMillis();
        log.info("[{}] >>> POST JSON 请求开始 URL={}, body={}", requestId, url, json);

        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建请求内容
            httpPost.setHeader("Accept", "*/*");
            httpPost.setHeader("Content-Type", "application/json");
            httpPost.setHeader("Accept-Encoding", "gzip, deflate, br");
            httpPost.setHeader("Connection", "keep-alive");

            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = HTTP_CLIENT.execute(httpPost);
            int statusCode = response.getStatusLine() != null ? response.getStatusLine().getStatusCode() : -1;
            resultString = response.getEntity() == null ? "" : EntityUtils.toString(response.getEntity(), "utf-8");

            long costMs = System.currentTimeMillis() - start;
            String preview = resultString == null ? "null" : (resultString.length() > 500 ? resultString.substring(0, 500) + "...(truncated)" : resultString);

            if (statusCode != 200) {
                log.warn("[{}] <<< POST JSON 响应异常 status={} costMs={} preview={}", requestId, statusCode, costMs, preview);
            } else if (resultString == null || resultString.trim().isEmpty()) {
                log.warn("[{}] <<< POST JSON 响应为空 status=200 costMs={}", requestId, costMs);
            } else {
                log.info("[{}] <<< POST JSON 响应成功 status=200 costMs={} preview={}", requestId, costMs, preview);
            }
        } catch (Exception e) {
            long costMs = System.currentTimeMillis() - start;
            String root = buildRootCause(e);
            log.error("[{}] !!! POST JSON 请求异常 costMs={} URL={} body={} exType={} exMsg={} rootCause={}",
                    requestId, costMs, url, json, e.getClass().getName(), e.getMessage(), root, e);
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                log.warn("[{}] 关闭HTTP响应失败: {}", requestId, e.getMessage(), e);
            }
        }

        return resultString;
    }

    private static String buildRootCause(Throwable t) {
        if (t == null) return "null";
        Throwable cur = t;
        while (cur.getCause() != null && cur.getCause() != cur) {
            cur = cur.getCause();
        }
        String msg = cur.getMessage();
        return cur.getClass().getName() + (msg == null ? "" : (": " + msg));
    }
}
