package com.cim.idm.utils;

import cn.hutool.core.util.XmlUtil;
import com.tibco.tibrv.TibrvException;
import com.tibco.tibrv.TibrvMsg;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


public class MessageUtil
{

	//private static Log			log						= LogFactory.getLog(MessageUtil.class);
	public static final String 							BPELName_Tag = "bpelname";
	public static final String 							Message_Tag = "Message";
	public static final String 							MessageName_Tag = "MESSAGENAME";
	public static final String 							Header_Tag = "Header";
	public static final String 							Body_Tag = "Body";
	public static final String 							Result_Name_Tag				= "Return";	        
	public static final String							Result_ReturnCode			= "RETURNCODE";
	public static final String							Result_ErrorMessage			= "RETURNMESSAGE";
	public static final String							dataField_TAG = "Message";
	
	private static final String 						ReplySubjectName_Tag = "ORIGINALSOURCESUBJECTNAME";
	
	

	
	private static Log log	= LogFactory.getLog(MessageUtil.class.getName());
	public static String getBpelName(Document doc)
	{                   
		String BpelName = null;
		try { 
			
			BpelName = (String) JdomUtils.getNodeText(doc, "//" + Message_Tag + "/" + Header_Tag + "/" + MessageName_Tag);
			if (BpelName != null && BpelName.length() > 0) {
				if (!BpelName.toLowerCase().endsWith(".bpel"))
					BpelName = BpelName + ".bpel";
			}
		} catch (Exception e) {                                                                 
		}                                                                                       
		return BpelName;                                                                              
	}      
	
	/*
	* Name : getDocumentFromTibrvMsg
	* Desc : This function is getDocumentFromTibrvMsg
	* Author : AIM Systems, Inc
	* Date : 2011.02.17
	*/
	public static Document getDocumentFromTibrvMsg(TibrvMsg data, String dataFieldTag)
	{
		
		Document document = null;
		String strMsg = "";
		String replySubjectName = "";
		if (data instanceof TibrvMsg)
		{
			TibrvMsg TibrvMsg = (com.tibco.tibrv.TibrvMsg)data;
			try {
				strMsg = (String)TibrvMsg.get(dataFieldTag);
				
				replySubjectName = (String)TibrvMsg.getReplySubject();
				if (replySubjectName == null) replySubjectName = "";
					
			} catch (TibrvException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		
		try {
			document = JdomUtils.loadText(strMsg);
//			document = new SAXBuilder("org.apache.xerces.parsers.SAXParser").build(new StringReader(strMsg));
		} catch (Exception e) {
			if(e instanceof JDOMException){
				log.error("["+getCurrentTime()+"]:Receive A Error Msg :["+strMsg+"]");
				log.error("["+getCurrentTime()+"]:Message can not be parsed to XML Document");
				log.error(e, e);
				return null;
			}
			else if(e instanceof IOException){
				log.error("["+getCurrentTime()+"]:Receive A New Msg :["+strMsg+"]");
				log.error("["+getCurrentTime()+"]:Message read I/O Exception");
				log.error(e, e);
				return null;
			}else{
				log.error("["+getCurrentTime()+"]:Receive A New Msg :["+strMsg+"]");
				log.error(e, e);
				return null;
			}
//			try {
//				document = createXmlDocument(strMsg);
//			} catch (Exception ex) {
//				log.error(ex, ex);
//			}
		} 
		
		if ( replySubjectName.length() > 0 )
			setItemValue(document, Header_Tag, ReplySubjectName_Tag, replySubjectName);
		return document;
	}
	
	public static String getCurrentTime()
	{
		long t = System.currentTimeMillis();
		Timestamp st = new Timestamp(t);
		return st.toString();
	}
	
	/*
	* Name : replyXMLMessage
	* Desc : This function is replyXMLMessage
	* Author : AIM Systems, Inc
	* Date : 2011.02.17
	*/
	public static String replyXMLMessage(String ReturnCode)
	{
		Document doc = JdomUtils.createDocument(Message_Tag);
		MessageUtil.setResultItemValue(doc, Result_ReturnCode, ReturnCode);
		MessageUtil.setResultItemValue(doc, Result_ErrorMessage, "");
		String replyMSG = JdomUtils.toString(doc);
		return replyMSG;
	}
	
	/*
	* Name : setElement
	* Desc : This function is setElement
	* Author : AIM Systems, Inc
	* Date : 2011.02.20
	*/
	public static void setElement(String nodePath, Document doc, String nodeName, String nodeValue)
	{
		if (nodeValue == null) nodeValue = "";
		try {
			Element element = JdomUtils.getNode(doc, nodePath + nodeName);
			if (element != null) {
				if (nodePath.substring(nodePath.length()-1 , nodePath.length()).equalsIgnoreCase("/"))
					nodePath = nodePath.substring(0, nodePath.length()-1);
				JdomUtils.setNodeText(doc, nodePath, nodeName, nodeValue);
			}
			// not Exist Case 
			else {
				if (nodePath.substring(nodePath.length()-1 , nodePath.length()).equalsIgnoreCase("/"))
					nodePath = nodePath.substring(0, nodePath.length()-1);
				Element parentElement = JdomUtils.getNode(doc, nodePath);
				Element newElement = JdomUtils.addElement(parentElement, nodeName, nodeValue);
			}
		} catch (Exception e) {                                                                 
			e.printStackTrace();                                                                
		}                                                                                                                                                                  
	}
	
	/*
	* Name : setResultItemValue
	* Desc : This function is setResultItemValue
	* Author : AIM Systems, Inc
	* Date : 2011.02.20
	*/
	public static void setResultItemValue(Document doc, String nodeName, String nodeValue)
	{
		if (doc.getRootElement().getChild(Result_Name_Tag) == null)
			doc.getRootElement().addContent(new Element(Result_Name_Tag));
		
		String nodePath = "//" + Message_Tag + "/" + Result_Name_Tag + "/";
		setElement(nodePath, doc, nodeName, nodeValue);

		if (nodeName.equalsIgnoreCase(MessageUtil.Result_ReturnCode) && !nodeValue.equalsIgnoreCase("0"))
			log.error(nodeName + " : " + nodeValue);
		else if (nodeName.equalsIgnoreCase(MessageUtil.Result_ErrorMessage) && nodeValue.length() > 0)
			log.error(nodeName + " : " + nodeValue);
		else if  (nodeName.equalsIgnoreCase(MessageUtil.Result_ErrorMessage) && nodeValue.length() == 0)
			log.error(nodeName + " : ");
	}
	
	
	public static void setBodyItemValue(Document doc, String nodeName, String nodeValue){
		if (doc.getRootElement().getChild(Body_Tag) == null)
			doc.getRootElement().addContent(new Element(Body_Tag));
		
		String nodePath = "//" + Message_Tag + "/" + Body_Tag + "/";
		setElement(nodePath, doc, nodeName, nodeValue);

		if (nodeName.equalsIgnoreCase(MessageUtil.Result_ReturnCode) && !nodeValue.equalsIgnoreCase("0"))
			log.error(nodeName + " : " + nodeValue);
		else if (nodeName.equalsIgnoreCase(MessageUtil.Result_ErrorMessage) && nodeValue.length() > 0)
			log.error(nodeName + " : " + nodeValue);
		else if  (nodeName.equalsIgnoreCase(MessageUtil.Result_ErrorMessage) && nodeValue.length() == 0)
			log.error(nodeName + " : ");
	}
	/*
	* Name : setReplyListItemValue
	* Desc : This function is setReplyListItemValue
	* Author : AIM Systems, Inc
	* Date : 2011.02.20
	*/
	public static void setReplyListItemValue(Document doc, String Path, String nodeName, String nodeValue)
	{
		if (doc.getRootElement().getChild(Result_Name_Tag) == null)
			doc.getRootElement().addContent(new Element(Result_Name_Tag));
		
		String nodePath = "//" + Message_Tag + "/" + Body_Tag + "/" + Path;
		setElement(nodePath, doc, nodeName, nodeValue);

		if (nodeName.equalsIgnoreCase(MessageUtil.Result_ReturnCode) && !nodeValue.equalsIgnoreCase("0"))
			log.error(nodeName + " : " + nodeValue);
		else if (nodeName.equalsIgnoreCase(MessageUtil.Result_ErrorMessage) && nodeValue.length() > 0)
			log.error(nodeName + " : " + nodeValue);
		else if  (nodeName.equalsIgnoreCase(MessageUtil.Result_ErrorMessage) && nodeValue.length() == 0)
			log.error(nodeName + " : ");
	}
	
	/*
	* Name : createXmlDocument
	* Desc : This function is createXmlDocument
	* Author : AIM Systems, Inc
	* Date : 2011.02.23
	*/
	public static Document createXmlDocument(String messageName, String receivedData) throws Exception
	{
		Element message = new Element( Message_Tag );
		Document document = new Document( message );

		
//		int idx = receivedData.indexOf(" ");
//		String commandName = receivedData.substring(0, idx).trim();
		HashMap<String, String> messageMap = null;
		messageMap = parsingStringMessage(receivedData);
		
		Element header = new Element( Header_Tag );
		
		Element subElement = new Element( BPELName_Tag );
		subElement.setText(messageName);
		header.addContent(subElement);
		
		subElement = new Element( MessageName_Tag );
		subElement.setText(messageName);
		header.addContent(subElement);
		message.addContent(header);
		Element body = new Element( Body_Tag );
		Element ele = null;
		while (messageMap.keySet().iterator().hasNext())
		{
			String keyName = messageMap.keySet().iterator().next();
			String keyValue = messageMap.remove(keyName);
			ele = new Element( keyName );
			ele.setText( keyValue );                                                                                                                            
			body.addContent( ele );       			
		}
		message.addContent(body);
		messageMap.clear();
		return document;
	}
	
	public static Document createXmlDocumentByJson(String sourcesubjectname, String targetsubjectname, String messageName, JSONObject json) throws Exception
	{
		Element message = new Element( Message_Tag );
		Document document = new Document( message );

		HashMap<String, String> messageMap = null;
		
		Element header = new Element( Header_Tag );
		
		Element subElement = new Element( MessageName_Tag );
		subElement.setText(messageName);
		header.addContent(subElement);
		
		subElement = new Element( "EVENTCOMMENT" );
		subElement.setText(messageName);
		header.addContent(subElement);
		
		subElement = new Element( "SOURCESUBJECTNAME" );
		subElement.setText(sourcesubjectname);
		header.addContent(subElement);
		
		subElement = new Element( "TARGETSUBJECTNAME" );
		subElement.setText(targetsubjectname);
		header.addContent(subElement);
		

		subElement = new Element( "SITENAME" );
		subElement.setText("");
		header.addContent(subElement);
		
		subElement = new Element( "EVENTUSER" );
		subElement.setText("");
		header.addContent(subElement);
		
		subElement = new Element( "LANGUAGE" );
		subElement.setText("");
		header.addContent(subElement);
		
		message.addContent(header);
		
		Element body = new Element( Body_Tag );
		Element ele = null;
		//调用从Json转化成XML格式的方法
		
		DocumentUtils.jsonToElement(body, json);
		Iterator keys = json.keys();
//		while (keys.hasNext())
//		{
//			String keyName = (String)keys.next();
//			String keyValue = json.getString(keyName);
////			JSONArray jsonArray = json.getJSONArray(keyName);
////			for (int i = 0; i < jsonArray.length(); i++) {
////				JSONObject o = jsonArray.getJSONObject(i);
////
////			}
//			ele = new Element( keyName );
//			ele.setText( keyValue );
//			body.addContent( ele );
//		}
		message.addContent(body);
//		messageMap.clear();
		return document;
	}

	public static Document createXmlDocumentByJsonV2(String sourcesubjectname, String targetsubjectname, String messageName, JSONObject json, JSONObject headerParam) throws Exception
	{
		Element message = new Element( Message_Tag );
		Document document = new Document( message );

		HashMap<String, String> messageMap = null;

		Element header = new Element( Header_Tag );

		Element subElement = new Element( MessageName_Tag );
		subElement.setText(messageName);
		header.addContent(subElement);

		if (headerParam != null && !headerParam.isEmpty()) {
			for (String key : headerParam.keySet()) {
				String value = headerParam.getString(key);
				subElement = new Element( key );
				subElement.setText(value);
				header.addContent(subElement);
			}
		}
		

		subElement = new Element( "EVENTCOMMENT" );
		subElement.setText(messageName);
		header.addContent(subElement);

		subElement = new Element( "SOURCESUBJECTNAME" );
		subElement.setText(sourcesubjectname);
		header.addContent(subElement);

		subElement = new Element( "TARGETSUBJECTNAME" );
		subElement.setText(targetsubjectname);
		header.addContent(subElement);
		String userId = "";
		String siteName = "";
		try {
			userId = json.getString("USERID");
			
		} catch (Exception e) {
			// TODO: handle exception
		}
		try {
			siteName = json.getString("SITENAME");
		} catch (Exception e) {
			// TODO: handle exception
		}
		if (!StringUtils.isEmpty(siteName)) {
			subElement = new Element( "SITENAME" );
			
			subElement.setText(siteName);
			header.addContent(subElement);
		}
		
		subElement = new Element( "EVENTUSER" );
		
		subElement.setText(userId);
		header.addContent(subElement);

		subElement = new Element( "LANGUAGE" );
		subElement.setText("");
		header.addContent(subElement);

		message.addContent(header);

		Element body = new Element( Body_Tag );
		Element ele = null;
		//调用从Json转化成XML格式的方法

		DocumentUtils.jsonToElementV2(body, json);

		message.addContent(body);

		return document;
	}

//
	/**B19创建xml文档通过string类型
	 * 20230915
	 * @param sourcesubjectname
	 * @param targetsubjectname
	 * @param messageName
	 * @param d 数据
	 * @return
	 * @throws Exception
	 */
	public static Document createXmlDocumentByString(String sourcesubjectname, String targetsubjectname, String messageName, String d) throws Exception
	{
		Element message = new Element( Message_Tag );//Message
		Document document = new Document( message );

		
		Element header = new Element( Header_Tag );//Header
		
		Element subElement = new Element( MessageName_Tag );//MESSAGENAME
		subElement.setText(messageName);
		header.addContent(subElement);
		
		subElement = new Element( "EVENTCOMMENT" );
		subElement.setText(messageName);
		header.addContent(subElement);
		
		subElement = new Element( "SOURCESUBJECTNAME" );
		subElement.setText(sourcesubjectname);
		header.addContent(subElement);
		
		subElement = new Element( "TARGETSUBJECTNAME" );
		subElement.setText(targetsubjectname);
		header.addContent(subElement);
		

		subElement = new Element( "SITENAME" );
		subElement.setText("");
		header.addContent(subElement);
		
		subElement = new Element( "EVENTUSER" );
		subElement.setText("");
		header.addContent(subElement);
		
		subElement = new Element( "LANGUAGE" );
		subElement.setText("");
		header.addContent(subElement);
		
		message.addContent(header);//头存储
		
//		Element body = new Element( Body_Tag );
//		body.setText(d);
		
		com.alibaba.fastjson.JSONObject jsonObject = xmlToJson(d);
		Element body = new Element( Body_Tag );
		Element ele = null;
		//调用从Json转化成XML格式的方法
		
		DocumentUtils.jsonToElement2(body, jsonObject);
		//Iterator keys = jsonObject.keys();
		message.addContent(body);
		return document;
	}
	

	/**B19去除xml开头和结尾的双引号
	 * 20230915
	 * @param xml
	 * @return
	 */
	public static com.alibaba.fastjson.JSONObject xmlToJson(String xml) {
        //去除xml开头和结尾的双引号
        StringBuilder sb = new StringBuilder();
        sb.append(xml);
        char charAt = sb.charAt(0);
        if (sb.charAt(0) == '\"') {
            sb.deleteCharAt(0);
        }
        if (sb.charAt(sb.length() - 1) == '\"') {
            sb.deleteCharAt(sb.length() - 1);
        }
        Map<String, Object> stringObjectMap = XmlUtil.xmlToMap(sb.toString());//xml转map
        String json = com.alibaba.fastjson.JSONObject.toJSONString(stringObjectMap);//转json
        return com.alibaba.fastjson.JSONObject.parseObject(json, com.alibaba.fastjson.JSONObject.class);
    }

/**
	 * 
	 * @param nodePath : The path that create new element 
	 * @param
	 * @param nodeName
	 * @param nodeValue
	 */
	public static void createElement(String nodePath, Element parentElement, String nodeName, String nodeValue)
	{
		if (nodeValue == null) nodeValue = "";
		try {
			if (nodePath.substring(nodePath.length()-1 , nodePath.length()).equalsIgnoreCase("/"))
				nodePath = nodePath.substring(0, nodePath.length()-1);
			//Element parentElement = JdomUtils.getNode(doc, nodePath);
			Element newElement = JdomUtils.addElement(parentElement, nodeName, nodeValue);
		} catch (Exception e) {                                                                 
			e.printStackTrace();                                                                
		}                                                                                                                                                                  
	}
	
	/*
	 *Create xml document
	 *Return as below
	 *<Message>
	 *	<Header>
	 *	</Header>
	 *	<Body>
	 *	</Body>
	 *</Message> 
	 */
	public static Document createERPXmlDocument(String MessageName, String EventComment)
	{
		Element message = new Element( Message_Tag );
		Document document = new Document( message );
		Element header = new Element( Header_Tag );
		message.addContent(header);		
		setElement("//" + Message_Tag + "/" + Header_Tag , document, MessageName_Tag, MessageName);		
		setElement("//" + Message_Tag + "/" + Header_Tag , document, "EVENTCOMMENT", EventComment);
		Element body = new Element( Body_Tag );
		message.addContent(body);
		return document;
	}
	public static Document createTQMSXmlDocument(String MessageName)
	{
		Element message=new Element("INT_WMB008");
		Document document=new Document(message);
		Element header=new Element("jsonParamsStr");
		message.addContent(header);
		String nodePath="//INT_WMB008/jsonParamsStr";
		Element parentElement;
		try {
			parentElement = JdomUtils.getNode(document, nodePath);
			parentElement.addContent(MessageName);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}								
		return document;
	}
	
	
	/*
	* Name : setItemValue
	* Desc : This function is setItemValue
	* Author : AIM Systems, Inc
	* Date : 2011.02.23
	*/
    public static void setItemValue(Document doc, String fatherElement, String nodeName, String nodeValue)
	{                                                                                         
		try {
			//String nodePath = "//" + Message_Tag + "/" + elementName + "/" + nodeName;
			Element root = doc.getRootElement();
			Element father = root.getChild(fatherElement);
			Element childnode = root.getChild(nodeName);
			if (childnode != null)
				childnode.setText(nodeValue);//	JdomUtils.setNodeText(doc, childnode, nodeValue);     
			else {

				childnode = new Element(nodeName);
				childnode.setText(nodeValue);
				father.addContent(childnode);

			}
		} catch (Exception e) {                                                                 
			log.error(e, e);
		}                                                                                                                                                                  	
	}      
	
    /*
	* Name : parsingStringMessage
	* Desc : This function is parsingStringMessage
	* Author : AIM Systems, Inc
	* Date : 2011.02.23
	*/
	private static  HashMap<String, String> parsingStringMessage(String msg)
	{
		String delimeter = "[{X*X}]";
		
		String msg2 = msg;
		while(true)
		{
			int idx1 = msg2.indexOf("=[");
			int idx2 = msg2.indexOf("]", idx1);
			if (idx1 > 0 && idx2 > 0)
			{
				String a = msg2.substring(idx1+2, idx2);
				if (a.length() == 0)
				{
					msg2 = msg2.substring(idx2+1, msg2.length()); continue;
				}
				String b = org.springframework.util.StringUtils.replace(a, "=", "($%^)");
				msg = org.springframework.util.StringUtils.replace(msg, a, b);				
				msg2 = msg2.substring(idx2, msg2.length());
			}
			else break;
		}
		
		String [] messageSplit = msg.split("=");
		HashMap<String, String> params = new HashMap<String, String>();
		StringBuffer keyNameBuffer = new StringBuffer();
		keyNameBuffer.append("Command").append(delimeter);
		StringBuffer valueBuffer = new StringBuffer();
		for (int i=0; i<messageSplit.length; i++)
		{
			if (getKeyName(messageSplit[i]).length() > 0) {
				keyNameBuffer.append(getKeyName(messageSplit[i])).append(delimeter);
				valueBuffer.append(getValue(messageSplit[i])).append(delimeter);
			}
			else {
				valueBuffer.append(messageSplit[i]).append(delimeter);
			}
		}

		String[] keyNames = org.springframework.util.StringUtils.delimitedListToStringArray(keyNameBuffer.toString(), delimeter);
		String[] keyvalues = org.springframework.util.StringUtils.delimitedListToStringArray(valueBuffer.toString(), delimeter);
		
		for (int i=1; i<keyNames.length; i++)
		{
			if (keyNames[i] == null || keyNames[i].trim().length() == 0) continue;
			try {
				keyvalues[i] = keyvalues[i].trim();
				keyvalues[i] = org.springframework.util.StringUtils.replace(keyvalues[i], "($%^)", "=");
				if (keyvalues[i].startsWith("[") && keyvalues[i].endsWith("]"))
					keyvalues[i] = keyvalues[i].substring(1, keyvalues[i].length()-1);
				params.put(keyNames[i], keyvalues[i].trim());
			} catch (Exception e) {
				params.put(keyNames[i], "");
				log.debug("Value of last data is empty");
			}
		}
		return params;
	}	
	
	/*
	* Name : getKeyName
	* Desc : This function is getKeyName
	* Author : AIM Systems, Inc
	* Date : 2011.02.23
	*/
	private static String getKeyName(String partialMsg)
	{
		if (partialMsg.startsWith("[") && partialMsg.endsWith("]"))
			return "";
		String character = "";
		String value = "";
		for (int i=partialMsg.length(); i>0; i--)
		{
			character = partialMsg. substring(i-1, i);
			if (character.equalsIgnoreCase(" "))
			{
				return StringUtils.reverse(value);
			}
			else {
				value += character;
			}
		}
		return "";
	}

	/*
	* Name : getValue
	* Desc : This function is getValue
	* Author : AIM Systems, Inc
	* Date : 2011.02.23
	*/
	private static String getValue(String partialMsg)
	{
		partialMsg = StringUtils.removeEnd(partialMsg, getKeyName(partialMsg));

		return partialMsg;
	}

	public static String setEventComment(Document doc)
	{
		Element root = doc.getDocument().getRootElement();
		String messageName  = root.getChild("Header").getChild("MESSAGENAME").getText();
		String eventComment = root.getChild("Header").getChild("EVENTCOMMENT").getText();
		if(eventComment == null || eventComment.isEmpty() )
		{
			eventComment = messageName;
		}
		return eventComment;
	}

	public static Document createXmlDocumentByExcel(String sourcesubjectname,String targetsubjectname, String messageName,InputStream is) throws Exception {
		Element message = new Element( Message_Tag );
		Document document = new Document( message );

		Element header = new Element( Header_Tag );

		Element subElement = new Element( MessageName_Tag );
		subElement.setText(messageName);
		header.addContent(subElement);

		subElement = new Element( "EVENTCOMMENT" );
		subElement.setText(messageName);
		header.addContent(subElement);

		subElement = new Element( "SOURCESUBJECTNAME" );
		subElement.setText(sourcesubjectname);
		header.addContent(subElement);

		subElement = new Element( "TARGETSUBJECTNAME" );
		subElement.setText(targetsubjectname);
		header.addContent(subElement);


		subElement = new Element( "SITENAME" );
		subElement.setText("");
		header.addContent(subElement);

		subElement = new Element( "EVENTUSER" );
		subElement.setText("");
		header.addContent(subElement);

		subElement = new Element( "LANGUAGE" );
		subElement.setText("");
		header.addContent(subElement);

		message.addContent(header);

		Element body = ExcelUtils.excelToDocument(is);
		message.addContent(body);
		return document;
	}

	public static JSONObject createJsonDocumentByExcel(InputStream is) throws Exception {


		JSONObject body = ExcelUtils.excelToJSON(is);
		//message.addContent(body);
		return body;
	}
	
	public static Document createXmlDocumentByJsonMDC(String sourcesubjectname, String targetsubjectname, String messageName, JSONObject json) throws Exception
	{
		Element message = new Element( Message_Tag );
		Document document = new Document( message );

		HashMap<String, String> messageMap = null;
		
		Element header = new Element( Header_Tag );
		
		Element subElement = new Element( MessageName_Tag );
		subElement.setText(messageName);
		header.addContent(subElement);
		
		subElement = new Element( "EVENTCOMMENT" );
		subElement.setText(messageName);
		header.addContent(subElement);
		
		subElement = new Element( "SOURCESUBJECTNAME" );
		subElement.setText(sourcesubjectname);
		header.addContent(subElement);
		
		subElement = new Element( "TARGETSUBJECTNAME" );
		subElement.setText(targetsubjectname);
		header.addContent(subElement);
		

		subElement = new Element( "SITENAME" );
		subElement.setText("");
		header.addContent(subElement);
		String eventUser="";
		Iterator keys = json.keys();
		while (keys.hasNext())
		{
			String keyName = (String)keys.next();
			if(keyName.equalsIgnoreCase("eventuser")) {
				String keyValue = json.getString(keyName);
				eventUser=keyValue;
			}
			
////			JSONArray jsonArray = json.getJSONArray(keyName);
////			for (int i = 0; i < jsonArray.length(); i++) {
////				JSONObject o = jsonArray.getJSONObject(i);
////
////			}
//			ele = new Element( keyName );
//			ele.setText( keyValue );
//			body.addContent( ele );
		}
		subElement = new Element( "EVENTUSER" );
		subElement.setText(eventUser);
		header.addContent(subElement);
		
		subElement = new Element( "LANGUAGE" );
		subElement.setText("");
		header.addContent(subElement);
		
		message.addContent(header);
		
		Element body = new Element( Body_Tag );
		Element ele = null;
		//调用从Json转化成XML格式的方法
		
		DocumentUtils.jsonToElementMDC(body, json);
//		Iterator keys = json.keys();
//		while (keys.hasNext())
//		{
//			String keyName = (String)keys.next();
//			String keyValue = json.getString(keyName);
////			JSONArray jsonArray = json.getJSONArray(keyName);
////			for (int i = 0; i < jsonArray.length(); i++) {
////				JSONObject o = jsonArray.getJSONObject(i);
////
////			}
//			ele = new Element( keyName );
//			ele.setText( keyValue );
//			body.addContent( ele );
//		}
		message.addContent(body);
//		messageMap.clear();
		return document;
	}
	public static Document createXmlDocumentByJsonPMS(String sourcesubjectname, String targetsubjectname, String messageName, JSONObject json) throws Exception
	{
		Element message = new Element( Message_Tag );
		Document document = new Document( message );

		HashMap<String, String> messageMap = null;
		
		Element header = new Element( Header_Tag );
		
		Element subElement = new Element( MessageName_Tag );
		subElement.setText(messageName);
		header.addContent(subElement);
		
		subElement = new Element( "EVENTCOMMENT" );
		subElement.setText(messageName);
		header.addContent(subElement);
		
		subElement = new Element( "SOURCESUBJECTNAME" );
		subElement.setText(sourcesubjectname);
		header.addContent(subElement);
		
		subElement = new Element( "TARGETSUBJECTNAME" );
		subElement.setText(targetsubjectname);
		header.addContent(subElement);
		

		subElement = new Element( "SITENAME" );
		subElement.setText("");
		header.addContent(subElement);
		
		subElement = new Element( "EVENTUSER" );
		subElement.setText("");
		header.addContent(subElement);
		
		subElement = new Element( "LANGUAGE" );
		subElement.setText("");
		header.addContent(subElement);
		
		message.addContent(header);
		
		Element body = new Element( Body_Tag );
		Element ele = null;
		//调用从Json转化成XML格式的方法
		
		DocumentUtils.jsonToElementPMS(body, json);
		Iterator keys = json.keys();
//		while (keys.hasNext())
//		{
//			String keyName = (String)keys.next();
//			String keyValue = json.getString(keyName);
////			JSONArray jsonArray = json.getJSONArray(keyName);
////			for (int i = 0; i < jsonArray.length(); i++) {
////				JSONObject o = jsonArray.getJSONObject(i);
////
////			}
//			ele = new Element( keyName );
//			ele.setText( keyValue );
//			body.addContent( ele );
//		}
		message.addContent(body);
//		messageMap.clear();
		return document;
	}
}
