package org.diagbot.pub.utils.http;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.StringEntity;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.codehaus.jackson.JsonParseException;
import org.diagbot.pub.utils.mapper.JsonMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.net.ConnectException;


/**
 * 
 * ClassName: HttpApi 
 * Function: HTTP请求工具类 
 * date: 2015年7月10日 下午10:50:24  
 * 
 * @author 楼辉荣(Fyeman) 
 * @version 1.0 
 * @since JDK 1.7
 */
@Component
public class HttpApi<T> {
	private static Logger log = LoggerFactory.getLogger(HttpApi.class);

	/**
	 * Description : HttpPost方式访问远程URL
	 * 
	 * @param httpUrl
	 *            URL
	 * @param obj
	 *            post方式传入参数对象
	 * @param type
	 *            返回Json构造对象类
	 * @return post访问返回数据对象
	 */
	@SuppressWarnings({ "deprecation", "unused" })
	public T doPost(String httpUrl, Object obj, Class<T> type) throws ConnectException, Exception {
		JsonMapper mapper = JsonMapper.nonEmptyMapper();
		try {
			/* post向服务器请求数据 */
			HttpPost httppost = new HttpPost(httpUrl);
			if (obj != null) {
				String post = mapper.toJson(obj);
//				log.info("开始发起远程请求Param String：" + post);
				StringEntity se = new StringEntity(post, HTTP.UTF_8);
				se.setContentType("application/json");
				se.setContentEncoding("utf-8");
				httppost.setEntity(se);
			}

			CloseableHttpResponse response = HttpConnectionManager.getHttpClient().execute(httppost, HttpClientContext.create());
			int code = response.getStatusLine().getStatusCode();
			HttpEntity entity = response.getEntity();
			String receive = EntityUtils.toString(entity, "UTF-8").trim();
//			log.info("服务器返回Response String：" + receive);
			return mapper.fromJson(receive, type);
		} catch (ConnectException connException) {
			throw connException;
		} catch (JsonParseException jsonException) {
			throw new Exception("Json映射对象错误！----" + jsonException.getMessage(), jsonException);
		} catch (Exception e) {
			throw new Exception("远程服务器调用接口失败！----" + e.getMessage(), e);
		}

	}
	
	/**
	 * Description : HttpPost方式访问远程URL
	 * 
	 * @param httpUrl
	 *            URL
	 * @param obj
	 *            post方式传入参数对象
	 * @param type
	 *            返回Json构造对象类
	 * @return post访问返回数据对象
	 */
	@SuppressWarnings({ "deprecation", "unused" })
	public T doPostReplace(String httpUrl, Object obj, Class<T> type) throws ConnectException, Exception {
		JsonMapper mapper = JsonMapper.nonEmptyMapper();
		try {
			/* post向服务器请求数据 */
			HttpPost httppost = new HttpPost(httpUrl);
			if (obj != null) {
				String post = mapper.toJson(obj);
				log.info("开始发起远程请求Param String：" + post);
				StringEntity se = new StringEntity(post, HTTP.UTF_8);
				se.setContentType("application/json");
				se.setContentEncoding("utf-8");
				httppost.setEntity(se);
			}

			CloseableHttpResponse response = HttpConnectionManager.getHttpClient().execute(httppost, HttpClientContext.create());
			int code = response.getStatusLine().getStatusCode();
			HttpEntity entity = response.getEntity();
			String receive = EntityUtils.toString(entity, "UTF-8").trim();
			log.info("服务器返回Response String：" + receive);			
			receive=receive.replace("\\\"", "\"").replace("\"[{", "[{").replace("}]\"", "}]").replace("\"{", "{").replace("}\"", "}").replace("\"data\":\"[]\"", "\"data\":null");			
			return mapper.fromJson(receive, type);
		} catch (ConnectException connException) {
			throw connException;
		} catch (JsonParseException jsonException) {
			throw new Exception("Json映射对象错误！----" + jsonException.getMessage(), jsonException);
		} catch (Exception e) {
			throw new Exception("远程服务器调用接口失败！----" + e.getMessage(), e);
		}

	}
}
