package com.lightinit.hsdataportal.common;


import com.google.gson.Gson;
import com.lightinit.hsdataportal.common.ssl.MySecureProtocolSocketFactory;
import com.lightinit.hsdataportal.dictionary.DicGitToken;
import com.lightinit.hsdataportal.model.ShareRegisterModel;
import net.sf.json.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.net.URI;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;


public class HttpUtil {

    private static Logger logger = LoggerFactory.getLogger(HttpUtil.class);

    /**
     * @describe:   服务于6.0接口
     * @param url  访问地址
     * @param head 请求头
     * @param req  请求体内容
     **/
    public static String httpPost(String url, Map<String,String> head,Map<String,?> req) throws Exception{
        //声明
        ProtocolSocketFactory fcty = new MySecureProtocolSocketFactory();
        //加入相关的https请求方式
        Protocol.registerProtocol("https", new Protocol("https", fcty, 443));
        //发送请求即可
        HttpClient client = new HttpClient();
        Gson gson = new Gson();
        PostMethod post = new PostMethod(url);
        String str = gson.toJson(req);
        gson.fromJson(str,Map.class) ;
        RequestEntity re = new StringRequestEntity(str,"application/json","utf-8");
        if(head!=null){
            Set<Map.Entry<String,String>> headSet = head.entrySet();
            for (Map.Entry<String, String> entry : headSet) {
                post.setRequestHeader(entry.getKey(),entry.getValue());
            }
        }
        post.setRequestEntity(re);
        int status = client.executeMethod(post);

        System.out.println("=================status:"+status);
        if(status!=200){
            //抛出异常
            byte[] bytes = post.getResponseBody();
            String content = new String(bytes,"UTF-8");
            System.out.println(content);
        }
        String content = post.getResponseBodyAsString();
        System.out.println("Access System authenticate, Response: " + content);

        return content;
    }

    public static String httpPost(String url, Map<String,String> head,String req){
        try {
            //声明
            ProtocolSocketFactory fcty = new MySecureProtocolSocketFactory();
            //加入相关的https请求方式
            Protocol.registerProtocol("https", new Protocol("https", fcty, 443));
            //发送请求即可
            HttpClient client = new HttpClient();
            Gson gson = new Gson();
            PostMethod post = new PostMethod(url);
       /* String str = gson.toJson(req);
        gson.fromJson(str,Map.class) ;*/
            RequestEntity re = new StringRequestEntity(req,"application/json","utf-8");
            if(head!=null){
                Set<Map.Entry<String,String>> headSet = head.entrySet();
                for (Map.Entry<String, String> entry : headSet) {
                    post.setRequestHeader(entry.getKey(),entry.getValue());
                }
            }
            post.setRequestEntity(re);
            int status = client.executeMethod(post);

            System.out.println("=================status:"+status);
            if(status!=200){
                //抛出异常
                byte[] bytes = post.getResponseBody();
                String content = new String(bytes,"UTF-8");
                System.out.println(content);
            }
            String content = post.getResponseBodyAsString();
            System.out.println("Access System authenticate, Response: " + content);

            return content;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
    /**
     * @describe:  服务于5.0接口
     * @param url  请求路径
     * @param head  请求头
     * @param req  请求体内容
     **/
    public static String  httpPost2(String url, Map<String,String> head,Map<String,?> req) throws Exception{
        //声明
        ProtocolSocketFactory fcty = new MySecureProtocolSocketFactory();
        //加入相关的https请求方式
        Protocol.registerProtocol("https", new Protocol("https", fcty, 443));
        //发送请求即可
        HttpClient client = new HttpClient();
        Map<String,Object> strMap = new HashMap();
        Gson gson = new Gson();
        PostMethod post = new PostMethod(url);
        strMap.put("head",head);
        strMap.put("body",req);
        String str = gson.toJson(strMap);
        RequestEntity re = new StringRequestEntity(str,"application/json","utf-8");
        post.setRequestEntity(re);
        int status = client.executeMethod(post);
        System.out.println("Access System authenticate, Status: " + post.getStatusCode());
        System.out.println("Access System authenticate, Response: " + post.getResponseBodyAsString());
        String content = post.getResponseBodyAsString();
        return content;
    }


    public static String httpGet(String url,String accessticket,Map<String,?> param) throws Exception {

        //CloseableHttpClient httpclient = HttpClients.createDefault();
        CloseableHttpClient httpclient = getIgnoeSSLClient();
        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);

            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, (String)param.get(key));
                }
            }
            URI uri = builder.build();

            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);
            if (accessticket!=null)  httpGet.addHeader("accessticket",accessticket);
            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            logger.info("访问的路径为："+url+"状态为:"+response.getStatusLine().getStatusCode());
            if (response.getStatusLine().getStatusCode() == 200) {
                byte[] bytes= EntityUtils.toByteArray(response.getEntity());
                resultString = new String(bytes);
                //resultString = EntityUtils.toString(response.getEntity(), "ISO-8859-1");
                //resultString= Base64.encodeBase64String(bytes);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        logger.info("查询的结果："+resultString);
        return resultString;
    }

    public static String httpGet(String url,Map<String,Object> params) throws Exception {
        return httpGet(url,null,params);
    }

    public static String httpGet(String url,String accessticket) throws Exception {
        return httpGet(url,accessticket,null);
    }


    public static Map<String,Object> strToMap(String message){
        Gson gson = new Gson();
        Map<String,Object> map = new HashMap<String, Object>();
        map = gson.fromJson(message,map.getClass());
        return map;
    }

    public static Map<String,String>  getHead(String appid,String appkey){
        Map<String,String> head = new HashMap<String,String>();
        head.put("appid",appid);
        head.put("appkey",appkey);
        return head;
    }

    public static String getToken(String url, Map<String,String> head,String contentType) throws Exception{
        //声明
        ProtocolSocketFactory fcty = new MySecureProtocolSocketFactory();
        //加入相关的https请求方式
        Protocol.registerProtocol("https", new Protocol("https", fcty, 443));
        //发送请求即可
        HttpClient client = new HttpClient();
//        HttpClient client = new HttpClient();
        PostMethod post = new PostMethod(url);
        String str = DicGitToken.PARAMS;
        RequestEntity re = new StringRequestEntity(str,contentType,"utf-8");
        if(head!=null){
            Set<Map.Entry<String,String>> headSet = head.entrySet();
            for (Map.Entry<String, String> entry : headSet) {
                post.setRequestHeader(entry.getKey(),entry.getValue());
            }
        }
        post.setRequestEntity(re);
        int status = client.executeMethod(post);

        System.out.println("=================status:"+status);
        if(status!=200){
            //抛出异常
            byte[] bytes = post.getResponseBody();
            String content = new String(bytes,"UTF-8");
            System.out.println(content);
        }
        String content = post.getResponseBodyAsString();
        System.out.println("Access System authenticate, Response: " + content);

        return content;
    }

    /**
     * 绕过验证
     *
     * @return
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     */
    public static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {
        SSLContext sc = SSLContext.getInstance("SSLv3");

        // 实现一个X509TrustManager接口，用于绕过验证，不用修改里面的方法
        X509TrustManager trustManager = new X509TrustManager() {
            @Override
            public void checkClientTrusted(
                    X509Certificate[] paramArrayOfX509Certificate,
                    String paramString) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(
                    X509Certificate[] paramArrayOfX509Certificate,
                    String paramString) throws CertificateException {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };

        sc.init(null, new TrustManager[] { trustManager }, null);
        return sc;
    }

    /**
     * 获取忽略证书验证的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;
    }


}
