package cn.myapps.scheduler;

import cn.myapps.authtime.common.dao.PersistenceUtils;
import cn.myapps.common.model.application.Application;
import cn.myapps.common.model.task.Task;
import cn.myapps.common.util.PropertyUtil;
import cn.myapps.designtime.application.service.ApplicationDesignTimeService;
import cn.myapps.designtime.common.service.DesignTimeServiceManager;
import cn.myapps.designtime.task.service.TaskDesignTimeService;
import cn.myapps.runtime.common.service.RunTimeServiceManager;
import cn.myapps.runtime.scheduler.ejb.TriggerProcess;
import cn.myapps.runtime.scheduler.ejb.TriggerVO;
import cn.myapps.runtime.scheduler.engine.job.BpmPlatformWorkFlowEventJob;
import cn.myapps.runtime.scheduler.engine.job.IscriptTaskJob;
import cn.myapps.runtime.scheduler.engine.job.Job;
import org.quartz.*;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.io.File;
import java.util.Date;

public 	/**
 * 执行触发器任务的线程
 *
 * @author Happy
 *
 */
class TriggerExecutor extends cn.myapps.scheduler.Job {

	@Override
	protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
		JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
		TriggerVO trigger = (TriggerVO) jobDataMap.get("triggervo");
		String applicationId = jobDataMap.getString("application");
		ApplicationDesignTimeService appService = DesignTimeServiceManager.applicationDesignTimeService();
		try {
		  Application app = appService.findById(applicationId);
		  if(app==null) {
			  return;
		  }
		} catch (Exception e) {
			e.printStackTrace();
		}

		try {
			Date lastExecuteTime = new Date();
			TriggerProcess process = RunTimeServiceManager.triggerProcess(applicationId);
			//拿到trigger的执行时间比较当前时间，执行时间小于当前时间时执行
			if (trigger!=null&&!process.isCancel(trigger.getId())) {
				System.out.println("触发器执行任务"+trigger.getId());
				Job job = trigger.getJob();
				if (job instanceof BpmPlatformWorkFlowEventJob) {
					BpmPlatformWorkFlowEventJob bpmPlatformWorkFlowEventJob = (BpmPlatformWorkFlowEventJob) job;
					bpmPlatformWorkFlowEventJob.setDoc(trigger.getDoc());
					bpmPlatformWorkFlowEventJob.execute();
				} else if (job instanceof IscriptTaskJob) {
					String rootPath = PropertyUtil.getPath();
					File file = new File(rootPath + File.separator + trigger.getDeadline() + ".log");
					if (!file.exists()) {
						file.createNewFile();
						IscriptTaskJob iscriptTaskJob = (IscriptTaskJob) job;
						iscriptTaskJob.setApplicationId(trigger.getApplicationId());
						iscriptTaskJob.execute();
						file.delete();
					} else {
						return;
					}
				} else {
					job.execute();
				}
				if(!trigger.isLoop()){
					//如果不是脚本任务的话,执行一次就删除就可以了,脚本任务不重复的话就执行一次将状态设为stop
					if(trigger.getJobType()!=TriggerVO.JOB_TYPE_ISCRITP_TASK){
						process.doRemove(trigger.getId());
					}else {
						trigger.setState(TriggerVO.STATE_STOP);
						trigger.setRunTimes(trigger.getRunTimes()+1);
						process.doUpdate(trigger);
					}
					String jobName = trigger.getId();
					String jobGroupName = trigger.getApplicationId();
					SchedulerUtil.cancelJob(jobName,jobGroupName);
				}else {
					trigger.setState(TriggerVO.STATE_WAITING);
					trigger.setRunTimes(trigger.getRunTimes()+1);
					TaskDesignTimeService tp = DesignTimeServiceManager.taskDesignTimeService();
					IscriptTaskJob iscriptTaskJob = (IscriptTaskJob) job;
					Task task = (Task) tp.findById(iscriptTaskJob.getTaskId());
					if (task != null) {
						long nextExecuteTime = task.getNextExecuteTime(lastExecuteTime);
						trigger.setDeadline(nextExecuteTime);
					}
					// 刷新下次执行时间
					process.doUpdate(trigger);

				}

			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				String jobName = trigger.getId();
				String jobGroupName = trigger.getApplicationId();
				SchedulerUtil.cancelJob(jobName,jobGroupName);
				SchedulerLock.unLock(trigger);
				PersistenceUtils.closeSessionAndConnection();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

}