# OooRoomSchedulerJobController.java

    package cloud.wconnect.frontoffice.controller.oooroom;

    import cloud.wconnect.commonlib.annotation.ApiId;
    import cloud.wconnect.commonlib.component.BeanMapper;
    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.entity.oooroom.OooRoomSchedulerJob;
    import cloud.wconnect.frontoffice.pojo.dto.oooroom.OooRoomSchedulerDTO;
    import cloud.wconnect.frontoffice.service.oooroom.IOooRoomSchedulerJobService;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.google.common.collect.ImmutableMap;
    import jakarta.validation.Valid;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.*;

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

    /**
     * <p>
     * 前端控制器
     * </p>
     *
     * @author yyt
     * @since 2024-03-14
     */
    @RestController
    @RequestMapping("/ooo-room/scheduler")
    public class OooRoomSchedulerJobController {

        @Autowired
        private BeanMapper beanMapper;
        @Autowired
        private SessionContext sessionContext;
        @Autowired
        private IOooRoomSchedulerJobService oooRoomSchedulerJobService;
        @Autowired
        private PropertyI18nRedisService propertyI18nRedisService;
        @Autowired
        private ObjectMapper objectMapper;
        @Autowired
        private I18nMessageUtils i18nMessageUtils;

        /**
         * 查询定时任务
         *
         * @param property 资产标识
         * @param category 类型（1：out of order 报告缺失，2：未关闭房间通知）
         * @return 定时任务
         * @author yyt
         * @date 2024/3/14
         */
        @ApiId(1079)
        @GetMapping("/{category:\\d+}")
        public List<OooRoomSchedulerDTO> get(String property, @PathVariable int category) {
            Integer propertyId = sessionContext.getPropertyId(property);
            // 查询非删除中的定时任务
            List<OooRoomSchedulerJob> schedulers = oooRoomSchedulerJobService.list(propertyId, category, null);
            return beanMapper.mapList(schedulers, OooRoomSchedulerDTO.class);
        }

        /**
         * 保存定时任务
         *
         * @param property     资产标识
         * @param id           定时任务 id
         * @param schedulerDTO 定时任务
         * @return {}
         * @author yyt
         * @date 2024/3/14
         */
        @ApiId(1080)
        @PostMapping("/{id}")
        public Map<String, String> save(String property, @PathVariable String id, @Valid @RequestBody OooRoomSchedulerDTO schedulerDTO) {
            // 校验定时规则
            checkScheduler(schedulerDTO);

            PropertyDTO propertyDTO = propertyI18nRedisService.get(sessionContext.getPropertyId(property));
            Integer propertyId = propertyDTO.getId();

            Integer category = schedulerDTO.getCategory();
            if (category == OooRoomSchedulerDTO.NOTIFY_NOT_CLOSED) {
                schedulerDTO.setParameters("{}");
            }

            // 校验 scheduler 不能重复
            checkSchedulerRepeat(propertyId, category, schedulerDTO.getScheduler(), id);

            if (id.equals("0")) {
                if (category == OooRoomSchedulerDTO.NOTIFY_NOT_CLOSED) {
                    // 未删除状态下，未关闭房间通知，最多只能创建 5个
                    oooRoomSchedulerJobService.checkCount(propertyId, category, 5);
                } else {
                    // 限制 同一个 category 只能存在一条未删除中的数据
                    oooRoomSchedulerJobService.checkCount(propertyId, category, 1);
                }

                id = oooRoomSchedulerJobService.save(propertyDTO, schedulerDTO, sessionContext.getLoginUserId());
            } else {
                //校验调度任务是否存在
                OooRoomSchedulerJob scheduler = oooRoomSchedulerJobService.checkExist(id);

                //校验是否归属于资产
                checkBelong(scheduler, propertyDTO.getId());

                if (scheduler.getStatus() == SchedulerCons.STATUS_DELETING) {
                    throw new BadRequestException(CommonErrorI18nConstant.SCHEDULER_CANNOT_UPDATE_DELETING,
                            BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                            "deleting oooRoomScheduler do not support update; oooRoomSchedulerId:" + id);
                }
                if (!scheduler.getCategory().equals(category)) {
                    throw new BadRequestException(CommonErrorI18nConstant.SCHEDULER_CANNOT_CHANGE_CATEGORY,
                            BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                            "oooRoomScheduler category do not support update; oooRoomSchedulerId:" + id);
                }

                id = oooRoomSchedulerJobService.update(propertyDTO, scheduler, schedulerDTO, sessionContext.getLoginUserId());
            }

            return ImmutableMap.of("id", id);
        }

        /**
         * 校验 scheduler 不能重复
         *
         * @param propertyId      资产 id
         * @param category        分类
         * @param updateScheduler 修改后的 scheduler
         * @param id              排除自身
         * @author yyt
         * @date 2024/3/19
         **/
        private void checkSchedulerRepeat(Integer propertyId, Integer category, String updateScheduler, String id) {
            List<OooRoomSchedulerJob> existSchedulerJobs = oooRoomSchedulerJobService.list(propertyId, category, id);
            if (existSchedulerJobs.isEmpty()) {
                return;
            }

            CronRuleUtil.checkSchedulerRepeat(objectMapper, existSchedulerJobs.stream().map(OooRoomSchedulerJob::getScheduler).toList(), updateScheduler);
        }

        /**
         * 删除定时任务
         *
         * @param property 资产标识
         * @param id       定时任务 id
         * @return {}
         * @author yyt
         * @date 2024/3/13
         **/
        @ApiId(1081)
        @DeleteMapping("/{id}")
        public Map<String, Object> delete(String property, @PathVariable String id) {
            PropertyDTO propertyDTO = propertyI18nRedisService.get(sessionContext.getPropertyId(property));
            //校验调度任务是否存在
            OooRoomSchedulerJob scheduler = oooRoomSchedulerJobService.checkExist(id);

            //校验是否归属于资产
            checkBelong(scheduler, propertyDTO.getId());

            if (scheduler.getStatus() == SchedulerCons.STATUS_DELETING) {
                throw new BadRequestException(CommonErrorI18nConstant.SCHEDULER_CANNOT_DELETE_DELETING,
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                        "deleting oooRoomScheduler do not support deletion; oooRoomSchedulerId:" + id);
            }
            if (scheduler.getCategory() == OooRoomSchedulerDTO.MISSING_OUT_OF_ORDER_REPORT) {
                throw new BadRequestException(CommonErrorI18nConstant.SCHEDULER_CANNOT_DELETE,
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                        "oooRoomScheduler that report missing types do not support deletion; oooRoomSchedulerId:" + id);
            }

            oooRoomSchedulerJobService.delete(propertyDTO, scheduler);

            return Collections.emptyMap();
        }

        /**
         * 校验定时规则
         *
         * @param schedulerDTO 定时
         * @author yyt
         * @date 2024/3/14
         **/
        private void checkScheduler(OooRoomSchedulerDTO schedulerDTO) {
            switch (schedulerDTO.getCategory()) {
                case OooRoomSchedulerDTO.MISSING_OUT_OF_ORDER_REPORT -> {
                    // 检查 scheduler json 格式是否合法，目前支持配置按天执行；
                    CronRuleUtil.validateCronRuleForScheduler(objectMapper, List.of(SchedulerCons.EVERY_DAY), schedulerDTO.getScheduler());

                    //检查 parameters json 格式是否合法
                    JobParameterUtils.checkParametersThreshold(objectMapper, schedulerDTO.getParameters(), i18nMessageUtils);
                }
                case OooRoomSchedulerDTO.NOTIFY_NOT_CLOSED -> {
                    // 检查 scheduler json 格式是否合法，目前支持配置按天 / 周 / 月 执行
                    CronRuleUtil.validateCronRuleForScheduler(objectMapper,
                            List.of(SchedulerCons.EVERY_DAY, SchedulerCons.EVERY_WEEK, SchedulerCons.EVERY_MONTH),
                            schedulerDTO.getScheduler());
                }
            }
        }

        /**
         * 校验数据归属
         *
         * @param oooRoomSchedulerJob 定时任务
         * @param propertyId          资产 id
         * @author yyt
         * @date 2024/3/13
         */
        private void checkBelong(OooRoomSchedulerJob oooRoomSchedulerJob, Integer propertyId) {
            if (!oooRoomSchedulerJob.getPropertyId().equals(propertyId)) {
                throw new ForbiddenException(BaseErrorCodeEnum.DATA_FORBIDDEN.getI18nCode(),
                        BaseErrorCodeEnum.DATA_FORBIDDEN.getCode(), "the property id parameter is different from " +
                        "the property id of the oooRoomSchedulerJob;propertyId:" + propertyId + ",oooRoomSchedulerJobPropertyId:" +
                        oooRoomSchedulerJob.getPropertyId() + ",oooRoomSchedulerJobId:" + oooRoomSchedulerJob.getId());
            }
        }

    }