package com.qmth.paper.library.common.util;

import com.qmth.paper.library.common.enums.ExceptionResultEnum;
import com.qmth.paper.library.common.contant.SystemConstant;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

public class HttpKit {
    private final static Logger log = LoggerFactory.getLogger(HttpKit.class);

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url    发送请求的 URL
     * @param params 请求的参数集合
     * @return 远程资源的响应结果
     */
    @SuppressWarnings("unused")
    public static String sendPost(String url, Map<String, String> params, Map<String, String> requestHeader) {
        OutputStreamWriter out = null;
        BufferedReader reader = null;
        int responseCode = 200;
        StringBuilder result = new StringBuilder();
        try {
            URL realUrl = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            // 发送POST请求必须设置如下两行
            connection.setDoOutput(true);
            connection.setDoInput(true);
            // POST方法
            connection.setRequestMethod("POST");
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            if (requestHeader != null && requestHeader.size() > 0) {
                for (Map.Entry<String, String> entry : requestHeader.entrySet()) {
                    connection.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }
//            conn.setRequestProperty("Authorization", authorization);
            connection.connect();
            // 获取URLConnection对象对应的输出流
            out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
            // 发送请求参数
            if (params != null) {
                StringBuilder param = new StringBuilder();
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    if (param.length() > 0) {
                        param.append("&");
                    }
                    param.append(entry.getKey());
                    param.append("=");
                    param.append(entry.getValue());
                }
                out.write(param.toString());
            }
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            responseCode = connection.getResponseCode();
            if (responseCode >= 400) {
                Map<String, List<String>> responseProperties = connection.getHeaderFields();
                if (responseProperties.containsKey("error-info")) {
                    List<String> strings = responseProperties.get("error-info");
                    if (!strings.isEmpty()) {
                        String message = String.join(";", strings);
                        throw ExceptionResultEnum.ERROR.exception(message);
                    }
                }
                throw ExceptionResultEnum.ERROR.exception("接口调用错误");
            } else {
                reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            }
            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception e) {
            throw ExceptionResultEnum.ERROR.exception("调用接口异常：错误码[" + responseCode + "]，错误原因[" + e.getMessage() + "]");
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException ex) {
                log.error(SystemConstant.LOG_ERROR, ex);
            }
        }
        return result.toString();
    }

    /**
     * 向指定 URL 发送POST方法的请求（JSON数据）
     *
     * @param url      发送请求的 URL
     * @param jsonData 请求的json
     * @return 远程资源的响应结果
     */
    @SuppressWarnings("unused")
    public static String sendPost(String url, String jsonData, Map<String, String> requestHeader) {
        DataOutputStream out = null;
        BufferedReader reader = null;
        StringBuilder result = new StringBuilder();
        int responseCode = 200;
        try {
            URL realUrl = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            // 发送POST请求必须设置如下两行
            connection.setDoOutput(true);
            connection.setDoInput(true);
            // POST方法
            connection.setRequestMethod("POST");
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            // 设置通用的请求属性
//            conn.setRequestProperty("accept", "application/json, text/plain, */*");
//            conn.setRequestProperty("connection", "Keep-Alive");
//            conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.9 Safari/537.36");
            connection.setRequestProperty("Content-Type", "application/json");
            if (requestHeader != null && requestHeader.size() > 0) {
                for (Map.Entry<String, String> entry : requestHeader.entrySet()) {
                    connection.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }
            connection.connect();
            // 获取URLConnection对象对应的输出流
            out = new DataOutputStream(connection.getOutputStream());
            // 发送请求参数
            if (StringUtils.isNotBlank(jsonData)) {
                out.writeChars(jsonData);
            }
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            responseCode = connection.getResponseCode();
            if (responseCode >= 400) {
                Map<String, List<String>> responseProperties = connection.getHeaderFields();
                if (responseProperties.containsKey("error-info")) {
                    List<String> strings = responseProperties.get("error-info");
                    if (!strings.isEmpty()) {
                        String message = String.join(";", strings);
                        throw ExceptionResultEnum.ERROR.exception(message);
                    }
                }
                throw ExceptionResultEnum.ERROR.exception("接口调用错误");
            } else {
                reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            }
            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception e) {
            throw ExceptionResultEnum.ERROR.exception("调用接口异常：错误码[" + responseCode + "]，错误原因[" + e.getMessage() + "]");
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException ex) {
                log.error(SystemConstant.LOG_ERROR, ex);
            }
        }
        return result.toString();
    }

    /**
     * 发送post请求
     *
     * @param requestUrl       请求url
     * @param requestHeader    请求头
     * @param formTexts        表单数据
     * @param files            上传文件
     * @param requestEncoding  请求编码
     * @param responseEncoding 响应编码
     * @return 页面响应html
     */
    public static String sendPost(String requestUrl, Map<String, String> requestHeader, Map<String, Object> formTexts, Map<String, String> files, String requestEncoding, String responseEncoding) {
        OutputStream out = null;
        BufferedReader reader = null;
        StringBuilder result = new StringBuilder();
        int responseCode = 200;
        try {
            if (requestUrl == null || requestUrl.isEmpty()) {
                return result.toString();
            }
            URL realUrl = new URL(requestUrl);
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setRequestProperty("accept", "text/html, application/xhtml+xml, image/jxr, */*");
            connection.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:53.0) Gecko/20100101 Firefox/53.0");
            if (requestHeader != null && requestHeader.size() > 0) {
                for (Map.Entry<String, String> entry : requestHeader.entrySet()) {
                    connection.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            if (requestEncoding == null || requestEncoding.isEmpty()) {
                requestEncoding = "UTF-8";
            }
            if (responseEncoding == null || responseEncoding.isEmpty()) {
                responseEncoding = "UTF-8";
            }
            if (files == null || files.size() == 0) {
                connection.setRequestProperty("content-type", "application/x-www-form-urlencoded");
                out = new DataOutputStream(connection.getOutputStream());
                if (formTexts != null && formTexts.size() > 0) {
                    String formData = "";
                    for (Map.Entry<String, Object> entry : formTexts.entrySet()) {
                        formData += entry.getKey() + "=" + entry.getValue() + "&";
                    }
                    formData = formData.substring(0, formData.length() - 1);
                    out.write(formData.getBytes(requestEncoding));
                }
            } else {
                String boundary = "-----------------------------" + System.currentTimeMillis();
                connection.setRequestProperty("content-type", "multipart/form-data; boundary=" + boundary);
                out = new DataOutputStream(connection.getOutputStream());
                if (formTexts != null && formTexts.size() > 0) {
                    StringBuilder sbFormData = new StringBuilder();
                    for (Map.Entry<String, Object> entry : formTexts.entrySet()) {
                        sbFormData.append("--" + boundary + "\r\n");
                        sbFormData.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"\r\n\r\n");
                        sbFormData.append(entry.getValue() + "\r\n");
                    }
                    out.write(sbFormData.toString().getBytes(requestEncoding));
                }
                for (Map.Entry<String, String> entry : files.entrySet()) {
                    String fileName = entry.getKey();
                    String filePath = entry.getValue();
                    if (fileName == null || fileName.isEmpty() || filePath == null || filePath.isEmpty()) {
                        continue;
                    }
                    File file = new File(filePath);
                    if (!file.exists()) {
                        continue;
                    }
                    out.write(("--" + boundary + "\r\n").getBytes(requestEncoding));
                    out.write(("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"\r\n").getBytes(requestEncoding));
                    out.write(("Content-Type: application/octet-stream\r\n\r\n").getBytes(requestEncoding));
                    DataInputStream in = new DataInputStream(new FileInputStream(file));
                    int bytes = 0;
                    byte[] bufferOut = new byte[1024];
                    while ((bytes = in.read(bufferOut)) != -1) {
                        out.write(bufferOut, 0, bytes);
                    }
                    in.close();
                    out.write(("\r\n").getBytes(requestEncoding));
                }
                out.write(("--" + boundary + "--").getBytes(requestEncoding));
            }
            out.flush();
            out.close();


            responseCode = connection.getResponseCode();
            if (responseCode >= 400) {
//                reader = new BufferedReader(new InputStreamReader(connection.getErrorStream(), responseEncoding));
                Map<String, List<String>> responseProperties = connection.getHeaderFields();
                if (responseProperties.containsKey("error-info")) {
                    List<String> strings = responseProperties.get("error-info");
                    if (!strings.isEmpty()) {
                        String message = String.join(";", strings);
                        throw ExceptionResultEnum.ERROR.exception(message);
                    }
                }
                throw ExceptionResultEnum.ERROR.exception("接口调用错误");
            } else {
                reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), responseEncoding));
            }
            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception e) {
            throw ExceptionResultEnum.ERROR.exception("调用接口异常：错误码[" + responseCode + "]，错误原因[" + e.getMessage() + "]");
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException ex) {
                log.error(SystemConstant.LOG_ERROR, ex);
            }
        }
        return result.toString();
    }

}
