package com.zcloud.util.docking;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;

/*
 * 利用HttpClient进行post请求的工具类
 */
@Component
public class HttpClientUtil {

    private final static String http = "https://218.11.12.147";

    public static CloseableHttpClient createSSLClientDefault() {
        try {
            //使用 loadTrustMaterial() 方法实现一个信任策略，信任所有证书
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                // 信任所有
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            }).build();
            //NoopHostnameVerifier类:  作为主机名验证工具，实质上关闭了主机名验证，它接受任何
            //有效的SSL会话并匹配到目标主机。
            HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
            return HttpClients.custom().setSSLSocketFactory(sslsf).build();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        }
        return HttpClients.createDefault();

    }

    public JSONObject doPost(String url, String token, String jsonText) {
        CloseableHttpClient httpClient = null;
        HttpPost post = null;
        String result = null;
        StringEntity se = null;
        try {
            httpClient = createSSLClientDefault();
            post = new HttpPost(http + url);
            post.setHeader("Content-Type", "application/json;charset=UTF-8");
            post.setHeader("Authorization", token);
            se = new StringEntity(jsonText, "UTF-8");
            se.setContentType("application/json");
            post.setEntity(se);
            HttpResponse response = httpClient.execute(post);
            String resultData = EntityUtils.toString(response.getEntity());
            System.out.println("请求参数:[" + jsonText + "]\n");
            System.out.println("返回参数:[" + resultData + "]\n");
            httpClient.close();
            return JSON.parseObject(resultData);

//            this.getResult(token,result);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    public String getResult(String token, String batchId) {
        CloseableHttpClient httpClient = null;
        HttpPost post = null;
        String result = null;
        StringEntity se = null;
        try {
            httpClient = createSSLClientDefault();
            post = new HttpPost(http + "/taskSys/busi/syf/getLog");
            post.setHeader("Content-Type", "application/json;charset=UTF-8");
            post.setHeader("Authorization", token);
            JSONObject json = new JSONObject();
            List<String> list = new ArrayList<String>();
            list.add(batchId);
            json.put("batchId", list);
            se = new StringEntity(json.toJSONString(), "UTF-8");
            se.setContentType("application/json");
            post.setEntity(se);

            HttpResponse response = httpClient.execute(post);
            HttpEntity entity = response.getEntity();
            String resultData = EntityUtils.toString(response.getEntity());
            System.out.println("查询-请求参数:[" + json + "]\n");
            System.out.println("查询-返回参数:[" + resultData + "]\n");
            JSONObject jsonObject = (JSONObject) JSON.parse(resultData);
            JSONObject data = (JSONObject) JSON.parse(jsonObject.get("data").toString());
            JSONArray objArray = (JSONArray) JSON.parse(data.get("obj").toString());
            JSONObject obj = (JSONObject) JSON.parse(objArray.get(0).toString());
            result = obj.get("status").toString();
            result = obj.toJSONString();
            //最后关闭HttpClient资源
            httpClient.close();
            System.out.println("查询结果：" + obj.get("status").toString() + "\n");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return result;
    }

}
