package com.ibeetl.admin.flow.utils;

import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
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.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.*;
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 接口请求帮助类
 */
public class HttpClientUtil {

    private static String CHAR_SET="UTF-8";

    /**
     * get请求
     * @param url
     * @param params
     * @return
     */
    public static String httpClienOfGet(String url, Map<String,Object> params){
        String res = "";
        StringBuilder paramsStr = new StringBuilder();
        if(params != null && params.size() > 0){
            for(String key : params.keySet()){
                paramsStr.append(key);
                paramsStr.append("=");
                try {
                    paramsStr.append(URLEncoder.encode(String.valueOf(params.get(key)),CHAR_SET));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                paramsStr.append("&");
            }
        }

        if(paramsStr != null && paramsStr.length() > 0){
            url = url + "?" + paramsStr.substring(0,paramsStr.length() - 1);
        }
        System.out.println("--------url-------"+url);
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        try {
            HttpResponse response = httpClient.execute(httpGet);
            if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                res = EntityUtils.toString(response.getEntity());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(httpClient != null){
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return res;
    }

    /**
     * post请求
     * @param url
     * @return
     */
    public static String httpClientOfPost(String url, Map<String, Object> createMap){
        HttpClient httpClient = null;
        HttpPost httpPost = null;
        String charset="UTF-8";
        String result = null;
        try{
            httpClient= HttpClients.custom().setSSLSocketFactory(getSslsf()).build();
            httpPost = new HttpPost(url);
            //设置参数
            List<NameValuePair> list = new ArrayList<NameValuePair>();
            Iterator iterator = createMap.entrySet().iterator();
            while(iterator.hasNext()){
                Map.Entry<String,String> elem = (Map.Entry<String, String>) iterator.next();
                list.add(new BasicNameValuePair(elem.getKey(),elem.getValue()));
            }
            if(list.size() > 0){
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,charset);
                httpPost.setEntity(entity);
            }
            HttpResponse response = httpClient.execute(httpPost);
            if(response != null){
                HttpEntity resEntity = response.getEntity();
                if(resEntity != null){
                    result = EntityUtils.toString(resEntity,charset);
                }
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }
        return result;
    }

    /**
     * json结构字符串Post请求
     * @param url
     * @param param
     * @return
     */
    public static String jsonOfPost(String url, String param){
        String res = "";
        DefaultHttpClient client = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Accept","application/json");
        httpPost.setHeader("Content-Type","application/json");
        HttpResponse response = null;

        try {
            StringEntity entity = new StringEntity(param,CHAR_SET);
            entity.setContentEncoding(CHAR_SET);
            entity.setContentType("application/json");
            httpPost.setEntity(entity);
            response = client.execute(httpPost);
            StatusLine statusLine = response.getStatusLine();
            int state = statusLine.getStatusCode();
            if(state == org.apache.http.HttpStatus.SC_OK){
                HttpEntity responseEntity = response.getEntity();
                res = EntityUtils.toString(responseEntity);
                return res;
            }else{
                System.out.println("请求出错");
            }
        } catch (Exception e) {
            System.out.println("-----"+url+"-----"+param);
            e.printStackTrace();
        }
        return res;
    }

    public static String httpsPost(String href, String data) throws Exception {
        HttpsURLConnection conn = null;
            try {
                //创建sslContext对象，并使指定的信任管理器初始化
                TrustManager[] tm={new MyX509TrustManager()};
                SSLContext sslContext=SSLContext.getInstance("SSL");
                sslContext.init(null, tm, new java.security.SecureRandom());
                //得到factory对象
                SSLSocketFactory ssf=sslContext.getSocketFactory();
                URL url = new URL(href);
                conn = (HttpsURLConnection) url.openConnection();
                conn.setSSLSocketFactory(ssf);
                conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
                conn.setRequestMethod("POST");
                conn.addRequestProperty("content-type", "text/plain");
                conn.setDoOutput(true);
                conn.setUseCaches(false);
                OutputStream os = conn.getOutputStream();
                os.write(data.getBytes("utf-8"));
                os.flush();
            } finally {
                if(conn != null) {
                    conn.getOutputStream().close();
                }
            }
            if(conn != null) {
                return readInputStream(conn.getInputStream());
            }
            return null;
    }

    /**
     * 解读流
     * @param inStream
     * @return
     * @throws Exception
     */
    public static String readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = null;
        try {
            outStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
            byte[] data = outStream.toByteArray();
            return new String(data, "utf-8");
        } finally{
            if(outStream != null)
                outStream.close();
            if(inStream != null)
                inStream.close();
        }
    }

    private static SSLConnectionSocketFactory getSslsf() throws NoSuchAlgorithmException, KeyManagementException {
        SSLContext sslContext = SSLContext.getInstance("SSL");//sslContext= SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {
            public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {

            }

            public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            }
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        sslContext.init(null, new TrustManager[]{tm}, null);
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        return sslsf;
    }
}
