package com.ozs.da.service.job.impl;

import com.ozs.da.constant.Constant;
import com.ozs.da.entity.task.Task;
import com.ozs.da.job.JobServer;
import com.ozs.da.utils.CronExpresUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.quartz.*;

import java.util.Date;
import java.util.Set;

/**
 * @author 许明
 * on 2019/3/11.
 * @version 2.0.0
 */
public class TimeTriggerJob implements org.quartz.Job {

    private static final Logger logger = LogManager.getLogger(TimeTriggerJob.class);

    // 存放在JobDataMap中的crontrigger的名称
    private static final String cronTriggers = "CRONTRIGGER";

    private static final String JOB_KEY = "jobid";

    public static TimeTriggerJob timeTriggerJob;

    /**
     * @param context
     * @return
     * @description 达到job运行时间后执行的操作，将job加入到可执行队列中去
     */
    @SuppressWarnings("unchecked")
    public void execute(JobExecutionContext context) throws JobExecutionException {
        JobDetail jobDetail = context.getJobDetail();
        // 获取本次要执行的job信息，以及对应的时间出发表达式信息
        String jobid = (String) jobDetail.getJobDataMap().get(JOB_KEY);
        logger.info("当前定时器中jobid为：" + jobid);
        Set<CronTrigger> cronList = (Set<CronTrigger>) jobDetail.getJobDataMap().get(cronTriggers);
        Date current = new Date();
        Date nextFireTime = CronExpresUtil.getNextFiredTime(cronList, current);
        logger.info("quartz任务JOBID[" + jobid + "]达到运行条件");
        logger.info("job[" + jobid + "]nextFireTime[" + nextFireTime + "]");

        Task thisJob = JobServer.MEM_JOB_CACHE.get(jobid);
        //任务状态，1：启用，2：停用
        if ("2".equals(thisJob.getTaskStatus())) {
            logger.info("job[" + jobid + "]处于未启用状态不进行触发");
        }
        // 将job放入执行队列start,首先需要判断前次执行是否完毕,是否可以并行
        // job在运行不允许并行
        // 任务运行状态，0：未运行，1：等待运行，2：运行中，3：运行完成，4：运行失败
        else if ("1,2".contains(thisJob.getRunStatus())) {
            // 写执行日志，当前时间未执行
            logger.info("job[" + jobid + "]处于等待运行或运行中状态，不进行并行触发");
        } else {
            logger.info("JOBID[" + jobid + "]开始进行数据采集任务");
            TriggerJob triggerJob = new TriggerJob();
            String result = "";
            try {
                result = triggerJob.execute(jobid, nextFireTime);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if ("0".equals(result)) {
                logger.info("JOBID[" + jobid + "]进行数据采集任务成功");
            }
            if ("-1".equals(result)) {
                logger.info("JOBID[" + jobid + "]进行数据采集任务失败");
            }
        }
        if (null == nextFireTime || (nextFireTime.getTime() - current.getTime()) > Constant.THREAD_SCANJOB_INTERVAL) {
            try {// 下次执行时间为空，job执行完成,没有可运行trigger，删除该job
                context.getScheduler().deleteJob(new JobKey(jobid));
            } catch (SchedulerException e) {
                logger.error("将job[" + jobid + "]从schedule删除异常", e);
            }
        }
    }
}
