# CbCaseSchedulerJobController.java

    package cloud.wconnect.finance.controller.chargeback;

    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.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.JobParameterUtils;
    import cloud.wconnect.commonlib.util.JsonUtils;
    import cloud.wconnect.finance.entity.chargeback.CbCaseSchedulerJob;
    import cloud.wconnect.finance.pojo.dto.chargeback.CbCaseSchedulerDTO;
    import cloud.wconnect.finance.service.chargeback.ICbCaseSchedulerJobService;
    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-16
     */
    @RestController
    @RequestMapping("/charge-back/scheduler")
    public class CbCaseSchedulerJobController {

        @Autowired
        private BeanMapper beanMapper;
        @Autowired
        private SessionContext sessionContext;
        @Autowired
        private ICbCaseSchedulerJobService schedulerJobService;
        @Autowired
        private ObjectMapper objectMapper;
        @Autowired
        private I18nMessageUtils i18nMessageUtils;
        @Autowired
        private PropertyI18nRedisService propertyI18nRedisService;

        /**
         * 查询定时任务
         *
         * @param property 资产标识
         * @param category 类型（1：journal 报告缺失，2：超期通知）
         * @return 定时任务
         * @author yyt
         * @date 2024/3/16
         */
        @ApiId(1097)
        @GetMapping("/{category:\\d+}")
        public List<CbCaseSchedulerDTO> get(String property, @PathVariable int category) {
            Integer propertyId = sessionContext.getPropertyId(property);
            // 查询非删除中的定时任务
            List<CbCaseSchedulerJob> schedulers = schedulerJobService.list(propertyId, category, null);
            return beanMapper.mapList(schedulers, CbCaseSchedulerDTO.class);
        }

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

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

            Integer category = schedulerDTO.getCategory();
            if (category == CbCaseSchedulerDTO.MISSING_JOURNAL_REPORT) {
                // 检测报告缺失的 dateRange默认为：-1，阈值
                JobParameterDTO jobParameterDTO = JsonUtils.convertStringToObject(objectMapper,
                        schedulerDTO.getParameters(), JobParameterDTO.class);
                jobParameterDTO.setDateRange("-1");
                jobParameterDTO.setDateRangeUnit(JobParameterDTO.DAY);
                schedulerDTO.setParameters(JsonUtils.convertObjToString(objectMapper, jobParameterDTO));
            } else if (category == CbCaseSchedulerDTO.NOTIFY_OVER_TIME) {
                schedulerDTO.setParameters("{}");
            }

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

            if (id.equals("0")) {
                if(category == CbCaseSchedulerDTO.NOTIFY_OVER_TIME){
                    // 未删除状态下，超期通知，最多只能创建 5个
                    schedulerJobService.checkCountLimit(propertyId, category, 5);
                } else {
                    // 限制只能存在一条未删除中的数据
                    schedulerJobService.checkCountLimit(propertyId, category, 1);
                }

                id = schedulerJobService.save(propertyDTO, schedulerDTO, sessionContext.getLoginUserId());
            } else {
                //校验调度任务是否存在
                CbCaseSchedulerJob scheduler = schedulerJobService.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 cbCaseScheduler do not support update; cbCaseSchedulerId:" + id);
                }
                if (!scheduler.getCategory().equals(category)) {
                    throw new BadRequestException(CommonErrorI18nConstant.SCHEDULER_CANNOT_CHANGE_CATEGORY,
                            BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                            "cbCaseScheduler category do not support update; cbCaseSchedulerId:" + id);
                }

                id = schedulerJobService.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<CbCaseSchedulerJob> existSchedulerJobs = schedulerJobService.list(propertyId, category, id);
            if (existSchedulerJobs.isEmpty()) {
                return;
            }

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

        /**
         * 删除定时任务
         *
         * @param property 资产标识
         * @param id       定时任务 id
         * @return {}
         * @author yyt
         * @date 2024/3/16
         **/
        @ApiId(1099)
        @DeleteMapping("/{id}")
        public Map<String, Object> delete(String property, @PathVariable String id) {
            //校验调度任务是否存在
            CbCaseSchedulerJob scheduler = schedulerJobService.checkExist(id);

            //校验是否归属于资产
            checkBelong(scheduler, sessionContext.getPropertyId(property));

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

            schedulerJobService.delete(scheduler);

            return Collections.emptyMap();
        }

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

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

        /**
         * 校验数据归属
         *
         * @param cbCaseSchedulerJob 定时任务
         * @param propertyId         资产 id
         * @author yyt
         * @date 2024/3/16
         */
        private void checkBelong(CbCaseSchedulerJob cbCaseSchedulerJob, Integer propertyId) {
            if (!cbCaseSchedulerJob.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 cbCaseScheduler;propertyId:" + propertyId + ",clcSchedulerPropertyId:" +
                        cbCaseSchedulerJob.getPropertyId() + ",clcSchedulerId:" + cbCaseSchedulerJob.getId());
            }
        }

    }