package com.ktg.web.controller.iscs;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ktg.common.annotation.Log;
import com.ktg.common.core.controller.BaseController;
import com.ktg.common.enums.BusinessType;
import com.ktg.common.exception.job.TaskException;
import com.ktg.common.pojo.CommonResult;
import com.ktg.common.utils.StringUtils;
import com.ktg.iscs.domain.IsCheckTask;
import com.ktg.iscs.service.IIsCheckTaskService;
import com.ktg.quartz.domain.SysJob;
import com.ktg.quartz.service.ISysJobService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.Parameter;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 小组Controller
 *
 * @author cc
 * @date 2024-09-13
 */
@Api(tags = "业务交叉api")
@RestController
@RequestMapping("/iscs/resapi")
public class ResApiController extends BaseController
{

    @Autowired
    private ISysJobService iSysJobService;

    @Autowired
    private IIsCheckTaskService iIsCheckTaskService;

    @Transactional
    @ApiOperation("新增检查任务-交叉定时任务")
    @PreAuthorize("@ss.hasPermi('iscs:resapi:add')")
    @Log(title = "检查任务", businessType = BusinessType.INSERT)
    @PostMapping("/insertIsCheckTask")
    public CommonResult<Boolean> insertIsCheckTask(@RequestBody @Parameter(name = "isCheckTask", description = "新增数据类,放到body") IsCheckTask isCheckTask) throws SchedulerException, TaskException {
        // 1.检查数据
        Assert.notBlank(isCheckTask.getCheckName(), "任务名称不可为空!");
        Assert.notBlank(isCheckTask.getCabinetIdStr(), "请选择需要检查的物资柜信息!");
        Assert.notBlank(isCheckTask.getUserIdStr(), "请选择参与人员信息!");
        Assert.notBlank(isCheckTask.getCron(), "请告知我cron!");
        // 2.开始新增定检查信息,但是缺失定时任务的关联信息，所以后面需要更新一下
        iIsCheckTaskService.save(isCheckTask);
        // 3.新增定时任务
        SysJob sysJob = new SysJob();
        sysJob.setJobName(isCheckTask.getCheckName());
        sysJob.setJobGroup("DEFAULT");
        sysJob.setInvokeTarget("sendEmailsTask.checkMaterialsCabinet("+ isCheckTask.getCheckId() + ")");
        sysJob.setCronExpression(isCheckTask.getCron());
        sysJob.setMisfirePolicy("3");
        sysJob.setConcurrent("1");
        sysJob.setStatus("1");
        iSysJobService.insertJob(sysJob);
        // 4.更新定检查信息
        iIsCheckTaskService.update(Wrappers.<IsCheckTask>lambdaUpdate()
                .eq(IsCheckTask::getCheckId, isCheckTask.getCheckId())
                .set(IsCheckTask::getJobId, sysJob.getJobId()));
        return CommonResult.success(true);
    }

    @Transactional
    @ApiOperation("修改检查任务-交叉定时任务")
    @PreAuthorize("@ss.hasPermi('iscs:resapi:edit')")
    @Log(title = "检查任务", businessType = BusinessType.UPDATE)
    @PostMapping("/updateIsCheckTask")
    public CommonResult<Boolean> updateIsCheckTask(@RequestBody @Parameter(name = "isCheckTask", description = "修改数据类,放到body") IsCheckTask isCheckTask)
    {
        // 1.检查数据
        Assert.notNull(isCheckTask.getCheckId(), "checkId不可为空!");
        IsCheckTask checkTask = iIsCheckTaskService.getById(isCheckTask.getCheckId());
        Assert.notNull(checkTask, "数据不存在!");
        // 2.开始更新操作
        iIsCheckTaskService.update(Wrappers.<IsCheckTask>lambdaUpdate()
                .eq(IsCheckTask::getCheckId, isCheckTask.getCheckId())
                .set(IsCheckTask::getUpdateTime, new Date())
                .set(StringUtils.isNotBlank(isCheckTask.getCheckName()), IsCheckTask::getCheckName, isCheckTask.getCheckName())
                .set(StringUtils.isNotBlank(isCheckTask.getCabinetIdStr()), IsCheckTask::getCabinetIdStr, isCheckTask.getCabinetIdStr())
                .set(StringUtils.isNotBlank(isCheckTask.getUserIdStr()), IsCheckTask::getUserIdStr, isCheckTask.getUserIdStr())
                .set(StringUtils.isNotBlank(isCheckTask.getCron()), IsCheckTask::getCron, isCheckTask.getCron()));
        // 3.如果cron变更，则需要变更sysJob
        if (StringUtils.isNotBlank(isCheckTask.getCron())) {
            iSysJobService.update(Wrappers.<SysJob>lambdaUpdate()
                    .eq(SysJob::getJobId, checkTask.getJobId())
                    .set(SysJob::getCronExpression, isCheckTask.getCron()));
        }
        return CommonResult.success(true);
    }

    @Transactional
    @ApiOperation("删除检查任务")
    @PreAuthorize("@ss.hasPermi('iscs:resapi:remove')")
    @Log(title = "检查任务", businessType = BusinessType.DELETE)
    @PostMapping("/deleteIsCheckTaskByCheckIds")
    public CommonResult<Boolean> deleteIsCheckTaskByCheckIds(String checkIds) throws SchedulerException {
        Assert.notBlank(checkIds, "请选择需要删除的数据!");
        List<String> longIds = Arrays.asList(checkIds);
        // 1.获取数据在删除
        List<IsCheckTask> list = iIsCheckTaskService.list(Wrappers.<IsCheckTask>lambdaQuery()
                .in(IsCheckTask::getCheckId, longIds));
        if (!list.isEmpty()) {
            // 删除IsCheckTask
            iIsCheckTaskService.removeByIds(longIds);
            List<Long> jobIds = list.stream().map(IsCheckTask::getJobId).collect(Collectors.toList());
            iSysJobService.deleteJobByIds(jobIds.toArray(new Long[0]));
        }
        return CommonResult.success(true);
    }

}
