package com.lightinit.hsdataplatformresdir.common;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
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.SSLContexts;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;
//import org.apache.xmlbeans.impl.common.NameUtil;
import org.springframework.util.StringUtils;

import javax.net.ssl.SSLContext;

/**
 * Created by Mr.Yao on 2017/5/4.
 */
public class HttpTookitUtils {
    public static int getApplicationStatus(String url) {
        int statusCode=-1;
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpGet httpget = new HttpGet(url);
            CloseableHttpResponse response = httpclient.execute(httpget);
            try {
                StatusLine statusLine = response.getStatusLine();
                statusCode= statusLine.getStatusCode();
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return statusCode;
    }
    public static String doGet(String url, List<NameValuePair> params, CharEncoding charset,String accept) {
        String responseContent="";
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            String queryParams="";
            if(params!= null) {
                for (NameValuePair pair : params) {
                    if (queryParams.length() > 0) {
                        queryParams += "&";
                    }
                    queryParams += pair.getName() + "=" + pair.getValue();
                }
            }
            if(StringUtils.isEmpty(queryParams)==false){
                if(url.contains("?")){
                    url+="&";
                }else{
                    url+="?";
                }
                url+=queryParams;
            }
            HttpGet httpget = new HttpGet(url);
            if(StringUtils.isEmpty(accept)==false)
                httpget.addHeader("Accept",accept);
            CloseableHttpResponse response = httpclient.execute(httpget);
            try {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    responseContent= EntityUtils.toString(entity, charset.value());
                }
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseContent;
    }
    public static String doGet(String url, List<NameValuePair> params, CharEncoding charset) {
        return doGet(url,params,charset,"");
    }
    public static String doPost(String url, List<NameValuePair> params, CharEncoding charset){
        return doPost(url,params,charset,"");
    }
    public static String doPost(String url, List<NameValuePair> params, CharEncoding charset,String accept) {
        String responseContent="";
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httppost = new HttpPost(url);
        if(StringUtils.isEmpty(accept)==false)
            httppost.addHeader("Accept",accept);
        UrlEncodedFormEntity uefEntity;
        try {
            uefEntity = new UrlEncodedFormEntity(params, charset.value());
            httppost.setEntity(uefEntity);
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    responseContent=EntityUtils.toString(entity, charset.value());
                }
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseContent;
    }

    public static String doPost(String url, List<NameValuePair> params, CharEncoding charset, Map<String,String> headers) throws Exception {
        String responseContent="";
        CloseableHttpClient httpclient = getIgnoeSSLClient();
        HttpPost httppost = new HttpPost(url);
        if(headers!=null) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                httppost.addHeader(entry.getKey(), entry.getValue());
            }
        }
        UrlEncodedFormEntity uefEntity;
        try {
            uefEntity = new UrlEncodedFormEntity(params, charset.value());
            httppost.setEntity(uefEntity);
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    responseContent=EntityUtils.toString(entity, charset.value());
                }
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseContent;
    }

    public static String doPost(String url, String body, CharEncoding charset) {
        String responseContent="";
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httppost = new HttpPost(url);
        try {
            StringEntity uefEntity=new StringEntity(body, charset.value());
            httppost.setEntity(uefEntity);
            httppost.addHeader("Content-type","application/json");
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    responseContent=EntityUtils.toString(entity, charset.value());
                }
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseContent;
    }

    /**
     * 获取忽略证书验证的client
     *
     * @return
     * @throws Exception
     */

    public static CloseableHttpClient getIgnoeSSLClient() throws Exception {
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                return true;
            }
        }).build();

        //创建httpClient
        CloseableHttpClient client = HttpClients.custom().setSSLContext(sslContext).
                setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
        return client;
    }
}
