package com.bonus.boot.manager.manager.controller;

import com.alibaba.fastjson.JSONObject;
import com.bonus.boot.manager.manager.utils.StringHelper;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.ParseException;
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.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.ssl.SSLContextBuilder;
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 java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;

public class HttpClientUtils {
    private static final String CHARSET = "utf-8";
    private static final String CONTENT_TYPE_TEXT_JSON = "text/json";

    /**
     * Header参数
     */
    private static final String Authorization = "Authorization";

    private static SSLConnectionSocketFactory sslConnectionSocketFactory;
    private static RequestConfig config;

    /**
     * 单例实现token
     */
    private String accessToken = null;

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

    public String getAccessToken() {
        return accessToken;
    }

    public void setAccessToken(String accessToken) {
        this.accessToken = accessToken;
    }

    public   void HttpClientUtils() {
        initTrustHosts();
        initConfig();
    }

    private static void initTrustHosts() {
        try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            }).build();
            sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        }catch (Exception e) {
            e.getStackTrace();
        }
    }

    private static void initConfig() {
        config = RequestConfig.custom().setConnectTimeout(10000000).setSocketTimeout(10000000).build();
    }
    public String doPost(String url, String token, Map<String, Object> params) {
        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(url);
        // 创建json参数
        JSONObject jsonObject = new JSONObject();
        for (String key:params.keySet()){
            jsonObject.put(key,params.get(key));
        }
        // 模拟表单
        //UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
        // 将user对象转换为json字符串，并放入entity中
        StringEntity entity = new StringEntity(jsonObject.toJSONString(), ContentType.APPLICATION_JSON);
        // post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
        httpPost.setEntity(entity);
        httpPost.setHeader("Content-Type", "application/json;charset=utf8");
        httpPost.setHeader(Authorization, "Bearer " + token);
        // 响应模型
        CloseableHttpResponse response = null;
        String result = null;
        try {
            // 由客户端执行(发送)Post请求
            response = httpClient.execute(httpPost);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();

            //System.out.println("响应状态为:" + response.getStatusLine());
            if (responseEntity != null) {
                result = EntityUtils.toString(responseEntity);
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return result;
    }
    public static String doHttpPost(String uri, JSONObject jsonObject, String token) {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        CloseableHttpResponse response = null;
        try {
            HttpPost httpPost = new HttpPost(uri);
            RequestConfig config = RequestConfig.custom()
                    .setConnectTimeout(60*1000) //连接超时时间
                    .setConnectionRequestTimeout(6000) //从连接池中取的连接的最长时间
                    .setSocketTimeout(30*60*1000) //数据传输的超时时间
                    .build();
            //设置请求配置时间
            httpPost.setConfig(config);
            //装填参数
            StringEntity s = new StringEntity(jsonObject.toString(), "utf-8");
            s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            //设置参数到请求对象中
            httpPost.setEntity(s);
            httpPost.setHeader("Content-type", "application/json");
            if(StringHelper.isNotEmpty(token)){
                httpPost.setHeader("Authorization", token);
            }
            httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            response = httpClient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            System.out.println("statusCode:" +statusCode );
            if (HttpStatus.SC_OK == statusCode) {
                HttpEntity entity = response.getEntity();
                if (null != entity) {
                    String resStr = EntityUtils.toString(entity, "utf-8");
                    return resStr;
                }
            }
        } catch (Exception e) {
            System.out.println("CloseableHttpClient-post-请求异常:" + e.getMessage()+",case" + String.valueOf(e.getStackTrace()));
        } finally {
            try {
                if (null != response) {
                    EntityUtils.consume(response.getEntity());
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}


