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

import java.sql.Timestamp;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

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.alibaba.fastjson.JSON;
import com.cim.idm.framework.IDMFrameServiceProxy;
import com.cim.idm.framework.exception.ext.FrameworkErrorSignal;
import com.cim.idm.framework.exception.ext.NotFoundSignal;
import com.cim.idm.wmsextend.generic.wmsmail.MailTask;

public class MailTimer implements Job
{	
	Logger log;
	private static Log logger = LogFactory.getLog("MailTimer");
	
	/*
	* Desc : This function is checkQueueTime
	*/
	public void checkQueueTime() throws FrameworkErrorSignal, NotFoundSignal
	{		
		System.out.println("do checkQueueTime ...");
	}
	
	/*
	* Desc : This function is execute
	*/
	public void execute(JobExecutionContext arg0) throws JobExecutionException 
	{
		System.out.println("do MAIL ...");
		logger.info("开始执行邮件发送任务1  ==========> ");
		MailTask  mt  = null;
		int flag = 0;
			try
			{
				mt  = new MailTask();
				IDMFrameServiceProxy.getTransactionManager().beginTransaction();

				String sql;
				List<Map<String, Object>> rs = null;
				
				//判断是否已经有进程在执行自动计算功能了
				sql = "SELECT CONSTANTVALUE FROM CONSTANTDEF WHERE CONSTANTNAME='WMSAutoMailStart' for update nowait";
				try {
					rs = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, new Object[]{});
				} catch (Exception e ) {
					log.info("其他定时任务进程已经在执行中了   e => " + JSON.toJSONString(e));
					return;
				}
				if(rs.equals(null) || rs.size()==0)//rs[0][0].equals(""))
				{
					try {
						//首次未有SPCAutoCalculateCLStart值时，插入该值
						sql="INSERT INTO CONSTANTDEF(CONSTANTNAME,DESCRIPTION,CONSTANTVALUE,CACHEFLAG) "
								+ "VALUES('WMSAutoMailStart','One of wms Server has started mail ','N','N')";
						IDMFrameServiceProxy.getSqlTemplate().update(sql, new Object[]{});
					} catch (Exception e )
					{
						//首次未有SPCAutoCalculateCLStart值时，第一个线程已经完成插入，因此后续线程退出计算
						System.out.println("Insert value failed for another process has started.");
						IDMFrameServiceProxy.getTransactionManager().commitTransaction();
						return;
					}	
				}
				else
				{
					System.out.println("WMSAutoMailStart = "+rs.get(0).get("CONSTANTVALUE").toString());
					logger.info("WMSAutoMailStart =   ==========> " + rs.get(0).get("CONSTANTVALUE").toString());
					if(rs.get(0).get("CONSTANTVALUE").toString().equals("Y"))//已经有进程在自动计算，退出等待下次执行
					{
						IDMFrameServiceProxy.getTransactionManager().commitTransaction();
						System.out.println("Another process has started.");
						logger.info("其他定时任务进程已经在执行中了  ==========> ");
						return;
					}
					logger.info("开始执行邮件发送任务2  ==========> ");
				}
					
				//无进程在自动计算，本进程开始自动计算。一下是

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

				/***End*****/
				
				IDMFrameServiceProxy.getTransactionManager().beginTransaction();
				
//				logger.info("1.待检  ==========> ");
//				mt.OQADailyTask();
//				logger.info("2.寿命管理  ==========> ");
//				mt.LifeManagementTask();
				logger.info("03.物料变成长期库存  ==========> ");
				//mt.LongTimeStorageTask();
//				logger.info("4.发送安全库存信息  ==========> ");
//				mt.SafetyStockInfoTask();
//				logger.info("5.过期和长期库存自动hold功能  ==========> ");
//				mt.HoldAbnormalBox();
//				logger.info("6.货位绑定报表  ==========> ");
//				mt.AssignLocationReport();
				
				logger.info("1.材料库存为质检状态的  ==========> ");
				//mt.SendPreOQAReport();
				logger.info("2.寿命资材  ==========> ");
				//mt.SendMaterialLifeReport();
				logger.info("3.成品长期库存自动hold  ==========> ");
				//mt.HoldPalletListSixMonth();
				logger.info("4.堆场入库List  ==========> ");
				mt.SendYardStockInList();
				logger.info("5.堆场在库List  ==========> ");
				mt.SendYardStockList();
				logger.info("6.堆场出库List  ==========> ");
				mt.SendYardStockOutList();
				logger.info("7.6点库存同步             ==========> ");
				mt.GetSixClockStorage();
				logger.info("8.堆场6点库存同步             ==========> ");
				mt.GetYardSixClockStorage();
				flag = 1;
			}
			catch (Exception e )
			{	
				IDMFrameServiceProxy.getTransactionManager().rollbackAllTransactions();			
				//首次未有SPCAutoCalculateCLStart值时，第一个线程已经完成插入，因此后续线程退出计算
				System.out.println("Insert value failed for another process has started.");
				String endsql = "UPDATE CONSTANTDEF SET CONSTANTVALUE='N'  WHERE CONSTANTNAME='WMSAutoMailStart'";	
				IDMFrameServiceProxy.getSqlTemplate().update(endsql, new Object[]{});
				flag = 2;
				return;	
			}	
			finally{
				if(flag == 1) {
					if(mt != null)
						mt = null;
						String endsql = "UPDATE CONSTANTDEF SET CONSTANTVALUE='N'  WHERE CONSTANTNAME='WMSAutoMailStart'";	
						IDMFrameServiceProxy.getSqlTemplate().update(endsql, new Object[]{});	
						IDMFrameServiceProxy.getTransactionManager().commitTransaction();	
				}
			}
		
		
	}
	
//	public void executeTransaction(JobExecutionContext arg0) throws JobExecutionException 
//	{	
//		
//		
//			Timestamp currentTime = TimeUtils.getCurrentTimestamp();
//			
//			try
//			{	
//				IDMFrameServiceProxy.getTransactionManager().beginTransaction();
//
//				String sql;
//				List<Map<String, Object>> rs;		
//				//判断是否已经有进程在执行自动计算功能了				
//				sql = "SELECT CONSTANTVALUE FROM CONSTANTDEF WHERE CONSTANTNAME='WMSAutoMailStart' for update";			
//				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('WMSAutoMailStart','One of wms Server has started mail ','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("WMSAutoMailStart = "+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='WMSAutoMailStart'";	
//				IDMFrameServiceProxy.getSqlTemplate().update(sql, new Object[]{});			
//				IDMFrameServiceProxy.getTransactionManager().commitTransaction();	
//
//				/***End*****/
//				
//				IDMFrameServiceProxy.getTransactionManager().beginTransaction();
//				
//			    Calendar  currentTimeC = Calendar.getInstance();
//			    currentTimeC.setTime(currentTime);
//			}
//			finally{
//					String endsql = "UPDATE CONSTANTDEF SET CONSTANTVALUE='N'  WHERE CONSTANTNAME='WMSAutoMailStart'";	
//					IDMFrameServiceProxy.getSqlTemplate().update(endsql, new Object[]{});			
//				}
//			}
			
			
 	
}
