package cn.pluss.platform.wap;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.xml.sax.InputSource;

/**
 * @author yuchen
 * 
 * @Description
 */
public class XmlUtil {

	/**
	 * 
	 * toMap:(xml字符串转map集合,测试无误 可用). <br/>
	 * 
	 * 
	 * @author Administrator
	 * @param xml
	 * @return
	 * @since JDK 1.8
	 */
	public static Map<String, Object> toMap(String xml) {
		Map<String, Object> result = new HashMap<>(16);
		if ("".equals(xml)) {
			return result;
		}
		try {
			StringReader read = new StringReader(xml);
			InputSource source = new InputSource(read);
			SAXBuilder sb = new SAXBuilder();

			Document doc = sb.build(source);
			Element root = doc.getRootElement();
			result.put(root.getName(), root.getText());
			parse(root, result);
		} catch (Exception e) {
			e.printStackTrace();
		}
		result.remove("xml");
		return result;
	}
	
	public static Map<String, Object> toMapLeshua(String xml) {
		Map<String, Object> result = new HashMap<>(16);
		if ("".equals(xml)) {
			return result;
		}
		try {
			StringReader read = new StringReader(xml);
			InputSource source = new InputSource(read);
			SAXBuilder sb = new SAXBuilder();

			Document doc = sb.build(source);
			Element root = doc.getRootElement();
			result.put(root.getName(), root.getText());
			parse(root, result);
		} catch (Exception e) {
			e.printStackTrace();
		}
		result.remove("leshua");
		return result;
	}
	

	private static Map<String, Object> parse(Element root, Map<String, Object> result) {
		List<Element> nodes = root.getChildren();
		int len = nodes.size();
		if (len == 0) {
			result.put(root.getName(), root.getText());
		} else {
			for (int i = 0; i < len; i++) {
				// 循环依次得到子元素
				Element element = nodes.get(i);
				result.put(element.getName(), element.getText());
				// parse(element,result);
			}
		}
		return result;
	}

	/**
	 * 
	 * toUTF8:(将微信支付成功的回调 request.InputStream转 UTF-8). <br/>
	 * 
	 * 
	 * @author Administrator
	 * @param is
	 * @return
	 * @since JDK 1.8
	 */
	public static String toUTF8(InputStream is) {
		String result = null;
		try {
			BufferedReader in = new BufferedReader(new InputStreamReader(is, "UTF-8"));
			StringBuffer buffer = new StringBuffer();
			String line = "";
			while ((line = in.readLine()) != null) {
				buffer.append(line);
			}
			result = buffer.toString();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return result;
	}

}
