/**
 * @Company: 北京慧点科技有限公司 | www.smartdot.com.cn
 * @Copyright 1998-2020 © Smartdot Technologies Co., Ltd.
 */
package com.search.supersearch.util;

import cn.hutool.json.JSONUtil;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.methods.HttpUriRequest;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * 会议与OA进行HTTP请求-工具类
 * zx
 *
 * @see
 */
public class HttpUtils {

    static Logger logger = LoggerFactory.getLogger(HttpUtils.class);

    public static String post(String url, Map<String, String> parameters, Map<String, File> files, String accessToken) {
        String entityStr = null;
        HttpPost httppost = new HttpPost(url);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        if (parameters != null) {
            parameters.forEach((parameterName, parameterValue) -> {
                StringBody stringBody = new StringBody(parameterValue, ContentType.TEXT_PLAIN);
                builder.addPart(parameterName, stringBody);
            });
        }

        if (files != null) {
            files.forEach((fieldName, needUploadFile) -> {
                FileBody fileBody = new FileBody(needUploadFile);
                builder.addPart(fieldName, fileBody);
            });
        }

        HttpEntity requestEntity = builder.build();
        httppost.setEntity(requestEntity);
        httppost.addHeader("Authorization", "Bearer " + accessToken);
        entityStr = httpClientExecuteWithMultipart(httppost);
        return entityStr;
    }

    public static String httpClientExecuteWithMultipart(final HttpUriRequest request) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        try {
            logger.info("请求参数：{}", JSONUtil.toJsonStr(request));
            response = httpClient.execute(request);
            if (response.getStatusLine().toString().indexOf("200") < 0) {
                logger.error("请求地址失败！错误代码：" + response.getStatusLine().toString());
            }
            String result = EntityUtils.toString(response.getEntity(), "utf-8");
            EntityUtils.consume(response.getEntity());
            return result;
        } catch (ClientProtocolException e) {
            logger.error("Http协议出现问题，请求失败!");
            e.printStackTrace();
        } catch (IOException e) {
            logger.error("IO异常，请求失败!");
            e.printStackTrace();
        } finally {
            // 释放连接
            if (null != response) {
                try {
                    response.close();
                    httpClient.close();
                } catch (IOException e) {
                    logger.error("释放连接出错!");
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public static String getResponseUplod(String url, Map<String, String> parameters, String accessToken) {
        String entityStr = null;
        try {
            HttpPost httpPost = new HttpPost(url);
            // 设置参数
            List<NameValuePair> list = new LinkedList<NameValuePair>();
            for (Map.Entry<String, String> entry : parameters.entrySet()) {
                list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
            // POST请求
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(list, "UTF-8");
            httpPost.setEntity(formEntity);
            httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
            httpPost.addHeader("Authorization", accessToken);

            entityStr = httpClientExecuteUplod(httpPost);
        } catch (ParseException e) {
            logger.error("解析错误，请求地址失败!");
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            logger.error("URI解析异常，请求地址失败 ： " + url);
            e.printStackTrace();
        }
        return entityStr;
    }


    public static String httpClientExecuteUplod(final HttpUriRequest request) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(request);
            if (response.getStatusLine().toString().indexOf("200") < 0) {
                logger.error("请求地址失败！错误代码：" + response.getStatusLine().toString());
            }
            String result = EntityUtils.toString(response.getEntity(), "utf-8");
            EntityUtils.consume(response.getEntity());
            return result;
        } catch (ClientProtocolException e) {
            logger.error("Http协议出现问题，请求失败!");
            e.printStackTrace();
        } catch (IOException e) {
            logger.error("IO异常，请求失败!");
            e.printStackTrace();
        } finally {
            // 释放连接
            if (null != response) {
                try {
                    response.close();
                    httpClient.close();
                } catch (IOException e) {
                    logger.error("释放连接出错!");
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * GET请求
     *
     * @param url
     * @param parameters
     * @return
     * @author shijunbao
     * @since 1.0, Aug 5, 2020
     */
    public static String get(String url, Map<String, String> parameters, String accessToken) {
        String entityStr = null;
        try {
            URIBuilder uriBuilder = new URIBuilder(url);
            // 设置参数
            List<NameValuePair> nameValuePairs = new LinkedList<NameValuePair>();
            for (Map.Entry<String, String> entry : parameters.entrySet()) {
                BasicNameValuePair nameValuePair = new BasicNameValuePair(entry.getKey(), entry.getValue());
                nameValuePairs.add(nameValuePair);
            }
            uriBuilder.setParameters(nameValuePairs);
            // GET请求
            HttpGet httpGet = new HttpGet(uriBuilder.build());
            entityStr = httpClientExecute(httpGet, accessToken);
        } catch (URISyntaxException e) {
            logger.error("URI解析异常，请求地址失败 ： " + url);
            e.printStackTrace();
        } catch (ParseException e) {
            logger.error("解析错误，请求地址失败!");
            e.printStackTrace();
        }
        return entityStr;
    }

    /**
     * httpClientExecute
     *
     * @param request
     * @return
     * @author shijunbao
     * @since 1.0, Aug 8, 2020
     */
    public static String httpClientExecute(final HttpUriRequest request, String accessToken) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        try {
            request.addHeader("Content-Type", "application/json");
            request.addHeader("Authorization", accessToken);
            response = httpClient.execute(request);
            if (response.getStatusLine().toString().indexOf("200") < 0) {
                logger.error("请求地址失败！错误代码：" + response.getStatusLine().toString());
            }
            String result = EntityUtils.toString(response.getEntity(), "utf-8");
            EntityUtils.consume(response.getEntity());
            return result;
        } catch (ClientProtocolException e) {
            logger.error("Http协议出现问题，请求失败!");
            e.printStackTrace();
        } catch (IOException e) {
            logger.error("IO异常，请求失败!");
            e.printStackTrace();
        } finally {
            // 释放连接
            if (null != response) {
                try {
                    response.close();
                    httpClient.close();
                } catch (IOException e) {
                    logger.error("释放连接出错!");
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

}
