package com.saye.hospitalgd.scheduler;


import java.util.HashMap;
import java.util.List;

import com.saye.hospitalgd.commons.string.StringDUtil;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.TriggerBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import com.saye.hospitalgd.model.BaseQuartzConfigEntity;
import com.saye.hospitalgd.service.quartz.BaseQuartzConfigService;
 
/**
 * 调度工厂类
 */
@Service("MySchedulerFactory")
@Component
public class MySchedulerFactory {
	private static Logger logger = LoggerFactory.getLogger(MySchedulerFactory.class);
	
	@Autowired
	SchedulerFactoryBean schedulerFactoryBean;
 
	/**
	 * 任务配置读取服务
	 */
	@Autowired
	private BaseQuartzConfigService baseQuartzConfigService;
 
	public void scheduleJobs() throws SchedulerException {
		Scheduler scheduler = getScheduler();
		// 为了避免org.quartz.ObjectAlreadyExistsException，在执行前将scheduler进行清理
		scheduler.clear();
		startJob(scheduler);
	}
 
	/**
	 * 获取scheduler
	 * @return
	 * @author 
	 * @date 2018年12月27日
	 */
	public Scheduler getScheduler() {
		return schedulerFactoryBean.getScheduler();
	}
 
	/**
	 * 项目启动 开启任务
	 * @param scheduler
	 * @author 
	 * @date 2018年12月27日
	 */
	private void startJob(Scheduler scheduler) {
		try {
			
			List<BaseQuartzConfigEntity> jobList = baseQuartzConfigService.findAll(new HashMap<Object, Object>());
			for (BaseQuartzConfigEntity config : jobList) {
				try {
					// 0-暂停的任务 1-正常运行任务
					if ("0".equals(config.getStatus())) {
						continue;
					}
					String classz = config.getQuartzClass();
					if (StringDUtil.isNotBlank(classz)) {
						@SuppressWarnings("unchecked")
						Class<? extends Job> clazz = (Class<? extends Job>) Class.forName(classz);
						String groupName = !StringDUtil.isNotBlank(config.getQuartzGroup()) ? "DEFAULT" : config.getQuartzGroup();
						JobDetail jobDetail = JobBuilder.newJob(clazz).withIdentity(config.getConfigId(), groupName)
								.usingJobData("id", config.getConfigId()).usingJobData("name", config.getQuartzName()).build();
						CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(config.getExpression());
						CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity(config.getConfigId(), groupName)
								.withSchedule(scheduleBuilder).build();
						scheduler.scheduleJob(jobDetail, cronTrigger);
					}
				} catch (Exception e) {
					logger.info("定时启动异常：" + config.getQuartzName() + " 异常信息：" + e.getMessage());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
 
	/**
	 * 任务暂停（就是删了）
	 * @param id
	 * @throws Exception
	 * @author 
	 * @date 2018年12月27日
	 */
	public void pauseJob(String id) throws Exception {
		Scheduler scheduler = getScheduler();
		BaseQuartzConfigEntity QuartzConfig = baseQuartzConfigService.get(String.valueOf(id));
		String groupName = !StringDUtil.isNotBlank(QuartzConfig.getQuartzGroup()) ? "DEFAULT" : QuartzConfig.getQuartzGroup();
		JobKey jobKey = JobKey.jobKey(QuartzConfig.getConfigId(), groupName);
		scheduler.deleteJob(jobKey);
	}
 
	/**
	 * 任务恢复
	 * @param id
	 * @throws Exception
	 * @author 
	 * @date 2018年12月27日
	 */
	public void resumeJob(String id) throws Exception {
		Scheduler scheduler = getScheduler();
		BaseQuartzConfigEntity QuartzConfig = baseQuartzConfigService.get(String.valueOf(id));
		String groupName = !StringDUtil.isNotBlank(QuartzConfig.getQuartzGroup()) ? "DEFAULT" : QuartzConfig.getQuartzGroup();
		JobKey jobKey = JobKey.jobKey(QuartzConfig.getConfigId(), groupName);
		Class<? extends Job> clazz = (Class<? extends Job>) Class.forName(QuartzConfig.getQuartzClass());
		JobDetail jobDetail1 = scheduler.getJobDetail(jobKey);
		if (jobDetail1 == null) {
			JobDetail jobDetail = JobBuilder.newJob(clazz).withIdentity(QuartzConfig.getConfigId(), groupName)
					.usingJobData("id", QuartzConfig.getConfigId()).usingJobData("name", QuartzConfig.getQuartzName()).build();
			CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(QuartzConfig.getExpression());
			CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity(QuartzConfig.getConfigId(), groupName)
					.withSchedule(scheduleBuilder).build();
			scheduler.scheduleJob(jobDetail, cronTrigger);
		} else {
			scheduler.resumeJob(jobKey);
		}
	}
	
	/**
	 * 添加新的定时任务
	 * @param id
	 * @param name
	 * @param group
	 * @param cron
	 * @param classz
	 * @throws Exception
	 */
	public void addJob(String id,String name, String group,String cron, String classz) throws Exception{

		Scheduler scheduler = schedulerFactoryBean.getScheduler();
		try {
			if (StringDUtil.isNotBlank(classz)) {
				@SuppressWarnings("unchecked")
				Class<? extends Job> clazz = (Class<? extends Job>) Class.forName(classz);
				String groupName = !StringDUtil.isNotBlank(group) ? "DEFAULT" : group;
				JobDetail jobDetail = JobBuilder.newJob(clazz).withIdentity(id, groupName)
						.usingJobData("id", id).usingJobData("name", name).build();
				CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cron);
				CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity(id, groupName)
						.withSchedule(scheduleBuilder).build();
				scheduler.scheduleJob(jobDetail, cronTrigger);
			}
		} catch (Exception e) {
			logger.info("添加定时任务失败：" + " 异常信息：" + e.getMessage());
		}

	}

}