package com.ruoyi.common.utils.http;

import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;


public class OkHttpUtils {

    public static OkHttpClient createOkHttpClient() {
        try {
            // 1. 创建「信任所有证书」的 TrustManager
//            X509TrustManager trustManager = new X509TrustManager() {
//                @Override
//                public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
//                    // 不校验客户端证书（开发环境忽略）
//                }
//
//                @Override
//                public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
//                    // 不校验服务器证书（核心：信任所有服务器证书）
//                }
//
//                @Override
//                public X509Certificate[] getAcceptedIssuers() {
//                    return new X509Certificate[0];
//                }
//            };

            // 2. 初始化 SSLContext（TLS 协议）
//            SSLContext sslContext = SSLContext.getInstance("TLS");
//            sslContext.init(null, new TrustManager[]{trustManager}, new java.security.SecureRandom());

            // 3. 禁用主机名校验（避免证书域名与实际调用域名不一致的错误，开发环境临时用）
//            HostnameVerifier hostnameVerifier = (hostname, session) -> true;

            // 4. 整合原有配置 + SSL 配置
            return new OkHttpClient.Builder()
                    .connectTimeout(60, TimeUnit.SECONDS)
                    .readTimeout(60, TimeUnit.SECONDS)
                    .writeTimeout(60, TimeUnit.SECONDS)
//                    .sslSocketFactory(sslContext.getSocketFactory(), trustManager) // 注入 SSL 上下文
//                    .hostnameVerifier(hostnameVerifier) // 禁用主机名校验
                    .build();
        } catch (Exception e) {
            // 异常处理（可根据业务抛自定义异常）
            throw new RuntimeException("OkHttpClient SSL error", e);
        }
    }

    public static Call newCall(Request request) {
        return createOkHttpClient().newCall(request);
    }
}
