package cn.cslg.pas.service.upLoadPatent;

import cn.cslg.pas.common.model.vo.QuartzVO;
import cn.cslg.pas.domain.QrtzTask;
import cn.cslg.pas.domain.Task;
import cn.cslg.pas.domain.asso.TaskCondition;
import cn.cslg.pas.service.TaskService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Slf4j
@RequiredArgsConstructor(onConstructor_ = {@Lazy})
public class JobService {

    private final Scheduler scheduler;

    private final QrTaskService qrTaskService;
    private final TaskService taskService;
    //private final QrTaskDetailService qrTaskDetailService;

    /**
     * 删除job
     *
     * @throws SchedulerException
     */
    public void deleteJob(Integer taskConditionId) throws SchedulerException {
        //删除job中的该定时任务条件
        QuartzVO quartzVO = this.generateQuartzVO(taskConditionId);
        TriggerKey triggerKey = TriggerKey.triggerKey(quartzVO.getTriggerName(), quartzVO.getTriggerGroupName());
        scheduler.pauseTrigger(triggerKey);
        scheduler.unscheduleJob(triggerKey);
        JobKey jobKey = JobKey.jobKey(quartzVO.getJobName(), quartzVO.getJobGroupName());
        scheduler.deleteJob(jobKey);

//        qrTaskService.removeById(taskId);
//        //同时删除该任务条件的所有任务执行情况记录
//        LambdaQueryWrapper<Task> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(Task::getTaskConditionId, taskId);
//        taskService.remove(queryWrapper);
    }

    /**
     * 暂停job
     *
     * @throws SchedulerException
     */
//    public void pauseJob(Integer taskId) throws SchedulerException {
//        QuartzVO quartzVO = this.generateQuartzVO(taskId);
//        //更新任务条件状态
//        qrTaskService.updateState(taskId, 6);
//        JobKey jobKey = JobKey.jobKey(quartzVO.getJobName(), quartzVO.getJobGroupName());
//        scheduler.pauseJob(jobKey);
//    }

    /**
     * 恢复job
     *
     * @throws SchedulerException
     */
//    public void resumeJob(Integer taskId) throws SchedulerException {
//        QuartzVO quartzVO = this.generateQuartzVO(taskId);
//        qrTaskService.updateState(taskId, 1);
//        JobKey jobKey = JobKey.jobKey(quartzVO.getJobName(), quartzVO.getJobGroupName());
//        scheduler.resumeJob(jobKey);
//    }

    /**
     * 修改定时任务
     *
     * @param
     */
    public void updateJob(QrtzTask qrtzTask) {
        //更新任务

        QuartzVO quartzVO = this.generateQuartzVO(qrtzTask.getId());
        JobDataMap jobDataMap = new JobDataMap();
        jobDataMap.put("qrtzTask", qrtzTask);
        TriggerKey oldTriggerKey = TriggerKey.triggerKey(quartzVO.getTriggerName(), quartzVO.getTriggerGroupName());
        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(qrtzTask.getCrons());
        CronTrigger cronTrigger = TriggerBuilder.newTrigger()
                .withIdentity(oldTriggerKey).usingJobData(jobDataMap).withSchedule(scheduleBuilder).build();
        try {
            scheduler.rescheduleJob(oldTriggerKey, cronTrigger);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    /**
     * 新增job任务
     *
     * @throws SchedulerException
     */
    @Transactional
    public void addJob(TaskCondition taskCondition) throws SchedulerException {
        //添加一条任务记录
        QuartzVO quartzVO = this.generateQuartzVO(taskCondition.getId());
        JobDataMap jobDataMap = new JobDataMap();
        jobDataMap.put("taskCondition", taskCondition);
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(taskCondition.getCrons());
        JobDetail jobDetail = JobBuilder
                .newJob(TaskAddJob.class)
                .withIdentity(quartzVO.getJobName(), quartzVO.getJobGroupName())
                .build();
        Trigger trigger = TriggerBuilder
                .newTrigger()
                .withIdentity(quartzVO.getTriggerName(), quartzVO.getTriggerGroupName())
                .withSchedule(cronScheduleBuilder)
                .usingJobData(jobDataMap)
                .build();
        scheduler.scheduleJob(jobDetail, trigger);

    }


    public QuartzVO generateQuartzVO(Integer taskId) {
        QuartzVO quartzVO = new QuartzVO();
        quartzVO.setJobName("Job_" + taskId);
        quartzVO.setJobGroupName("Default");
        quartzVO.setTriggerName("Trigger_" + taskId);
        quartzVO.setTriggerGroupName("Default");
        return quartzVO;

    }

    /**
     * 停止正在进行的job
     *
     * @throws SchedulerException
     */
    public void interruptJob(Integer taskId) throws SchedulerException {
        QuartzVO quartzVO = this.generateQuartzVO(taskId);
        JobKey jobKey = JobKey.jobKey(quartzVO.getJobName(), quartzVO.getJobGroupName());
        scheduler.interrupt(jobKey);
    }
}
