package com.huimv.admin.device.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.*;

/**
 * @Project : huimv.shiwan
 * @Package : com.huimv.biosafety.uface.controller
 * @Description : TODO
 * @Version : 1.0
 * @Author : ZhuoNing
 * @Create : 2020-12-25
 **/
@Component
public class HttpTemplete {
    private String testHttpIp = "http://localhost:9105";

//    public static void main(String[] args) throws Exception {
//        //
//        HttpTemplete client = new HttpTemplete();
////        client.testGetRequest1();
//        client.testGetRequest2();
//    }
    private Integer connectTimeout = null;
    private Integer requestTimeout = null;
    private Integer socketTimeout = null;

    static {
    }

    //发送简单数据
    public void doPostSimple(String serviceUrl,String data){
        System.out.println("推送数据地址："+serviceUrl);
        //
        Map<String,String> paramsMap = new HashMap<String,String>();
        paramsMap.put("data", data);
        //
        Map<String,Integer> timeoutMap = new HashMap<String,Integer>();
        timeoutMap.put("connectTimeout", 5000);
        timeoutMap.put("requestTimeout", 5000);
        timeoutMap.put("socketTimeout", 5000);
        try{
            // 用Post方法推送接口数据
            doPost(serviceUrl,paramsMap,timeoutMap);
        } catch (IOException e) {
            System.out.println("###错误信息："+e.getMessage());
            System.out.println("###错误信息："+e.getLocalizedMessage());
            e.printStackTrace();
        }
    }


    /**
     * @Method      : doPost
     * @Description : post方式推送接口
     * @Params      : [url, paramsMap, timeoutMap]
     * @Return      : com.alibaba.fastjson.JSONObject
     * 
     * @Author      : ZhuoNing
     * @Date        : 2021/11/19       
     * @Time        : 14:55
     */
    public JSONObject doPost(String url, Map<String, String> paramsMap, Map<String, Integer> timeoutMap) throws IOException {
        // 创建默认的httpClient实例.
        CloseableHttpClient httpClient = getHttpClientConnection();
        //
        int connectTimeout = timeoutMap.get("connectTimeout");
        int requestTimeout = timeoutMap.get("requestTimeout");
        int socketTimeout = timeoutMap.get("socketTimeout");
        // 创建httpPost
        HttpPost httpPost = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(socketTimeout) //服务器响应超时时间
                .setConnectTimeout(connectTimeout) //连接服务器超时时间
                .setConnectionRequestTimeout(requestTimeout)
                .build();
        httpPost.setConfig(requestConfig);
        // 创建参数队列
        List<NameValuePair> paramsList = new ArrayList<NameValuePair>();
        Set<Map.Entry<String, String>> entrySet = paramsMap.entrySet();
        for (Map.Entry<String, String> e : entrySet) {
            String name = e.getKey();
            String value = e.getValue();
            NameValuePair pair = new BasicNameValuePair(name, value);
            paramsList.add(pair);
        }
        UrlEncodedFormEntity content = new UrlEncodedFormEntity(paramsList, "UTF-8");
        //处理乱码
//        StringEntity content = new StringEntity(paramsList.toString(), Charset.forName("UTF-8"));// 第二个参数，设置后才会对，内容进行编码
//        content.setContentType("application/soap+xml; charset=UTF-8");
//        content.setContentEncoding("UTF-8");
        httpPost.setEntity(content);
//        HttpUriRequest httpPost = RequestBuilder.post().setUri(url).setEntity(content).setConfig(requestConfig);
        CloseableHttpResponse response = httpClient.execute(httpPost);
        // 获取响应实体
        HttpEntity entity = response.getEntity();
        try {
            if (response.getStatusLine().getStatusCode() == 200) {
                // 打印响应内容
                String text = EntityUtils.toString(entity, "utf-8");
                JSONObject resultJo = new JSONObject();
                resultJo.put("status", true);
                resultJo.put("content", text);
                return resultJo;
            }else{
                String text = EntityUtils.toString(entity, "utf-8");
                JSONObject resultJo = new JSONObject();
                resultJo.put("status", false);
                resultJo.put("content", text);
                return resultJo;
            }
        } finally {
            //释放资源
            if (response != null) {
                response.close();
            }
            if (httpClient != null) {
                httpClient.close();
            }
        }
    }

    /**
     * @Method      : setTimeout
     * @Description : 
     * @Params      : [connectTimeout, requestTimeout, socketTimeout]
     * @Return      : void
     * 
     * @Author      : ZhuoNing
     * @Date        : 2021/11/23       
     * @Time        : 9:36
     */
    public Map<String, Integer> setTimeout(Integer connectTimeout, Integer requestTimeout, Integer socketTimeout){
        //
        if(connectTimeout == null){
            this.connectTimeout = 3000;
        }else{
            this.connectTimeout = connectTimeout;
        }
        //
        if(requestTimeout == null){
            this.requestTimeout = 3000;
        }else{
            this.requestTimeout = requestTimeout;
        }
        //
        if(socketTimeout == null){
            this.socketTimeout = 3000;
        }else{
            this.socketTimeout = socketTimeout;
        }
        Map<String, Integer> timeoutMap = new HashMap<String, Integer>();
        timeoutMap.put("connectTimeout", this.connectTimeout);
        timeoutMap.put("requestTimeout", this.requestTimeout);
        timeoutMap.put("socketTimeout", this.socketTimeout);
        return timeoutMap;
    }

    /**
     * @Method      : setTimeout
     * @Description : 
     * @Params      : [connectTimeout, requestTimeout, socketTimeout]
     * @Return      : java.util.Map<java.lang.String,java.lang.Integer>
     * 
     * @Author      : ZhuoNing
     * @Date        : 2021/11/23       
     * @Time        : 9:41
     */
    public Map<String, Integer> setTimeout(String connectTimeout, String requestTimeout, String socketTimeout){
        //
        if(connectTimeout == null){
            this.connectTimeout = 3000;
        }else{
            this.connectTimeout = Integer.parseInt(connectTimeout);
        }
        //
        if(requestTimeout == null){
            this.requestTimeout = 3000;
        }else{
            this.requestTimeout = Integer.parseInt(requestTimeout);
        }
        //
        if(socketTimeout == null){
            this.socketTimeout = 3000;
        }else{
            this.socketTimeout = Integer.parseInt(socketTimeout);
        }
        Map<String, Integer> timeoutMap = new HashMap<String, Integer>();
        timeoutMap.put("connectTimeout", this.connectTimeout);
        timeoutMap.put("requestTimeout", this.requestTimeout);
        timeoutMap.put("socketTimeout", this.socketTimeout);
        return timeoutMap;
    }

    /**
     * @Method      : doGet
     * @Description : 
     * @Params      : [url, paramsMap]
     * @Return      : com.alibaba.fastjson.JSONObject
     * 
     * @Author      : ZhuoNing
     * @Date        : 2021/11/23       
     * @Time        : 9:34
     */
    public JSONObject doGet(String url, Map<String, String> paramsMap) throws IOException {
        //
        if(this.connectTimeout == null){
            this.connectTimeout = 3000;
        }
        //
        if(this.requestTimeout == null)
        {
            this.requestTimeout = 3000;
        }
        //
        if(this.socketTimeout == null){
            this.socketTimeout = 3000;
        }
        Map<String, Integer> timeoutMap = new HashMap<String, Integer>();
        timeoutMap.put("connectTimeout", this.connectTimeout);
        timeoutMap.put("requestTimeout", this.requestTimeout);
        timeoutMap.put("socketTimeout", this.socketTimeout);
        //
        CloseableHttpClient httpClient = getHttpClientConnection();
        //执行//获取请求内容
        CloseableHttpResponse response = httpClient.execute(getHttpRequest(url, paramsMap, timeoutMap));
        try {
            // 获取响应实体
            HttpEntity entity = response.getEntity();
            // 打印响应状态
            if (response.getStatusLine().getStatusCode() == 200) {
                // 打印响应内容
                String text = EntityUtils.toString(entity, "utf-8");
                JSONObject resultJo = new JSONObject();
                resultJo.put("status", true);
                resultJo.put("content", text);
                return resultJo;
            } else {
                String text = EntityUtils.toString(entity, "utf-8");
                JSONObject resultJo = new JSONObject();
                resultJo.put("status", false);
                resultJo.put("content", text);
                return resultJo;
            }
        } finally {
            //释放资源
            if (response != null) {
                response.close();
            }
            if (httpClient != null) {
                httpClient.close();
            }
        }
    }

    private CloseableHttpClient httpClient = null;
    private CloseableHttpResponse response = null;

    public JSONObject doGetBatch(String url, Map<String, String> paramsMap) throws IOException {
        //
        if(this.connectTimeout == null){
            this.connectTimeout = 3000;
        }
        //
        if(this.requestTimeout == null)
        {
            this.requestTimeout = 3000;
        }
        //
        if(this.socketTimeout == null){
            this.socketTimeout = 3000;
        }
        Map<String, Integer> timeoutMap = new HashMap<String, Integer>();
        timeoutMap.put("connectTimeout", this.connectTimeout);
        timeoutMap.put("requestTimeout", this.requestTimeout);
        timeoutMap.put("socketTimeout", this.socketTimeout);
        //
        httpClient = getHttpClientConnection();
        //执行//获取请求内容
        response = httpClient.execute(getHttpRequest(url, paramsMap, timeoutMap));
        // 获取响应实体
        HttpEntity entity = response.getEntity();
        // 打印响应状态
        if (response.getStatusLine().getStatusCode() == 200) {
                // 打印响应内容
                String text = EntityUtils.toString(entity, "utf-8");
                JSONObject resultJo = new JSONObject();
                resultJo.put("status", true);
                resultJo.put("content", text);
                return resultJo;
        } else {
                String text = EntityUtils.toString(entity, "utf-8");
                JSONObject resultJo = new JSONObject();
                resultJo.put("status", false);
                resultJo.put("content", text);
                return resultJo;
        }
    }

    //关闭http连接
    public void closeHttpConn() throws IOException {
        System.out.println("开始释放http连接资源");
        //释放资源
        if (response != null) {
            response.close();
        }
        if (httpClient != null) {
            httpClient.close();
        }
    }

    /**
     * @Method : doGet
     * @Description :get方式推送接口
     * @Params : [url, paramsMap, timeoutMap]
     * @Return : com.alibaba.fastjson.JSONObject
     * @Author : ZhuoNing
     * @Date : 2021/11/18
     * @Time : 17:39
     */
    public JSONObject doGet(String url, Map<String, String> paramsMap, Map<String, Integer> timeoutMap) throws IOException {
        if (timeoutMap == null) {
            timeoutMap.put("connectTimeout", 5000);
            timeoutMap.put("requestTimeout", 5000);
            timeoutMap.put("socketTimeout", 5000);
        }
        //
        CloseableHttpClient httpClient = getHttpClientConnection();
        //执行//获取请求内容
        CloseableHttpResponse response = httpClient.execute(getHttpRequest(url, paramsMap, timeoutMap));
        try {
            // 获取响应实体
            HttpEntity entity = response.getEntity();
            // 打印响应状态
            if (response.getStatusLine().getStatusCode() == 200) {
                // 打印响应内容
                String text = EntityUtils.toString(entity, "utf-8");
                JSONObject resultJo = new JSONObject();
                resultJo.put("status", true);
                resultJo.put("content", text);
                return resultJo;
            } else {
                String text = EntityUtils.toString(entity, "utf-8");
                JSONObject resultJo = new JSONObject();
                resultJo.put("status", false);
                resultJo.put("content", text);
                return resultJo;
            }
        } finally {
            //释放资源
            if (response != null) {
                response.close();
            }
            if (httpClient != null) {
                httpClient.close();
            }
        }
    }

    private void testGetRequest1() throws IOException {
        Map<String, Integer> timeoutMap = new HashMap<String, Integer>();
        timeoutMap.put("connectTimeout", 5000);
        timeoutMap.put("requestTimeout", 5000);
        timeoutMap.put("socketTimeout", 5000);
        String url = testHttpIp + "/token/getToken?userId=20210501&timestamp=45546546454&random=1156&sign=7fa431325504e01e9fa87ed0e274c40c";
        // test error
        url = testHttpIp + "/token/getToken?userId=20210501&timestamp=45546546454&random=1156&sign=7fa431325504e01e9fa87ed0e274c40c&userId=20210501&timestamp=45546546454&random=1156&sign=7fa431325504e01e9fa87ed0e274c40c";
        CloseableHttpClient httpClient = getHttpClientConnection();
        CloseableHttpResponse response = httpClient.execute(getHttpRequest(url, timeoutMap));
        // 打印响应状态
        System.out.println("响应状态1 =" + response.getStatusLine());
        try {
            if (response.getStatusLine().getStatusCode() == 200) {
                // 获取响应实体
                HttpEntity entity = response.getEntity();
                // 打印响应内容
                String text = EntityUtils.toString(entity, "utf-8");
                System.out.println("响应内容=" + text);

                JSONObject resultJo = JSONObject.parseObject(text);
                System.out.println("accessToken=" + resultJo.getString("accessToken"));
            } else {
                System.out.println("请求失败");
            }
        } finally {
            //释放资源
            if (response != null) {
                response.close();
            }
            if (httpClient != null) {
                httpClient.close();
            }
        }
    }

    //
    private CloseableHttpClient getHttpClientConnection() {
        //创建默认实例
        CloseableHttpClient httpclient = HttpClients.createDefault();
        //
//        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        return httpclient;
    }
    //
    private HttpUriRequest getHttpRequest(String url, Map<String, String> map, Map<String, Integer> timeoutMap) {
        int connectTimeout = timeoutMap.get("connectTimeout");
        int requestTimeout = timeoutMap.get("requestTimeout");
        int socketTimeout = timeoutMap.get("socketTimeout");
//        System.out.println("core connectTimeout="+connectTimeout);
//        System.out.println("core requestTimeout="+requestTimeout);
//        System.out.println("core socketTimeout="+socketTimeout);

        List<NameValuePair> params = new ArrayList<NameValuePair>();
        Set<Map.Entry<String, String>> entrySet = map.entrySet();
        for (Map.Entry<String, String> e : entrySet) {
            String name = e.getKey();
            String value = e.getValue();
            NameValuePair pair = new BasicNameValuePair(name, value);
            params.add(pair);
        }
        //
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(connectTimeout).setConnectionRequestTimeout(requestTimeout)
                .setSocketTimeout(socketTimeout).build();
        HttpUriRequest httpGet = RequestBuilder.get().setUri(url)
                .addParameters(params.toArray(new BasicNameValuePair[params.size()]))
                .setConfig(requestConfig).build();
        return httpGet;
    }
    //
    private HttpGet getHttpRequest(String url, Map<String, Integer> timeoutMap) {
        int connectTimeout = timeoutMap.get("connectTimeout");
        int requestTimeout = timeoutMap.get("requestTimeout");
        int socketTimeout = timeoutMap.get("socketTimeout");

        HttpGet httpGet = new HttpGet(url);
        //设置超时时间
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(connectTimeout).setConnectionRequestTimeout(requestTimeout)
                .setSocketTimeout(socketTimeout).build();
        httpGet.setConfig(requestConfig);
        return httpGet;
    }

    //test
    private void get() {
//        CloseableHttpClient httpclient = HttpClients.createDefault();
//        try {
//            // 创建httpget.
//            HttpGet httpget = new HttpGet(httpIp + "/token/getToken?userId=20210501&timestamp=45546546454&random=1156&sign=7fa431325504e01e9fa87ed0e274c40c");
//            System.out.println("executing request " + httpget.getURI());
//            // 执行get请求.
//            CloseableHttpResponse response = httpclient.execute(httpget);
//            try {
//                // 获取响应实体
//                HttpEntity entity = response.getEntity();
//                System.out.println("--------------------------------------");
//                // 打印响应状态
//                System.out.println(response.getStatusLine());
//                if (entity != null) {
//                    // 打印响应内容长度
//                    System.out.println("Response content length: " + entity.getContentLength());
//                    // 打印响应内容
//                    System.out.println("Response content: " + EntityUtils.toString(entity));
//                }
//                System.out.println("------------------------------------");
//            } 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();
//            }
//        }
    }


    private void getRequest() throws IOException {
//        //1.打开浏览器
//        CloseableHttpClient httpClient = HttpClients.createDefault();
//        //2.声明get请求
//        HttpGet httpGet = new HttpGet(httpIp + "/token/getToken?userId=20210501&timestamp=45546546454&random=1156&sign=7fa431325504e01e9fa87ed0e274c40c");
//        //3.发送请求
//        CloseableHttpResponse response = httpClient.execute(httpGet);
//        System.out.println("StatusCode=" + response.getStatusLine().getStatusCode());
//        //4.判断状态码
//        if (response.getStatusLine().getStatusCode() == 200) {
//            HttpEntity entity = response.getEntity();
//            //使用工具类EntityUtils，从响应中取出实体表示的内容并转换成字符串
//            String string = EntityUtils.toString(entity, "utf-8");
//            System.out.println(string);
//        }
//        //5.关闭资源
//        response.close();
//        httpClient.close();
    }
}
