# BudgetDatabaseConfigSchedulerJobServiceImpl.java

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

    import cloud.wconnect.commonlib.component.BeanMapper;
    import cloud.wconnect.commonlib.cons.*;
    import cloud.wconnect.commonlib.exception.BadRequestException;
    import cloud.wconnect.commonlib.exception.ForbiddenException;
    import cloud.wconnect.commonlib.pojo.dto.scheduler.JobBodyDTO;
    import cloud.wconnect.commonlib.redis.PropertyI18nRedisService;
    import cloud.wconnect.commonlib.service.SchedulerInternalService;
    import cloud.wconnect.commonlib.util.CommonUtils;
    import cloud.wconnect.commonlib.util.CronRuleUtil;
    import cloud.wconnect.commonlib.util.TransactionUtils;
    import cloud.wconnect.commonlib.util.UpdateLogUtil;
    import cloud.wconnect.rateshop.entity.budgetdatabase.BudgetDatabaseConfigSchedulerJob;
    import cloud.wconnect.rateshop.mapper.budgetdatabase.BudgetDatabaseConfigSchedulerJobMapper;
    import cloud.wconnect.rateshop.pojo.dto.budgetdatabase.BudgetDatabaseSchedulerDTO;
    import cloud.wconnect.rateshop.service.budgetdatabase.IBudgetDatabaseConfigSchedulerJobService;
    import com.baomidou.dynamic.datasource.annotation.DS;
    import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
    import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
    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.HashMap;
    import java.util.List;
    import java.util.Objects;
    import java.util.concurrent.Executor;

    /**
     * <p>
     * 服务实现类
     * </p>
     *
     * @author yyt
     * @since 2025-08-13
     */
    @Service
    @DS("rate_shop")
    public class BudgetDatabaseConfigSchedulerJobServiceImpl extends ServiceImpl<BudgetDatabaseConfigSchedulerJobMapper, BudgetDatabaseConfigSchedulerJob> implements IBudgetDatabaseConfigSchedulerJobService {

        @Autowired
        private BeanMapper beanMapper;
        @Autowired
        private UpdateLogUtil updateLogUtil;
        @Autowired
        private Executor executor;
        @Autowired
        private ObjectMapper objectMapper;
        @Autowired
        private SchedulerInternalService schedulerInternalService;
        @Autowired
        private PropertyI18nRedisService propertyI18nRedisService;

        @Value("${default.timezone}")
        private String defaultTimezone;

        /**
         * 查询非删除中的定时任务
         *
         * @param propertyId 资产 id
         * @param category   分类 (1:到期通知)
         * @return 定时任务
         * @author yyt
         * @date 2025/8/16
         **/
        @Override
        public List<BudgetDatabaseConfigSchedulerJob> list(int propertyId, int category) {
            return list(new QueryWrapper<BudgetDatabaseConfigSchedulerJob>().lambda()
                    .eq(BudgetDatabaseConfigSchedulerJob::getPropertyId, propertyId)
                    .eq(BudgetDatabaseConfigSchedulerJob::getCategory, category)
                    .ne(BudgetDatabaseConfigSchedulerJob::getStatus, SchedulerCons.STATUS_DELETING));
        }

        /**
         * 校验分类下最大可配置调度任务的数量
         *
         * @param propertyId 资产 id
         * @param category   分类
         * @param maxNum     最大数量
         * @author yyt
         * @date 2025/8/16
         **/
        @Override
        public void checkMaxNum(Integer propertyId, Integer category, Integer maxNum) {
            long count = count(new QueryWrapper<BudgetDatabaseConfigSchedulerJob>().lambda()
                    .eq(BudgetDatabaseConfigSchedulerJob::getPropertyId, propertyId)
                    .eq(BudgetDatabaseConfigSchedulerJob::getCategory, category)
                    .ne(BudgetDatabaseConfigSchedulerJob::getStatus, SchedulerCons.STATUS_DELETING));
            if (count >= maxNum) {
                throw new BadRequestException(CommonErrorI18nConstant.SCHEDULER_COUNT_TRANSFINITE,
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                        MessageFormat.format("The BudgetDatabaseConfigSchedulerJob maximum configuration:{0}, propertyId{1}, category:{2}",
                                maxNum, propertyId, category));
            }
        }

        /**
         * 保存定时任务
         *
         * @param propertyId   资产 id
         * @param schedulerDTO 定时任务
         * @param loginUserId  登录用户idY
         * @return 定时任务 id
         * @author yyt
         * @date 2025/8/16
         **/
        @Override
        @Transactional(rollbackFor = Exception.class)
        public String save(Integer propertyId, BudgetDatabaseSchedulerDTO schedulerDTO, int loginUserId) {
            BudgetDatabaseConfigSchedulerJob scheduler = beanMapper.map(schedulerDTO, BudgetDatabaseConfigSchedulerJob.class);
            scheduler.setPropertyId(propertyId).setRunTimes(0).setSyncState(schedulerDTO.getStatus() == BaseConstant.ZERO)
                    .setUpdateLog(updateLogUtil.get(loginUserId));
            save(scheduler);
            String schedulerId = scheduler.getId();

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

            return schedulerId;
        }

        /**
         * 调用内部接口保存任务
         *
         * @param originJobId     原调度任务 id
         * @param scheduler       调度任务对象
         * @param propertyId      资产 id
         * @param defaultTimezone 默认时区
         * @author yyt
         * @date 2025/8/16
         */
        private void callInternalServiceLaunchJob(String originJobId, BudgetDatabaseConfigSchedulerJob scheduler, Integer propertyId, String defaultTimezone) throws JsonProcessingException {
            JobBodyDTO task = new JobBodyDTO()
                    .setJobId(scheduler.getId()).setOriginJobId(originJobId)
                    .setModuleId(MoudleIdConstant.RATE_SHOP).setFunctionId(FunctionIdConstant.BUDGET_DATABASE)
                    .setStartDate(scheduler.getStartDate())
                    .setCronRule(CronRuleUtil.generateCronRuleForScheduler(objectMapper.readValue(scheduler.getScheduler(), HashMap.class),
                            scheduler.getStartDate(), propertyI18nRedisService.get(propertyId).getTimezone(), defaultTimezone));
            schedulerInternalService.launchJob(task);
        }

        /**
         * 修改同步状态
         *
         * @param scheduleId 定时任务 id
         * @param syncState  同步状态
         * @author yyt
         * @date 2025/8/16
         **/
        @Override
        public void updateSyncState(String scheduleId, boolean syncState) {
            updateById(new BudgetDatabaseConfigSchedulerJob().setId(scheduleId).setSyncState(syncState));
        }

        /**
         * 检查存在
         *
         * @param id 定时任务 id
         * @return 定时任务
         * @author yyt
         * @date 2025/8/16
         **/
        @Override
        public BudgetDatabaseConfigSchedulerJob checkExist(String id) {
            BudgetDatabaseConfigSchedulerJob scheduler = getById(id);
            if (Objects.isNull(scheduler)) {
                throw new BadRequestException(CommonErrorI18nConstant.DATA_NOT_FOUND,
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(), "the schedulerJob is not found;id:" + id);
            }
            return scheduler;
        }

        /**
         * 修改定时任务
         *
         * @param propertyId   资产 id
         * @param scheduler    定时任务
         * @param schedulerDTO 定时任务修改内容
         * @param loginUserId  登录用户id
         * @return job id
         * @author yyt
         * @date 2025/8/16
         **/
        @Override
        @Transactional(rollbackFor = Exception.class)
        public String update(Integer propertyId, BudgetDatabaseConfigSchedulerJob scheduler, BudgetDatabaseSchedulerDTO schedulerDTO, int loginUserId) {
            BudgetDatabaseConfigSchedulerJob updateScheduler = beanMapper.map(schedulerDTO, BudgetDatabaseConfigSchedulerJob.class);
            updateScheduler.setId(scheduler.getId());
            updateScheduler.setRunTimes(BaseConstant.ZERO);
            updateScheduler.setUpdateLog(updateLogUtil.append(scheduler.getUpdateLog(), loginUserId));
            // 设为未同步
            updateScheduler.setSyncState(false);

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

            // 同步任务调度中心
            TransactionUtils.afterCommitAsyncExecute(executor, () -> {
                if (updateScheduler.getStatus() == SchedulerCons.STATUS_START) {
                    try {
                        //调用内部接口保存任务
                        callInternalServiceLaunchJob(originJobId, updateScheduler, propertyId, defaultTimezone);
                        //指定数据源
                        appointDataSource();
                        //更新为已同步
                        updateSyncState(newJobId, true);
                    } catch (Exception e) {
                        log.error("Launch budgetDatabase scheduler job[" + newJobId + "] failed", e);
                    } finally {
                        DynamicDataSourceContextHolder.clear();
                    }
                } else {
                    try {
                        //调用内部接口删除任务
                        callInternalServiceDeleteJob(originJobId);
                        //指定数据源
                        appointDataSource();
                        //更新为已同步
                        updateSyncState(newJobId, true);
                    } catch (Exception e) {
                        log.error("Delete budgetDatabase scheduler job[" + originJobId + "] failed", e);
                    } finally {
                        DynamicDataSourceContextHolder.clear();
                    }
                }
            });
            return newJobId;
        }

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

        /**
         * 指定数据源
         *
         * @author yyt
         * @date 2024/3/28
         **/
        private void appointDataSource() {
            DynamicDataSourceContextHolder.push("rate_shop");
        }

        /**
         * 执行内部接口更新（删除）任务
         *
         * @param schedulerId 定时任务 id
         * @author yyt
         * @date 2025/8/16
         */
        private void callInternalServiceDeleteJob(String schedulerId) {
            schedulerInternalService.deleteJob(new JobBodyDTO().setJobId(schedulerId)
                    .setModuleId(MoudleIdConstant.RATE_SHOP).setFunctionId(FunctionIdConstant.BUDGET_DATABASE));
        }

        /**
         * 校验数据归属
         *
         * @param scheduler  定时任务
         * @param propertyId 资产 id
         * @author yyt
         * @date 2025/8/16
         */
        @Override
        public void checkBelong(BudgetDatabaseConfigSchedulerJob scheduler, Integer propertyId) {
            if (!scheduler.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 budgetDatabaseConfigSchedulerJob;propertyId:" + propertyId + ",budgetDatabaseConfigSchedulerJobPropertyId:" +
                        scheduler.getPropertyId() + ",budgetDatabaseConfigSchedulerJobId:" + scheduler.getId());
            }
        }

        /**
         * 批量刷新同步状态为已同步
         *
         * @param updateJobIds 定时任务 id
         * @author yyt
         * @date 2025/8/16
         **/
        @Override
        public void refreshSyncStateByIds(List<String> updateJobIds) {
            update(new BudgetDatabaseConfigSchedulerJob().setSyncState(true), new QueryWrapper<BudgetDatabaseConfigSchedulerJob>()
                    .lambda().in(BudgetDatabaseConfigSchedulerJob::getId, updateJobIds));
        }

        /**
         * 调度任务执行次数递增
         *
         * @param jobId 定时任务 id
         * @author yyt
         * @date 2025/8/16
         */
        @Override
        public void plusRunTimes(String jobId) {
            baseMapper.plusRunTimes(jobId);
        }

    }