# AdjSchedulerController.java

    package cloud.wconnect.frontoffice.controller.adjustment;

    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.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.frontoffice.cons.adjustment.AdjNotifyConfigTypeEnum;
    import cloud.wconnect.frontoffice.entity.adjustment.SchedulerJob;
    import cloud.wconnect.frontoffice.pojo.dto.adjustment.SchedulerDTO;
    import cloud.wconnect.frontoffice.service.adjustment.ISchedulerService;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.google.common.collect.Lists;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.*;

    import jakarta.validation.Valid;

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

    @RestController
    @RequestMapping("/adjustment/scheduler")
    public class AdjSchedulerController {

        @Autowired
        private ISchedulerService schedulerService;
        @Autowired
        private PropertyI18nRedisService propertyI18nRedisService;
        @Autowired
        private ObjectMapper objectMapper;
        @Autowired
        private SessionContext sessionContext;
        @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/11
         */
        @ApiId(1039)
        @PostMapping("{id}")
        public Map<String, String> save(String property, @PathVariable String id,
                                        @RequestBody @Valid SchedulerDTO schedulerDTO) {
            // 校验Category是否合法
            ArrayList<Integer> cagegoryList = Lists.newArrayList(AdjNotifyConfigTypeEnum.DRAFT_STATISTICS.getType(),
                    AdjNotifyConfigTypeEnum.APPROVING_DAILY_SUMMARY.getType(),
                    AdjNotifyConfigTypeEnum.JOURNAL_REPORT_MISSED.getType(),
                    AdjNotifyConfigTypeEnum.DRAFT_STATISTICS_EACH_TYPE.getType(),
                    AdjNotifyConfigTypeEnum.JOURNAL_VOIDED_REPORT_MISSED.getType());
            if (!cagegoryList.contains(schedulerDTO.getCategory())) {
                throw new BadRequestException(CommonErrorI18nConstant.MUST_IN_LIST,
                        i18nMessageUtils.getErrorParamMapNotNeedTranslate("category", cagegoryList),
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                        "The category must between in [1:draft statistics 2:approving daily summary 3:journal report missed 4:draft statistics each type 10:journal voided report missed]");
            }

            int propertyId = sessionContext.getPropertyId(property);
            int loginUserId = sessionContext.getLoginUserId();
            PropertyDTO propertyDTO = propertyI18nRedisService.get(propertyId);
            schedulerDTO.setPropertyId(propertyId);

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

            Integer category = schedulerDTO.getCategory();
            if (category.equals(AdjNotifyConfigTypeEnum.JOURNAL_REPORT_MISSED.getType())
                    || category.equals(AdjNotifyConfigTypeEnum.JOURNAL_VOIDED_REPORT_MISSED.getType())) {
                //检查 parameters json格式是否合法
                JobParameterUtils.checkParameters(objectMapper, schedulerDTO.getParameters(), i18nMessageUtils);

                //检测报告缺失的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 {
                schedulerDTO.setParameters("{}");
                //校验定时任务执行时间唯一
                schedulerService.checkCornRuleSole(propertyDTO.getId(), category, schedulerDTO.getScheduler(), id);
            }

            if (!id.equals("0")) {
                //校验调度任务是否存在
                SchedulerJob 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 adjustment 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(),
                            "adjustment SchedulerJob category cannot update, SchedulerJobId=" + oriSchedulerJob.getId());
                }
                //修改
                schedulerDTO.setId(id);
                return Map.of("id", schedulerService.update(propertyDTO, oriSchedulerJob, schedulerDTO, loginUserId));
            } else {
                //校验同一个category下最大可配置的数量
                if (category == AdjNotifyConfigTypeEnum.JOURNAL_REPORT_MISSED.getType()
                        || category.equals(AdjNotifyConfigTypeEnum.JOURNAL_VOIDED_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(1034)
        @DeleteMapping("{id}")
        public Map delete(@PathVariable String id, String property) {
            int propertyId = sessionContext.getPropertyId(property);
            PropertyDTO propertyDTO = propertyI18nRedisService.get(propertyId);
            //校验是否存在
            SchedulerJob oriSchedulerJob = schedulerService.checkExist(id);
            //校验归属
            checkBelong(oriSchedulerJob, propertyDTO.getId());
            //报告缺失的不允许删除
            if (oriSchedulerJob.getCategory() == AdjNotifyConfigTypeEnum.JOURNAL_REPORT_MISSED.getType()
                    || oriSchedulerJob.getCategory().equals(AdjNotifyConfigTypeEnum.JOURNAL_VOIDED_REPORT_MISSED.getType())) {
                throw new BadRequestException(CommonErrorI18nConstant.SCHEDULER_CANNOT_DELETE_DELETING,
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                        "adjustment SchedulerJob category cannot delete, SchedulerJobId=" + oriSchedulerJob.getId());
            }
            //删除任务
            schedulerService.delete(oriSchedulerJob, propertyDTO);
            return Collections.emptyMap();
        }

        /**
         * 查询调度任务
         *
         * @param category 调度任务类型
         * @param property 资产标识
         * @return java.util.List<cloud.wconnect.frontoffice.entity.adjustment.SchedulerJob>
         * @author lichen
         * @date 2024/3/12
         */
        @ApiId(1040)
        @GetMapping("{category:\\d+}")
        public List<SchedulerJob> 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/12
         */
        private void checkBelong(SchedulerJob 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));
            }
        }
    }