package com.ruoyi.platform.utils;

import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.platform.vo.HttpDeleteWithBody;
import org.apache.http.HttpHost;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.Map;

@Component
public class NewHttpUtils {

    private static final Logger log = LoggerFactory.getLogger(NewHttpUtils.class);

    @Value("${proxy.useProxy:false}")
    private boolean useProxy;

    @Value("${proxy.host}")
    private String host;

    @Value("${proxy.port}")
    private Integer port;

    private static CloseableHttpClient httpClient;

    @PostConstruct
    public void init() {
        try {
            SSLContext sslContext = SSLContextBuilder.create()
                    .loadTrustMaterial(new TrustSelfSignedStrategy())
                    .build();

            SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext);

            if (useProxy) {
                httpClient = HttpClients.custom()
                        .setSSLSocketFactory(sslSocketFactory)
                        .setProxy(new HttpHost(host, port))
                        .build();
            } else {
                httpClient = HttpClients.custom()
                        .setSSLSocketFactory(sslSocketFactory)
                        .build();
            }
        } catch (Exception e) {
            throw new RuntimeException("Failed to initialize HttpClient", e);
        }
    }

    public static String sendGet(String url, String param) throws Exception {
        return sendRequest(new HttpGet(), url, param, null, null);
    }

    public static String sendPost(String url, String param, String body) throws Exception {
        return sendRequest(new HttpPost(), url, param, null, body);
    }

    public static String sendGetWithToken(String url, String param, String token) throws Exception {
        return sendRequest(new HttpGet(), url, param, token, null);
    }

    public static String sendPostWithToken(String url, String param, String token, String body) throws Exception {
        return sendRequest(new HttpPost(), url, param, token, body);
    }

    public static String sendDeleteWithToken(String url, String param, String token, String body) throws Exception {
        if (StringUtils.isNotEmpty(body)) {
            return sendRequest(new HttpDeleteWithBody(), url, param, token, body);
        } else {
            return sendRequest(new HttpDelete(), url, param, token, body);
        }
    }

    public static String sendPatchWithToken(String url, String param, String token, String body) throws Exception {
        return sendRequest(new HttpPatch(), url, param, token, body);
    }

    private static String sendRequest(HttpRequestBase request, String url, String param, String token, String body) throws Exception {
        if (httpClient == null) {
            throw new IllegalStateException("HttpClient is not initialized");
        }

        String result = "";
        try {
            URIBuilder uriBuilder = new URIBuilder(url);
            if (param != null && !param.isEmpty()) {
                String[] pairs = param.split("&");
                for (String pair : pairs) {
                    int idx = pair.indexOf("=");
                    if (idx != -1) {
                        uriBuilder.setParameter(pair.substring(0, idx), pair.substring(idx + 1));
                    }
                }
            }

            URI uri = uriBuilder.build();
            request.setURI(uri);

            request.setHeader("Content-Type", "application/json");
            if (token != null) {
                request.setHeader("Authorization", "Bearer " + token);
            }

            if (request instanceof HttpEntityEnclosingRequestBase && body != null) {
                ((HttpEntityEnclosingRequestBase) request).setEntity(new StringEntity(body, StandardCharsets.UTF_8));
            }

            log.info("Executing request: " + request.getRequestLine());

            try (CloseableHttpResponse response = httpClient.execute(request)) {
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode >= 200 && statusCode < 300) {
                    result = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
                } else {
                    throw new IOException("HTTP request failed with response code: " + statusCode);
                }
                log.info("Response: " + result);
                if (result.startsWith("{")) {
                    Map<String, Object> resultMap = JsonUtils.jsonToMap(result);
                    Integer status = (Integer) resultMap.get("status");
                    if (status != null && status != 0 && status != 1) {
                        throw new Exception((String) resultMap.get("message"));
                    }
                }
            }
        } catch (URISyntaxException e) {
            log.error("URISyntaxException, url=" + url + ", param=" + param, e);
            throw e;
        } catch (IOException e) {
            log.error("IOException, url=" + url + ", param=" + param, e);
            throw e;
        }
        return result;
    }
}
