package com.cim.idm.mwmsextend.timer.pms;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.cim.idm.wmsextend.generic.GenericServiceProxy;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdom.Document;
import org.jdom.Element;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.cim.idm.framework.IDMFrameServiceProxy;
import com.cim.idm.framework.util.xml.JdomUtils;
import com.cim.idm.wmsextend.generic.util.SMessageUtil;

public class PMSTimer implements Job{
	
	private static Log log = LogFactory.getLog(PMSTimer.class);
	static String factory = System.getProperty("factory");
	@SuppressWarnings("static-access")
	@Override
	public void execute(JobExecutionContext arg0) throws JobExecutionException {
		// TODO Auto-generated method stub
		log.info("do PMSInventory Sumary ...");
		try
		{	 
			IDMFrameServiceProxy.getTransactionManager().beginTransaction();
			String sql;
			List<Map<String, Object>> rs;		
			//判断是否已经有进程在执行自动计算功能了				
			sql = "SELECT CONSTANTVALUE FROM CONSTANTDEF WHERE CONSTANTNAME='WMSAutoPMSInventoryStart' ";			
			rs = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, new Object[]{});			
			if(rs.equals(null) || rs.size()==0)//rs[0][0].equals(""))
			{							
				try {			
					//首次未有SPCAutoCalculateCLStart值时，插入该值
					sql="INSERT INTO CONSTANTDEF(CONSTANTNAME,DESCRIPTION,CONSTANTVALUE,CACHEFLAG) "
							+ "VALUES('WMSAutoPMSInventoryStart','One of wms Server has started PMS ','N','N')";
					IDMFrameServiceProxy.getSqlTemplate().update(sql, new Object[]{});	
				} catch (Exception e )
				{					
					//首次未有SPCAutoCalculateCLStart值时，第一个线程已经完成插入，因此后续线程退出计算
					log.info("Insert value failed for another process has started.");
					IDMFrameServiceProxy.getTransactionManager().commitTransaction();
					return;	
				}		
			}
			else
			{
				log.info("WMSAutoPMSInventoryStart = "+rs.get(0).get("CONSTANTVALUE").toString());
				if(rs.get(0).get("CONSTANTVALUE").toString().equals("Y"))//已经有进程在自动计算，退出等待下次执行
				{
					IDMFrameServiceProxy.getTransactionManager().commitTransaction();	
					log.info("Another process has started.");					
					return;
				}		
			}
				
			//无进程在自动计算，本进程开始自动计算。一下是

			sql = "UPDATE CONSTANTDEF SET CONSTANTVALUE='Y'  WHERE CONSTANTNAME='WMSAutoPMSInventoryStart'";	
			IDMFrameServiceProxy.getSqlTemplate().update(sql, new Object[]{});			
			IDMFrameServiceProxy.getTransactionManager().commitTransaction();	

			/***End*****/
			
			IDMFrameServiceProxy.getTransactionManager().beginTransaction();
			
			/***
			 * 查询List
			 */
			Calendar c = Calendar.getInstance();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmssSSS");
			Date dt = new Date();
			c.setTime(dt);
			String endTime = sdf.format(dt)+"000000000000";
			c.add(Calendar.DATE, -1);
			Date startDt = c.getTime();
			String startTime = sdf.format(startDt)+"000000000000";
			String sqlSearch = "SELECT SITENAME,MATERIALSPECNAME AS PARTSSPECNAME,SUM(MATERIALQUANTITY) AS QUANTITY "
					+ " FROM MATERIALPACKING "
					+ "  WHERE STOCKSTATE='Stocked' "
					+ " AND MATERIALSPECNAME IN "
					+ " (SELECT distinct MATERIALSPECNAME "
					+ "  FROM MATERIALPACKINGHISTORY "
					+ "  WHERE MATERIALTYPE='ERSA' "
					+ "  AND SITENAME=:SITENAME "
					+ "  AND TIMEKEY BETWEEN :STARTTIME AND :ENDTIME) "
					+ " GROUP BY SITENAME,MATERIALSPECNAME";
			Map<String, String> bindMap = new HashMap<String, String>();
			bindMap.put("SITENAME", factory);
			bindMap.put("STARTTIME", startTime);
			bindMap.put("ENDTIME", endTime);
			List<Map<String, Object>> sqlResult = IDMFrameServiceProxy.getSqlTemplate().queryForList(sqlSearch, bindMap);
			
			if(sqlResult.size()>0){

				String messageName = "GetWMSStock";
				String shopName = "ARRAY";
				String machineName = "";
				String transactionId = dateFormat.format(dt);
				String sourceSubjectName = "BOE."+factory+".MWMS."+System.getProperty("mode")+".CNMsvr";
				String originalSourceSubjectName = sourceSubjectName;
				String targetSubjectName = "BOE."+factory+".PMS."+System.getProperty("mode")+".INFsvr";
				String eventUser = "WMS";
				String eventComment = "MachineStateChanged";
				Document shiptoPMSMessage = SMessageUtil.createPMSMessageDocument(messageName, factory, shopName, machineName, 
						transactionId, originalSourceSubjectName, sourceSubjectName, targetSubjectName, eventUser, eventComment);
				String nodePath = "//Message/Body";
				Element parentElement = JdomUtils.getNode(shiptoPMSMessage, nodePath);

				for(int i=0;i<sqlResult.size();i++){
					Element childElementA=new Element("item");
					parentElement.addContent(childElementA);
					SMessageUtil.createElement(nodePath, childElementA, "SITENAME", sqlResult.get(i).get("SITENAME").toString());
					SMessageUtil.createElement(nodePath, childElementA, "PARTSSPECNAME", sqlResult.get(i).get("PARTSSPECNAME").toString());
					SMessageUtil.createElement(nodePath, childElementA, "QUANTITY", sqlResult.get(i).get("QUANTITY").toString());
					SMessageUtil.createElement(nodePath, childElementA, "DESCRIPTION", "");
				}

				String replyMSG = JdomUtils.toString(shiptoPMSMessage);
				log.info("shiptoMESMessage:>>"+replyMSG);
				String senderName = "PMSSender";
				GenericServiceProxy.getGenericSender(senderName).setDataField("Message");
				GenericServiceProxy.getGenericSender(senderName).send(replyMSG);
			}
			
			IDMFrameServiceProxy.getTransactionManager().commitTransaction();				
			
		}
		catch (Exception e )
		{	
			IDMFrameServiceProxy.getTransactionManager().rollbackAllTransactions();			
			//首次未有SPCAutoCalculateCLStart值时，第一个线程已经完成插入，因此后续线程退出计算
			log.info("Insert value failed for another process has started.");
			String endsql = "UPDATE CONSTANTDEF SET CONSTANTVALUE='N'  WHERE CONSTANTNAME='WMSAutoPMSInventoryStart'";	
			IDMFrameServiceProxy.getSqlTemplate().update(endsql, new Object[]{});	
			return;	
		}	
		finally{
		String endsql = "UPDATE CONSTANTDEF SET CONSTANTVALUE='N'  WHERE CONSTANTNAME='WMSAutoPMSInventoryStart'";	
		IDMFrameServiceProxy.getSqlTemplate().update(endsql, new Object[]{});	
		IDMFrameServiceProxy.getTransactionManager().commitTransaction();	
	}
		
		

	}

}
