package com.jeesharp.business.modules.pay.tlinx.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.security.cert.X509Certificate;
import java.util.Map;

/**
 * HTTPS工具类
 * 
 * @author wangmeng
 * @since 2026-03-16
 */
public class HttpsUtil {
    
    private static final Logger logger = LoggerFactory.getLogger(HttpsUtil.class);
    
    private static final int CONNECT_TIMEOUT = 30000;
    private static final int READ_TIMEOUT = 30000;
    
    static {
        // 初始化信任所有证书的SSL上下文（仅用于测试环境）
        try {
            TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    public X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }
                    public void checkClientTrusted(X509Certificate[] certs, String authType) {}
                    public void checkServerTrusted(X509Certificate[] certs, String authType) {}
                }
            };
            
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
            
            HostnameVerifier allHostsValid = (hostname, session) -> true;
            HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
            
        } catch (Exception e) {
            logger.error("初始化SSL上下文失败", e);
        }
    }
    
    /**
     * HTTPS POST请求
     *
     * @param url 请求URL
     * @param params 请求参数
     * @param charset 字符集
     * @return 响应字符串
     */
    public static String post(String url, Map<String, String> params, String charset) {
        HttpsURLConnection conn = null;
        OutputStream out = null;
        BufferedReader reader = null;
        
        try {
            URL httpsUrl = new URL(url);
            conn = (HttpsURLConnection) httpsUrl.openConnection();
            
            // 设置请求属性
            conn.setRequestMethod("POST");
            conn.setConnectTimeout(CONNECT_TIMEOUT);
            conn.setReadTimeout(READ_TIMEOUT);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);
            
            // 构建请求参数
            StringBuilder paramBuilder = new StringBuilder();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                if (paramBuilder.length() > 0) {
                    paramBuilder.append("&");
                }
                paramBuilder.append(entry.getKey())
                           .append("=")
                           .append(URLEncoder.encode(entry.getValue(), charset));
            }
            
            String postData = paramBuilder.toString();
            logger.debug("HTTPS POST请求参数: {}", postData);
            
            // 发送请求
            out = conn.getOutputStream();
            out.write(postData.getBytes(charset));
            out.flush();
            
            // 读取响应
            int responseCode = conn.getResponseCode();
            if (responseCode == HttpsURLConnection.HTTP_OK) {
                reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), charset));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                String result = response.toString();
                logger.debug("HTTPS POST响应: {}", result);
                return result;
            } else {
                logger.error("HTTPS请求失败，响应码: {}", responseCode);
                return "";
            }
            
        } catch (Exception e) {
            logger.error("HTTPS POST请求异常", e);
            return "";
        } finally {
            // 关闭资源
            try {
                if (out != null) {
                    out.close();
                }
                if (reader != null) {
                    reader.close();
                }
                if (conn != null) {
                    conn.disconnect();
                }
            } catch (Exception e) {
                logger.warn("关闭HTTPS连接时发生异常", e);
            }
        }
    }
    
    /**
     * HTTPS GET请求
     *
     * @param url 请求URL
     * @param params 请求参数
     * @param charset 字符集
     * @return 响应字符串
     */
    public static String get(String url, Map<String, String> params, String charset) {
        try {
            // 构建完整URL
            StringBuilder urlBuilder = new StringBuilder(url);
            if (params != null && !params.isEmpty()) {
                urlBuilder.append("?");
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    urlBuilder.append(entry.getKey())
                             .append("=")
                             .append(URLEncoder.encode(entry.getValue(), charset))
                             .append("&");
                }
                // 移除最后一个&
                urlBuilder.deleteCharAt(urlBuilder.length() - 1);
            }
            
            String fullUrl = urlBuilder.toString();
            logger.debug("HTTPS GET请求URL: {}", fullUrl);
            
            URL httpsUrl = new URL(fullUrl);
            HttpsURLConnection conn = (HttpsURLConnection) httpsUrl.openConnection();
            
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(CONNECT_TIMEOUT);
            conn.setReadTimeout(READ_TIMEOUT);
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);
            
            int responseCode = conn.getResponseCode();
            if (responseCode == HttpsURLConnection.HTTP_OK) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), charset));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();
                conn.disconnect();
                
                String result = response.toString();
                logger.debug("HTTPS GET响应: {}", result);
                return result;
            } else {
                logger.error("HTTPS GET请求失败，响应码: {}", responseCode);
                conn.disconnect();
                return "";
            }
            
        } catch (Exception e) {
            logger.error("HTTPS GET请求异常", e);
            return "";
        }
    }
}