package com.bcxin.ins.third.gzx.huatai;


import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Stopwatch;
import com.google.common.collect.Maps;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
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.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class HttpUtil {


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

	/**
	 * POST方式调用
	 *
	 * @param url
	 * @param params
	 *            参数为NameValuePair键值对对象
	 * @return 响应字符串
	 * @throws java.io.UnsupportedEncodingException
	 */
	public static String sendPostRequest(String url, List<NameValuePair> params) {

		log.info("--------开始发送http请求--------");
		log.info("请求地址:[{}]："+url);
		log.info(params.toString());
			Stopwatch stopwatch = Stopwatch.createStarted();
			String result = "";
			try {
				CloseableHttpClient httpClient = HttpClients.createDefault();
				HttpPost httpPost = new HttpPost(url);
				httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));
				CloseableHttpResponse resp = httpClient.execute(httpPost);
				HttpEntity entity = resp.getEntity();
				result = EntityUtils.toString(entity,StandardCharsets.UTF_8.toString());
				long nanos = stopwatch.elapsed(TimeUnit.MILLISECONDS);
				log.info("返回结果：[{}]"+result);
				log.info("共耗时[{}]毫秒："+nanos);
				log.info("--------结束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);
				//在报文上送时，如果字段的值为空，则不上送<下面的处理为在获取所有参数数据时，判断若值为空，则删除这个字段>
				//log.info("ServletUtil类247行  temp数据的键=="+en+"     值==="+value);
				if (null == res.get(en) || "".equals(res.get(en))) {
					res.remove(en);
				}
			}
		}
		return res;
	}

	/** 将json转换为map
	 * */
	public static Map<String,String> getMapValue(String data) {
		JSONObject jsonback = JSONObject.parseObject(data);
		Map<String,String> map = Maps.newHashMap();
		for(String key : jsonback.keySet()){
			if(jsonback.get(key)!=null){
				String value = (String) jsonback.get(key);
				map.put(key,value);
			}
		}
		return map;
	}

	private static String convertStreamToString(InputStream is) {
		StringBuilder sb1 = new StringBuilder();
		byte[] bytes = new byte[4096];
		int size = 0;

		try {
			while ((size = is.read(bytes)) > 0) {
				String str = new String(bytes, 0, size, "UTF-8");
				sb1.append(str);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb1.toString();
	}

}
