package com.unis.detectionnum.server.schedule;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger.TriggerState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.unis.detectionnum.server.schedule.pojo.TaskPojo;
import com.unis.detectionnum.server.schedule.pojo.TriggerStatus;

import lombok.extern.slf4j.Slf4j;
 
//@Configuration
//@EnableScheduling
//@Component
@Slf4j
public class ScheduleRefresh {
	
	@Resource
	private TaskServer taskServer;

	@Autowired
	private QuartzManager quartzManager;

//	@Scheduled(cron = "00 0/5 * * * ?") //每隔8分钟扫描一次
//	@Scheduled(cron = "0 0 0/1 * * ?") //每1个小时执行一次
	public void scheduleRefresh() throws SchedulerException {

		log.info("---->	定时任务刷新start	!!!!!!!!!!!1111111111111111111111111111111111111111111111111");
		List<TaskPojo> pojos = taskServer.selectList();//根据时间获取各个任务
		List<String> list = new ArrayList<String>();//定义jobid列表
		if(pojos!=null) {
			for(TaskPojo pojo:pojos) {
				log.info("cron表达式为："+pojo.getCronExpression());
				list.add(pojo.getId());//将jobid留下备用
			}
		}
		List<TriggerStatus> triggerStatus = quartzManager.getJobsStatus();//获取各个任务运行状态


		for(TriggerStatus status: triggerStatus) {
			if(!list.contains(status.getTriggerName())) {//获取数据库中当前job是否存在
				if(status.getTriggerState()==TriggerState.NORMAL) {//判断当前任务是否执行完成并移除
					log.info("---->	定时任务删除	!!!!!!!!!!!目标名称为："+status.getTriggerName());
					quartzManager.removeJob(status.getTriggerName(), Scheduler.DEFAULT_GROUP, status.getTriggerName(), Scheduler.DEFAULT_GROUP);
				}
			}
		}

		for(TaskPojo taskPojo:pojos) {//刷新任务列表
			TriggerState triggerState = quartzManager.getJobStatus(taskPojo.getId(), Scheduler.DEFAULT_GROUP);
			if(triggerState==TriggerState.NONE) {
				log.info("---->	定时任务添加	!!!!!!!!!!!cron表达式为："+taskPojo.getCronExpression());
				quartzManager.addJob(taskPojo.getId(), Scheduler.DEFAULT_GROUP, taskPojo.getId(), Scheduler.DEFAULT_GROUP, taskPojo.getExecuteJobClass(), taskPojo.getCronExpression(),taskPojo.getSbCode());
			} else {
				String currentCron = quartzManager.getCurrentCron(taskPojo.getId(), Scheduler.DEFAULT_GROUP);//获取当前任务执行的cron表达式
				if(!currentCron.equals(taskPojo.getCronExpression())){//如果获取的表达式不同更新任务cron
					log.info("---->	定时任务更新	!!!!!!!!!!!cron表达式为："+taskPojo.getCronExpression());
					quartzManager.modifyJobTime(taskPojo.getId(), Scheduler.DEFAULT_GROUP, taskPojo.getId(), Scheduler.DEFAULT_GROUP, taskPojo.getCronExpression());
				}
			}
		}
		log.info("---->	定时任务刷新end	!!!!!!!!!!!");
	}
}
