package com.bcxin.auth.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 使用HttpClient模拟HTTP访问
 * 
 * @see ===============================================================================================================================
 * @see
 * @see ===============================================================================================================================
 */
@SuppressWarnings("deprecation")
public class HttpClientUtil {

	private static final Log log = LogFactory.getLog(HttpClientUtils.class);
	/**
	 * 初始化HttpClient
	 */
	private static HttpClient httpClient = null;

	/**
	 * 生产HttpClient实例 公开，静态的工厂方法，需要使用时才去创建该单体
	 *
	 * @return
	 */
	public static HttpClient getHttpClient() {
		if (httpClient == null) {
			httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager());
		}
		return httpClient;
	}

	/**
	 * POST方式调用
	 *
	 * @param url
	 * @param params
	 *            参数为NameValuePair键值对对象
	 * @return 响应字符串
	 * @throws java.io.UnsupportedEncodingException
	 */
	public static String sendPostRequest(String url, List<NameValuePair> params) {
		HttpClient httpclient = getHttpClient();
		HttpPost post = new HttpPost(url);
		ResponseHandler<String> responseHandler = new BasicResponseHandler();
		String responseJson = null;
		try {
			if (params != null) {
//				StringEntity entity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
//				post.setEntity(entity);
				post.setEntity(new UrlEncodedFormEntity(params));
			}
			responseJson = getHttpClient().execute(post, responseHandler);
			log.info("HttpClient POST请求结果：" + responseJson);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			log.info("HttpClient POST请求异常：" + e.getMessage());
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			httpclient.getConnectionManager().closeExpiredConnections();
			httpclient.getConnectionManager().closeIdleConnections(30, TimeUnit.SECONDS);
		}
		return responseJson;
	}

	public static CookieStore cookieStore = null;
	

	public static String doPost(String postUrl,List<NameValuePair> parameterList) {
		String retStr = "";
		// 创建HttpClientBuilder
		@SuppressWarnings("unused")
		HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
		// HttpClient
		CloseableHttpClient closeableHttpClient = null;
		
		HttpPost httpPost = new HttpPost(postUrl);
		// 设置请求和传输超时时间
		RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).build();
		httpPost.setConfig(requestConfig);
		try {
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameterList, "UTF-8");
			httpPost.setEntity(entity);
			@SuppressWarnings("null")
			CloseableHttpResponse response = closeableHttpClient.execute(httpPost);

			HttpEntity httpEntity = response.getEntity();
			retStr = EntityUtils.toString(httpEntity, "UTF-8");
//			System.out.println(retStr);
			closeableHttpClient.close();
		} catch (Exception e) {
			e.printStackTrace();
			log.info("HttpClient POST请求异常：" + e.getMessage());
		}
		return retStr;
	}



	public static JSONObject post(String serverUrl, String data) {
		StringBuilder responseBuilder = null;
		BufferedReader reader = null;
		OutputStreamWriter wr = null;
		JSONObject jsonObject=new JSONObject();
		try {
			URL url = new URL(serverUrl);
			URLConnection conn = url.openConnection();
			conn.setDoOutput(true);
			conn.setConnectTimeout(5000);
			wr = new OutputStreamWriter(conn.getOutputStream());
			wr.write(data);
			wr.flush();
				reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
				responseBuilder = new StringBuilder();
				String line = null;
				while((line = reader.readLine()) != null) {
					responseBuilder.append(line + "\n");
				}
				log.debug(responseBuilder.toString());
				jsonObject= JSON.parseObject(responseBuilder.toString());

		} catch (IOException var22) {
			log.error("", var22);
		} finally {
			if (wr != null) {
				try {
					wr.close();
				} catch (IOException var21) {
					log.error("close error", var21);
				}
			}

			if (reader != null) {
				try {
					reader.close();
				} catch (IOException var20) {
					log.error("close error", var20);
				}
			}

		}

		return jsonObject;
	}


	/**
	 * Get方式请求
	 *
	 * @param url
	 *            带参数占位符的URL，例：
	 * @param params
	 *            参数值数组，需要与url中占位符顺序对应
	 * @return 响应字符串
	 * @throws java.io.UnsupportedEncodingException
	 */
	public static JSONObject executeByGET(String url, Object[] params) {
		HttpClient httpclient = getHttpClient();
		String messages = MessageFormat.format(url, params);
		HttpGet get = new HttpGet(messages);
		ResponseHandler<String> responseHandler = new BasicResponseHandler();
		JSONObject responseJson = null;
		responseJson = getJsonObject(httpclient, get, responseHandler, responseJson);
		return responseJson;
	}

	/**
	 * @param url
	 * @return
	 */
	public static JSONObject executeByGET(String url) {
		HttpClient httpclient = getHttpClient();
		HttpGet get = new HttpGet(url);
		ResponseHandler<String> responseHandler = new BasicResponseHandler();
		JSONObject responseJson = null;
		responseJson = getJsonObject(httpclient, get, responseHandler, responseJson);
		return responseJson;
	}

	/**
	 * 请求
	 * 
	 * @param httpclient
	 * @param get
	 * @param responseHandler
	 * @param responseJson
	 * @return
	 */
	private static JSONObject getJsonObject(HttpClient httpclient, HttpGet get, ResponseHandler<String> responseHandler,
                                            JSONObject responseJson) {
		try {

			responseJson = JSONObject.parseObject(httpclient.execute(get, responseHandler));
			log.info("HttpClient GET请求结果：" + responseJson);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			log.info("HttpClient GET请求异常：" + e.getMessage());
		} catch (IOException e) {
			e.printStackTrace();
			log.info("HttpClient GET请求异常：" + e.getMessage());
		} finally {
			httpclient.getConnectionManager().closeExpiredConnections();
			httpclient.getConnectionManager().closeIdleConnections(30, TimeUnit.SECONDS);
		}
		return responseJson;
	}




}