package com.saye.hospitalgd.util;

import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;

import javax.net.ssl.*;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * SSL证书工具类
 * 用于处理HTTPS请求时的SSL证书验证问题
 * 
 * @author thuang
 * @date 2025/10/24
 */
public class SSLUtil {

    /**
     * 创建一个信任所有证书的HttpClient
     * 注意：此方法会跳过SSL证书验证，仅用于开发/测试环境
     * 生产环境建议导入正确的SSL证书到JVM信任库
     * 
     * @return CloseableHttpClient
     * @throws KeyStoreException
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     */
    public static CloseableHttpClient createSSLClientDefault() 
            throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
        
        // 创建信任所有证书的策略
        TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] chain, String authType) 
                    throws CertificateException {
                return true;
            }
        };

        // 构建SSL上下文
        SSLContext sslContext = SSLContextBuilder
                .create()
                .loadTrustMaterial(null, acceptingTrustStrategy)
                .build();

        // 创建SSL连接工厂（不验证主机名）
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(
                sslContext,
                new String[]{"TLSv1", "TLSv1.1", "TLSv1.2", "SSLv3"},
                null,
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER
        );

        // 创建HttpClient
        return HttpClients.custom()
                .setSSLSocketFactory(sslSocketFactory)
                .build();
    }

    /**
     * 全局禁用SSL证书验证（针对HttpsURLConnection）
     * 注意：此方法会影响整个JVM，请谨慎使用
     */
    public static void disableSSLVerification() {
        try {
            // 创建信任所有证书的TrustManager
            TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }

                    @Override
                    public void checkClientTrusted(X509Certificate[] certs, String authType) {
                    }

                    @Override
                    public void checkServerTrusted(X509Certificate[] certs, String authType) {
                    }
                }
            };

            // 安装信任所有证书的TrustManager
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

            // 创建不进行主机名验证的HostnameVerifier
            HostnameVerifier allHostsValid = new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            };

            // 安装不进行主机名验证的HostnameVerifier
            HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            e.printStackTrace();
        }
    }
}



