package com.gyee.frame.common.quartz.task;

import com.gyee.frame.common.quartz.QuartzSchedulerUtil;

import com.gyee.frame.common.spring.SpringUtils;
import com.gyee.frame.model.auto.SysQuartzJob;
import com.gyee.frame.model.auto.SysQuartzJobExample;
import com.gyee.frame.service.SysQuartzJobService;
import org.quartz.SchedulerException;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 * @purpose 根据socket 对一些job任务进行管制
 */
@Configuration
public class SocketTaskUtil {
    private QuartzSchedulerUtil quartzSchedulerUtil = SpringUtils.getBean(QuartzSchedulerUtil.class);
    private SysQuartzJobService sysQuartzJobService = SpringUtils.getBean(SysQuartzJobService.class);


    public void pauseJob(SysQuartzJob sysQuartzJob){
        quartzSchedulerUtil.pauseJob(sysQuartzJob);
    }
    public void startJob(SysQuartzJob sysQuartzJob){

        try {
            quartzSchedulerUtil.run(sysQuartzJob);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }
    public void deleteJob(SysQuartzJob sysQuartzJob){
        quartzSchedulerUtil.deleteJob(sysQuartzJob);
    }
    /**
     *@author:Wang Jiawen
     *
     *@description: 该方法通过计算jobid来找到job，通过job的对象来进一步控制job任务，用来重启某一具体的任务
     *
     *@param:[jobid] job的编码
     *
     *@return:void
     *
     *@createTime:2020/1/9
     *
     */
    public void restartJob(String jobid){

        List<SysQuartzJob> quartzJobs=sysQuartzJobService.selectByExample(new SysQuartzJobExample());
        SysQuartzJob sysQuartzJob1 = null;
        //找到具体的任务
        for(SysQuartzJob sysQuartzJob:quartzJobs){
            if(sysQuartzJob.getId().equalsIgnoreCase(jobid)){
                sysQuartzJob1=sysQuartzJob;
                break;
            }
        }
        this.deleteJob(sysQuartzJob1);//符合标准步骤删除-创建-启动流程
        try {
           // //System.out.println(sysQuartzJob1.getJobName());

            sysQuartzJob1.setStatus(0);//开启任务
            quartzSchedulerUtil.createSchedule(sysQuartzJob1);

            //startJob(sysQuartzJob1);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        //this.startJob(sysQuartzJob1);
    }
    public void deleteJob(String jobid){

        List<SysQuartzJob> quartzJobs=sysQuartzJobService.selectByExample(new SysQuartzJobExample());
        SysQuartzJob sysQuartzJob1 = null;
        //找到具体的任务
        for(SysQuartzJob sysQuartzJob:quartzJobs){
            if(sysQuartzJob.getId().equalsIgnoreCase(jobid)){
                sysQuartzJob1=sysQuartzJob;
                break;
            }
        }
        if(sysQuartzJob1!=null)
        {
            this.deleteJob(sysQuartzJob1);
        }

    }
}
