package com.cim.idm.util;

import com.alibaba.fastjson.JSONObject;
import com.cim.idm.data.ErpMessageLog;
import com.cim.idm.framework.IDMFrameServiceProxy;
import com.cim.idm.framework.util.sys.SystemPropHelper;
import com.cim.idm.framework.util.time.TimeStampUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.LinkedBlockingQueue;

public class MessageLogUtil {

	private static Logger log = LoggerFactory.getLogger(MessageLogUtil.class);
	private static MessageLogUtil messageLogUtil = new MessageLogUtil();
	private static MessageLogWriter messageLogWriter = messageLogUtil.new MessageLogWriter();
	static {
		Thread messageLogThread = new Thread(messageLogWriter);
		messageLogThread.setDaemon(true);
		messageLogThread.setName("MESSAGELOGGING");
	    messageLogThread.start();
	}
	public static void writeMessageLog(ErpMessageLog erpMessageLog) {
	      messageLogWriter.getQueue().offer(erpMessageLog);
	}
	public static void insertSapMessageLog(String eventName,String resultCode,Object messageLog,String messageId,Object resultMessage) {
		try {
			String serverName = System.getProperty("Seq");
			String currentEventTimeKey = TimeStampUtil.getCurrentEventTimeKey();
			String sql="insert into bs_erpmessagelog (servername,eventname,eventtimekey,resultcode,messagelog,messageid,resultmessage) "
					+ "values(:servername,:eventname,:eventtimekey,:resultcode,:messagelog,:messageid,:resultmessage)";
//			Object messageLogStr = JSONObject.toJSON(messageLog);
//			Object resultMessageLogStr = JSONObject.toJSON(resultMessage);
			HashMap<String,Object> hashMap = new HashMap<String,Object>();
			hashMap.put("servername", serverName);
			hashMap.put("eventname", eventName);
			hashMap.put("eventtimekey", currentEventTimeKey);
			hashMap.put("resultcode", resultCode);
			hashMap.put("messagelog", JSONObject.toJSONString(messageLog));
			hashMap.put("messageid", messageId);
			hashMap.put("resultmessage", JSONObject.toJSONString(resultMessage));
			IDMFrameServiceProxy.getSqlTemplate().update(sql, hashMap);
		} catch (Exception e) {
			log.error(e.getMessage(),e);
		}
	}
	
	public static void saveMessageLog(ErpMessageLog erpMessagelog) {
		try {
	        String sql = "INSERT INTO BS_ERPMESSAGELOG(INTERFACETIME,SERVERNAME, EVENTNAME, EVENTTIMEKEY, EVENTUSER, MESSAGELOG2,RESULTCODE,MESSAGEID,RESULTMESSAGE,MESSAGELOG,RESULTMESSAGE2)" + SystemPropHelper.CR
	                + "VALUES(TO_DATE(:INTERFACETIME,'yyyy-mm-dd hh24:mi:ss'),:SERVERNAME, :EVENTNAME, :EVENTTIMEKEY, :EVENTUSER, :MESSAGELOG2,:RESULTCODE,:MESSAGEID,:RESULTMESSAGE,:MESSAGELOG,:RESULTMESSAGE2)";
	        Map<String, Object> bindMap = new HashMap<String, Object>();
	        bindMap.put("SERVERNAME", erpMessagelog.getServerName());
	        bindMap.put("EVENTNAME", erpMessagelog.getEventName());
	        bindMap.put("EVENTTIMEKEY", TimeStampUtil.getCurrentEventTimeKey());
	        bindMap.put("EVENTUSER", erpMessagelog.getEventUser());
	        bindMap.put("MESSAGEID", erpMessagelog.getMessageId());
	        bindMap.put("INTERFACETIME", erpMessagelog.getInterfaceTime());
	        bindMap.put("RESULTCODE", erpMessagelog.getResultCode());
	        bindMap.put("MESSAGELOG", erpMessagelog.getSendMsg());// 推送ERP的json
	        bindMap.put("RESULTMESSAGE", erpMessagelog.getReturnMsg());// 返回结果的json
	        bindMap.put("MESSAGELOG2", null);// 推送ERP的json
	        bindMap.put("RESULTMESSAGE2", erpMessagelog.getReturnMsg2());// 返回结果的json
	        IDMFrameServiceProxy.getSqlTemplate().update(sql, bindMap);
		}catch(Exception e) {
			log.error(e.getMessage(),e);
		}
    }
	class MessageLogWriter implements Runnable {
		private LinkedBlockingQueue<Object> queue;
		private boolean run = true;
		public MessageLogWriter() {
		    log.debug("default constructor for spring...");
		    this.queue = new LinkedBlockingQueue();
		}
		public LinkedBlockingQueue<Object> getQueue() {
			return this.queue;
		}
		public void setRun(boolean run) {
			this.run = run;
		}
		@Override
		public void run() {
			Object annex = new Object();
			while(this.run) {
				synchronized(this.getQueue()) {
		            try {
		               Object obj = this.getQueue().take();
		               if (obj != null) {
		                  annex = obj;
		               }
		            } catch (InterruptedException e) {
		               log.error(e.getMessage(),e);
		            }
	         	}
				if (annex instanceof ErpMessageLog) {
		            saveMessageLog((ErpMessageLog)annex);
		        }
			}
		}
		
	}
}
