package com.jeeplus.finance.invoice.util.OMS;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;

/**
 * 纯原生POST请求工具类 - 仅支持JSON格式请求体 + UTF-8编码
 * 无任何冗余代码、无第三方依赖、支持HTTP/HTTPS、异常兜底返回空JSON
 */
public class HttpPostJsonUtil {

    /**
     * 核心方法：发送POST请求
     * @param requestUrl 接口请求地址 (HTTP/HTTPS均可)
     * @param outputStr  JSON格式的请求参数字符串
     * @return 接口返回的JSON字符串，异常则返回 {}
     */
    public static String doPost(String requestUrl, String outputStr) {
        HttpURLConnection httpUrlConn = null;
        try {
            URL url = new URL(requestUrl);
            httpUrlConn = (HttpURLConnection) url.openConnection();

            // HTTPS 证书信任配置 (必须保留，兼容HTTPS请求)
            if (httpUrlConn instanceof HttpsURLConnection) {
                SSLContext sslContext = SSLContext.getInstance("TLS");
                sslContext.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new SecureRandom());
                ((HttpsURLConnection) httpUrlConn).setSSLSocketFactory(sslContext.getSocketFactory());
                ((HttpsURLConnection) httpUrlConn).setHostnameVerifier((hostname, session) -> true);
            }

            // 核心配置
            httpUrlConn.setRequestMethod("POST");
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            httpUrlConn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");

            // 写入JSON参数 并 UTF-8编码
            if (outputStr != null && !outputStr.trim().isEmpty()) {
                OutputStream os = httpUrlConn.getOutputStream();
                os.write(outputStr.getBytes("UTF-8"));
                os.flush();
                os.close();
            }

            // 读取返回结果 并 UTF-8解码
            BufferedReader br = new BufferedReader(new InputStreamReader(httpUrlConn.getInputStream(), "UTF-8"));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            br.close();
            return sb.toString();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (httpUrlConn != null) {
                httpUrlConn.disconnect();
            }
        }
        return "{}";
    }

    /**
     * 重载方法：带token请求头的POST请求 (你的业务必用，无冗余新增)
     * @param requestUrl 接口地址
     * @param outputStr   JSON参数
     * @param token       令牌(accessToken/Authorization)
     * @return 接口返回的JSON字符串
     */
    public static String doPost(String requestUrl, String outputStr, String token) {
        HttpURLConnection httpUrlConn = null;
        try {
            URL url = new URL(requestUrl);
            httpUrlConn = (HttpURLConnection) url.openConnection();

            if (httpUrlConn instanceof HttpsURLConnection) {
                SSLContext sslContext = SSLContext.getInstance("TLS");
                sslContext.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new SecureRandom());
                ((HttpsURLConnection) httpUrlConn).setSSLSocketFactory(sslContext.getSocketFactory());
                ((HttpsURLConnection) httpUrlConn).setHostnameVerifier((hostname, session) -> true);
            }

            httpUrlConn.setRequestMethod("POST");
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            httpUrlConn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            // 添加token请求头
            if (token != null && !token.trim().isEmpty()) {
                httpUrlConn.setRequestProperty("accessToken", token);
                // 如果接口要求 Bearer 前缀，放开下面这行注释即可
                // httpUrlConn.setRequestProperty("Authorization", "Bearer " + token);
            }

            if (outputStr != null && !outputStr.trim().isEmpty()) {
                OutputStream os = httpUrlConn.getOutputStream();
                os.write(outputStr.getBytes("UTF-8"));
                os.flush();
                os.close();
            }

            BufferedReader br = new BufferedReader(new InputStreamReader(httpUrlConn.getInputStream(), "UTF-8"));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            br.close();
            return sb.toString();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (httpUrlConn != null) {
                httpUrlConn.disconnect();
            }
        }
        return "{}";
    }

    /**
     * 内部类：HTTPS证书信任管理器 (极简实现，无冗余代码)
     */
    private static class TrustAnyTrustManager implements X509TrustManager {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) {}

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

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    }
}