package com.bcxin.identify.util.common;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapUtil;
import com.google.common.base.Stopwatch;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
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 javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Slf4j
public class BcxinHttpUtil {


	/**
	 * POST方式调用
	 *
	 * @param url
	 * @param paramMap
	 * @return 响应字符串
	 * @throws java.io.UnsupportedEncodingException
	 */
	public static String sendPostRequest(String url, Map<String,Object> paramMap) {
		if (CollectionUtil.isEmpty(paramMap)) {
			return sendPostRequest(url, Lists.newArrayList());
		}
		List<NameValuePair> pairList = Lists.newArrayList();
		if (MapUtil.isNotEmpty(paramMap)) {
			Iterator iterator = paramMap.entrySet().iterator();
			while(iterator.hasNext()){
				Map.Entry<String,String> elem = (Map.Entry<String, String>) iterator.next();
				pairList.add(new BasicNameValuePair(elem.getKey(),elem.getValue()));
			}
		}
		return sendPostRequest(url, pairList);
	}

	/**
	 * POST方式调用
	 *
	 * @param url
	 * @param params
	 *            参数为NameValuePair键值对对象
	 * @return 响应字符串
	 * @throws java.io.UnsupportedEncodingException
	 */
	public static String sendPostRequest(String url, List<NameValuePair> params) {
		log.debug("--------开始发送http请求--------");
		log.debug("请求地址:[{}]：",url);
		Stopwatch stopwatch = Stopwatch.createStarted();
		String result = "";
		try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
			HttpPost httpPost = new HttpPost(url);
			httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));
			RequestConfig defaultRequestConfig = RequestConfig.custom()
					.setSocketTimeout(60000)
					.setConnectTimeout(60000)
					.setConnectionRequestTimeout(60000)
					.build();
			httpPost.setConfig(defaultRequestConfig);
			try ( CloseableHttpResponse resp = httpClient.execute(httpPost)) {
				HttpEntity entity = resp.getEntity();
				result = EntityUtils.toString(entity, StandardCharsets.UTF_8);
				long nanos = stopwatch.elapsed(TimeUnit.MILLISECONDS);
				log.debug("返回结果：[{}]",result);
				log.debug("共耗时[{}]毫秒："+ nanos);
				log.debug("--------结束http请求--------");
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return result;
	}

	/**
	 * 获取请求参数中所有的信息
	 * @param request
	 * @return
	 */
	public static Map<String, String> getAllRequestParam(HttpServletRequest request) {
		Map<String, String> res = new HashMap<String, String>();
		Enumeration<?> temp = request.getParameterNames();
		if (null != temp) {
			while (temp.hasMoreElements()) {
				String en = (String) temp.nextElement();
				String value = request.getParameter(en);
				res.put(en, value);
				//在报文上送时，如果字段的值为空，则不上送<下面的处理为在获取所有参数数据时，判断若值为空，则删除这个字段>
				//System.out.println("ServletUtil类247行  temp数据的键=="+en+"     值==="+value);
				if (null == res.get(en) || "".equals(res.get(en))) {
					res.remove(en);
				}
			}
		}
		return res;
	}
}
