package com.keystar.plane.inspection.utils;

import org.apache.http.HttpEntity;
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.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URI;
import java.util.Map;
import java.util.Set;


public class HttpUtils {


    /**
     * http get请求方法
     */
    public static String doGet(String url,Map<String, String> headers) {
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建url
            URIBuilder builder = new URIBuilder(url);
            URI uri = builder.build();
            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);
            // 设置超时时间
            RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(3000)
                    .setSocketTimeout(3000).setConnectTimeout(3000).build();
            httpGet.setConfig(requestConfig);
            try {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    httpGet.addHeader(entry.getKey(), entry.getValue());
                }
            }catch (Exception e){
            }

//            // 设置token值
//            httpGet.addHeader("Authorization", "eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyIjoie1widXNlcm5hbWVcIjpcInN5c3RlbVwiLFwiaXBcIjpudWxsLFwiaWRcIjotMSxcImp3dFwiOlwiZXlKaGJHY2lPaUpJVXpJMU5pSjkuZXlKMWMyVnlJam9pZTF3aWRYTmxjbTVoYldWY0lqcGNJbk41YzNSbGJWd2lMRndpYVhCY0lqcHVkV3hzTEZ3aWFXUmNJam90TVN4Y0ltcDNkRndpT201MWJHeDlJaXdpYVdGMElqb3hOakk1TkRZMk1qWXhMQ0pxZEdraU9pSlpWRkUxV2xkTmVrOVVUWFJOYWs1cVRVTXdNRTlFV1RKTVYwWnNUVmROZEU1RVp6Rk9WRTVxVGxSbmVFNUhXVFFpTENKbGVIQWlPakUyTWprMU5USTJOakY5LkpVZjBZNVE2SnJVTlZoaXpZQ2dJNWpWVUJVTzluOGhlVnFqTkd4eGdZNHNcIn0iLCJpYXQiOjE2Mjk0NjYyNjEsImp0aSI6Ill6QXpOVFZrWVRZdE5UZGhNeTAwTURVMkxXRTBOVEF0TWpRMk5qVTNabVV4T1RneSIsImV4cCI6Mjc0MDU3NzM3Mn0.peHm3MmYLWyqne1-K-3JHqpZhW5jtQX-STDfgIaNjpI");
            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception ignored) {

        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException ignored) {
            }
        }
        return resultString;
    }

    /**
     * http post请求方法
     */
    public static String doPost(String url, Map<String,Object> paramMap, Map<String, String> headers)  {
        CloseableHttpClient httpclient = HttpClients.createDefault();

        try {
            // 创建url
            URIBuilder builder = new URIBuilder(url);
            URI uri = builder.build();
            // 创建http post请求
            HttpPost httpPost = new HttpPost(uri);
            // 设置超时时间
            RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(3000)
                    .setSocketTimeout(3000).setConnectTimeout(3000).build();
            httpPost.setConfig(requestConfig);
            String body = paramToString(paramMap);
            StringEntity stringEntity = new StringEntity(body, "utf-8");
            httpPost.setEntity(stringEntity);
            try {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    httpPost.addHeader(entry.getKey(), entry.getValue());
                }
            }catch (Exception e){
            }

            httpPost.addHeader("Content-Type","application/json;charset=utf-8");
            CloseableHttpResponse apiRes = httpclient.execute(httpPost);

            HttpEntity entity = apiRes.getEntity();
            //            System.out.println("接收到了返回信息:"+content);
            return EntityUtils.toString(entity);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String paramToString(Map<String, Object> paramMap) {
        String json;
        StringBuffer stringBuffer = new StringBuffer();
        //json字符串的第一个位置应该是 {
        stringBuffer.append("{");
        //去除Map中的所有Key值，放入Set集合中
        Set<String> paramKey = paramMap.keySet();
        //遍历出每一个key值，然后取出Map中的对应value做非空判断，若非空就进行拼接到stringBuffer中
        for (String param : paramKey) {
            if (paramMap.get(param) != null) {
                stringBuffer.append("\"" + param + "\":\"" + paramMap.get(param).toString().trim() + "\",");
            }
        }
        //若stringBuffer的长度大于2，则表示Map中有非空value并拼接到stringBuffer，那么就要去掉stringBuffer最后位置的逗号，然后再拼接上}即可；
        //若stringBuffer的长度小于2，则表示Map中没有非空value拼接到stringBuffer,那么只需给stringBuffer再拼接上}即可
        if (stringBuffer.length() > 2) {
            String substring = stringBuffer.substring(0, stringBuffer.length() - 1);
            json = substring + "}";
        } else {
            json = stringBuffer.toString() + "}";
        }
        return json;
    }
}
