package com.iamberry.wechat.tools;


import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.springframework.stereotype.Component;

@Component
public class GetWxOrderno {

  /**
   *description:获取预支付id
   */
  public static Object getPayNo(String url,String xmlParam){
	try {
		String jsonStr = HttpClient431Util.doPostContent(xmlParam, "application/json", url);
		//判断
		assert jsonStr != null;
		if(jsonStr.contains("FAIL")){
			return (WxPrepayIdErrorResult) MessageUtil.xmlToBean(jsonStr, WxPrepayIdErrorResult.class);
	    }
	    Map map = doXMLParse(jsonStr);
		return (String) map.get("prepay_id");
	} catch (Exception e1) {
		// TODO Auto-generated catch block
		e1.printStackTrace();
	}
	return null;
	/*  //创建连接
	  DefaultHttpClient client = new DefaultHttpClient();
	  //参数
	  client.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
	  ///请求方式
	  HttpPost httpost= HttpClientConnectionManager.getPostMethod(url);
	  //接受预支付id
	  String prepay_id = "";
     try {
    	 //参数赋值
		 httpost.setEntity(new StringEntity(xmlParam, "UTF-8"));
		 //执行POST请求
		 HttpResponse response = httpclient.execute(httpost);
		 //解析执行接口
	     String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
	     
	     //判断
	    if(jsonStr.indexOf("FAIL")!=-1){
	    	
	    	WxPrepayIdErrorResult errorResult = (WxPrepayIdErrorResult) MessageUtil.xmlToBean(jsonStr, WxPrepayIdErrorResult.class);
	    	return errorResult;
	    }
	    Map map = doXMLParse(jsonStr);
	    prepay_id  = (String) map.get("prepay_id");
	} catch (Exception e) {
		e.printStackTrace();
	}
	return prepay_id;*/
  }
  
  /**
   *description:获取扫码支付连接
   *@param url
   *@param xmlParam
   *@return
   * @author ex_yangxiaoyi
   * @see
   */
  public static String getCodeUrl(String url,String xmlParam){
	String code_url = null;
	try {
		String jsonStr = HttpClient431Util.doPostContent(xmlParam, "JSON", url);
		if(jsonStr.indexOf("FAIL")!=-1){
	    	return code_url;
	    }
	    Map map = doXMLParse(jsonStr);
	    code_url  = (String) map.get("code_url");
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return code_url;
	  /*
	 DefaultHttpClient client = new DefaultHttpClient();
	 client.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
	 HttpPost httpost= HttpClientConnectionManager.getPostMethod(url);
	 String code_url = "";
     try {
		 httpost.setEntity(new StringEntity(xmlParam, "UTF-8"));
		 HttpResponse response = httpclient.execute(httpost);
	     String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
	    if(jsonStr.indexOf("FAIL")!=-1){
	    	return code_url;
	    }
	    Map map = doXMLParse(jsonStr);
	    code_url  = (String) map.get("code_url");
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return code_url;*/
  }
  
  
  /**
	 * 解析xml,返回第一级元素键值对。
	 * @param strxml
	 * @return
	 * @throws JDOMException
	 * @throws IOException
	 */
	public static Map doXMLParse(String strxml) throws Exception {
		if(null == strxml || "".equals(strxml)) {
			return null;
		}
		
		Map m = new HashMap();
		InputStream in = String2Inputstream(strxml);
		SAXBuilder builder = new SAXBuilder();


		// 防止XXE
		builder.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
		builder.setFeature("http://xml.org/sax/features/external-general-entities", false);
		builder.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
		builder.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);

		Document doc = builder.build(in);
		Element root = doc.getRootElement();
		List list = root.getChildren();
		Iterator it = list.iterator();
		while(it.hasNext()) {
			Element e = (Element) it.next();
			String k = e.getName();
			String v = "";
			List children = e.getChildren();
			if(children.isEmpty()) {
				v = e.getTextNormalize();
			} else {
				v = getChildrenText(children);
			}
			
			m.put(k, v);
		}
		
		//关闭io
		in.close();
		
		return m;
	}
	/**
	 * 获取子结点的xml
	 * @param children
	 * @return String
	 */
	public static String getChildrenText(List children) {
		StringBuffer sb = new StringBuffer();
		if(!children.isEmpty()) {
			Iterator it = children.iterator();
			while(it.hasNext()) {
				Element e = (Element) it.next();
				String name = e.getName();
				String value = e.getTextNormalize();
				List list = e.getChildren();
				sb.append("<" + name + ">");
				if(!list.isEmpty()) {
					sb.append(getChildrenText(list));
				}
				sb.append(value);
				sb.append("</" + name + ">");
			}
		}
		
		return sb.toString();
	}
  public static InputStream String2Inputstream(String str) {
		return new ByteArrayInputStream(str.getBytes());
	}
  
}