# RateShopSchedulerServiceImpl.java

    package cloud.wconnect.rateshop.service.rateshop.impl;

    import cloud.wconnect.commonlib.component.BeanMapper;
    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.JobBodyDTO;
    import cloud.wconnect.commonlib.pojo.dto.scheduler.JobParameterDTO;
    import cloud.wconnect.commonlib.service.SchedulerInternalService;
    import cloud.wconnect.commonlib.util.*;
    import cloud.wconnect.rateshop.entity.rateshop.RateShopScheduler;
    import cloud.wconnect.rateshop.mapper.rateshop.RateShopSchedulerMapper;
    import cloud.wconnect.rateshop.pojo.dto.rateshop.emailconfig.RateShopSchedulerDTO;
    import cloud.wconnect.rateshop.service.rateshop.IRateShopSchedulerService;
    import com.baomidou.dynamic.datasource.annotation.DS;
    import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
    import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
    import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
    import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
    import com.fasterxml.jackson.core.JsonProcessingException;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import org.apache.commons.lang3.StringUtils;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;

    import java.text.MessageFormat;
    import java.util.*;
    import java.util.concurrent.Executor;

    /**
     * <p>
     * 服务实现类
     * </p>
     *
     * @author lichen
     * @since 2024-03-15
     */
    @Service
    @DS("rate_shop")
    public class RateShopSchedulerServiceImpl extends ServiceImpl<RateShopSchedulerMapper, RateShopScheduler> implements IRateShopSchedulerService {

        @Autowired
        private BeanMapper beanMapper;
        @Autowired
        private Executor executor;
        @Autowired
        private ObjectMapper objectMapper;
        @Autowired
        private SchedulerInternalService schedulerInternalService;
        @Value("${default.timezone}")
        private String defaultTimezone;
        @Autowired
        private UpdateLogUtil updateLogUtil;
        private final static Integer MODULE_ID = MoudleIdConstant.RATE_SHOP; // rate shop module id
        private final static Integer FUNCTION_ID = FunctionIdConstant.RATE_SHOP; // Rate Shop feature id

        /**
         * 刷新调度任务同步状态为已同步
         *
         * @param ids 调度任务ID集合
         * @return void
         * @author lichen
         * @date 2024/3/15
         */
        @Override
        public void refreshSyncStateByIds(List<String> ids) {
            baseMapper.refreshSyncStateByIds(ids);
        }

        /**
         * 获取日期区间
         *
         * @param propertyDTO 资产DTO
         * @param type        邮件配置类型
         * @return java.util.Map<java.lang.String, java.lang.Long>
         * @author lichen
         * @date 2024/3/15
         */
        @Override
        public Map<String, Long> getDateRange(PropertyDTO propertyDTO, int type) {
            RateShopScheduler schedulerJob = getOne(new LambdaQueryWrapper<RateShopScheduler>()
                    .eq(RateShopScheduler::getPropertyId, propertyDTO.getId())
                    .eq(RateShopScheduler::getCategory, type));

            if (Objects.isNull(schedulerJob)) return Collections.emptyMap();

            String parameters = schedulerJob.getParameters();
            if (StringUtils.isBlank(parameters) || parameters.equals("{}")) return Collections.emptyMap();

            //type等于2（history and forecast报告缺失），schedulerJob不为空
            JobParameterDTO jobParameterDTO = JsonUtils.convertStringToObject(objectMapper, parameters, JobParameterDTO.class);

            //解析日期表达式
            return JobParameterUtils.parseDateRange(jobParameterDTO.getDateRange(), jobParameterDTO.getDateRangeUnit(), propertyDTO.getTimezone(), null);
        }

        /**
         * 校验调度任务是否存在
         *
         * @param id 主键ID
         * @return cloud.wconnect.rateshop.entity.rateshop.RateShopScheduler
         * @author lichen
         * @date 2024/3/15
         */
        @Override
        public RateShopScheduler checkExist(String id) {
            RateShopScheduler schedulerJob = getById(id);
            if (Objects.isNull(schedulerJob)) {
                throw new BadRequestException(CommonErrorI18nConstant.DATA_NOT_FOUND,
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(), "rate shop SchedulerJob not found, id = " + id);
            }
            return schedulerJob;
        }

        /**
         * 修改调度任务
         *
         * @param propertyDTO     资产DTO
         * @param oriSchedulerJob 修改前的调度任务
         * @param schedulerDTO    修改后的调度任务DTO
         * @param loginUserId     登录用户id
         * @return job id
         * @author lichen
         * @date 2024/3/15
         */
        @Override
        @Transactional(rollbackFor = Exception.class)
        public String update(PropertyDTO propertyDTO, RateShopScheduler oriSchedulerJob, RateShopSchedulerDTO schedulerDTO, int loginUserId) {
            //修改调度任务
            RateShopScheduler schedulerJob = beanMapper.map(schedulerDTO, RateShopScheduler.class);
            schedulerJob.setRunTimes(0);
            schedulerJob.setUpdateLog(updateLogUtil.append(oriSchedulerJob.getUpdateLog(), loginUserId));
            //设为未同步
            schedulerJob.setSyncState(false);

            String originJobId = oriSchedulerJob.getId();
            // 更新调度任务的 job id
            updateAndGenerateNewJobId(schedulerJob);
            String newJobId = schedulerJob.getId();

            //若和定时任务触发条件相关的值发生了变化，则更新步骤
            // 同步任务调度中心
            TransactionUtils.afterCommitAsyncExecute(executor, () -> {
                if (schedulerJob.getStatus() == SchedulerCons.STATUS_START) {
                    try {
                        //调用内部接口保存任务
                        callInternalServiceLaunchJob(originJobId, schedulerJob, propertyDTO, defaultTimezone);
                        //指定数据源
                        pushDynamicDataSource();
                        //更新为已同步
                        updateSyncState(newJobId, true);
                    } catch (Exception e) {
                        log.error("Launch rate shop scheduler job[" + newJobId + "] failed", e);
                    } finally {
                        DynamicDataSourceContextHolder.clear();
                    }
                } else {
                    try {
                        //调用内部接口删除任务
                        callInternalServiceDeleteJob(originJobId);
                        //指定数据源
                        pushDynamicDataSource();
                        //更新为已同步
                        updateSyncState(newJobId, true);
                    } catch (Exception e) {
                        log.error("Delete rate shop scheduler job[" + originJobId + "] failed", e);
                    } finally {
                        DynamicDataSourceContextHolder.clear();
                    }
                }
            });
            return newJobId;
        }

        /**
         * 更新调度任务和生成新的 job id
         *
         * @param schedulerJob 调度任务
         * @author zc
         * @date 2024/5/27
         */
        private void updateAndGenerateNewJobId(RateShopScheduler schedulerJob) {
            String newJobId = CommonUtils.randomUuidWithoutDashes();
            update(schedulerJob, new LambdaUpdateWrapper<RateShopScheduler>()
                    .set(RateShopScheduler::getId, newJobId)
                    .eq(RateShopScheduler::getId, schedulerJob.getId()));
            schedulerJob.setId(newJobId);
        }

        /**
         * 删除任务
         *
         * @param schedulerJob 调度任务
         * @param propertyDTO  资产DTO
         * @return void
         * @author liche
         * @date 2024/3/15
         */
        @Override
        @Transactional(rollbackFor = Exception.class)
        public void delete(RateShopScheduler schedulerJob, PropertyDTO propertyDTO) {
            //更新为未同步 删除中
            schedulerJob.setSyncState(false).setStatus(SchedulerCons.STATUS_DELETING);
            updateById(schedulerJob);

            // 同步任务调度中心
            TransactionUtils.afterCommitAsyncExecute(executor, () -> {
                try {
                    //调用内部接口删除任务
                    callInternalServiceDeleteJob(schedulerJob.getId());
                    //指定数据源
                    pushDynamicDataSource();
                    //删除记录
                    removeById(schedulerJob.getId());
                } catch (Exception e) {
                    log.error("Delete rate shop scheduler job[" + schedulerJob.getId() + "] failed", e);
                } finally {
                    DynamicDataSourceContextHolder.clear();
                }
            });
        }

        /**
         * 调度任务执行次数递增
         *
         * @param jobId 主键ID
         * @return void
         * @author lichen
         * @date 2024/3/15
         */
        @Override
        public void plusRunTimes(String jobId) {
            //执行次数递增
            baseMapper.plusRunTimes(jobId);
        }

        /**
         * 更新同步状态
         *
         * @param id        主键ID
         * @param syncState 同步状态
         * @return void
         * @author lichen
         * @date 2024/3/15
         */
        @Override
        public void updateSyncState(String id, boolean syncState) {
            updateById(new RateShopScheduler().setId(id).setSyncState(syncState));
        }

        /**
         * 校验分类下最大可配置调度任务的数量
         *
         * @param propertyId 资产Id
         * @param category   分类
         * @param maxNum     最大数量
         * @return void
         * @author lichen
         * @date 2024/3/15
         */
        @Override
        public void checkMaxNum(Integer propertyId, Integer category, int maxNum) {
            long count = count(new LambdaQueryWrapper<RateShopScheduler>().eq(RateShopScheduler::getPropertyId, propertyId)
                    .eq(RateShopScheduler::getCategory, category)
                    .ne(RateShopScheduler::getStatus, SchedulerCons.STATUS_DELETING));
            if (count >= maxNum) {
                throw new BadRequestException(CommonErrorI18nConstant.SCHEDULER_COUNT_TRANSFINITE,
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                        MessageFormat.format("rate shop SchedulerJob maximum configuration:{0}, propertyId{1}, categroy:{2}",
                                maxNum, propertyId, category));
            }
        }

        /**
         * 根据分类获取调度任务列表
         *
         * @param propertyId 资产Id
         * @param category   分类
         * @return java.util.List<cloud.wconnect.rateshop.entity.rateshop.RateShopScheduler>
         * @author lichen
         * @date 2025/12/30
         */
        @Override
        public List<RateShopScheduler> listByCategory(int propertyId, Integer category) {
            return list(new LambdaQueryWrapper<RateShopScheduler>()
                    .eq(RateShopScheduler::getPropertyId, propertyId)
                    .eq(RateShopScheduler::getCategory, category)
                    .ne(RateShopScheduler::getStatus, SchedulerCons.STATUS_DELETING));
        }

        /**
         * 创建调度任务
         *
         * @param schedulerDTO 调度任务DTO
         * @param propertyDTO  资产DTO
         * @param loginUserId  登录用户id
         * @return job id
         * @author lichen
         * @date 2024/3/15
         */
        @Override
        @Transactional(rollbackFor = Exception.class)
        public String createScheduler(RateShopSchedulerDTO schedulerDTO, PropertyDTO propertyDTO, int loginUserId) {
            RateShopScheduler schedulerJob = beanMapper.map(schedulerDTO, RateShopScheduler.class);
            schedulerJob.setRunTimes(0);

            // 如果新任务的status为0-停止，则只创建DB记录，不创建定时任务job（DB记录的sync_state设为1）
            if (schedulerJob.getStatus() == SchedulerCons.STATUS_STOP) {
                schedulerJob.setSyncState(true);
            } else {
                schedulerJob.setSyncState(false);
            }
            schedulerJob.setUpdateLog(updateLogUtil.get(loginUserId));
            save(schedulerJob);

            //同步定时任务
            if (!schedulerJob.getSyncState()) {
                TransactionUtils.afterCommitAsyncExecute(executor, () -> {
                    // 同步任务调度中心
                    try {
                        //调用内部接口保存任务
                        callInternalServiceLaunchJob(StringUtils.EMPTY, schedulerJob, propertyDTO, defaultTimezone);
                        //指定数据源
                        pushDynamicDataSource();
                        //更新为已同步
                        updateSyncState(schedulerJob.getId(), true);
                    } catch (Exception e) {
                        log.error("Launch rate shop scheduler job[" + schedulerJob.getId() + "] failed", e);
                    } finally {
                        DynamicDataSourceContextHolder.clear();
                    }
                });
            }

            return schedulerJob.getId();
        }

        /**
         * 调用内部接口删除任务
         *
         * @param jobId 任务ID
         * @return void
         * @author lichen
         * @date 2024/3/15
         */
        private void callInternalServiceDeleteJob(String jobId) {
            schedulerInternalService.deleteJob(new JobBodyDTO().setJobId(jobId)
                    .setModuleId(MODULE_ID).setFunctionId(FUNCTION_ID));
        }

        /**
         * 调用内部接口保存任务
         *
         * @param originJobId     原调度任务 id
         * @param schedulerJob    调度任务对象
         * @param propertyDTO     资产DTO
         * @param defaultTimezone 默认时区
         * @return void
         * @author lichen
         * @date 2024/3/15
         */
        private void callInternalServiceLaunchJob(String originJobId, RateShopScheduler schedulerJob, PropertyDTO propertyDTO, String defaultTimezone) throws JsonProcessingException {
            JobBodyDTO task = new JobBodyDTO()
                    .setJobId(schedulerJob.getId()).setOriginJobId(originJobId)
                    .setModuleId(MODULE_ID).setFunctionId(FUNCTION_ID)
                    .setStartDate(schedulerJob.getStartDate())
                    .setCronRule(CronRuleUtil.generateCronRuleForScheduler(objectMapper.readValue(schedulerJob.getScheduler(), HashMap.class),
                            schedulerJob.getStartDate(), propertyDTO.getTimezone(), defaultTimezone));
            schedulerInternalService.launchJob(task);
        }

        /**
         * 设置数据源
         *
         * @return void
         * @author lichen
         * @date 2024/3/15
         */
        private void pushDynamicDataSource() {
            DynamicDataSourceContextHolder.push("rate_shop");
        }

    }