package com.nbclass.util;

import com.alibaba.fastjson.JSONObject;
import com.nbclass.exception.ServiceException;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.CookieSpecs;
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.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Map.Entry;

/**
 * HttpClients 请求工具类
 * @author Leon
 * @datetime 2018年8月13日 下午4:42:17
 */
public class HttpClientUtil {
 
	private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
	
	private static final CloseableHttpClient httpClient;
	
	static {
		RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.IGNORE_COOKIES).setConnectTimeout(10000).setSocketTimeout(10000).build();  
		httpClient = HttpClientBuilder.create().setDefaultRequestConfig(globalConfig).build();
    }
	
	/**
	 * POST请求
	 * @param url
	 * @param json
	 * @return
	 */
	public static JSONObject doPost(String url, JSONObject json){
	//	CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(globalConfig).build();
		HttpPost httpPost = new HttpPost(url);
        JSONObject response = null;
        CloseableHttpResponse res = null;
        try {
        	// 设置请求的header
        //	httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
        	httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        	httpPost.setHeader("Accept", "application/json;charset=utf-8");  
        	
        //	StringEntity s = new StringEntity(json.toString(), "UTF-8");
            StringEntity s = new StringEntity(formatPostData(json), "UTF-8");
        //	s.setContentEncoding("UTF-8");
        //	s.setContentType("application/json");//发送json数据需要设置contentType
            httpPost.setEntity(s);
            
            res = httpClient.execute(httpPost);
            int statusCode = res.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
            	logger.info("请求接口返回状态吗, getStatusCode="+statusCode+", getReasonPhrase="+res.getStatusLine().getReasonPhrase());
            	httpPost.abort();
                throw new ServiceException("HttpClient,error status code :" + statusCode);
            }
            
            HttpEntity entity = res.getEntity();
            if (entity != null) {
            	String result = EntityUtils.toString(entity, "UTF-8");
            	response = JSONObject.parseObject(result);
            }
        } catch (Exception e) {
        	logger.error("HTTP-POST请求出错, URL="+url, e);
        } finally {
        	httpPost.releaseConnection();
        	if (res != null) {
        		try {
					EntityUtils.consume(res.getEntity());
				} catch (IOException e){}
        		try {
                	res.close();
                } catch (IOException e){}
            }
        }
        return response;
    }
	
	/**
	 * GET请求
	 * @param url
	 * @return
	 */
	public static JSONObject doGet(String url){
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse res = null;
        JSONObject response = null;
        try {
        	// 设置请求的header
        	httpGet.setHeader("Content-Type", "application/json;charset=utf-8");
        	httpGet.setHeader("Accept", "application/json;charset=utf-8");
        	
            res = httpClient.execute(httpGet);
            int statusCode = res.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
            	logger.info("请求接口返回状态码, getStatusCode="+statusCode+", getReasonPhrase="+res.getStatusLine().getReasonPhrase());
            	httpGet.abort();
                throw new ServiceException("HttpClient,error status code :" + statusCode);
            }
            
            HttpEntity entity = res.getEntity();
            if (entity != null) {
            	String result = EntityUtils.toString(entity, "UTF-8");
            	response = JSONObject.parseObject(result);
            }
        } catch (Exception e) {
        	logger.error("HTTP-GET请求出错, URL="+url, e);
        } finally {
        	httpGet.releaseConnection();
        	if (res != null) {
        		try {
					EntityUtils.consume(res.getEntity());
				} catch (IOException e){}
        		try {
                	res.close();
                } catch (IOException e){}
            }
        }
        return response;
    }
	
	protected static String formatPostData(JSONObject json){
		String result = null;
		try {
			JSONObject jsonObject = json;
			if(jsonObject != null){
				result = "?";
				for (Entry<String, Object> entry : jsonObject.entrySet()) {
		            if(StringUtils.isEmpty(result)){
		            	result = entry.getKey() + "=" + entry.getValue();
		            }else{
		            	result += "&" + entry.getKey() + "=" + entry.getValue();
		            }
		        }
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	protected static String formatPostData(String strdata){
		String result = strdata;
		try {
			JSONObject jsonObject = JSONObject.parseObject(strdata);
			if(jsonObject != null){
				result = "";
				for (Entry<String, Object> entry : jsonObject.entrySet()) {
		            if(StringUtils.isEmpty(result)){
		            	result = entry.getKey() + "=" + entry.getValue();
		            }else{
		            	result += "&" + entry.getKey() + "=" + entry.getValue();
		            }
		        }
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
}
