package com.jiayue.insu.incloud.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiayue.insu.incloud.entity.Quartz;
import com.jiayue.insu.incloud.mapper.QuartzMapper;
import com.jiayue.insu.incloud.quartz.ScheduledTask;
import com.jiayue.insu.incloud.service.QuartzService;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
/**
 * 定时任务业务实现
 *
 * @author yh
 * @version 1.0
 * @since 2022/5/22 11:29
 */
@Service
public class QuartzServiceImpl extends ServiceImpl<QuartzMapper, Quartz> implements QuartzService {

    @Autowired
    private ScheduledTask scheduledTask;

    @Override
    public Quartz findByJobName(String jobName) {
        LambdaQueryWrapper<Quartz> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Quartz::getJobName,jobName);
        return this.getOne(lambdaQueryWrapper);
    }

    @Override
    public boolean saveQuartz(Quartz quartz) throws SchedulerException, ClassNotFoundException, ParseException {

        if(!quartz.getOperate().equals("stop")){
            scheduledTask.deleteJob(quartz.getJobName());
            Class c = Class.forName(quartz.getExecuteClass());
            scheduledTask.scheduleJob(c,quartz.getJobName(),quartz.getStartTime(),quartz.getCronExpression(),null);
        }
        this.save(quartz);
        return Boolean.TRUE;
    }

    @Override
    public boolean updateQuartz(Quartz quartz) throws SchedulerException, ClassNotFoundException, ParseException {

        if(!quartz.getOperate().equals("stop")){
            scheduledTask.deleteJob(quartz.getJobName());
            Class c = Class.forName(quartz.getExecuteClass());
            scheduledTask.scheduleJob(c,quartz.getJobName(),quartz.getStartTime(),quartz.getCronExpression(),null);
        }else{
            scheduledTask.deleteJob(quartz.getJobName());
        }
        this.updateById(quartz) ;
        return Boolean.TRUE;
    }

    @Override
    public boolean deleteQuartz(Integer id) throws SchedulerException {
        Quartz quartz = this.getById(id);
        this.removeById(quartz);
        scheduledTask.deleteJob(quartz.getJobName());
        return Boolean.TRUE;
    }
}
