package com.platform.http;

import java.beans.IntrospectionException;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.http.HttpStatus;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.platform.utils.Bean2MapUtils;

/** http请求客户端
 * @author chen
 *
 */
public class HttpUtils {
	
	private static ObjectMapper mapper = new ObjectMapper();
	/**
	 * 日志
	 */
	public final static Logger log = Logger.getLogger(HttpUtils.class);

	/** post请求前 对象 转成 json
	 * @param subUrl
	 * @param data
	 * @return
	 * @throws IOException 
	 * @throws JsonMappingException 
	 * @throws JsonGenerationException 
	 */
	public String sendAjaxPost(String subUrl, Object data) throws JsonGenerationException, JsonMappingException, IOException {
		String jsondata = null;
		//转成json
		if (null != data) {
			Writer strWriter = new StringWriter();
			mapper.writeValue(strWriter, data);
			jsondata = strWriter.toString();
		}
		return sendAjaxPost(subUrl, jsondata);
	}
	
	/** 发post请求
	 * @param subUrl
	 * @param map
	 * @return
	 */
	public String sendAjaxPost(String subUrl, String json) {
		String resultStr = "";
		HttpClient client = new DefaultHttpClient();
		
		HttpPost post = new HttpPost(HttpClientConstant.URL_IP_PORT + subUrl);
		try {
			// 传参
			if (null != json && !"".equals(json)) {
				 // 建立一个NameValuePair数组，用于存储欲传送的参数  
				StringEntity entity = new StringEntity(json,"UTF-8");
				entity.setContentEncoding("UTF-8");    
                entity.setContentType("application/json");  
                
				post.setEntity(entity);
			}
			// 发送
			HttpResponse respone = client.execute(post);
			//接收返回值
			if(respone.getStatusLine().getStatusCode() == HttpStatus.OK.value()){
				HttpEntity result = respone.getEntity();
				if (null != result) {
					resultStr = EntityUtils.toString(result);
				}
			}
		} catch (Exception e) {
			log.info(HttpClientConstant.URL_IP_PORT + subUrl);
			log.error(e);
		}
		return resultStr;
	}
	
	/** post请求前 对象 转成 map
	 * @param subUrl
	 * @param data
	 * @return
	 */
	public String sendPost(String subUrl, Object data) {
		Map<String, Object> map = null;
		if (null != data) {
			//转成json
			 try {
				map = Bean2MapUtils.convertBean(data);
			} catch (IllegalAccessException e) {
				log.error(e);
			} catch (InvocationTargetException e) {
				log.error(e);
			} catch (IntrospectionException e) {
				log.error(e);
			}
		}
		return sendPost(subUrl, map);
	}
	
	/** 普通map 发送
	 * @param subUrl
	 * @param map
	 * @return
	 */
	public String sendPost(String subUrl, Map<String, Object> map) {
		String resultStr = "";
		HttpClient client = new DefaultHttpClient();
		
		HttpPost post = new HttpPost(HttpClientConstant.URL_IP_PORT + subUrl);
		try {
			// 传参
			List<NameValuePair> parameters = new ArrayList<NameValuePair>();
			if (null != map) {
				// 封装数据
				for (String key : map.keySet()) {
					String value = "";
					Object obj = map.get(key);
					String type = obj.getClass().getName();
					//字符串
					if (type.equals("java.lang.String")) {
						value = (String) obj;
					}
					//数组
					else if(type.contains("[L")){
						JSONArray jsonarr = JSONArray.fromObject(obj);
						value = jsonarr.toString();
					}
					//集合
					else if(type.contains("java.util.")){
						JSONArray jsonarr = JSONArray.fromObject(obj);
						value = jsonarr.toString();
					}
					//除字符外的 其他 基本类型
					else if(type.contains("java.lang.")){
						value = String.valueOf(obj);
					}
					//对象
					else {
						JSONObject jsondata = JSONObject.fromObject(obj);
						value = jsondata.toString();
					}
					parameters.add(new BasicNameValuePair(key, value));
				}
				// 传参 放入 url的 form中
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters,
						"UTF-8");
				post.setEntity(entity);
			}
			
			// 发送
			HttpResponse respone = client.execute(post);
			HttpEntity result = respone.getEntity();
			if (null != result) {
				resultStr = EntityUtils.toString(result);
			}
		} catch (Exception e) {
			log.info(HttpClientConstant.URL_IP_PORT + subUrl);
			log.error(e);
		}
		return resultStr;
	}

//	public static void main(String[] args) {
//		HttpUtils ht = new HttpUtils();
//		Volume v = new Volume("a", 200, 10, null, null);
//		String rest = ht.sendPost("data/getOperateTasks", v);
//		System.out.println(rest);
//		Map<String, Object> m = new HashMap<String, Object>();
//		m.put("a", 1);
//		rest = ht.sendPost("data/getOperateTasks", m);
//		System.out.println(rest);
//		rest = ht.sendPost("data/getOperateTasks", null);
//		System.out.println(rest);
//		//
//		String[] str = new String[2];
//		str[1] = "1";
//		str[0] = "0";
//		m.put("arr", str);
//		
//		Volume[] vli = new Volume[2];
//		vli[1] =  new Volume("a", 200, 10, null, null);
//		vli[0] =  new Volume("a", 200, 10, null, null);
//		m.put("vli", vli);
//		List<Integer> num = new ArrayList<Integer>();
//		num.add(2);
//		m.put("num", num);
//		m.put("bool", true);
//		rest = ht.sendPost("data/getOperateTasks", m);
//		System.out.println(rest);
//	}

}
