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

import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.cim.idm.framework.IDMFrameServiceProxy;
import com.cim.idm.mwmsextend.generic.util.CommonValidation;


public class SAPTimer implements Job {

	private static Log log = LogFactory.getLog(SAPTimer.class);
	@SuppressWarnings("static-access")
	@Override
	public void execute(JobExecutionContext arg0) throws JobExecutionException {
		// TODO Auto-generated method stub
		log.info("do SAPSend ...");
		
//       ERPInterfaceServiceImpl erpImpl=new ERPInterfaceServiceImpl();
		
		
		String failedSql = "SELECT MESSAGEID,EVENTTIMEKEY , RECEIVEACTNO,EVENTNAME ,EVENTUSER ,RECEIVEREQUESTNAME,SHIPREQUESTNAME,FAILMESSAGE,RESULTCODE ,REPEATCOUNT,SITENAME  FROM BS_SAPMESSAGELOG WHERE (REPEATCOUNT IS NULL OR REPEATCOUNT< 3 ) AND (RESULTCODE IS NULL OR RESULTCODE<>'S')  ORDER BY EVENTTIMEKEY ";
		List<Map<String, Object>> failInfoList = IDMFrameServiceProxy.getSqlTemplate().queryForList(failedSql, new Object[] {});
		// 如果没有超时信息，不进行下一步操作
		if (failInfoList.equals(null) || failInfoList.size() == 0) return;
		IDMFrameServiceProxy.getTransactionManager().beginTransaction();
		String messageID;
		String eventName;
		String eventTimeKey;
		String eventUser;
		String resultCode;
		String siteName;
		String sql;
		String newMessageID;
		
		for (int i = 0; i < failInfoList.size(); i++) {

			messageID = failInfoList.get(i).get("MESSAGEID").toString();
			eventName = failInfoList.get(i).get("EVENTNAME").toString();
			eventTimeKey = failInfoList.get(i).get("EVENTTIMEKEY").toString();
			resultCode=failInfoList.get(i).get("RESULTCODE").toString();
			siteName=failInfoList.get(i).get("SITENAME").toString();
			eventUser=failInfoList.get(i).get("EVENTUSER").toString();
			
			
			IDMFrameServiceProxy.getTransactionManager().commitTransaction();
			
			try {
				
				IDMFrameServiceProxy.getTransactionManager().beginTransaction();
				//判断是否已经有进程在执行自动计算功能了				
				sql = "SELECT CONSTANTVALUE FROM CONSTANTDEF WHERE CONSTANTNAME='WMSAutoSapStart' for update";			
				List<Map<String, Object>> sqlResult = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, new Object[]{});			
				if(sqlResult.equals(null) || sqlResult.size()==0)//rs[0][0].equals(""))
				{							
					try {			
						//首次未有WMSAutoSapStart值时，插入该值
						sql="INSERT INTO CONSTANTDEF(CONSTANTNAME,DESCRIPTION,CONSTANTVALUE,CACHEFLAG) "
								+ "VALUES('WMSAutoSapStart','One of wms Server has started sap ','N','N')";
						IDMFrameServiceProxy.getSqlTemplate().update(sql, new Object[]{});	
						
					} catch (Exception e )
					{					
						//首次未有WMSAutoSapStart值时，第一个线程已经完成插入，因此后续线程退出计算
						log.info("Insert value failed for another process has started.");
						IDMFrameServiceProxy.getTransactionManager().commitTransaction();
						return;	
					}		
				}
				else
				{
					log.info("WMSAutoSapStart = "+sqlResult.get(0).get("CONSTANTVALUE").toString());
					if(sqlResult.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='WMSAutoSapStart'";	
				IDMFrameServiceProxy.getSqlTemplate().update(sql, new Object[]{});			
				IDMFrameServiceProxy.getTransactionManager().commitTransaction();	

				/***End*****/
				
//				IDMFrameServiceProxy.getTransactionManager().beginTransaction();
				newMessageID=new CommonValidation().GetMessageID(siteName);
//				PIReturn pireturn=erpImpl.GetPIReturn(eventName, eventTimeKey, eventUser, messageID, resultCode, newMessageID, siteName);
//				if(pireturn !=null){
//					//处理出错，不影响整理循环，继续执行下一条
//					String endsql = "UPDATE CONSTANTDEF SET CONSTANTVALUE='N'  WHERE CONSTANTNAME='WMSAutoSapStart'";	
//					IDMFrameServiceProxy.getSqlTemplate().update(endsql, new Object[]{});
//					IDMFrameServiceProxy.getTransactionManager().commitTransaction();	
//				}else {
//					IDMFrameServiceProxy.getTransactionManager().rollbackTransaction();
//				}
				
				
			} catch (Exception e) {
				IDMFrameServiceProxy.getTransactionManager().rollbackAllTransactions();			
				//首次未有WMSAutoSapStart值时，第一个线程已经完成插入，因此后续线程退出计算
				log.info("Insert value failed for another process has started.");
				String endsql = "UPDATE CONSTANTDEF SET CONSTANTVALUE='N'  WHERE CONSTANTNAME='WMSAutoSapStart'";	
				IDMFrameServiceProxy.getSqlTemplate().update(endsql, new Object[]{});
				
				return;	
			} finally {
				
				String endsql = "UPDATE CONSTANTDEF SET CONSTANTVALUE='N'  WHERE CONSTANTNAME='WMSAutoSapStart'";	
				IDMFrameServiceProxy.getSqlTemplate().update(endsql, new Object[]{});	
				IDMFrameServiceProxy.getTransactionManager().commitTransaction();	
			}

		}

	}

}