package mobvista.dmp.datasource.iqiyi;

//import ch.ethz.ssh2.Session;
//import ch.ethz.ssh2.StreamGobbler;
//import ch.ethz.ssh2.Connection;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import mobvista.dmp.util.PropertyUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.*;
import java.util.*;



public class IQiYiLaHuo {

    private static String doneServerUrl = "https://zongheng.iqiyi.com/gh-api/callback/people/checkDone";
    private static String serverUrl = "http://192.168.0.232:8688/dmp/iqiyi/devicePeopleBatch";
    private static String DEFAULTCHARTSET = "UTF-8";

    public static String sign(Map<String, String> params, String secretKey) {
        SortedMap<String, String> sortedParams = new TreeMap<>(params);
        StringBuilder sb = new StringBuilder();
        for (String key : sortedParams.keySet()) {
            String v = sortedParams.get(key);
            sb.append(key).append("=").append(StringUtils.defaultIfEmpty(v,
                    "")).append("&");
        }
        final String data = sb.append(secretKey).toString();
        return DigestUtils.md5Hex(data);
    }


    public static JSONObject request(String deviceId) {


        JSONObject requestObject = new JSONObject();
//        requestObject.put("jobId",2);
//        requestObject.put("sign","1fda16b028ad057b0d49c4955587e99b");
//        requestObject.put("deviceIdType","1");
//        requestObject.put("encryptType","1");

        //android
        requestObject.put("jobId",40);
        requestObject.put("encryptType","1");
        requestObject.put("deviceIdType","1");

        Map<String, String> map = new HashMap<String,String>();       //数据采用的哈希表结构
        //给map中添加元素
        map.put("jobId","40");
        map.put("encryptType","1");
        map.put("deviceIdType","1");
        String secretKey="57bdede217ae941222f470d047c3ceac";
        String signResult = sign(map, secretKey);
        System.out.println(signResult);
        requestObject.put("sign",signResult);

        CloseableHttpClient client = HttpClients.createDefault();

        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(2000).setConnectionRequestTimeout(2000)
                .setSocketTimeout(2000).build();
        HttpPost post = new HttpPost(doneServerUrl);
        post.setHeader("Content-Type","application/json;charset=utf-8");
        JSONObject jsonObject = new JSONObject();
        HttpResponse response;
        try {
            post.setConfig(requestConfig);
            post.setEntity(new StringEntity(requestObject.toJSONString()));
            response = client.execute(post);
            BufferedReader rd = new BufferedReader(
                    new InputStreamReader(response.getEntity().getContent()));
            StringBuilder result = new StringBuilder();
            String line;
            while ((line = rd.readLine()) != null) {
                result.append(line);
                System.out.println(line);
            }
            String s1 = result.toString();
            System.out.println(s1);
            jsonObject = JSON.parseObject(result.toString());
            System.out.println(jsonObject);
        } catch (Exception e) {
            try {
                post.setConfig(requestConfig);
                post.setEntity(new StringEntity(requestObject.toJSONString()));
                response = client.execute(post);
                BufferedReader rd = new BufferedReader(
                        new InputStreamReader(response.getEntity().getContent()));
                StringBuilder result = new StringBuilder();
                String line;
                while ((line = rd.readLine()) != null) {
                    result.append(line);
                }
                jsonObject = JSON.parseObject(result.toString());
            } catch (IOException ex) {
                System.out.println("IOException -->> " + ex.getMessage());
                jsonObject.put("status", -1);
            }
        } finally {
            post.abort();
        }
        return jsonObject;
    }


    public static JSONObject requestToQps(String deviceId) {
        JSONObject requestObject = new JSONObject();
        //android
        requestObject.put("jobId",40);
//        requestObject.put("deviceIds","00041ac949ac71d18e1193d3213e1581,0004ffe7d73e00e49658c3fba47935fd");
        requestObject.put("deviceIds",deviceId);
        requestObject.put("encryptType","1");
        requestObject.put("deviceIdType","1");

        Map<String, String> map = new HashMap<String,String>();       //数据采用的哈希表结构
        //给map中添加元素
        map.put("jobId","40");
//        map.put("deviceIds","00041ac949ac71d18e1193d3213e1581,0004ffe7d73e00e49658c3fba47935fd");
        map.put("deviceIds",deviceId);
        map.put("encryptType","1");
        map.put("deviceIdType","1");
        String secretKey="57bdede217ae941222f470d047c3ceac";
        String signResult = sign(map, secretKey);
        requestObject.put("sign",signResult);

        CloseableHttpClient client = HttpClients.createDefault();

        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(2000).setConnectionRequestTimeout(2000)
                .setSocketTimeout(2000).build();
        HttpPost post = new HttpPost(serverUrl);
        post.setHeader("Content-Type","application/json;charset=utf-8");
        JSONObject jsonObject = new JSONObject();
        HttpResponse response;
        try {
            post.setConfig(requestConfig);
            post.setEntity(new StringEntity(requestObject.toJSONString()));
            response = client.execute(post);
            BufferedReader rd = new BufferedReader(
                    new InputStreamReader(response.getEntity().getContent()));
            StringBuilder result = new StringBuilder();
            String line;
            while ((line = rd.readLine()) != null) {
                result.append(line);
            }
            String s1 = result.toString();
            jsonObject = JSON.parseObject(result.toString());
        } catch (Exception e) {
            try {
                post.setConfig(requestConfig);
                post.setEntity(new StringEntity(requestObject.toJSONString()));
                response = client.execute(post);
                BufferedReader rd = new BufferedReader(
                        new InputStreamReader(response.getEntity().getContent()));
                StringBuilder result = new StringBuilder();
                String line;
                while ((line = rd.readLine()) != null) {
                    result.append(line);
                }
                jsonObject = JSON.parseObject(result.toString());
            } catch (IOException ex) {
                System.out.println("IOException -->> " + ex.getMessage());
                jsonObject.put("status", -1);
            }
        } finally {
            post.abort();
        }
        return jsonObject;
    }

//    public static JSONObject requestQps(String deviceIds) {
//        String key="-----BEGIN RSA PRIVATE KEY-----\n" +
//                "MIIEpQIBAAKCAQEAkqt55XH4xmM0ytstivFa/iRElksV2mjmcD/tCFfE3I3uWlod\n" +
//                "nghIVskUrORBO56iwvJN7/hn1neyZQXnP1FDTX/1wEnRxng28J71U3d/hKk/LQ58\n" +
//                "H9yT022E7MtNi/2qcZgj6DAFxzLk7CIT5vSD0FT622FvdcF8xZHuOMYnZU+s0L68\n" +
//                "nM3i3J+x6fhzMvdacgcbtCmZrV53WxhdLmXhAp+PxpYxiNv5bnDAUmGfu3ABVy7k\n" +
//                "/6qaK6LhrsQcj95bTEgA+DO0hDCylgzZPNOSpImPJYxWNpsYtHEeliPx1KZeczqT\n" +
//                "zpAcmCwAC5FV664gudP/OqsjQeZAo2DN2UzD8QIDAQABAoIBAQCKHlkILS/tAvdw\n" +
//                "IL7enTLnKRg9wC+wIiD/i/OXa6/DUxUmmL5TV9FniKyjs7+KeXUkyDGEzhRa7xVb\n" +
//                "9RczlT8f+GRg1CNsF0EFj2vPUjUPpKINuBpDluDOtc/7fehk8FhV6MPHn5GRaOgT\n" +
//                "RnQfhhurUJt7hGIGLlNlams/o7rtt481130ioPXHxG81xwdlcBnWUHsE6gTpyzim\n" +
//                "Wan/aZ4ZlscrcL3HzsPtVzpo6iKU5fah5B/mzWnauqLl9j7qqVQSdQ1Eg7f1QDW1\n" +
//                "NULwjaUlUh3gq+TsTUeK8rqiYVyfHxQhi1ZKtjBNznuB5rvRPCounGoNiO1xchtm\n" +
//                "VgrWM60BAoGBANdUsh5WxR9oi5LzKZpOy2k3JfoGNpRiCnhSeSlYshNdPamyLEwI\n" +
//                "etLZcpV9rm8CKdEiTCfXdhCIX4xl5p8cpg8CiMKwoTFsbuan3EmDt9lO1d8JUM5F\n" +
//                "3pk2p+lpBBcDOlmKbTgtvAybQ15S3qUy/YwYrBxezugZ6JsA90CkaJY5AoGBAK5f\n" +
//                "AHogiz4IeCz96q8YAe8c3wkRTHYWnUYGX1JCoZyvmXqvruXp/HREE5a6mSjL9GQb\n" +
//                "fQFOLd1pLAOy2dpLvwgHaDO8sSwhIYEcUfG1bCOUF2S0Pgeh8p9H6yHPA41/KM67\n" +
//                "xfmgaVzPPFEmA6cdXvMgdNq0OdTfWjHFDPquM9t5AoGBALsWZm+/uiNw5Rv3U6Uz\n" +
//                "Yr524PMb5N4FVM138rd+zbHPaF0BZkVldLmvnkPOX/kpKwX+w6Y2KOlyY3oLq1WB\n" +
//                "QbJ25DYr2tGjQbP8EoR5Agq32VCgummOATqjZz6ANMJ91nunrv+JlQJrABx66eEk\n" +
//                "rXDEmv1HToQQxq2uKCUs84XZAoGAG3HSdmZm5BWbLKGubW6e506pABlb6n42tM3N\n" +
//                "9PmNzEaLJpc+NOu2E2qflqq57oTja1o0O59dcqraBZ8B0Oz5HT9lNDdvv11bk6Gs\n" +
//                "eBmw8oydffkshjEEKfO8225kxcGM37UIPPj1fGkVukP8cTIbPrMOEVoqfAnHfWvh\n" +
//                "VhdTDCkCgYEAtFjcnLKOoyUIFFEOeQpIDo7DAHgiCdsUw0M3FQXI2AnHl0cHYDkb\n" +
//                "13oH58Gy/1ehoTuw1W8pKNVK27vuvPMHzTGk223TEpjgSKrriMhfo8jtnOXuUWaO\n" +
//                "s7mGXBfPe4837SAhKGA+zJaPwpZciiof9CcfIfcczx9mhjRKLfxxZ+0=\n" +
//                "-----END RSA PRIVATE KEY-----";
//
//        System.out.println("threadnamelogin=="+Thread.currentThread().getName());
//        Connection conn=new Connection("182.92.177.185");
//        System.out.println("conn===========================" + System.identityHashCode(conn));
//        Boolean flag = loginByCharsKey(conn, "root", key.toCharArray(), null);
//        System.out.println("flag=="+flag);
//        System.out.println("deviceIds=="+deviceIds);
//        if(flag==true){
//            String executeResult = execute(conn,String.format("java -cp /root/jiangfan/test03/scalatest-1.0-SNAPSHOT-jar-with-dependencies.jar mytest.IQiYiLaHuo %s",deviceIds));
//            System.out.println("====================================================111====");
//            System.out.println("executeResult=="+executeResult);
//            JSONObject jsonObject = JSON.parseObject(executeResult);
//            System.out.println("jsonObject=="+jsonObject);
//            return jsonObject;
//        }else{
//            return null;
//        }
//    }

    public static JSONObject requestHttpQps(String deviceIds,String encryptType,String deviceIdType) {
        System.out.println("threadnamehttp=="+Thread.currentThread().getName());
        JSONObject requestObject = new JSONObject();
        requestObject.put("deviceIds",deviceIds);
        requestObject.put("encryptType",encryptType);
        requestObject.put("deviceIdType",deviceIdType);

        CloseableHttpClient client = HttpClients.createDefault();

        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(3000).setConnectionRequestTimeout(3000)
                .setSocketTimeout(3000).build();
        HttpPost post = new HttpPost(serverUrl);
        post.setHeader("Content-Type","application/json;charset=utf-8");
        JSONObject jsonObject = new JSONObject();
        HttpResponse response;
        try {
            post.setConfig(requestConfig);
            post.setEntity(new StringEntity(requestObject.toJSONString()));
            response = client.execute(post);
            BufferedReader rd = new BufferedReader(
                    new InputStreamReader(response.getEntity().getContent()));
            StringBuilder result = new StringBuilder();
            String line;
            while ((line = rd.readLine()) != null) {
                result.append(line);
            }
            jsonObject = JSON.parseObject(result.toString());
        } catch (Exception e) {
            try {
                post.setConfig(requestConfig);
                post.setEntity(new StringEntity(requestObject.toJSONString()));
                response = client.execute(post);
                BufferedReader rd = new BufferedReader(
                        new InputStreamReader(response.getEntity().getContent()));
                StringBuilder result = new StringBuilder();
                String line;
                while ((line = rd.readLine()) != null) {
                    result.append(line);
                }
                jsonObject = JSON.parseObject(result.toString());
            } catch (IOException ex) {
                System.out.println("httpconnect IOException -->> " + ex.getMessage());
                jsonObject.put("status", -1);
            }
        } finally {
            post.abort();
        }
        return jsonObject;
    }


//
//    public static Boolean loginByCharsKey(Connection conn, String UserName, char[] keys, String keyPass) {
//        boolean flag = false;
//        try {
//            conn.connect();
//            // 登录认证
//            flag = conn.authenticateWithPublicKey(UserName, keys, keyPass);
//            if (!flag) {
//                System.out.println("loginByCharKey failed~~~~~");
//                conn.close();
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return flag;
//    }
//
//    public static String execute(Connection conn,String cmd){
//        String result = "";
//        try {
//            Session session = conn.openSession();// 打开一个会话
//            session.execCommand(cmd);// 执行命令
//            result = processStdout(session.getStdout(), DEFAULTCHARTSET);
//            // 如果为得到标准输出为空,说明脚本执行出错了
//            if (StringUtils.isBlank(result)) {
//                result = processStdout(session.getStderr(), DEFAULTCHARTSET);
//            }
//            conn.close();
//            session.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return result;
//    }
//
//    public static String processStdout(InputStream in, String charset) {
//        InputStream stdout = new StreamGobbler(in);
//        StringBuffer buffer = new StringBuffer();
//        try {
//            BufferedReader br = new BufferedReader(new InputStreamReader(stdout, charset));
//            String line = null;
//            while ((line = br.readLine()) != null) {
//                buffer.append(line + "\n");
//            }
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return buffer.toString();
//    }

    public static void main(String[] args) {
//        String deviceId=args[0];
//        JSONObject request = request(deviceId);
//        JSONObject request = requestQps(deviceId);
//        System.out.println(request);
    }
}