package com.yfd.platform.system.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yfd.platform.annotation.Log;
import com.yfd.platform.config.ResponseResult;
import com.yfd.platform.system.domain.QuartzJob;
import com.yfd.platform.system.service.IQuartzJobService;
import com.yfd.platform.system.service.impl.UserServiceImpl;
import com.yfd.platform.utils.QuartzManage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.quartz.CronExpression;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.time.LocalDateTime;

/**
 * <p>
 * 定时任务 前端控制器
 * </p>
 *
 *
 * @since 2023-03-19
 */
@RestController
@RequestMapping("/system/quartzjob")
@Api(tags = "定时任务")
@Transactional
public class QuartzJobController {

    @Resource
    private IQuartzJobService quartzJobService;

    @Resource
    private UserServiceImpl currentUser;

    @Resource
    private QuartzManage quartzManage;

    @ApiOperation("查询定时任务")
    @GetMapping("/getQuartzJobList")
    public ResponseResult getQuartzJobList(Page<QuartzJob> page,
                                           String jobName) {
        LambdaQueryWrapper<QuartzJob> queryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(jobName)) {
            queryWrapper.like(QuartzJob::getJobName, jobName);
        }
        queryWrapper.orderByAsc(QuartzJob::getOrderno);
        Page<QuartzJob> pageList = quartzJobService.page(page, queryWrapper);
        return ResponseResult.successData(pageList);
    }

    @Log(module = "定时任务管理", value = "新增定时任务",type = "0")
    @ApiOperation("新增定时任务")
    @PostMapping("/addQuartzJob")
    public ResponseResult addQuartzJob(@RequestBody QuartzJob quartzJob) {
        if (quartzJob == null) {
            return ResponseResult.error("参数为空");
        }
        // 添加最近修改人
        quartzJob.setLastmodifier(currentUser.getUsername());
        // 添加最近修改时间
        quartzJob.setLastmodifydate(new Timestamp(System.currentTimeMillis()));
        if (StrUtil.isBlank(quartzJob.getJobCron()) || !CronExpression.isValidExpression(quartzJob.getJobCron())) {
            return ResponseResult.error("cron表达式格式错误");
        }
        quartzJob.setStatus("0");
        boolean ok = quartzJobService.addQuartzJob(quartzJob);
        quartzManage.addJob(quartzJob);
        if (ok) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error("新增失败");
        }
    }

    @Log(module = "定时任务管理", value = "设置定时任务是否有效",type = "0")
    @ApiOperation("设置定时任务是否有效")
    @PostMapping("/setQuartzStatus")
    public ResponseResult setQuartzStatus(@RequestParam String id,
                                          @RequestParam String status) {
        if (StrUtil.isBlank(id) || StrUtil.isBlank(status)) {
            return ResponseResult.error("参数为空");
        }
        LambdaUpdateWrapper<QuartzJob> updateWrapper =
                new LambdaUpdateWrapper<>();
        //根据id 更新状态，最近修改人，最近修改时间
        updateWrapper.eq(QuartzJob::getId, id).set(QuartzJob::getStatus,
                status).set(
                QuartzJob::getLastmodifier, currentUser.getUsername()).set(QuartzJob::getLastmodifydate,
                LocalDateTime.now());
        boolean ok = quartzJobService.update(updateWrapper);
        QuartzJob quartzJob = quartzJobService.getById(id);
        if ("0".equals(quartzJob.getStatus())) {
            quartzManage.pauseJob(quartzJob);
        } else {
            quartzManage.resumeJob(quartzJob);
        }

        if (ok) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error();
        }
    }

    @ApiOperation("根据ID查询定时任务")
    @GetMapping("/getQuartzJobById")
    public ResponseResult getQuartzJobById(String id) {
        QuartzJob quartzJob = quartzJobService.getById(id);
        return ResponseResult.successData(quartzJob);
    }

    @Log(module = "定时任务管理", value = "修改定时任务",type = "0")
    @ApiOperation("修改定时任务")
    @PostMapping("/updateQuartzJob")
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult updateQuartzJob(@RequestBody QuartzJob quartzJob) {
        // 添加最近修改人
        quartzJob.setLastmodifier(currentUser.getUsername());
        // 添加最近修改时间
        quartzJob.setLastmodifydate(new Timestamp(System.currentTimeMillis()));
        if (StrUtil.isBlank(quartzJob.getJobCron()) || !CronExpression.isValidExpression(quartzJob.getJobCron())) {
            return ResponseResult.error("cron表达式格式错误");
        }
        boolean ok = quartzJobService.updateById(quartzJob);
        quartzManage.updateJobCron(quartzJob);
        if (ok) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error("修改失败");
        }
    }

    @Log(module = "定时任务管理", value = "删除定时任务",type = "0")
    @ApiOperation("删除定时任务")
    @PostMapping("/deleteQuartzJob")
    public ResponseResult deleteQuartzJob(@RequestParam String id) {
        if (StrUtil.isBlank(id)) {
            return ResponseResult.error("参数为空");
        }
        boolean ok = quartzJobService.deleteQuartzJob(id);
        if (ok) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error("删除失败");
        }
    }

    @Log(module = "定时任务管理", value = "执行定时任务",type = "0")
    @ApiOperation("执行定时任务")
    @PostMapping("/execution")
    public ResponseResult execution(@RequestParam String id) {
        quartzJobService.execution(quartzJobService.getById(id));
        return ResponseResult.success();
    }

    /**********************************
     * 用途说明: 拖动修改定时顺序
     * 参数说明  fromID 当前ID  toID 到达ID
     * 返回值说明: com.yfd.platform.config.ResponseResult 成功或者失败
     ***********************************/
    @Log(module = "定时任务管理", value = "拖动定时任务",type = "0")
    @PostMapping("/changeDictOrder")
    @ApiOperation("拖动修改定时任务顺序")
    public ResponseResult changeQuartzOrder(@RequestParam String fromID,
                                            @RequestParam String toID) {

        boolean ok = quartzJobService.changeDictOrder(fromID, toID);
        if (ok) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error();
        }

    }
}
