package com.bcxin.auth.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.error("=====================http post 请求=====================");
        logger.error("postId：" + postId);
        logger.error("请求地址：" + url);
//        logger.error("请求参数：" + bodyJson);
        logger.error("=======================================================");
        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();
            result = EntityUtils.toString(response.getEntity());
            logger.error("调用接口返回值：{}", result);
            if (statusCode != 200) {
                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.error("=====================http post 请求结果=====================");
        logger.error("postId：" + postId);
        logger.error("请求结果：" + result);
        logger.error("=======================================================");
        return result;
    }

    /**
     * description: http get请求
     * author: linchunpeng
     * date:  2023-04-18 9:55
     */
    public static String get(String url) {
        return get(url, null);
    }

    /**
     * description: http get请求
     * author: linchunpeng
     * date:  2023-04-18 9:55
     */
    public static String get(String url, Map<String, String> headerMap) {
        String getId = UUID.randomUUID().toString();
        logger.error("=====================http get 请求=====================");
        logger.error("getId：" + getId);
        logger.error("请求地址：" + url);
        logger.error("=======================================================");
        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");
            if (headerMap != null) {
                for (Map.Entry<String, String> header : headerMap.entrySet()) {
                    get.addHeader(header.getKey(), header.getValue());
                }
            }
            // 执行get请求
            response = client.execute(get);
            // 获取响应码
            int statusCode = response.getStatusLine().getStatusCode();
            result = EntityUtils.toString(response.getEntity());
            logger.error("调用接口返回值：{}", result);
            if (statusCode != 200) {
                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.error("=====================http get 请求结果=====================");
        logger.error("getId：" + getId);
        logger.error("请求结果：" + result);
        logger.error("=======================================================");
        return result;
    }

}
