# HotelKpiSchedulerController.java

    package cloud.wconnect.workperformance.controller.hotelkpi;

    import cloud.wconnect.commonlib.annotation.ApiId;
    import cloud.wconnect.commonlib.component.BeanMapper;
    import cloud.wconnect.commonlib.component.SessionContext;
    import cloud.wconnect.commonlib.cons.*;
    import cloud.wconnect.commonlib.exception.BadRequestException;
    import cloud.wconnect.commonlib.pojo.dto.PropertyDTO;
    import cloud.wconnect.commonlib.pojo.dto.scheduler.JobParameterDTO;
    import cloud.wconnect.commonlib.redis.PropertyI18nRedisService;
    import cloud.wconnect.commonlib.util.CronRuleUtil;
    import cloud.wconnect.commonlib.util.I18nMessageUtils;
    import cloud.wconnect.commonlib.util.JsonUtils;
    import cloud.wconnect.workperformance.cons.hotelkpi.HotelKpiCons;
    import cloud.wconnect.workperformance.cons.hotelkpi.HotelKpiReportCategoryEnum;
    import cloud.wconnect.workperformance.entity.hotelkpi.HotelKpiScheduler;
    import cloud.wconnect.workperformance.pojo.dto.hotelkpi.notification.HotelKpiSchedulerDTO;
    import cloud.wconnect.workperformance.service.hotelkpi.IHotelKpiSchedulerService;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.google.common.collect.ImmutableMap;
    import com.google.common.collect.Lists;
    import jakarta.annotation.Resource;
    import jakarta.validation.Valid;
    import org.apache.commons.collections.CollectionUtils;
    import org.apache.commons.lang3.StringUtils;
    import org.springframework.web.bind.annotation.*;

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

    /**
     * <p>
     * Hotel KPI scheduler 前端控制器
     * </p>
     *
     * @author zc
     * @since 2024-06-29
     */
    @RestController
    @RequestMapping("/hotel-kpi/scheduler")
    public class HotelKpiSchedulerController {

        @Resource
        private IHotelKpiSchedulerService schedulerService;
        @Resource
        private PropertyI18nRedisService propertyI18nRedisService;
        @Resource
        private SessionContext sessionContext;
        @Resource
        private BeanMapper beanMapper;
        @Resource
        private ObjectMapper objectMapper;
        @Resource
        private I18nMessageUtils i18nMessageUtils;

        /**
         * 查询调度任务
         *
         * @param property 资产标识
         * @param category 调度任务类型
         * @return 调度任务
         * @author zc
         * @date 2024/6/29
         */
        @ApiId(1220)
        @GetMapping("/{category:\\d+}")
        public List<HotelKpiSchedulerDTO> list(String property, @PathVariable int category) {
            int propertyId = sessionContext.getPropertyId(property);
            PropertyDTO propertyDTO = propertyI18nRedisService.get(propertyId);
            // 校验支持的定时任务类型
            checkSchedulerCategory(propertyDTO.getPmsType(), category);
            // 查询调度任务
            List<HotelKpiScheduler> schedulerList = schedulerService.list(propertyId, category);
            if (CollectionUtils.isEmpty(schedulerList)) {
                return Collections.emptyList();
            }
            return beanMapper.mapList(schedulerList, HotelKpiSchedulerDTO.class);
        }

        /**
         * 保存调度任务
         *
         * @param property     资产标识
         * @param id           调度任务id
         * @param schedulerDTO 调度任务DTO
         * @return 调度任务 Job Id
         * @author zc
         * @date 2024/6/29
         */
        @ApiId(1221)
        @PostMapping("/{id}")
        public Map<String, String> save(@RequestParam String property, @PathVariable String id,
                                        @RequestBody @Valid HotelKpiSchedulerDTO schedulerDTO) {
            int propertyId = sessionContext.getPropertyId(property);
            PropertyDTO propertyDTO = propertyI18nRedisService.get(propertyId);
            // 校验支持的定时任务类型
            checkSchedulerCategory(propertyDTO.getPmsType(), schedulerDTO.getCategory());
            // 检查 parameters json 格式是否合法
            checkJobParameters(schedulerDTO.getParameters());
            // 检查 scheduler json 格式是否合法
            CronRuleUtil.validateCronRuleForScheduler(objectMapper, Lists.newArrayList(SchedulerCons.EVERY_DAY),
                    schedulerDTO.getScheduler());
            // 设置 Job Parameter
            setJobParameter(schedulerDTO);

            schedulerDTO.setPropertyId(propertyDTO.getId());
            if (id.equals("0")) {
                // 校验分类下最大可配置调度任务的数量
                schedulerService.checkMaxNum(propertyDTO.getId(), schedulerDTO.getCategory(), 1);
                // 新增调度任务
                id = schedulerService.save(schedulerDTO, propertyDTO, sessionContext.getLoginUserId());
            } else {
                // 校验调度任务是否存在
                HotelKpiScheduler scheduler = schedulerService.checkExist(id);
                // 校验归属
                schedulerService.checkBelong(propertyDTO.getId(), scheduler);
                if (scheduler.getStatus() == SchedulerCons.STATUS_DELETING) {
                    throw new BadRequestException(CommonErrorI18nConstant.SCHEDULER_CANNOT_UPDATE_DELETING,
                            BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                            "The deleting Scheduler cannot update, SchedulerJobId=" + scheduler.getId());
                }
                if (!scheduler.getCategory().equals(schedulerDTO.getCategory())) {
                    throw new BadRequestException(CommonErrorI18nConstant.SCHEDULER_CANNOT_CHANGE_CATEGORY,
                            BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                            "The Scheduler category cannot update, SchedulerJobId=" + scheduler.getId());
                }
                // 修改调度任务
                schedulerDTO.setId(id);
                id = schedulerService.update(propertyDTO, scheduler, schedulerDTO, sessionContext.getLoginUserId());
            }
            return ImmutableMap.of("id", id);
        }

        /**
         * 删除任务
         *
         * @param id       任务ID
         * @param property 资产标识
         * @return java.util.Map
         * @author zc
         * @date 2024/7/16
         */
        @ApiId(1235)
        @DeleteMapping("/{id}")
        public Map<Object, Object> delete(@PathVariable String id, String property) {
            int propertyId = sessionContext.getPropertyId(property);
            // 校验是否存在
            HotelKpiScheduler oriSchedulerJob = schedulerService.checkExist(id);
            // 校验归属
            schedulerService.checkBelong(propertyId, oriSchedulerJob);
            // 删除中状态的数据不可删除
            if (oriSchedulerJob.getStatus() == SchedulerCons.STATUS_DELETING) {
                throw new BadRequestException(CommonErrorI18nConstant.SCHEDULER_CANNOT_DELETE_DELETING,
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                        "The deleting hotelKPI scheduler cannot delete; SchedulerJobId=" + oriSchedulerJob.getId());
            }
            // 删除任务
            schedulerService.delete(propertyId, oriSchedulerJob);

            return Collections.emptyMap();
        }

        /**
         * 设置 Job Parameter
         *
         * @param schedulerDTO 调度任务DTO
         * @author zc
         * @date 2025/7/23
         */
        private void setJobParameter(HotelKpiSchedulerDTO schedulerDTO) {
            JobParameterDTO jobParameterDTO = JsonUtils.convertStringToObject(objectMapper,
                    schedulerDTO.getParameters(), JobParameterDTO.class);
            jobParameterDTO.setDateRangeUnit(JobParameterDTO.DAY);
            jobParameterDTO.setDateRange(HotelKpiReportCategoryEnum.getDateRange(schedulerDTO.getCategory()));
            schedulerDTO.setParameters(JsonUtils.convertObjToString(objectMapper, jobParameterDTO));
        }

        /**
         * 校验定时任务 parameters 参数
         *
         * @param parameters 调度任务自定义参数
         * @author zc
         * @date 2024/7/11
         */
        private void checkJobParameters(String parameters) {
            if (StringUtils.isBlank(parameters)) {
                throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                        i18nMessageUtils.getErrorParamMapNeedTranslate(CommonFieldI18nConstant.SCHEDULER_EXEC_PARAMETERS),
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                        "The parameters cannot be blank");
            }
            JobParameterDTO jobParameterDTO = JsonUtils.convertStringToObject(objectMapper, parameters, JobParameterDTO.class);
            // 校验阈值
            if (Objects.isNull(jobParameterDTO.getThreshold())) {
                throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                        i18nMessageUtils.getErrorParamMapNeedTranslate(CommonFieldI18nConstant.SCHEDULER_THRESHOLD),
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                        "The threshold cannot be null");
            }
        }

        /**
         * 校验支持的定时任务类型
         *
         * @param propertyPmsType 属性PMS类型
         * @param schedulerType   定时任务类型
         * @author zc
         * @date 2025/7/23
         */
        private void checkSchedulerCategory(String propertyPmsType, int schedulerType) {
            List<Integer> effectiveSchedulerTypeList;
            if (SystemPlatformEnum.OPERA.getDesc().equals(propertyPmsType)) {
                effectiveSchedulerTypeList = HotelKpiCons.OPERA_PMS_TYPE_LIST;
            } else {
                effectiveSchedulerTypeList = HotelKpiCons.SHIJI_PMS_TYPE_LIST;
            }
            if (!effectiveSchedulerTypeList.contains(schedulerType)) {
                throw new BadRequestException(CommonErrorI18nConstant.NOTIFY_TYPE_NOT_SUPPORTED,
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                        MessageFormat.format("The currently selected scheduler type is not supported, " +
                                "schedulerCategory must be in {0}", effectiveSchedulerTypeList));
            }
        }
    }