package com.platform.common.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang.StringUtils;

import javax.net.ssl.*;


/**
 * HttpClientHelper
 */
public class HttpClientHelper {

    /**
     * @Description:使用HttpURLConnection发送post请求
     */
    public static String sendPost(String urlParam, Map<String, Object> params, String charset,boolean isProxy) {
        StringBuffer resultBuffer = null;
        // 构建请求参数
        String sbParams = buildingParams(params);
        HttpURLConnection con = null;
        OutputStreamWriter osw = null;
        BufferedReader br = null;
        // 发送请求
        try {
            URL url = new URL(urlParam);

            con = (HttpURLConnection) url.openConnection();
            if(isProxy){
                InetSocketAddress addr = new InetSocketAddress("47.93.4.104",80);
                Proxy proxy = new Proxy(Proxy.Type.HTTP, addr);
                con = (HttpURLConnection) url.openConnection(proxy);
            }

            con.setRequestMethod("POST");
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setUseCaches(false);

            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            if (sbParams != null && sbParams.length() > 0) {
                osw = new OutputStreamWriter(con.getOutputStream(), charset);
                osw.write(sbParams.substring(0, sbParams.length() - 1));
                osw.flush();
            }

            // 读取返回内容
            resultBuffer = new StringBuffer();
            int contentLength = Integer.parseInt(con.getHeaderField("Content-Length"));
            if (contentLength > 0) {
                br = new BufferedReader(new InputStreamReader(con.getInputStream(), charset));
                String temp;
                while ((temp = br.readLine()) != null) {
                    resultBuffer.append(temp);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (osw != null) {
                try {
                    osw.close();
                } catch (IOException e) {
                    osw = null;
                    throw new RuntimeException(e);
                } finally {
                    if (con != null) {
                        con.disconnect();
                        con = null;
                    }
                }
            }
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    br = null;
                    throw new RuntimeException(e);
                } finally {
                    if (con != null) {
                        con.disconnect();
                        con = null;
                    }
                }
            }
        }

        return resultBuffer.toString();
    }

    /**
     * @Description:使用HttpURLConnection发送get请求
     */
    public static String sendGet(String urlParam, Map<String, Object> params, String charset,boolean isProxy) {
        StringBuffer resultBuffer = null;
        // 构建请求参数
        String sbParams = buildingParams(params);
        HttpURLConnection con = null;
        BufferedReader br = null;
        try {
            URL url = null;
            if (sbParams != null && sbParams.length() > 0) {
                url = new URL(urlParam + "?" + sbParams.substring(0, sbParams.length() - 1));
            } else {
                url = new URL(urlParam);
            }
            con = (HttpURLConnection) url.openConnection();
            if(isProxy){
                InetSocketAddress addr = new InetSocketAddress("47.93.4.104",80);
                Proxy proxy = new Proxy(Proxy.Type.HTTP, addr);
                con = (HttpURLConnection) url.openConnection(proxy);
            }
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            con.connect();
            resultBuffer = new StringBuffer();
            br = new BufferedReader(new InputStreamReader(con.getInputStream(), charset));
            String temp;
            while ((temp = br.readLine()) != null) {
                resultBuffer.append(temp);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    br = null;
                    throw new RuntimeException(e);
                } finally {
                    if (con != null) {
                        con.disconnect();
                        con = null;
                    }
                }
            }
        }
        return resultBuffer.toString();
    }

    public static void sendGetAndSaveFile(String urlParam, Map<String, Object> params, String fileSavePath,boolean isProxy) {
        // 构建请求参数
        String sbParams = buildingParams(params);
        HttpURLConnection con = null;
        BufferedReader br = null;
        FileOutputStream os = null;
        try {
            URL url = null;
            if (sbParams != null && sbParams.length() > 0) {
                url = new URL(urlParam + (urlParam.indexOf("?")>-1 ? "&" : "?") + sbParams.substring(0, sbParams.length() - 1));
            } else {
                url = new URL(urlParam);
            }
            con = (HttpURLConnection) url.openConnection();
            if(isProxy){
                InetSocketAddress addr = new InetSocketAddress("47.93.4.104",80);
                Proxy proxy = new Proxy(Proxy.Type.HTTP, addr);
                con = (HttpURLConnection) url.openConnection(proxy);
            }
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            con.connect();
            InputStream is = con.getInputStream();

            File outFile=new File(fileSavePath);
            if (!outFile.getParentFile().exists())
                outFile.getParentFile().mkdirs();

            os = new FileOutputStream(fileSavePath);

            byte buf[] = new byte[1024];
            int count = 0;
            while ((count = is.read(buf)) != -1) {
                os.write(buf, 0, count);
            }
            os.flush();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    os = null;
                    throw new RuntimeException(e);
                } finally {
                    if (con != null) {
                        con.disconnect();
                        con = null;
                    }
                }
            }
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    br = null;
                    throw new RuntimeException(e);
                } finally {
                    if (con != null) {
                        con.disconnect();
                        con = null;
                    }
                }
            }
        }
    }

    /**
     * 读取文件内容
     * @param urlParam
     * @param isProxy
     */
    public static String sendGetAndGetFileContent(String urlParam,boolean isProxy) {
        if(urlParam.startsWith("https://")){
            return sendHttpsGetAndGetFileContent(urlParam,isProxy);
        }
        HttpURLConnection con = null;
        BufferedReader br = null;
        FileOutputStream os = null;
        InputStreamReader isReader = null;
        BufferedReader reader = null;
        StringBuffer buffer = new StringBuffer();
        try {
            URL url = new URL(urlParam);

            con = (HttpURLConnection) url.openConnection();

            if(isProxy){
                InetSocketAddress addr = new InetSocketAddress("47.93.4.104",80);
                Proxy proxy = new Proxy(Proxy.Type.HTTP, addr);
                con = (HttpURLConnection) url.openConnection(proxy);
            }
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            con.connect();

            int HttpResult = con.getResponseCode();
            if(HttpResult != HttpURLConnection.HTTP_OK) {
                System.out.print("无法连接到");
            } else {
                isReader = new InputStreamReader(con.getInputStream(),"UTF-8");
                reader = new BufferedReader(isReader);

                String line; // 用来保存每行读取的内容
                line = reader.readLine(); // 读取第一行
                while (line != null) { // 如果 line 为空说明读完了
                    buffer.append(line).append("\n");
                    line = reader.readLine(); // 读取下一行
                }
                isReader.close();
                reader.close();
            }

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    os = null;
                    throw new RuntimeException(e);
                } finally {
                    if (con != null) {
                        con.disconnect();
                        con = null;
                    }
                }
            }
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    br = null;
                    throw new RuntimeException(e);
                } finally {
                    if (con != null) {
                        con.disconnect();
                        con = null;
                    }
                }
            }
            if (isReader != null) {
                try {
                    isReader.close();
                } catch (IOException e) {
                    isReader = null;
                    throw new RuntimeException(e);
                } finally {
                    if (con != null) {
                        con.disconnect();
                        con = null;
                    }
                }
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    reader = null;
                    throw new RuntimeException(e);
                } finally {
                    if (con != null) {
                        con.disconnect();
                        con = null;
                    }
                }
            }
        }
        return buffer.toString();
    }


    /**
     * 读取文件内容
     * @param urlParam
     * @param isProxy
     */
    public static String sendHttpsGetAndGetFileContent(String urlParam,boolean isProxy) {

        if(urlParam.startsWith("http://")){
            return sendGetAndGetFileContent(urlParam,isProxy);
        }

        HttpsURLConnection con = null;
        BufferedReader br = null;
        FileOutputStream os = null;
        InputStreamReader isReader = null;
        BufferedReader reader = null;
        StringBuffer buffer = new StringBuffer();
        try {
            URL url = new URL(urlParam);

            con = (HttpsURLConnection) url.openConnection();
            // 创建SSLContext对象，并使用我们指定的信任管理器初始化
            TrustManager[] tm = { new MyX509TrustManager() };
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new SecureRandom());
            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();

            con.setSSLSocketFactory(ssf);


            if(isProxy){
                InetSocketAddress addr = new InetSocketAddress("47.93.4.104",80);
                Proxy proxy = new Proxy(Proxy.Type.HTTP, addr);
                con = (HttpsURLConnection) url.openConnection(proxy);
            }
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            con.connect();

            int HttpResult = con.getResponseCode();
            if(HttpResult != HttpURLConnection.HTTP_OK) {
                System.out.print("无法连接到");
            } else {
                isReader = new InputStreamReader(con.getInputStream(),"UTF-8");
                reader = new BufferedReader(isReader);

                String line; // 用来保存每行读取的内容
                line = reader.readLine(); // 读取第一行
                while (line != null) { // 如果 line 为空说明读完了
                    buffer.append(line).append("\n");
                    line = reader.readLine(); // 读取下一行
                }
                isReader.close();
                reader.close();
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    os = null;
                    throw new RuntimeException(e);
                } finally {
                    if (con != null) {
                        con.disconnect();
                        con = null;
                    }
                }
            }
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    br = null;
                    throw new RuntimeException(e);
                } finally {
                    if (con != null) {
                        con.disconnect();
                        con = null;
                    }
                }
            }
            if (isReader != null) {
                try {
                    isReader.close();
                } catch (IOException e) {
                    isReader = null;
                    throw new RuntimeException(e);
                } finally {
                    if (con != null) {
                        con.disconnect();
                        con = null;
                    }
                }
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    reader = null;
                    throw new RuntimeException(e);
                } finally {
                    if (con != null) {
                        con.disconnect();
                        con = null;
                    }
                }
            }
        }
        return buffer.toString();
    }

    // 构建请求参数
    public static String buildingParams(Map<String, Object> params){
        StringBuffer sbParams = new StringBuffer();
        if (params != null && params.size() > 0) {
            for (Entry<String, Object> entry : params.entrySet()) {
                if(StringUtils.isBlank(entry.getKey()) || entry.getValue()==null){
                    continue;
                }
                sbParams.append(entry.getKey());
                sbParams.append("=");
                sbParams.append(entry.getValue());
                sbParams.append("&");
            }
        }
        return sbParams.toString();
    }

    public static void main(String[] args) {
//	  int page = 1;
//	  int pageSize = 10;
//	  String keyword = "交通";
//	  Long startTime = null;
//	  Long endTime = null;
//	  String latlng = null;
//	  Integer precision = null; // 经纬度点方圆多少公里（1,5,10,15,20,30,50,100,150,200,300)，默认值是5
//	  Integer order = null; // 视频列表排序（0匹配度,1时间降序,2时间升序,3播放数,4点赞数)，默认值是0
//	  Boolean originWork = null; // 是否为快手用户本人手机原创拍摄
//	  String operatorId = "1";
//		String paramList = String.format("page=%d&count=%d&keyword=%s&startTime=%d&endTime=%d&latlng=%s&precision=%d&order=%d&originWork=%s&operatorId=%s&secret=%s",
//				page, pageSize, keyword, startTime, endTime, latlng, precision, order, originWork,operatorId, "e85fdba04bf261e");
//		String md5Str = DigestUtils.md5Hex(paramList);
//		Map<String, Object> params = new HashMap<String, Object>();
//		params.put("page", page);
//		params.put("count", pageSize);
//		params.put("keyword", " ");
//		params.put("operatorId", 1);
//		params.put("signature", md5Str);
//		String result_json = HttpClientHelper.sendPost("http://lc.test.gifshow.com/rest/n/partner/xinhua/search",params,"UTF-8");
//		System.out.println(md5Str);
//		System.out.println(result_json);
//
//		System.out.println(MapUtils.json2map(result_json));

//    	String BASE_PATH = ClassUtils.getDefaultClassLoader().getResource("").getPath().substring(1) + File.separator + "kuaishou/";
////    	String BASE_PATH = "c:\\kuaishou"+ File.separator + VideoUtils.getDateDir() + File.separator ;
//        String newFilePath = FileUtils.BASE_PATH + "11111111.mp4";
//        System.out.println(newFilePath);
//        Map<String, Object> params = new HashMap<String, Object>();
//		params.put("page", 1);
//		params.put("count", 10);
//		params.put("keyword", " ");
//		params.put("operatorId", 1);
//
//    	HttpClientHelper.sendGetAndSaveFile(url, params, newFilePath,false);
        String url = "https://hhtestlive.zhongkedongxin.com/caster/a65223a812504cfea858edf241f93255.m3u8?auth_key=1618455146-0-0-473ebb9ef6c40a3147c90a2cd0a444ba&aliyunols=on&lhs_start_human_s_8=20210412105226&lhs_vodend_human_s_8=20210412113337";

        System.out.println(HttpClientHelper.sendGetAndGetFileContent(url,false));

//    	Map<String, Object> map = new HashMap<String, Object>();
//    	map.put("page", 1);
//    	map.put("count", 10);
//    	System.out.println(sendPost("http://lc.test.gifshow.com/rest/n/partner/xinhua/search", map, "utf-8"));
//
    }
}

class MyX509TrustManager implements X509TrustManager {
    public void checkClientTrusted(X509Certificate[] chain, String authType)
            throws CertificateException {
    }

    public void checkServerTrusted(X509Certificate[] chain, String authType)
            throws CertificateException {
    }

    public X509Certificate[] getAcceptedIssuers() {
        return null;
    }
}
