/**
 *
 */
package easydo.technology.util;

import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;

import javax.net.ssl.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * 发送https请求的工具类
 */
@Component
public class HttpsUtil {

    public static final String charset = "UTF-8";

    public static final String CONTENTTYPE_APPLICATION_JSON = "application/json;charset=UTF-8";
    public static final String CONTENTTYPE_APPLICATION_XML = "application/xml;charset=UTF-8";
    public static final String CONTENTTYPE_MULTIPART_FORM = "multipart/form-data;charset=UTF-8";
    public static final String TEXTPLAIN = "text/plain;charset=UTF-8";
    public static final String TEXTHTML = "text/html;charset=UTF-8";
    /**
     * 忽视证书HostName
     */
    private static HostnameVerifier ignoreHostnameVerifier = new HostnameVerifier() {
        public boolean verify(String s, SSLSession sslsession) {
            return true;
        }
    };

    /**
     * Ignore Certification
     */
    private static TrustManager ignoreCertificationTrustManger = new X509TrustManager() {
        private X509Certificate[] certificates;

        public void checkClientTrusted(X509Certificate certificates[], String authType) throws CertificateException {
            if (this.certificates == null) {
                this.certificates = certificates;
            }
        }

        public void checkServerTrusted(X509Certificate[] ax509certificate, String s) throws CertificateException {
            if (this.certificates == null) {
                this.certificates = ax509certificate;
            }
        }

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

    public static byte[] getByteFromUrl(String filePath) {

        byte[] data = null;
        InputStream is = null;
        HttpURLConnection conn = null;
        HttpsURLConnection conns = null;
        try {

            URL url = new URL(filePath);
            if (filePath.startsWith("https")) {
                HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
                conns = (HttpsURLConnection) url.openConnection();
                // Prepare SSL Context
                TrustManager[] tm = {ignoreCertificationTrustManger};
                SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
                sslContext.init(null, tm, new java.security.SecureRandom());

                // 从上述SSLContext对象中得到SSLSocketFactory对象
                SSLSocketFactory ssf = sslContext.getSocketFactory();
                conns.setSSLSocketFactory(ssf);
                if (conns.getResponseCode() != 200) {
                    return null;
                }
                is = conns.getInputStream();
                if (conns.getResponseCode() == 200) {
                    data = readInputStream(is);
                } else {
                    data = null;
                }
            } else {
                conn = (HttpURLConnection) url.openConnection();
                conn.setDoInput(true);
                conn.setConnectTimeout(6000);
                is = conn.getInputStream();
                if (conn.getResponseCode() == 200) {
                    data = readInputStream(is);
                } else {
                    data = null;
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
        return data;
    }

    public static byte[] readInputStream(InputStream is) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length = -1;
        try {
            while ((length = is.read(buffer)) != -1) {
                baos.write(buffer, 0, length);
            }
            baos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] data = baos.toByteArray();
        try {
            is.close();
            baos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return data;
    }

    /**
     * 发送Get请求
     */
    public static JSONObject sendSSLGetMethod(String urlString) throws Exception {
        JSONObject jsonObject = null;
        StringBuffer buffer = null;
        InputStream is = null;
        InputStreamReader isr = null;
        BufferedReader bufferedReader = null;
        HttpsURLConnection connection = null;
        try {

            URL url = new URL(urlString);
            HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
            connection = (HttpsURLConnection) url.openConnection();

            // Prepare SSL Context
            TrustManager[] tm = {ignoreCertificationTrustManger};
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());

            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();
            connection.setSSLSocketFactory(ssf);
            if (connection.getResponseCode() != 200) {
                return null;
            }

            is = connection.getInputStream();
            isr = new InputStreamReader(is, "UTF-8");
            bufferedReader = new BufferedReader(isr);

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

            jsonObject = JSONObject.parseObject(buffer.toString());
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (bufferedReader != null) {
                bufferedReader.close();
                bufferedReader = null;
            }
            if (isr != null) {
                isr.close();
                isr = null;
            }
            if (is != null) {
                is.close();
                is = null;
            }
            if (connection != null) {
                connection.disconnect();
            }
        }
        return jsonObject;
    }

    /**
     * 发送Post请求
     */
    public static JSONObject sendSSLPostMethod(String urlString, String postData) throws Exception {
        JSONObject jsonObject = null;
        StringBuffer buffer = null;
        InputStream is = null;
        InputStreamReader isr = null;
        BufferedReader bufferedReader = null;
        HttpsURLConnection connection = null;
        try {

            URL url = new URL(urlString);
            HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
            connection = (HttpsURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("content-type", "text/json");
            connection.setRequestProperty("content-length", String.valueOf(postData.getBytes().length));
            connection.getOutputStream().write(postData.getBytes("utf-8"));
            connection.getOutputStream().flush();
            connection.getOutputStream().close();

            // Prepare SSL Context
            TrustManager[] tm = {ignoreCertificationTrustManger};
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());

            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();
            connection.setSSLSocketFactory(ssf);
            if (connection.getResponseCode() != 200) {
                return null;
            }

            is = connection.getInputStream();
            isr = new InputStreamReader(is, "UTF-8");
            bufferedReader = new BufferedReader(isr);

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

            jsonObject = JSONObject.parseObject(buffer.toString());
        } finally {
            if (null != is) {
                is.close();
                is = null;
            }
            if (null != connection) {
                connection.disconnect();
            }
        }
        return jsonObject;
    }

    /**
     * 发送Post请求
     */
/*    public static String postForm(String urlString, byte[] postData) throws Exception {
        String buffer = "";
        InputStream is = null;
        InputStreamReader isr = null;
        BufferedReader bufferedReader = null;
        HttpsURLConnection connection = null;
        try {

            URL url = new URL(urlString);
            HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
            connection = (HttpsURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("content-type", "application/x-www-form-urlencoded");
            // Prepare SSL Context
            TrustManager[] tm = {ignoreCertificationTrustManger};
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());

            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();
            connection.setSSLSocketFactory(ssf);
            OutputStream outStrm = connection.getOutputStream();
            outStrm.write(postData);
            outStrm.flush();
            outStrm.close();

            if (connection.getResponseCode() != 200) {
                return null;
            }
            is = connection.getInputStream();
            buffer = IOUtils.toString(is, "utf-8");
        } finally {
            if (null != is) {
                is.close();
                is = null;
            }
            if (null != connection) {
                connection.disconnect();
            }
        }
        return buffer;
    }*/
    public static String downloadFile(String localFile, String fileUrl) throws Exception {
        InputStream is = null;
        HttpsURLConnection connection = null;
        File file = new File(localFile);
        FileOutputStream fos = new FileOutputStream(file);
        try {
            URL url = new URL(fileUrl);
            HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
            connection = (HttpsURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestMethod("GET");
//            connection.setRequestProperty("content-type", "application/x-www-form-urlencoded");
            // Prepare SSL Context
            TrustManager[] tm = {ignoreCertificationTrustManger};
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());

            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();
            connection.setSSLSocketFactory(ssf);

            if (connection.getResponseCode() != 200) {
                return null;
            }
            is = connection.getInputStream();
            int bytesum = 0;
            int byteread = 0;

            byte[] buffer = new byte[1204];
            while ((byteread = is.read(buffer)) != -1) {
                bytesum += byteread;
                System.out.println(bytesum);
                fos.write(buffer, 0, byteread);
            }
            fos.close();
            is.close();
            connection.disconnect();
            return localFile;
        } finally {
            if (null != is) {
                fos.close();
                fos = null;
            }
            if (null != is) {
                is.close();
                is = null;
            }
            if (null != connection) {
                connection.disconnect();
            }
        }
    }

//    public static void main(String[] args) {
//        byte[] byteFromUrl = getByteFromUrl("https://pmbimcloud-company.oss-cn-hangzhou.aliyuncs.com/af560077-7ead-2c94-b2dc-02170a833273.jpg?Expires=1672812245&OSSAccessKeyId=LTAI8PPrIEVEAQCK&Signature=9oy9s8HS%2FvIczLQJQUeWBqL7MII%3D");
//        System.out.println(byteFromUrl.length);
//    }
}