package com.openhis.web.externalintegration.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

/**
 * 【BPC】HTTP请求共通方法
 *
 * @author Thanking
 * @date 2025-10-16
 */
@Slf4j
@Component
public class BpcHttpUtil {

    /**
     * 发起post请求
     *
     * @param jsonData JSON数据
     * @param md5SharedSecret MD5签名密钥
     * @param requestUrl 请求URL
     * @return 请求结果
     */
    public static String httpPost(String jsonData, String md5SharedSecret, String requestUrl) throws Exception {
        HttpsURLConnection conn = null;
        try {
            // 生成MD5签名
            String rawData = jsonData + "&" + md5SharedSecret;
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] digestBytes = md.digest(rawData.getBytes());
            StringBuilder hexString = new StringBuilder();
            for (byte b : digestBytes) {
                hexString.append(String.format("%02x", b & 0xff));
            }
            String md5Sign = hexString.toString();
            // 发起请求
            URL obj = new URL(requestUrl);
            conn = (HttpsURLConnection)obj.openConnection();
            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) {}
            }};
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, trustAllCerts, new SecureRandom());
            conn.setSSLSocketFactory(sslContext.getSocketFactory());
            conn.setHostnameVerifier((hostname, session) -> true);
            conn.setRequestMethod("POST");
            conn.setConnectTimeout(30_000);
            conn.setReadTimeout(60_000);
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            conn.setRequestProperty("sign", md5Sign);
            conn.setDoOutput(true);
            try (OutputStream os = conn.getOutputStream()) {
                byte[] input = jsonData.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }
            int responseCode = conn.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                try (BufferedReader br =
                    new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = br.readLine()) != null) {
                        response.append(line);
                    }
                    return response.toString();
                }
            } else {
                throw new RuntimeException("HTTP请求失败，返回" + responseCode);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new Exception("HTTP请求发生未知异常");
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
    }

}
