/**
 * @ProjectName: 智慧评标-主观分助手
 * @Package: com.zhpb.gdyd_zhpb_zgf.utils
 * @ClassName: HttpClientUtils
 * @Description: HTTP客户端工具类，提供HTTP GET请求功能，用于调用外部ES接口
 * @Author: 张志锋
 * @Date: 2025-10-31
 * @Version: 1.0
 * @Copyright: © 2025 智慧评标-主观分助手
 */
package com.zhpb.gdyd_zhpb_zgf.utils;

import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * HTTP 请求工具类
 */
public class HttpClientUtils {
    
    /**
     * 发送GET请求
     *
     * @param url 请求URL
     * @return 响应内容
     */
    public static String doGet(String url) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet httpGet = new HttpGet(url);

            return httpClient.execute(httpGet, response -> {
                int statusCode = response.getCode();
                if (statusCode == 200) {
                    return EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
                } else {
                    throw new RuntimeException("HTTP请求失败，状态码: " + statusCode);
                }
            });
        } catch (Exception e) {
            throw new RuntimeException("HTTP请求异常: " + e.getMessage(), e);
        }
    }

    /**
     * 发送POST JSON请求
     *
     * @param url 请求URL
     * @param jsonData JSON数据
     * @param headers 请求头
     * @return 响应内容
     */
    public static String postJson(String url, String jsonData, Map<String, String> headers) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(url);

            // 设置请求体
            StringEntity entity = new StringEntity(jsonData, StandardCharsets.UTF_8);
            httpPost.setEntity(entity);
            httpPost.setHeader("Content-Type", "application/json");

            // 设置请求头
            if (headers != null) {
                headers.forEach(httpPost::setHeader);
            }

            return httpClient.execute(httpPost, response -> {
                int statusCode = response.getCode();
                String responseBody = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);

                if (statusCode >= 200 && statusCode < 300) {
                    return responseBody;
                } else {
                    throw new RuntimeException("HTTP请求失败，状态码: " + statusCode + ", 响应: " + responseBody);
                }
            });
        } catch (Exception e) {
            throw new RuntimeException("HTTP请求异常: " + e.getMessage(), e);
        }
    }

    private static final Logger logger = LoggerFactory.getLogger(HttpClientUtils.class);

    /**
     * 下载文件（带进度日志）
     *
     * @param url 文件URL
     * @return 文件字节数组
     */
    public static byte[] downloadFile(String url) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet httpGet = new HttpGet(url);

            return httpClient.execute(httpGet, response -> {
                int statusCode = response.getCode();
                if (statusCode == 200) {
                    org.apache.hc.core5.http.HttpEntity entity = response.getEntity();
                    long contentLength = entity.getContentLength();
                    
                    if (contentLength < 0) {
                        logger.info("开始下载文件: {}, 大小未知", url);
                    } else {
                        logger.info("开始下载文件: {}, 大小: {} bytes", url, contentLength);
                    }

                    try (java.io.InputStream instream = entity.getContent();
                         java.io.ByteArrayOutputStream buffer = new java.io.ByteArrayOutputStream()) {
                        
                        byte[] data = new byte[8192];
                        int nRead;
                        long totalRead = 0;
                        long lastLogTime = System.currentTimeMillis();
                        
                        while ((nRead = instream.read(data, 0, data.length)) != -1) {
                            buffer.write(data, 0, nRead);
                            totalRead += nRead;
                            
                            long now = System.currentTimeMillis();
                            if (now - lastLogTime > 2000) { // 每2秒打印一次日志
                                if (contentLength > 0) {
                                    int percent = (int) ((totalRead * 100) / contentLength);
                                    logger.info("下载进度: {}% ({}/{})", percent, totalRead, contentLength);
                                } else {
                                    logger.info("已下载: {} bytes", totalRead);
                                }
                                lastLogTime = now;
                            }
                        }
                        
                        logger.info("下载完成，总大小: {} bytes", totalRead);
                        return buffer.toByteArray();
                    }
                } else {
                    throw new RuntimeException("文件下载失败，状态码: " + statusCode);
                }
            });
        } catch (Exception e) {
            throw new RuntimeException("文件下载异常: " + e.getMessage(), e);
        }
    }
}

