# CompRoomSchedulerController.java

    package cloud.wconnect.frontoffice.controller.comproom;

    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.commonlib.util.JobParameterUtils;
    import cloud.wconnect.frontoffice.cons.comproom.CompRoomNotifyConfigTypeEnum;
    import cloud.wconnect.frontoffice.entity.comproom.CompRoomScheduler;
    import cloud.wconnect.frontoffice.pojo.dto.comproom.CompRoomSchedulerDTO;
    import cloud.wconnect.frontoffice.service.comproom.ICompRoomSchedulerService;
    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;

    /**
     * 免费房动态任务配置Controller
     *
     * @author lichen
     * @date 2024/3/13
     */
    @RestController
    @RequestMapping("/comp-room/scheduler")
    public class CompRoomSchedulerController {

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

        /**
         * 保存调度任务
         *
         * @param property     资产标识
         * @param id           调度任务主键ID
         * @param schedulerDTO 调度任务DTO
         * @return java.util.Map<java.lang.String, java.lang.Integer>
         * @author lichen
         * @date 2024/3/11
         */
        @ApiId(1042)
        @PostMapping("{id}")
        public Map<String, String> save(String property, @PathVariable String id,
                                        @RequestBody @Valid CompRoomSchedulerDTO 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), schedulerDTO.getScheduler());

            Integer category = schedulerDTO.getCategory();
            if (category.equals(CompRoomNotifyConfigTypeEnum.REPORT_MISSED.getType())) {
                //检查 parameters json格式是否合法
                JobParameterUtils.checkParametersThreshold(objectMapper, schedulerDTO.getParameters(), i18nMessageUtils);
            } else {
                //校验定时任务执行时间唯一
                schedulerService.checkCornRuleSole(propertyDTO.getId(), category, schedulerDTO.getScheduler(), id);
                schedulerDTO.setParameters("{}");
            }

            if (!id.equals("0")) {
                //校验调度任务是否存在
                CompRoomScheduler oriScheduler = schedulerService.checkExist(id);
                //校验是否归属于资产
                checkBelong(oriScheduler, propertyDTO.getId());
                if (oriScheduler.getStatus() == SchedulerCons.STATUS_DELETING) {
                    throw new BadRequestException(CommonErrorI18nConstant.SCHEDULER_CANNOT_UPDATE_DELETING,
                            BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                            "deleting SchedulerJob cannot update, SchedulerJobId=" + oriScheduler.getId());
                }
                if (!oriScheduler.getCategory().equals(schedulerDTO.getCategory())) {
                    throw new BadRequestException(CommonErrorI18nConstant.CANNOT_MODIFIED,
                            i18nMessageUtils.getErrorParamMapNotNeedTranslate("category"),
                            BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                            "SchedulerJob category cannot update, SchedulerJobId=" + oriScheduler.getId());
                }
                //修改
                schedulerDTO.setId(id);
                return Map.of("id", schedulerService.update(propertyDTO, oriScheduler, schedulerDTO, loginUserId));
            } else {
                //校验同一个category下最大可配置的数量
                if (category == CompRoomNotifyConfigTypeEnum.REPORT_MISSED.getType()) {
                    schedulerService.checkMaxNum(propertyDTO.getId(), schedulerDTO.getCategory(), 1);
                } else {
                    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/12
         */
        @ApiId(1036)
        @DeleteMapping("{id}")
        public Map delete(@PathVariable String id, String property) {
            int propertyId = sessionContext.getPropertyId(property);
            PropertyDTO propertyDTO = propertyI18nRedisService.get(propertyId);
            //校验是否存在
            CompRoomScheduler 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.comproom.CompRoomScheduler>
         * @author lichen
         * @date 2024/3/14
         */
        @ApiId(1041)
        @GetMapping("{category:\\d+}")
        public List<CompRoomScheduler> list(@PathVariable Integer category, String property) {
            int propertyId = sessionContext.getPropertyId(property);
            //查询调度任务
            return schedulerService.listByCategory(propertyId, category);
        }

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

    }