package com.ruoyi.system.utils;

import com.amazonaws.retry.v2.SimpleRetryPolicy;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
//调用获取商品信息工具类
@Component
@Slf4j
public class HttpUtil {
    private static String BASE_URL;

    @Value("${zs-operation.url}")
    public void setBaseUrl(String baseUrl) {
        HttpUtil.BASE_URL = baseUrl;
    }

    //private static final RestTemplate restTemplate = new RestTemplate();

    /**
     * 发送GET请求并处理响应
     * @param url 请求URL
     * @param needScreenshot 是否需要截图
     * @return 响应结果
     */
    public static Map<String, Object> sendGetRequest(String url, boolean needScreenshot,String platform) {
        return send(url,needScreenshot,platform,0);
    }

    public static Map<String, Object> send(String url, boolean needScreenshot,String platform,int count) {
        log.info("调用 第"+(count+1)+"次");
            Long start = System.currentTimeMillis();
            try {
                // 构建请求URL和参数
                UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(BASE_URL)
                    .queryParam("url", url)
                    .queryParam("needScreenshot", needScreenshot)
                    .queryParam("platform", platform);

                // 发送GET请求
                log.info("开始时间="+getdate());
/*                HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(HttpClientBuilder.create().build());
                factory.setConnectTimeout(300000); // 连接超时，单位为毫秒
                factory.setReadTimeout(300000);    // 读取超时，单位为毫秒
                RestTemplate restTemplate = new RestTemplate(factory);
                ResponseEntity<Map> response = restTemplate.getForEntity(builder.toUriString(), Map.class);*/

                RestTemplate restTemplate = createRobustRestTemplate();
                ResponseEntity<Map> response = restTemplate.getForEntity(builder.toUriString(), Map.class);
                log.info("成功结束时间="+getdate());
                Map body = response.getBody();
                Long end = System.currentTimeMillis();
                log.info("调用获取商品最新信息接口成功耗时=："+(end-start));
                return body;
            } catch (Exception e) {
                log.info("失败结束时间="+getdate());
                Long end = System.currentTimeMillis();
                log.info("调用获取商品最新信息接口失败耗时=："+(end-start));
     /*           if (count<1) {
                    count++;
                    send(url,needScreenshot,platform,count);
                }*/
                Map<String, Object> reMap = new HashMap<>();
                reMap.put("success", false);
                reMap.put("message", "请求发生错误: " + e.getMessage());
                return reMap;
            }


    }


    public static String getdate() {
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        // 定义时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 格式化并输出
        String formattedTime = now.format(formatter);
        return formattedTime;
    }


    public static RestTemplate createRobustRestTemplate() {
        // 配置连接池
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
        connectionManager.setMaxTotal(10);         // 最大连接数:ml-citation{ref="3" data="citationList"}
        connectionManager.setDefaultMaxPerRoute(10); // 每个路由最大连接数:ml-citation{ref="3" data="citationList"}

        // 配置重试策略（最多重试3次）
        HttpRequestRetryHandler retryHandler = (exception, executionCount, context) ->
            executionCount <= 0 && exception instanceof org.apache.http.NoHttpResponseException;

        // 构建HttpClient
        HttpClient httpClient = HttpClients.custom()
            .setConnectionManager(connectionManager)
            .setRetryHandler(retryHandler)          // 失败重试策略:ml-citation{ref="5" data="citationList"}
            .setKeepAliveStrategy((response, context) -> 180_000) // Keep-Alive策略:ml-citation{ref="3" data="citationList"}
            .build();

        // 配置请求工厂
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);
        factory.setConnectTimeout(120000);     // 连接超时
        factory.setReadTimeout(300000);        // 读取超时
        factory.setConnectionRequestTimeout(120000); // 从连接池获取连接超时

        return new RestTemplate(factory);
    }
}
