package hw.tagApi.service.utils;

import hw.tagApi.service.constant.ApiConstants;
import hw.tagApi.service.domain.ApiContent;
import hw.tagApi.service.domain.ApiResponse;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
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.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.List;

public class httpClientUtils {
    private static final Logger log = LoggerFactory.getLogger(httpClientUtils.class);
    private static final ObjectMapper objectMapper = new ObjectMapper();
    private static final CloseableHttpClient httpClient = HttpClients.createDefault();

    // 超时配置
    private static final int CONNECT_TIMEOUT = 5000;
    private static final int SOCKET_TIMEOUT = 10000;
    private static final RequestConfig requestConfig = RequestConfig.custom()
            .setConnectTimeout(CONNECT_TIMEOUT)
            .setSocketTimeout(SOCKET_TIMEOUT)
            .build();

    /**
     * 创建并配置HttpGet请求
     *
     * @param url 请求URL
     * @return 配置好的HttpGet请求对象
     */
    public static HttpGet createHttpGetRequest(String url) {
        HttpGet httpGet = new HttpGet(url);
        // 设置请求头
        httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36");
        httpGet.setHeader("Accept", "*/*");
        httpGet.setHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8");
        httpGet.setHeader("Connection", "keep-alive");
        return httpGet;
    }

    /**
     * 从URL获取字节数组
     *
     * @param url 请求URL
     * @return 字节数组，如果发生错误则返回null
     */
    public static byte[] getByteArrayFromUrl(String url) {
        HttpGet httpGet = createHttpGetRequest(url);
        try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
            // 获取响应状态码
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                log.error("获取文件失败，响应码: {}", statusCode);
                return null;
            }

            // 获取响应实体
            HttpEntity entity = response.getEntity();
            if (entity == null) {
                log.error("无法获取响应实体");
                return null;
            }

            // 将响应实体转换为字节数组
            byte[] fileData = EntityUtils.toByteArray(entity);

            if (fileData.length == 0) {
                log.error("获取到的文件为空");
                return null;
            }

            log.info("成功获取文件，大小: {} 字节", fileData.length);
            return fileData;
        } catch (IOException e) {
            log.error("获取文件时发生错误: {}", e.getMessage(), e);
            return null;
        }
    }

    /**
     * 发送处理结果到回调接口
     *
     * @param resList 处理结果列表
     */
    public static void sendResultToCallback(List<ApiContent> resList, String url) {
        if (resList == null || resList.isEmpty()) {
            log.warn("处理结果列表为空，不发送回调请求");
            return;
        }

        HttpPost httpPost = null;
        try {
            // 创建POST请求
            httpPost = new HttpPost(url);
            httpPost.setConfig(requestConfig);

            // 设置请求头
            httpPost.setHeader("Content-Type", "application/json");
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Connection", "close");

            // 创建响应对象
            ApiResponse response = new ApiResponse();
            response.setCaseCode(ApiConstants.DATA_IMPORT);
            response.setResult(resList);

            // 将对象转换为JSON字符串
            String jsonBody = objectMapper.writeValueAsString(response);
            log.debug("准备发送的数据: {}", jsonBody);

            // 设置请求体
            StringEntity entity = new StringEntity(jsonBody, "UTF-8");
            httpPost.setEntity(entity);

            // 发送请求
            try (CloseableHttpResponse httpResponse = httpClient.execute(httpPost)) {
                int statusCode = httpResponse.getStatusLine().getStatusCode();
                HttpEntity responseEntity = httpResponse.getEntity();
                String responseBody = responseEntity != null ? EntityUtils.toString(responseEntity, "UTF-8") : "";

                if (statusCode == 200) {
                    log.info("发送处理结果到回调接口成功，响应状态码: {}", statusCode);
                    log.debug("回调接口响应内容: {}", responseBody);
                } else {
                    log.error("发送处理结果到回调接口失败，响应状态码: {}, 响应内容: {}", statusCode, responseBody);
                }
            }
        } catch (Exception e) {
            log.error("发送处理结果到回调接口失败: {}", e.getMessage());
        } finally {
            if (httpPost != null) {
                httpPost.releaseConnection();
            }
        }
    }

}
