package io.renren.common.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
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.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.HashMap;
import java.util.Map;

/**
 * HttpClient4.3工具类
 * @author lsy
 * @version 1.0.0
 */
public class HttpClientUtil {

    private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class); // 日志记录

    private static RequestConfig requestConfig = null;

    static {
        // 设置请求和传输超时时间
        requestConfig = RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000).build();
    }

    /**
     * POST请求传输JSON参数
     *
     * @param url
     * @param jsonParam
     * @return JSONObject
     */
    public static String post(String url, JSONObject param) {
        String result = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);
        try {
            if (null != param) {
                StringEntity entity = new StringEntity(param.toString(), "utf-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");
                httpPost.setEntity(entity);
            }
//            logger.info("POST请求:" + httpPost);
            CloseableHttpResponse response = httpClient.execute(httpPost);
//            logger.info("POST返回:" + response);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                try {
                    result = EntityUtils.toString(response.getEntity(), "utf-8");
                } catch (Exception e) {
                    logger.error("POST请求提交失败:" + url, e);
                }
            }
        } catch (IOException e) {
            logger.error("POST请求提交失败:" + url, e);
        } finally {
            httpPost.releaseConnection();
        }
        return result;
    }

    /**
     * POST请求传输JSON参数
     *
     * @param url
     * @param jsonParam
     * @return JSONObject
     */
    public static String postToZijie(String url, JSONObject param) {
        String result = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);
        try {
            if (null != param) {
                StringEntity entity = new StringEntity(param.toString(), "utf-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");
                httpPost.setEntity(entity);
            }
//            logger.info("POST请求:" + httpPost);
            CloseableHttpResponse response = httpClient.execute(httpPost);
//            logger.info("POST返回:" + response);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                try {
                    result = EntityUtils.toString(response.getEntity(), "utf-8");
                } catch (Exception e) {
                    logger.error("POST请求提交失败:" + url, e);
                }
            }
        } catch (IOException e) {
            logger.error("POST请求提交失败:" + url, e);
        } finally {
            httpPost.releaseConnection();
        }
        return result;
    }

    /**
     * POST请求传输String参数
     * 例如：name=jack&sex=1&type=2
     *
     * @param url
     * @param strParam
     * @return String
     */
    public static String post(String url, String param) {
        String result = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);
        try {
            if (null != param) {
                StringEntity entity = new StringEntity(param, "utf-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/x-www-form-urlencoded");
                httpPost.setEntity(entity);
            }
            CloseableHttpResponse response = httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                try {
                    result = EntityUtils.toString(response.getEntity(), "utf-8");
                } catch (Exception e) {
                    logger.error("POST请求提交失败:" + url, e);
                }
            }
        } catch (IOException e) {
            logger.error("POST请求提交失败:" + url, e);
        } finally {
            httpPost.releaseConnection();
        }
        return result;
    }

    /**
     * 发送GET请求
     *
     * @param url
     * @return String
     */
    public static String get(String url) {
        String result = null;
        CloseableHttpClient client = HttpClients.createDefault();
        HttpGet request = new HttpGet(url);
        request.setConfig(requestConfig);
        try {
            CloseableHttpResponse response = client.execute(request);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                result = EntityUtils.toString(entity, "utf-8");
            } else
                logger.error("GET请求提交失败:" + url);
        } catch (IOException e) {
            logger.error("GET请求提交失败:" + url, e);
        } finally {
            request.releaseConnection();
        }
        return result;
    }


    /**
     * 获取url中指定的参数值
     * @param url
     * @param param
     * @return
     */
    public static String getUrlParam(String url,String param) {
        if(StringUtils.isEmpty(url)) {
            return "";
        }
        if (StringUtils.indexOf(url,"?")==-1) {
            return "";
        }
        url= StringUtils.substringAfter(url,"?");
        Map<String, String> mapRequest = new HashMap<String, String>();
        String[] arrSplit = url.split("[&]");
        for (String strSplit : arrSplit) {
            String[] arrSplitEqual = null;
            arrSplitEqual = strSplit.split("[=]");
            //解析出键值
            if (arrSplitEqual.length > 1) {
                //正确解析
                mapRequest.put(arrSplitEqual[0], arrSplitEqual[1]);
            } else {
                if (arrSplitEqual[0] != "") {
                    //只有参数没有值，不加入
                    mapRequest.put(arrSplitEqual[0], "");
                }
            }
        }
        return mapRequest.get(param);
    }

}
