/**
 * @Title: HttpsUtils.java
 * @Package com.paytend.api.utils
 * @Description: TODO
 * @author wanghuaiqing
 * @date 2023年8月15日 下午6:11:57
 * @version V1.0
 */
package com.paytend.api.utils;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;

import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;
import java.util.Map;

/**
 * @ClassName: HttpsUtils
 * @Description: https 工具类
 * @author wanghuaiqing
 * @date 2023年8月15日 下午6:11:57
 */
public class HttpsUtils {

    private static final String POST = "POST";
    private static final String GET = "GET";
    private static final String UTF_8 = "UTF-8";
    private static final String PARAM_TOO_LONG = "param is too long";
    private static final String RESULT_TOO_LONG = "result is too long";
    private static final Log logger = LogFactory.get();

    private static final int INT_10 = 10;
    private static final int INT_128 = 128;
    /**
     * 日志输入输出参数的长度限制
     */
    private static final int INT_10000 = 10000;

    /**
     * https post请求发送
     *
     * @param reqUrl 请求地址
     * @param param 请求参数
     * @param requestHeader 请求头部信息
     * @return
     */
    public static String sendPost(String reqUrl, String param, Map<String, String> requestHeader) {
        return sendRequest(reqUrl, POST, param, requestHeader);
    }

    /**
     * https请求发送
     *
     * @param reqUrl 请求地址
     * @param reqMethod 请求方式（GET/POST）
     * @param param 请求参数
     * @param requestHeader 请求头部信息
     * @return
     */
    public static String sendRequest(String reqUrl, String reqMethod, String param, Map<String, String> requestHeader) {
        long timeStart = System.currentTimeMillis();
        HttpsURLConnection httpUrlConn = null;
        try {

            URL url = new URL(reqUrl);
            httpUrlConn = (HttpsURLConnection)url.openConnection();
            httpUrlConn.setDoInput(true);
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setUseCaches(false);
            // （单位：毫秒）
            httpUrlConn.setReadTimeout(90000);
            httpUrlConn.setConnectTimeout(30000);
            httpUrlConn.setRequestProperty("Content-type", "application/json;charset=utf-8");
            httpUrlConn.setRequestProperty("Accept-Charset", "UTF-8");
            httpUrlConn.setRequestProperty("contentType", "UTF-8");

            // 请求头不为空,添加请求头
            if (requestHeader != null) {
                requestHeader.forEach(httpUrlConn::setRequestProperty);
            }

            // 设置请求方式（GET/POST）
            httpUrlConn.setRequestMethod(reqMethod);
            if (GET.equalsIgnoreCase(reqMethod)) {
                httpUrlConn.connect();
            }

            // 当有数据需要提交时
            if (null != param) {
                OutputStream outputStream = httpUrlConn.getOutputStream();
                // 注意编码格式，防止中文乱码
                outputStream.write(param.getBytes(UTF_8));
                outputStream.close();
            }

            // 将返回的输入流转换成字符串
            InputStream inputStream = httpUrlConn.getInputStream();
            String ret = getOutPutRet(inputStream);
            inputStream.close();

            logger.info("sendRequest url {}, param {}. result: {}, cost: {}", url, getPrintParam(param),
                getPrintResult(ret), System.currentTimeMillis() - timeStart);
            return ret;
        } catch (ConnectException ce) {
            logger.error("HttpsUtils.sendHttpsRequest ConnectException error,", ce);
        } catch (Exception e) {
            logger.error("HttpsUtils.sendHttpsRequest Exception error,", e);
        } finally {
            if (httpUrlConn != null) {
                httpUrlConn.disconnect();
            }
        }
        return null;
    }

    private static String getOutPutRet(InputStream inputStream) throws Exception {
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, UTF_8);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

        String str;
        StringBuffer buffer = new StringBuffer(INT_128);
        while ((str = bufferedReader.readLine()) != null) {
            buffer.append(str);
        }

        // 释放资源
        bufferedReader.close();
        inputStreamReader.close();

        return buffer.toString();
    }

    private static String getPrintParam(String param) {
        if (param != null && param.length() > INT_10000) {
            return PARAM_TOO_LONG;
        }

        return param;
    }

    private static String getPrintResult(String result) {
        if (result != null && result.length() > INT_10000) {
            return RESULT_TOO_LONG + result.substring(0, INT_10);
        }

        return result;
    }

    /**
     * 获取文件流
     *
     * @param filePath
     * @return
     */
    private static InputStream getInputStream(String filePath) {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        return classLoader.getResourceAsStream(filePath);
    }

}
