# GlcSchedulerController.java

    package cloud.wconnect.frontoffice.controller.guestledgercheck;

    import cloud.wconnect.commonlib.annotation.ApiId;
    import cloud.wconnect.commonlib.component.SessionContext;
    import cloud.wconnect.commonlib.cons.BaseErrorCodeEnum;
    import cloud.wconnect.commonlib.cons.CommonErrorI18nConstant;
    import cloud.wconnect.commonlib.cons.SchedulerCons;
    import cloud.wconnect.commonlib.exception.BadRequestException;
    import cloud.wconnect.commonlib.exception.ForbiddenException;
    import cloud.wconnect.commonlib.pojo.dto.PropertyDTO;
    import cloud.wconnect.commonlib.redis.PropertyI18nRedisService;
    import cloud.wconnect.commonlib.util.CronRuleUtil;
    import cloud.wconnect.commonlib.util.I18nMessageUtils;
    import cloud.wconnect.frontoffice.cons.guestledgercheck.GuestLedgerCheckNotifyConfigEnum;
    import cloud.wconnect.frontoffice.entity.guestledgercheck.GlcScheduler;
    import cloud.wconnect.frontoffice.pojo.dto.guestledgercheck.GlcSchedulerDTO;
    import cloud.wconnect.frontoffice.service.guestledgercheck.IGlcSchedulerService;
    import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.*;

    import jakarta.validation.Valid;

    import java.text.MessageFormat;
    import java.util.Collections;
    import java.util.List;
    import java.util.Map;

    /**
     * <p>
     * 前端控制器
     * </p>
     *
     * @author lichen
     * @since 2024-03-15
     */
    @RestController
    @RequestMapping("/guest-ledger-check/scheduler")
    public class GlcSchedulerController {

        @Autowired
        private IGlcSchedulerService schedulerService;
        @Autowired
        private ObjectMapper objectMapper;
        @Autowired
        private SessionContext sessionContext;
        @Autowired
        private PropertyI18nRedisService propertyI18nRedisService;
        @Autowired
        private I18nMessageUtils i18nMessageUtils;

        /**
         * 保存调度任务
         *
         * @param property     资产标识
         * @param id           调度任务主键ID
         * @param schedulerDTO 调度任务DTO
         * @return java.util.Map<java.lang.String, java.lang.Integer>
         * @author lichen
         * @date 2024/3/15
         */
        @ApiId(1059)
        @PostMapping("{id}")
        public Map<String, String> save(String property, @PathVariable String id,
                                        @RequestBody @Valid GlcSchedulerDTO schedulerDTO) {
            int propertyId = sessionContext.getPropertyId(property);
            int loginUserId = sessionContext.getLoginUserId();
            PropertyDTO propertyDTO = propertyI18nRedisService.get(propertyId);
            schedulerDTO.setPropertyId(propertyDTO.getId());

            // 检查 scheduler json格式是否合法
            CronRuleUtil.validateCronRuleForScheduler(objectMapper, List.of(SchedulerCons.EVERY_DAY,
                    SchedulerCons.EVERY_WEEK, SchedulerCons.EVERY_MONTH), schedulerDTO.getScheduler());

            Integer category = schedulerDTO.getCategory();
            if (category == GuestLedgerCheckNotifyConfigEnum.WAITING_FOR_RESOLUTION.getType()) {
                schedulerDTO.setParameters("{}");
                //校验定时任务执行时间唯一
                schedulerService.checkCornRuleSole(propertyDTO.getId(), category, schedulerDTO.getScheduler(), id);
            }
            if (!id.equals("0")) {
                //校验调度任务是否存在
                GlcScheduler oriSchedulerJob = schedulerService.checkExist(id);
                //校验是否归属于资产
                checkBelong(oriSchedulerJob, propertyDTO.getId());
                if (oriSchedulerJob.getStatus() == SchedulerCons.STATUS_DELETING) {
                    throw new BadRequestException(CommonErrorI18nConstant.SCHEDULER_CANNOT_UPDATE_DELETING,
                            BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                            "deleting SchedulerJob cannot update, SchedulerJobId=" + oriSchedulerJob.getId());
                }
                if (!oriSchedulerJob.getCategory().equals(schedulerDTO.getCategory())) {
                    throw new BadRequestException(CommonErrorI18nConstant.CANNOT_MODIFIED,
                            i18nMessageUtils.getErrorParamMapNotNeedTranslate("category"),
                            BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                            "SchedulerJob category cannot update, SchedulerJobId=" + oriSchedulerJob.getId());
                }
                //修改
                schedulerDTO.setId(id);
                return Map.of("id", schedulerService.update(propertyDTO, oriSchedulerJob, schedulerDTO, loginUserId));
            } else {
                //校验同一个category下最大可配置的数量
                schedulerService.checkMaxNum(propertyDTO.getId(), schedulerDTO.getCategory(), 5);
                //新增
                return Map.of("id", schedulerService.createScheduler(schedulerDTO, propertyDTO, loginUserId));
            }
        }

        /**
         * 删除任务
         *
         * @param id       任务ID
         * @param property 资产标识
         * @return java.util.Map
         * @author lichen
         * @date 2024/3/15
         */
        @ApiId(1060)
        @DeleteMapping("{id}")
        public Map delete(@PathVariable String id, String property) {
            int propertyId = sessionContext.getPropertyId(property);
            PropertyDTO propertyDTO = propertyI18nRedisService.get(propertyId);
            //校验是否存在
            GlcScheduler oriSchedulerJob = schedulerService.checkExist(id);
            //校验归属
            checkBelong(oriSchedulerJob, propertyDTO.getId());
            //删除任务
            schedulerService.delete(oriSchedulerJob, propertyDTO);
            return Collections.emptyMap();
        }

        /**
         * 查询调度任务
         *
         * @param category 调度任务类型
         * @param property 资产标识
         * @return java.util.List<cloud.wconnect.frontoffice.entity.guestledger.GlcScheduler>
         * @author lichen
         * @date 2024/3/15
         */
        @ApiId(1058)
        @GetMapping("{category:\\d+}")
        public List<GlcScheduler> list(@PathVariable Integer category, String property) {
            int propertyId = sessionContext.getPropertyId(property);
            //查询调度任务
            return schedulerService.listByCategory(propertyId, category);
        }

        /**
         * 校验调度任务是否归属于资产
         *
         * @param oriSchedulerJob 调度任务
         * @param propertyId      资产ID
         * @return void
         * @author lichen
         * @date 2024/3/15
         */
        private void checkBelong(GlcScheduler oriSchedulerJob, Integer propertyId) {
            if (!oriSchedulerJob.getPropertyId().equals(propertyId)) {
                throw new ForbiddenException(BaseErrorCodeEnum.DATA_FORBIDDEN.getI18nCode(),
                        BaseErrorCodeEnum.DATA_FORBIDDEN.getCode(),
                        MessageFormat.format("SchedulerJob not belong current property,SchedulerJobId:{0},SchedulerJobBelongPropertyId:{1},currentPropertyId:{2}",
                                oriSchedulerJob.getId(), oriSchedulerJob.getPropertyId(), propertyId));
            }
        }

    }