package cn.api.system;

import cn.common.annotation.Log;
import cn.common.enums.BizOpType;
import cn.common.enums.ResultCode;
import cn.common.page.response.Result;
import cn.pojo.entity.TSysJob;
import cn.schedule.util.CronUtil;
import cn.service.IJobService;
import org.quartz.SchedulerException;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**定时任务调度*/
@RestController
@RequestMapping("/api/job")
public class JobCtrl 
{
	@Resource
	private IJobService jobService;

	/**定时任务状态修改*/
	@PutMapping("/changeStatus")
	@Log(title = "定时任务-修改任务状态", businessType = BizOpType.UPDATE)
	public Result<?> changeStatus(@RequestBody TSysJob job)
	{
		try {
			return Result.ok(jobService.updateJobStatus(job));
		} catch (Exception e) {
			return Result.warnMsg(ResultCode.JOB_STATUS.getMsg());
		}        
	} 
	/**修改定时任务 先执行获取定时任务详细信息getInfo*/
	@PutMapping
	@Log(title = "定时任务-修改定时任务", businessType = BizOpType.UPDATE)
	public Result<?> update(@RequestBody TSysJob sysJob)  
	{
		if (!CronUtil.isValid(sysJob.getCronExpression())) {
			return Result.warnMsg(ResultCode.JOB_CRON.getMsg());
		}
		try {
			return Result.ok(jobService.updateJob(sysJob));
		} catch (Exception e) {
			return Result.warnMsg(ResultCode.JOB_UPDATE.getMsg());
		}
	}

	/**新增定时任务*/
	@PostMapping
	@Log(title = "定时任务-新增定时任务", businessType = BizOpType.INSERT)
	public Result<?> insert(@RequestBody TSysJob sysJob)  
	{
		if (!CronUtil.isValid(sysJob.getCronExpression())) {
			return Result.warnMsg(ResultCode.JOB_CRON.getMsg());
		}
		try {
			return Result.ok(jobService.saveJob(sysJob));
		} catch (Exception e) {
			return Result.warnMsg(ResultCode.JOB_ADD.getMsg());
		}
	}
	/**删除定时任务 @PathVariable @PathVariable Long[] jobIds*/
	@DeleteMapping("/{jobIds}")
	@Log(title = "定时任务-删除定时任务-deleteJobByIds", businessType = BizOpType.DELETE)
	public Result<?> deleteJobByIds(@PathVariable String[] jobIds) 
	{
		try {
			jobService.deleteJobs(jobIds);
		} catch (Exception e) {
			return Result.warnMsg(ResultCode.JOB_DELETE.getMsg());
		}
		return Result.ok();
	} 
	/**获取定时任务详细信息*/
	@GetMapping(value = "/{jobId}")
	@Log(title = "定时任务-任务详细信息-getInfo", businessType = BizOpType.SELECT)
	public Result<?> getInfo(@PathVariable("jobId") Long jobId) 
	{
		TSysJob job;
		try {
			job = jobService.queryJob(jobId);
		} catch (Exception e) {
			return Result.warnMsg(ResultCode.SQL_RUN.getMsg());
		}
		return Result.ok(job);
	}

	/**定时任务立即执行一次*/
	@PutMapping("/run")
	@Log(title = "定时任务-定时任务立即执行一次", businessType = BizOpType.UPDATE)
	public Result<?> run(@RequestBody TSysJob job) {
		try {
			jobService.runJob(job);
		} catch (SchedulerException e) {
			return Result.warnMsg(ResultCode.JOB_RUN.getMsg());
		}
		return Result.ok();
	} 
	
	/**关闭定时任务*/
	@PutMapping("/close")
	@Log(title = "定时任务-关闭定时任务", businessType = BizOpType.UPDATE)
	public Result<?> close(@RequestBody TSysJob job)
	{
		return Result.ok(jobService.pauseJob(job));
	} 
	
}
