package cn.thinkjoy.dataInsight.starter;

import cn.thinkjoy.dataInsight.domain.Task;
import cn.thinkjoy.dataInsight.job.TaskJob;
import cn.thinkjoy.dataInsight.service.ITaskExService;
import cn.thinkjoy.dataInsight.service.ITaskService;
import cn.thinkjoy.dataInsight.utils.NetUtil;
import com.alibaba.fastjson.JSONObject;
import javassist.*;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.FileOutputStream;
import java.lang.reflect.Modifier;
import java.util.Map;
import java.util.*;

import static org.quartz.JobBuilder.newJob;

/**
 * Created by chanming on 2019/1/9.
 */
@Service("starter")
public class DTaskStarter {

    public static final String dingd_group = "dd";

    private static final Logger logger = LoggerFactory.getLogger(DTaskStarter.class);

    @Autowired
    private ITaskService taskService;

    @Autowired
    private ITaskExService taskExService;

    @Autowired
    private Scheduler scheduler;

    public void init() throws SchedulerException, NoSuchMethodException, ClassNotFoundException {
        Map<String, Object> map = new HashMap<>();
        map.put("status", 0);
        List<Task> taskList=taskService.queryList(map, null, null);
        if (!CollectionUtils.isEmpty(taskList)) {
            for (final Task task : taskList) {
                scheulerTask(task);
            }
            scheduler.start();
        }
    }

    public void scheulerTask(Task task) throws ClassNotFoundException, NoSuchMethodException, SchedulerException {
        CronTrigger trigger = TriggerBuilder.newTrigger()
                .withIdentity(task.getName(),dingd_group)
                .withSchedule(CronScheduleBuilder.cronSchedule(task.getCron()))
                .build();
        MethodInvokingJobDetailFactoryBean jobDetail = new MethodInvokingJobDetailFactoryBean();
        TaskJob taskJob = new TaskJob();
        taskJob.setTask(task);
        taskJob.setTaskExService(taskExService);
        jobDetail.setTargetObject(taskJob);
        jobDetail.setTargetMethod("execute");
        jobDetail.setName(task.getName());
        jobDetail.setGroup(dingd_group);
        jobDetail.setConcurrent(false);
        jobDetail.afterPropertiesSet();
        scheduler.scheduleJob(jobDetail.getObject(), trigger);
    }

}


    public void reScheduleTask(){
        List<Task> taskList = null;
        try {
            Map<String, Object> map = new HashMap<>();
            taskList=taskService.queryList(map, null, null);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        }

        if (!org.springframework.util.CollectionUtils.isEmpty(taskList)) {
            for (Task task : taskList) {
                TriggerKey triggerKey = new TriggerKey(task.getName(),"dd");
                JobKey jobKey = new JobKey(task.getName(),"dd");
                try {
                    CronTrigger trigger= (CronTrigger) scheduler.getTrigger(triggerKey);

                    if (trigger == null&&task.getStatus()!=-1) {
                        dTaskStarter.scheulerTask(task);
                        System.out.println("新增任务:"+task.getName());
                        continue;
                    }

                    if (trigger == null) {
                        continue;
                    }

                    if (task.getStatus() == -1) {
                        scheduler.pauseTrigger(triggerKey);// 停止触发器
                        scheduler.unscheduleJob(triggerKey);// 移除触发器
                        scheduler.deleteJob(jobKey);// 删除任
                        System.out.println("删除任务:"+task.getName());
                        continue;
                    }

                    String oldExp=trigger.getCronExpression();
                    if (!oldExp.equals(task.getCron())) {//重新调度
                        CronTrigger newtrigger = TriggerBuilder.newTrigger()
                                .withIdentity(task.getName(),"dd")
                                .withSchedule(CronScheduleBuilder.cronSchedule(task.getCron()))
                                .build();
                        scheduler.rescheduleJob(triggerKey, newtrigger);
                        System.out.println("重新调度任务:"+task.getName());
                        continue;
                    }
                } catch (SchedulerException e) {
                    logger.error(e.getMessage(),e);
                    e.printStackTrace();
                } catch (NoSuchMethodException e) {
                    logger.error(e.getMessage(),e);
                    e.printStackTrace();
                } catch (ClassNotFoundException e) {
                    logger.error(e.getMessage(),e);
                    e.printStackTrace();
                }

            }
        }
    }



	<bean id="scheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"/>
01-10 03:32