package com.prolog.cs.biz.inbound.utils;

import org.apache.commons.lang.StringUtils;
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.HttpClient;
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.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HttpClientUtil {

	private CloseableHttpClient closeableHttpClient = null;

	private HttpClientUtil() {
		closeableHttpClient = HttpClients.createDefault();
	}

	public static HttpClientUtil getInstance() {
		return new HttpClientUtil();
	}

	/**
	 * 
	 * 
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public String post(String url, Map<String, String> paramMap) throws ClientProtocolException, IOException {
		String retn = "";
		
		HttpPost httppost = new HttpPost(url);
		List<NameValuePair> formparams = new ArrayList<NameValuePair>();
		for (String key : paramMap.keySet()) {
			formparams.add(new BasicNameValuePair(key, paramMap.get(key)));
		}

		UrlEncodedFormEntity uefEntity;
		CloseableHttpResponse response = null;
		try {
			// ISO8859-1   GBK  UTF-8
			uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
			//uefEntity = new UrlEncodedFormEntity(formparams);
			httppost.setEntity(uefEntity);
			
			response = closeableHttpClient.execute(httppost);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				retn = EntityUtils.toString(entity, "UTF-8");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			response.close();
			closeableHttpClient.close();
		}
		return retn;
	}
	
	/**
	 * 
	 * @param url
	 * @param parameter
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public String post(String url, String parameter) throws ClientProtocolException, IOException {
		String retn = "";
		HttpClient client = HttpClientBuilder.create().build();
		// 创建httppost
		HttpPost httppost = new HttpPost(url);
		HttpResponse response = null;
		try {
			ContentType contentType = ContentType.create("application/json","UTF-8");
			// 设置请求参数
			httppost.setEntity(new StringEntity(parameter, contentType));
			// 执行请求，获取返回对象
			response = client.execute(httppost);
			int code = response.getStatusLine().getStatusCode();
            if (code == 200) {
            	HttpEntity entity = response.getEntity();
    			if (entity != null) {
    				retn = EntityUtils.toString(entity);
    			} else {
    				throw new RuntimeException("business-Interface no response data!");
				}
			} else {
				throw new RuntimeException("Request vipapis interface Exception【" + code + "】！");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 关闭连接,释放资源
			httppost.releaseConnection();
		}
		return retn;
	}
	public Map<String,String> post(String url, String parameter,String type) throws ClientProtocolException, IOException {
		Map<String,String> map = new HashMap<>();
		String retn = "connection failed";
		HttpClient client = HttpClientBuilder.create().build();
		// 创建httppost
		HttpPost httppost = new HttpPost(url);
		HttpResponse response = null;
		RequestConfig config = RequestConfig.custom().setConnectTimeout(10000) //连接超时时间
                .build();
		httppost.setConfig(config);
		int j=0;
		try {
			ContentType contentType = ContentType.create(type,"UTF-8");
			// 设置请求参数
			httppost.setEntity(new StringEntity(parameter, contentType));
			for(int i=0;i<5;i++){
				// 执行请求，获取返回对象
				j=j+1;
				try {
					response = client.execute(httppost);
					//System.out.println(response);
				} catch (Exception e) {
					retn = e.getMessage();
					continue;
				}
				
				int code = response.getStatusLine().getStatusCode();
				if(code == 200){
					HttpEntity entity = response.getEntity();
					if (entity != null) {
	    				retn = EntityUtils.toString(entity);
	    				//JsonUtils.toMap(retn).get("code");
	    			} else {
	    				throw new RuntimeException("business-Interface no response data!");
					}
					break;
				}
			}
		} catch (Exception e) {
			retn = e.getMessage();
		} finally {
			// 关闭连接,释放资源
			httppost.releaseConnection();
		}
		map.put("retn", retn);
		map.put("size", j+"");
		
		return map;
	}

	/**
	 * 
	 * 
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public String get(String url, String tokenkey, String tokenvalue) throws ClientProtocolException, IOException {
		String retn = "";
		CloseableHttpResponse response = null;
		try {
			
			HttpGet httpget = new HttpGet(url);
			httpget.setHeader(tokenkey, tokenvalue);
			response = closeableHttpClient.execute(httpget);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				retn = EntityUtils.toString(entity);
			}
		} finally {
			response.close();
			closeableHttpClient.close();
		}
		return retn;
	}
	/**
	 * 
	 * @param url
	 * @param parameter
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public String post(String url, String parameter, String token,String str) throws ClientProtocolException, IOException {
		String retn = "";
		HttpClient client = HttpClientBuilder.create().build();
		// 创建httppost
		HttpPost httppost = new HttpPost(url);
		HttpResponse response = null;
		try {
			ContentType contentType = ContentType.create("application/json","UTF-8");
			// 设置请求参数
			httppost.setEntity(new StringEntity(parameter, contentType));
			if(StringUtils.isNotBlank(token)) {
				httppost.setHeader("Authorization", token);
			}
			// 执行请求，获取返回对象
			response = client.execute(httppost);
			int code = response.getStatusLine().getStatusCode();
            if (code == 200) {
            	HttpEntity entity = response.getEntity();
    			if (entity != null) {
    				retn = EntityUtils.toString(entity);
    			} else {
    				throw new RuntimeException("business-Interface no response data!");
				}
			} else {
				throw new RuntimeException("Request vipapis interface Exception【" + code + "】！");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 关闭连接,释放资源
			httppost.releaseConnection();
		}
		return retn;
	}
}
