/**
 * 
 */
/**
 * @author Administrator
 *
 */
package com.tzy.framework.pay.util.bofoo.bank;

import com.alibaba.fastjson.JSONObject;
import com.tzy.framework.pay.util.bofoo.http.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Slf4j
public class HttpUtil {
	
	public static String RequestForm(String Url,Map<String,String> Parms){		
		if(Parms.isEmpty()){
			return  "参数不能为空！";
		}
		String PostParms = "";
		int PostItemTotal = Parms.keySet().size();
		int Itemp=0;
		for (String key : Parms.keySet()){
			PostParms += key + "="+Parms.get(key);
			Itemp++;
			if(Itemp<PostItemTotal){
				PostParms +="&";
			}
		}
		HttpSendModel httpSendModel = new HttpSendModel(Url + "?" + PostParms);
		log.info("【请求全部参数】：" + Url + "?" + PostParms);
		httpSendModel.setMethod(HttpMethod.POST);
		SimpleHttpResponse response = null;
		try {
			response = doRequest(httpSendModel, "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
			log.error(" 请求异常 {}",e);
			return e.getMessage();
		}
		return response.getEntityString();

	}
	
	public static SimpleHttpResponse doRequest(HttpSendModel httpSendModel,
			String getCharSet) throws Exception {

		// 创建默认的httpClient客户端端
		SimpleHttpClient simpleHttpclient = new SimpleHttpClient();

		try {
			return doRequest(simpleHttpclient, httpSendModel, getCharSet);
		} finally {
			simpleHttpclient.getHttpclient().getConnectionManager().shutdown();
		}

	}

	/**
	 * @param simpleHttpclient
	 * @param httpSendModel
	 * @param getCharSet
	 * @return
	 * @throws Exception 
	 */
	public static SimpleHttpResponse doRequest(
			SimpleHttpClient simpleHttpclient, HttpSendModel httpSendModel,
			String getCharSet) throws Exception {

		HttpRequestBase httpRequest = buildHttpRequest(httpSendModel);

		if (httpSendModel.getUrl().startsWith("https://")) {
			simpleHttpclient.enableSSL();
		}

		try {
			HttpResponse response = simpleHttpclient.getHttpclient().execute(
					httpRequest);
			int statusCode = response.getStatusLine().getStatusCode();

			if (isRequestSuccess(statusCode)) {
				return new SimpleHttpResponse(statusCode, EntityUtils.toString(
						response.getEntity(), getCharSet), null);
			} else {
				return new SimpleHttpResponse(statusCode, null, response
						.getStatusLine().getReasonPhrase());
			}

		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("http请求异常", e);
		}

	}

	/**
	 * @param httpSendModel
	 * @return
	 * @throws Exception 
	 */
	protected static HttpRequestBase buildHttpRequest(
			HttpSendModel httpSendModel) throws Exception {
		HttpRequestBase httpRequest;
		if (httpSendModel.getMethod() == null) {
			throw new Exception("请求方式未设定");
		} else if (httpSendModel.getMethod() == HttpMethod.POST) {

			String url = httpSendModel.getUrl();
			String sendCharSet = httpSendModel.getCharSet();
			List<HttpFormParameter> params = httpSendModel.getParams();
			List<NameValuePair> qparams = new ArrayList<NameValuePair>();
			if (params != null && params.size() != 0) {

				for (HttpFormParameter param : params) {
					qparams.add(new BasicNameValuePair(param.getName(), param
							.getValue()));
				}

			}

			HttpPost httppost = new HttpPost(url);
			try {
				UrlEncodedFormEntity Str = new UrlEncodedFormEntity(qparams,sendCharSet);
				Str.setContentType("application/x-www-form-urlencoded");
				httppost.setEntity(Str);				
			} catch (UnsupportedEncodingException e) {
				throw new Exception("构建post请求参数失败", e);
			}

			httpRequest = httppost;
		} else if (httpSendModel.getMethod() == HttpMethod.GET) {
			HttpGet httpget = new HttpGet(httpSendModel.buildGetRequestUrl());

			httpRequest = httpget;
		} else {
			throw new Exception("请求方式不支持：" + httpSendModel.getMethod());
		}

		return httpRequest;
	}

	/**
	 * 请求是否成功
	 * 
	 * @param statusCode
	 * @return
	 */
	public static boolean isRequestSuccess(int statusCode) {
		return statusCode == 200;
	}

	/**
	 * 默认application/x-www-form-urlencoded，使用application/json需指定
	 * @param url
	 * @param parms
	 * @param contentType
	 * @return
	 */
	public static String requestPostByType(String url, Map<String, Object> parms, String contentType) {
		log.info("【请求地址】：{}",url);
		log.info("【请求参数】：{}", JSONObject.toJSONString(parms));
		// 创建默认的httpClient客户端
		SimpleHttpClient simpleHttpclient = new SimpleHttpClient();
		HttpPost hPost = new HttpPost(url);
		String result = null;
		try {
			if (contentType.isEmpty() || contentType.toLowerCase().contains("form")) {
				// application/x-www-form-urlencoded请求
				List<NameValuePair> qparams = new ArrayList<NameValuePair>();
				for (Map.Entry<String, Object> entry : parms.entrySet()) {
					String key = entry.getKey();
					String value = (String) entry.getValue();
					qparams.add(new BasicNameValuePair(key, value));
				}
				UrlEncodedFormEntity Str = new UrlEncodedFormEntity(qparams, "UTF-8");
				hPost.setEntity(Str);
			} else if(contentType.toLowerCase().contains("json")){
				// application/json请求
				StringEntity Str = new StringEntity(JSONObject.toJSONString(parms), "UTF-8");
				Str.setContentEncoding("UTF-8");
				Str.setContentType("application/json");
				hPost.setEntity(Str);
			}
			long startTime=System.currentTimeMillis();
			HttpResponse response = simpleHttpclient.getHttpclient().execute(hPost);
			long endTime=System.currentTimeMillis();
			int statusCode = response.getStatusLine().getStatusCode();
			String errorMsg = response.getStatusLine().toString();
			log.info("【HTTP状态码：{} ---请求耗时：{} ms】",statusCode ,(endTime-startTime));
			if (isRequestSuccess(statusCode)) {
				result = EntityUtils.toString(response.getEntity(), "UTF-8");
				log.info("【请求成功，返回内容】：{}",result);
			} else {
				log.info("【HTTP请求异常,请检查请求地址！】{}",errorMsg);
				throw new RuntimeException("HTTP请求响应码为:"+statusCode);
			}
		} catch (UnsupportedEncodingException e) {
			log.info("【构建请求失败】");
			e.printStackTrace();
		} catch (Exception e) {
			log.info("【请求异常】");
			e.printStackTrace();
		}finally {
			simpleHttpclient.getHttpclient().getConnectionManager().shutdown();
		}
		return result;

	}
	
	
}