package com.bcxin.ferry.common.utils;

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.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Map;
import java.util.UUID;

/**
 * description: http 请求工具类
 * author: linchunpeng
 * date:  2023-04-18 9:54
 */
public class HttpUtil {

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

    /**
     * description: http post请求
     * author: linchunpeng
     * date:  2023-04-18 9:54
     */
    public static String post(String url, String bodyJson) {
        return post(url, bodyJson, null);
    }
    /**
     * description: http post请求
     * author: linchunpeng
     * date:  2023-04-18 9:54
     */
    public static String post(String url, String bodyJson, Map<String, String> headerMap) {
        String postId = UUID.randomUUID().toString();
        logger.info("=====================http post 请求=====================");
        logger.info("postId：" + postId);
        logger.info("请求地址：" + url);
//        logger.info("请求参数：" + bodyJson);
        logger.info("=======================================================");
        String result = "";
        // 创建一个httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();
        // 创建一个post对象
        HttpPost post = new HttpPost(url);
        CloseableHttpResponse response = null;
        try {
            // 设置请求的内容
            post.setEntity(new StringEntity(bodyJson, "utf-8"));
            // 设置请求的报文头部的编码
            post.addHeader("Content-Type", "application/json;charset=utf-8");
            if (headerMap != null) {
                for (Map.Entry<String, String> header : headerMap.entrySet()) {
                    post.addHeader(header.getKey(), header.getValue());
                }
            }
            // 执行post请求
            response = client.execute(post);
            // 获取响应码
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                // 获取数据
                result = EntityUtils.toString(response.getEntity());
            } else {
                result = "fail";
                logger.error("调用接口请求失败,错误码为：" + statusCode);
                post.abort();
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("调用接口请求失败：" + e.getMessage(), e);
            result = "fail";
            post.abort();
        } finally {
            if (response != null) {
                try {
                    response.close();
                    post.abort();
                } catch (IOException e) {
                    e.printStackTrace();
                    logger.error("关闭接口response出错：" + e.getMessage(), e);
                }
            }
            try {
                client.close();
                post.abort();
            } catch (IOException e) {
                e.printStackTrace();
                logger.error("关闭http接口client出错：" + e.getMessage(), e);
            }
        }
        logger.info("=====================http post 请求结果=====================");
        logger.info("postId：" + postId);
        logger.info("请求结果：" + result);
        logger.info("=======================================================");
        return result;
    }

    /**
     * description: http get请求
     * author: linchunpeng
     * date:  2023-04-18 9:55
     */
    public static String get(String url) {
        String getId = UUID.randomUUID().toString();
        logger.info("=====================http get 请求=====================");
        logger.info("getId：" + getId);
        logger.info("请求地址：" + url);
        logger.info("=======================================================");
        String result = "";
        // 创建一个httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();
        // 创建一个post对象
        HttpGet get = new HttpGet(url);
        CloseableHttpResponse response = null;
        try {
            // 设置请求的报文头部的编码
            get.addHeader("Content-Type", "application/json;charset=utf-8");
            // 执行get请求
            response = client.execute(get);
            // 获取响应码
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                // 获取数据
                result = EntityUtils.toString(response.getEntity());
            } else {
                result = "fail";
                logger.error("调用接口请求失败,错误码为：" + statusCode);
                get.abort();
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("调用接口请求失败：" + e.getMessage(), e);
            result = "fail";
            get.abort();
        } finally {
            if (response != null) {
                try {
                    response.close();
                    get.abort();
                } catch (IOException e) {
                    e.printStackTrace();
                    logger.error("关闭接口response出错：" + e.getMessage(), e);
                }
            }
            try {
                client.close();
                get.abort();
            } catch (IOException e) {
                e.printStackTrace();
                logger.error("关闭http接口client出错：" + e.getMessage(), e);
            }
        }
        logger.info("=====================http get 请求结果=====================");
        logger.info("getId：" + getId);
        logger.info("请求结果：" + result);
        logger.info("=======================================================");
        return result;
    }

}
