/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.quartz.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.quartz.SchedulerException;
import org.springblade.common.constant.Constants;
import org.springblade.common.utils.StringUtil;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.quartz.entity.Job;
import org.springblade.modules.quartz.exception.TaskException;
import org.springblade.modules.quartz.service.IJobService;
import org.springblade.modules.quartz.utils.CronUtils;
import org.springblade.modules.quartz.utils.ScheduleUtils;
import org.springblade.modules.quartz.vo.JobVO;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * 定时任务调度表 控制器
 *
 * @author BladeX
 * @since 2023-02-17
 */
@RestController
@AllArgsConstructor
@RequestMapping("quartz/job")
@Api(value = "定时任务调度表", tags = "定时任务调度表接口")
public class JobController extends BladeController {

    private final IJobService jobService;

    /**
     * 详情
     */
    @GetMapping("/detail")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "详情", notes = "传入job")
    public R<JobVO> detail(Job job) {
        Job detail = jobService.getOne(Condition.getQueryWrapper(job));
        JobVO jobVO = BeanUtil.copyProperties(detail, JobVO.class);
        return R.data(jobVO);
    }

    /**
     * 分页 定时任务调度表
     */
    @GetMapping("/list")
    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "分页", notes = "传入job")
    public R<IPage<Job>> list(Job job, Query query) {
        IPage<Job> pages = jobService.page(Condition.getPage(query), Condition.getQueryWrapper(job));
        return R.data(pages);
    }

    /**
     * 自定义分页 定时任务调度表
     */
    @GetMapping("/page")
    @ApiOperationSupport(order = 3)
    @ApiOperation(value = "自定义分页", notes = "传入job")
    public R<IPage<JobVO>> page(JobVO job, Query query) {
        IPage<JobVO> pages = jobService.selectJobPage(Condition.getPage(query), job);
        return R.data(pages);
    }

    /**
     * 新增 定时任务调度表
     */
    @PostMapping("/save")
    @ApiOperationSupport(order = 4)
    @ApiOperation(value = "新增", notes = "传入job")
    public R save(@Valid @RequestBody Job job) throws TaskException, SchedulerException {
        if (!CronUtils.isValid(job.getCronExpression())) {
            return fail("新增任务'" + job.getJobName() + "'失败，Cron表达式不正确");
        } else if (StringUtil.containsIgnoreCase(job.getInvokeTarget(), Constants.LOOKUP_RMI)) {
            return fail("新增任务'" + job.getJobName() + "'失败，目标字符串不允许'rmi'调用");
        } else if (StringUtil.containsAnyIgnoreCase(job.getInvokeTarget(), new String[]{Constants.LOOKUP_LDAP, Constants.LOOKUP_LDAPS})) {
            return fail("新增任务'" + job.getJobName() + "'失败，目标字符串不允许'ldap(s)'调用");
        } else if (StringUtil.containsAnyIgnoreCase(job.getInvokeTarget(), new String[]{Constants.HTTP, Constants.HTTPS})) {
            return fail("新增任务'" + job.getJobName() + "'失败，目标字符串不允许'http(s)'调用");
        } else if (StringUtil.containsAnyIgnoreCase(job.getInvokeTarget(), Constants.JOB_ERROR_STR)) {
            return fail("新增任务'" + job.getJobName() + "'失败，目标字符串存在违规");
        } else if (!ScheduleUtils.whiteList(job.getInvokeTarget())) {
            return fail("新增任务'" + job.getJobName() + "'失败，目标字符串不在白名单内");
        }
        jobService.insertJob(job);
        return success("ok");
    }

    /**
     * 修改 定时任务调度表
     */
    @PostMapping("/update")
    @ApiOperationSupport(order = 5)
    @ApiOperation(value = "修改", notes = "传入job")
    public R update(@Valid @RequestBody Job job) throws TaskException, SchedulerException {
        if (!CronUtils.isValid(job.getCronExpression())) {
            return fail("修改任务'" + job.getJobName() + "'失败，Cron表达式不正确");
        } else if (StringUtil.containsIgnoreCase(job.getInvokeTarget(), Constants.LOOKUP_RMI)) {
            return fail("修改任务'" + job.getJobName() + "'失败，目标字符串不允许'rmi'调用");
        } else if (StringUtil.containsAnyIgnoreCase(job.getInvokeTarget(), new String[]{Constants.LOOKUP_LDAP, Constants.LOOKUP_LDAPS})) {
            return fail("修改任务'" + job.getJobName() + "'失败，目标字符串不允许'ldap(s)'调用");
        } else if (StringUtil.containsAnyIgnoreCase(job.getInvokeTarget(), new String[]{Constants.HTTP, Constants.HTTPS})) {
            return fail("修改任务'" + job.getJobName() + "'失败，目标字符串不允许'http(s)'调用");
        } else if (StringUtil.containsAnyIgnoreCase(job.getInvokeTarget(), Constants.JOB_ERROR_STR)) {
            return fail("修改任务'" + job.getJobName() + "'失败，目标字符串存在违规");
        } else if (!ScheduleUtils.whiteList(job.getInvokeTarget())) {
            return fail("修改任务'" + job.getJobName() + "'失败，目标字符串不在白名单内");
        }
        jobService.updateJob(job);
        return success("ok");
    }

    /**
     * 新增或修改 定时任务调度表
     */
    @PostMapping("/submit")
    @ApiOperationSupport(order = 6)
    @ApiOperation(value = "新增或修改", notes = "传入job")
    public R submit(@Valid @RequestBody Job job) {
		if (!CronUtils.isValid(job.getCronExpression())) {
			return fail("修改任务'" + job.getJobName() + "'失败，Cron表达式不正确");
		} else if (StringUtil.containsIgnoreCase(job.getInvokeTarget(), Constants.LOOKUP_RMI)) {
			return fail("修改任务'" + job.getJobName() + "'失败，目标字符串不允许'rmi'调用");
		} else if (StringUtil.containsAnyIgnoreCase(job.getInvokeTarget(), new String[]{Constants.LOOKUP_LDAP, Constants.LOOKUP_LDAPS})) {
			return fail("修改任务'" + job.getJobName() + "'失败，目标字符串不允许'ldap(s)'调用");
		} else if (StringUtil.containsAnyIgnoreCase(job.getInvokeTarget(), new String[]{Constants.HTTP, Constants.HTTPS})) {
			return fail("修改任务'" + job.getJobName() + "'失败，目标字符串不允许'http(s)'调用");
		} else if (StringUtil.containsAnyIgnoreCase(job.getInvokeTarget(), Constants.JOB_ERROR_STR)) {
			return fail("修改任务'" + job.getJobName() + "'失败，目标字符串存在违规");
		} else if (!ScheduleUtils.whiteList(job.getInvokeTarget())) {
			return fail("修改任务'" + job.getJobName() + "'失败，目标字符串不在白名单内");
		}
        return R.status(jobService.saveOrUpdate(job));
    }


    /**
     * 删除 定时任务调度表
     */
    @PostMapping("/remove")
    @ApiOperationSupport(order = 7)
    @ApiOperation(value = "逻辑删除", notes = "传入ids")
    public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) throws SchedulerException {
        jobService.deleteJobByIds(Func.toLongList(ids));
        return R.status(true);
    }


    /**
     * 定时任务状态修改
     */
    @ApiOperationSupport(order = 8)
    @ApiOperation(value = "定时任务状态修改")
    @PostMapping("/changeStatus")
    public R changeStatus(@RequestBody Job job) throws SchedulerException {
        Job newJob = jobService.selectJobById(job.getId());
        newJob.setStatus(job.getStatus());
        return data(jobService.changeStatus(newJob));
    }

    /**
     * 定时任务立即执行一次
     */
    @ApiOperationSupport(order = 9)
    @ApiOperation(value = "定时任务立即执行一次")
    @PutMapping("/run")
    public R run(@RequestBody Job job) throws SchedulerException {
        boolean result = jobService.run(job);
        return result ? success("操作成功") : fail("任务不存在或已过期！");
    }
}
