package com.scm.contract.web.quartz;

import com.scm.contract.model.quartz.QuartzJob;
import com.scm.contract.service.quartz.QuartzJobService;
import com.set.direwolf.core.web.OperationResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;


/**
 * @Description: 定时任务在线管理
 * @Author: jeecg-boot
 * @Date: 2019-01-02
 * @Version:V1.0
 */
@Api(value = "定时任务接口")
@RestController
@RequestMapping(value = "/quartzJob")
public class QuartzJobController {

    private final QuartzJobService quartzJobService;

    public QuartzJobController(QuartzJobService quartzJobService) {
        this.quartzJobService = quartzJobService;
    }

    /**
     * 暂停定时任务
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/pause")
    @ApiOperation(value = "暂停定时任务")
    public @ResponseBody OperationResult pauseJob(@RequestParam(name = "id") String id) {
        QuartzJob job = quartzJobService.getById(id);
        if (job == null) {
            throw new RuntimeException("定时任务不存在!");
        }
        quartzJobService.pause(job);
        return OperationResult.buildSuccessResult("暂停定时任务成功", true);
    }

    /**
     * 启动定时任务
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/resume")
    @ApiOperation(value = "恢复定时任务")
    public @ResponseBody OperationResult resumeJob(@RequestParam(name = "id") String id) {
        QuartzJob job = quartzJobService.getById(id);
        if (job == null) {
            throw new RuntimeException("定时任务不存在!");
        }
        quartzJobService.resumeJob(job);
        return OperationResult.buildSuccessResult("恢复定时任务成功", true);
    }


    /**
     * 立即执行
     *
     * @param id
     * @return
     */
    @GetMapping("/execute")
    public @ResponseBody OperationResult execute(@RequestParam("id") String id) {
        QuartzJob quartzJob = quartzJobService.getById(id);
        if (quartzJob == null) {
            throw new RuntimeException("未找到对应实体");
        }
        try {
            quartzJobService.execute(quartzJob);
        } catch (Exception e) {
            throw new RuntimeException("执行失败!");
        }
        return OperationResult.buildSuccessResult("立即执行定时任务成功", true);
    }
}
