package com.crm.rely.backend.util;


import com.alibaba.fastjson.JSON;
import com.google.common.base.Strings;
import org.jsoup.Connection;
import org.jsoup.Connection.Method;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.X509TrustManager;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

/**
 * @program: cwg-my-base
 * @description:
 * @author: houn
 * @create: 2019-08-02 09:42
 */
public class HttpUtil {

    /**
     * 请求超时时间
     */
    private static final int TIME_OUT = 300000;

    /**
     * Https请求
     */
    private static final String HTTPS = "https";

    /**
     * Content-Type
     */
    private static final String CONTENT_TYPE = "Content-Type";

    /**
     * 表单提交方式Content-Type
     */
    private static final String FORM_TYPE = "application/x-www-form-urlencoded;charset=UTF-8";

    /**
     * JSON提交方式Content-Type
     */
    private static final String JSON_TYPE = "application/json;charset=UTF-8";

    /**
     * 发送Get请求
     *
     * @param url 请求URL
     * @return HTTP响应对象
     * @throws IOException 程序异常时抛出，由调用者处理
     */
    public static Response get(String url) throws IOException {
        return get(url, null);
    }

    public static Response getForm(String url, Map<String, String> data) throws IOException {
        return get(url, null, data);
    }

    /**
     * 发送Get请求
     *
     * @param url     请求URL
     * @param headers 请求头参数
     * @return HTTP响应对象
     * @throws IOException 程序异常时抛出，由调用者处理
     */
    public static Response get(String url, Map<String, String> headers) throws IOException {

        return get(url, headers, null);
    }

    public static Response get(String url, Map<String, String> headers, Map<String, String> data) throws IOException {

        Connection connection = getConnection(url, headers, Method.GET, data);
        Response response = connection.execute();
        return response;
    }

    public static Response put(String url, Map<String, String> headers, Map<String, String> data) throws IOException {

        Connection connection = getConnection(url, headers, Method.PUT, data);
        Response response = connection.execute();
        return response;
    }

    public static Response post(String url) throws IOException {
        return doPostRequest(url, null, null);
    }

    public static Response post(String url, Map<String, String> headers, Object ob) throws IOException {
        return doPostRequest(url, headers, JSON.toJSONString(ob));
    }

    /**
     * 发送JSON格式参数POST请求
     *
     * @param url    请求路径
     * @param params JSON格式请求参数
     * @return HTTP响应对象
     * @throws IOException 程序异常时抛出，由调用者处理
     */
    public static Response post(String url, String params) throws IOException {
        return doPostRequest(url, null, params);
    }

    /**
     * 发送JSON格式参数POST请求
     *
     * @param url     请求路径
     * @param headers 请求头中设置的参数
     * @param params  JSON格式请求参数
     * @return HTTP响应对象
     * @throws IOException 程序异常时抛出，由调用者处理
     */
    public static Response post(String url, Map<String, String> headers, String params) throws IOException {
        return doPostRequest(url, headers, params);
    }

    /**
     * 字符串参数post请求
     *
     * @param url      请求URL地址
     * @param paramMap 请求字符串参数集合
     * @return HTTP响应对象
     * @throws IOException 程序异常时抛出，由调用者处理
     */
    public static Response post(String url, Map<String, String> paramMap) throws IOException {
        return doPostRequest(url, null, paramMap, null);
    }

    /**
     * 带请求头的普通表单提交方式post请求
     *
     * @param headers  请求头参数
     * @param url      请求URL地址
     * @param paramMap 请求字符串参数集合
     * @return HTTP响应对象
     * @throws IOException 程序异常时抛出，由调用者处理
     */
    public static Response post(Map<String, String> headers, String url, Map<String, String> paramMap) throws IOException {
        return doPostRequest(url, headers, paramMap, null);
    }

    /**
     * 带上传文件的post请求
     *
     * @param url      请求URL地址
     * @param paramMap 请求字符串参数集合
     * @param fileMap  请求文件参数集合
     * @return HTTP响应对象
     * @throws IOException 程序异常时抛出，由调用者处理
     */
    public static Response post(String url, Map<String, String> paramMap, Map<String, File> fileMap) throws IOException {
        return doPostRequest(url, null, paramMap, fileMap);
    }

    /**
     * 带请求头的上传文件post请求
     *
     * @param url      请求URL地址
     * @param headers  请求头参数
     * @param paramMap 请求字符串参数集合
     * @param fileMap  请求文件参数集合
     * @return HTTP响应对象
     * @throws IOException 程序异常时抛出，由调用者处理
     */
    public static Response post(String url, Map<String, String> headers, Map<String, String> paramMap, Map<String,
            File> fileMap) throws IOException {
        return doPostRequest(url, headers, paramMap, fileMap);
    }

    /**
     * 执行post请求
     *
     * @param url        请求URL地址
     * @param headers    请求头
     * @param jsonParams 请求JSON格式字符串参数
     * @return HTTP响应对象
     * @throws IOException 程序异常时抛出，由调用者处理
     */
    private static Response doPostRequest(String url, Map<String, String> headers, String jsonParams) throws IOException {
        if (null == url || url.isEmpty()) {
            throw new RuntimeException("The request URL is blank.");
        }

        // 如果是Https请求
        if (url.startsWith(HTTPS)) {
            getTrust();
        }

        Connection connection = Jsoup.connect(url);
        connection.method(Method.POST);
        connection.timeout(getTimeOut(headers));
        connection.ignoreHttpErrors(true);
        connection.ignoreContentType(true);
        connection.maxBodySize(0);
        String jsonType = null;
        if (null != headers) {
            connection.headers(headers);
            for (Entry<String, String> header : headers.entrySet()) {
                if (CONTENT_TYPE.equals(header.getKey())) {
                    jsonType = header.getValue();
                    break;
                }
            }

        }
        if (jsonType == null) {
            jsonType = JSON_TYPE;
        }
        if (headers != null && headers.size() > 0) {

            connection.headers(headers);
        }
        connection.header(CONTENT_TYPE, jsonType);
        if (!Strings.isNullOrEmpty(jsonParams)) {

            connection.requestBody(jsonParams);
        }

        Response response = connection.execute();
        return response;
    }

    /**
     * 普通表单方式发送POST请求
     *
     * @param url      请求URL地址
     * @param headers  请求头
     * @param paramMap 请求字符串参数集合
     * @param fileMap  请求文件参数集合
     * @return HTTP响应对象
     * @throws IOException 程序异常时抛出，由调用者处理
     */
    private static Response doPostRequest(String url, Map<String, String> headers, Map<String, String> paramMap,
                                          Map<String, File> fileMap) throws IOException {

        Connection connection = getConnection(url, headers, Method.POST, null);

        // 收集上传文件输入流，最终全部关闭
        List<InputStream> inputStreamList = null;
        try {

            // 添加文件参数
            if (null != fileMap && !fileMap.isEmpty()) {
                inputStreamList = new ArrayList<InputStream>();
                InputStream in = null;
                File file = null;
                for (Entry<String, File> e : fileMap.entrySet()) {
                    file = e.getValue();
                    in = new FileInputStream(file);
                    inputStreamList.add(in);
                    connection.data(e.getKey(), file.getName(), in);
                }
            }

            // 普通表单提交方式
            else {
                boolean isType = false;
                if (null != headers) {
                    connection.headers(headers);
                    for (Entry<String, String> header : headers.entrySet()) {
                        if (CONTENT_TYPE.equals(header.getKey())) {
                            connection.header(CONTENT_TYPE, header.getValue());
                            isType = true;
                            break;
                        }
                    }

                }
                if (!isType) {

                    connection.header(CONTENT_TYPE, FORM_TYPE);
                }
            }

            // 添加字符串类参数
            if (null != paramMap && !paramMap.isEmpty()) {

                for (Entry<String, String> mapEntrySet : paramMap.entrySet()) {
                    if (mapEntrySet.getValue() == null) {
                        mapEntrySet.setValue("");
                    }
                }
                connection.data(paramMap);
            }

            Response response = connection.execute();
            return response;
        }

        // 关闭上传文件的输入流
        finally {
            closeStream(inputStreamList);
        }
    }

    /**
     * 关流
     *
     * @param streamList 流集合
     */
    private static void closeStream(List<? extends Closeable> streamList) {
        if (null != streamList) {
            for (Closeable stream : streamList) {
                try {
                    stream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 获取服务器信任
     */
    private static void getTrust() {
        try {
            HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> true);
            SSLContext context = SSLContext.getInstance("TLS");
            context.init(null, new X509TrustManager[]{new 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];
                }
            }}, new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取连接
     *
     * @param url
     * @param headers
     * @param method
     * @return
     */
    private static Connection getConnection(String url, Map<String, String> headers, Method method, Map<String,
            String> data) {
        if (null == url || url.isEmpty()) {
            throw new RuntimeException("The request URL is blank.");
        }

        // 如果是Https请求
        if (url.startsWith(HTTPS)) {
//            getTrust();
        }
        Connection connection = Jsoup.connect(url);
        connection.method(method);

        connection.timeout(getTimeOut(headers));

        connection.ignoreHttpErrors(true);
        connection.ignoreContentType(true);
        connection.maxBodySize(0);

        if (null != headers) {
            connection.headers(headers);
        }

        if (null != data) {
            if (Method.PUT.equals(method)) {
                connection.requestBody(JSON.toJSONString(data));
            } else {
                connection.data(data);
            }
        }
        return connection;
    }

    private static int getTimeOut(Map<String, String> headers) {
        int time = 0;
        try {
            if (headers != null && !headers.isEmpty()) {
                String timeOut = headers.get("TIME_OUT");
                if (!Strings.isNullOrEmpty(timeOut)) {
                    time = Integer.parseInt(timeOut);
                }
            }
        } finally {
            if (time <= 0) {
                time = TIME_OUT;
            }
        }
        return time;
    }

    public static boolean download(String urlPath, String targetDirectory, String fileName) throws Exception {
        // 解决url中可能有中文情况
        URL url = new URL(urlPath);
        HttpURLConnection http = (HttpURLConnection) url.openConnection();
        http.setConnectTimeout(3000);
        // 设置 User-Agent 避免被拦截
        http.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)");
        String contentType = http.getContentType();
        // 获取文件大小
        long length = http.getContentLengthLong();
        // 获取文件名
        InputStream inputStream = http.getInputStream();
        byte[] buff = new byte[1024 * 10];
        File file = new File(targetDirectory, fileName);
        if (!file.exists()) {
            OutputStream out = new FileOutputStream(file);
            int len;
            int count = 0; // 计数
            while ((len = inputStream.read(buff)) != -1) {
                out.write(buff, 0, len);
                out.flush();
                ++count;
            }
            // 关闭资源
            out.close();
            inputStream.close();
            http.disconnect();
            return true;
        }
        return false;
    }
}