package com.winsun.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.winsun.auth.core.util.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
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.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLContext;
import javax.security.cert.CertificateException;
import javax.security.cert.X509Certificate;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;

/**
 * HTTP请求封装
 *
 *
 */
public class HttpHelper {

	 private static Logger log = LoggerFactory.getLogger(HttpHelper.class);


    /**
     * @desc ：1.发起GET请求
     *
     * @param url
     * @return JSONObject
     * @throws Exception
     */
    public static JSONObject doGet(String url) throws Exception {

        //1.生成一个请求
        HttpGet httpGet = new HttpGet(url);
        //2.配置请求的属性
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(50000).setConnectTimeout(50000).build();//2000
        httpGet.setConfig(requestConfig);

        //3.发起请求，获取响应信息
        //3.1 创建httpClient
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        try {
            //3.2 发起请求，获取响应信息
            response = httpClient.execute(httpGet, new BasicHttpContext());

            //如果返回结果的code不等于200，说明出错了
            if (response.getStatusLine().getStatusCode() != 200) {

               /* log.info("request url failed, http code=" + response.getStatusLine().getStatusCode()
                        + ", url=" + url);*/
                return null;
            }
            //4.解析请求结果
            HttpEntity entity = response.getEntity();      //reponse返回的数据在entity中
            if (entity != null) {
                String resultStr = EntityUtils.toString(entity, "utf-8");  //将数据转化为string格式
               log.info("GET请求结果："+resultStr);
                JSONObject result = JSON.parseObject(resultStr);    //将String转换为 JSONObject
                log.info("GET请求结果："+resultStr);
                if(result.getInteger("errcode")==null) {
                    return result;
                }else if (0 == result.getInteger("errcode")) {
                    return result;
                }else {
                   // log.info("request url=" + url + ",return value="+resultStr);
                   // log.info(resultStr);
                    int errCode = result.getInteger("errcode");
                    String errMsg = result.getString("errmsg");
                    throw new Exception("error code:"+errCode+", error message:"+errMsg);
                }
            }
        } catch (IOException e) {
            log.error("http请求异常"+e.getMessage(), e);
        } finally {
       IOUtils.closeQuite(response,httpClient);
        }

        return null;
    }


    /** 2.发起POST请求
     * @desc ：
     *
     * @param url   请求url
     * @param data  请求参数（json）
     * @return
     * @throws Exception JSONObject
     */
    public static JSONObject doPost(String url, String data) throws Exception {
        //1.生成一个请求
        HttpPost httpPost = new HttpPost(url);

        //2.配置请求属性
        //2.1 设置请求超时时间
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(100000).setConnectTimeout(100000).build();
        httpPost.setConfig(requestConfig);
        //2.2 设置数据传输格式-json
        httpPost.addHeader("Content-Type", "application/json");
        //2.3 设置请求实体，封装了请求参数
        StringEntity requestEntity = new StringEntity(data, "utf-8");
        httpPost.setEntity(requestEntity);

        //3.发起请求，获取响应信息
        //3.1 创建httpClient
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;

        try {
            //3.3 发起请求，获取响应
            response = httpClient.execute(httpPost, new BasicHttpContext());

            if (response.getStatusLine().getStatusCode() != 200) {

                log.info("request url failed, http code=" + response.getStatusLine().getStatusCode()
                        + ", url=" + url);
                return null;
            }

            //获取响应内容
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String resultStr = EntityUtils.toString(entity, "utf-8");
              //  log.info("POST请求结果："+resultStr);

                //解析响应内容
                JSONObject result = JSON.parseObject(resultStr);

                if(result.getInteger("errcode")==null) {
                    return result;
                }else if (0 == result.getInteger("errcode")) {
                    return result;
                }else {
                   /* log.info("request url=" + url + ",return value="+resultStr);*/
                    //log.info(resultStr);
                    int errCode = result.getInteger("errcode");
                    String errMsg = result.getString("errmsg");
                    throw new Exception("error code:"+errCode+", error message:"+errMsg);
                }
            }
        } catch (IOException e) {
            log.error("http请求异常"+e.getMessage(), e);
        } finally {
            IOUtils.closeQuite(response,httpClient);
        }

        return null;
    }

    // 新方法 走代理
    public static String sendGet(String url) {
        String string = "";
        CloseableHttpClient httpClient = HttpClients.createDefault();

        HttpPost httpPost = new HttpPost(url);
        try {
            HttpHost proxy = new HttpHost("172.18.101.170", 3128);
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(200000).setConnectTimeout(200000).setProxy(proxy).build();

            httpPost.setConfig(requestConfig);
            CloseableHttpResponse result = httpClient.execute(httpPost);
            string =  EntityUtils.toString(result.getEntity(), "utf-8"); ;

        } catch (ClientProtocolException e) {
            log.error("http代理请求异常"+e.getMessage(), e);
        } catch (IOException e) {
            log.error("http代理请求异常"+e.getMessage(), e);
        } catch (IllegalStateException e) {
            log.error("http代理请求异常"+e.getMessage(), e);
        }
        log.info("GET请求结果："+string);
        return string;
    }


    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    // 走代理
    public static String sendPost(String url, String param) {
        String string = "";

        CloseableHttpClient httpClient = createSSLClientDefault();
        HttpPost httpPost = new HttpPost(url);
        StringEntity s = new StringEntity(param, "UTF-8"); // 中文乱码在此解决
        s.setContentType("application/json");
        httpPost.setEntity(s);
        HttpResponse res;

        try {
            HttpHost proxy = new HttpHost("172.18.101.170", 3128);
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(200000).setConnectTimeout(200000).setProxy(proxy).build();

            httpPost.setConfig(requestConfig);
            CloseableHttpResponse result = httpClient.execute(httpPost);
            string =  EntityUtils.toString(result.getEntity(), "utf-8");

        } catch (ClientProtocolException e) {
            log.error("http代理请求异常"+e.getMessage(), e);
        } catch (IOException e) {
            log.error("http代理请求异常"+e.getMessage(), e);
        } catch (IllegalStateException e) {
            log.error("http代理请求异常"+e.getMessage(), e);
        }finally {
            IOUtils.closeQuite(httpClient);
        }

        return string;
    }

    public static CloseableHttpClient createSSLClientDefault() {
        try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(
                    null, new TrustStrategy() {
                        // 信任所有
                        public boolean isTrusted(X509Certificate[] chain,
                                                 String authType) throws CertificateException {
                            return true;
                        }

                        @Override
                        public boolean isTrusted(
                                java.security.cert.X509Certificate[] arg0,
                                String arg1)
                                throws java.security.cert.CertificateException {
                            // TODO Auto-generated method stub
                            return false;
                        }
                    }).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                    sslContext);
            return HttpClients.custom().setSSLSocketFactory(sslsf).build();
        } catch (KeyManagementException e) {
            log.error("http代理请求异常"+e.getMessage(), e);
        } catch (NoSuchAlgorithmException e) {
            log.error("http代理请求异常"+e.getMessage(), e);
        } catch (KeyStoreException e) {
            log.error("http代理请求异常"+e.getMessage(), e);
        }
        return HttpClients.createDefault();
    }

}
