# OooRoomSchedulerJobServiceImpl.java

    package cloud.wconnect.frontoffice.service.oooroom.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.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.frontoffice.entity.oooroom.OooRoomSchedulerJob;
    import cloud.wconnect.frontoffice.mapper.oooroom.OooRoomSchedulerJobMapper;
    import cloud.wconnect.frontoffice.pojo.dto.oooroom.OooRoomSchedulerDTO;
    import cloud.wconnect.frontoffice.service.oooroom.IOooRoomSchedulerJobService;
    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.util.HashMap;
    import java.util.List;
    import java.util.Objects;
    import java.util.concurrent.Executor;

    /**
     * <p>
     * 服务实现类
     * </p>
     *
     * @author yyt
     * @since 2024-03-14
     */
    @Service
    @DS("ratelog_manage")
    public class OooRoomSchedulerJobServiceImpl extends ServiceImpl<OooRoomSchedulerJobMapper, OooRoomSchedulerJob> implements IOooRoomSchedulerJobService {

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

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

        private static final String RATELOG_MANAGE = "ratelog_manage";

        /**
         * 校验指定 category, 状态是未删除的记录是否存在
         *
         * @param propertyId 资产 id
         * @param category   分类
         * @author yyt
         * @date 2024/3/14
         **/
        @Override
        public void checkRepeat(Integer propertyId, Integer category) {
            OooRoomSchedulerJob scheduler = getOne(new QueryWrapper<OooRoomSchedulerJob>().lambda()
                    .eq(OooRoomSchedulerJob::getPropertyId, propertyId)
                    .eq(OooRoomSchedulerJob::getCategory, category)
                    .ne(OooRoomSchedulerJob::getStatus, SchedulerCons.STATUS_DELETING)
                    .last("limit 1"));
            if (Objects.nonNull(scheduler)) {
                throw new BadRequestException(CommonErrorI18nConstant.DATA_EXISTED,
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                        "ooo room scheduler job already exist, propertyId=" + propertyId + ",category=" + category);
            }
        }

        /**
         * 保存定时任务
         *
         * @param propertyDTO  资产
         * @param schedulerDTO 定时任务
         * @param userId       操作人
         * @return 定时任务 id
         * @author yyt
         * @date 2024/3/14
         **/
        @Override
        @Transactional(rollbackFor = Exception.class)
        public String save(PropertyDTO propertyDTO, OooRoomSchedulerDTO schedulerDTO, int userId) {
            Integer propertyId = propertyDTO.getId();
            OooRoomSchedulerJob scheduler = beanMapper.map(schedulerDTO, OooRoomSchedulerJob.class);
            scheduler.setPropertyId(propertyId).setRunTimes(0).setSyncState(schedulerDTO.getStatus() == BaseConstant.ZERO)
                    .setUpdateLog(updateLogUtil.get(userId));
            save(scheduler);
            String schedulerId = scheduler.getId();

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

            return schedulerId;
        }

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

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

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

        /**
         * 修改定时任务
         *
         * @param propertyDTO  资产
         * @param scheduler    定时任务
         * @param schedulerDTO 定时任务修改内容
         * @param userId       操作人
         * @return 定时任务 id
         * @author yyt
         * @date 2024/3/14
         **/
        @Override
        @Transactional(rollbackFor = Exception.class)
        public String update(PropertyDTO propertyDTO, OooRoomSchedulerJob scheduler, OooRoomSchedulerDTO schedulerDTO, int userId) {
            OooRoomSchedulerJob updateScheduler = beanMapper.map(schedulerDTO, OooRoomSchedulerJob.class);
            updateScheduler.setId(scheduler.getId());
            updateScheduler.setRunTimes(BaseConstant.ZERO);
            updateScheduler.setUpdateLog(updateLogUtil.append(scheduler.getUpdateLog(), userId));
            // 设为未同步
            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, propertyDTO, defaultTimezone);
                        //指定数据源
                        DynamicDataSourceContextHolder.push(RATELOG_MANAGE);
                        //更新为已同步
                        updateSyncState(newJobId, true);
                    } catch (Exception e) {
                        log.error("Launch ooo room scheduler job[" + newJobId + "] failed", e);
                    } finally {
                        DynamicDataSourceContextHolder.clear();
                    }
                } else {
                    try {
                        //调用内部接口删除任务
                        callInternalServiceDeleteJob(originJobId);
                        //指定数据源
                        DynamicDataSourceContextHolder.push(RATELOG_MANAGE);
                        //更新为已同步
                        updateSyncState(newJobId, true);
                    } catch (Exception e) {
                        log.error("Delete ooo room scheduler job[" + originJobId + "] failed", e);
                    } finally {
                        DynamicDataSourceContextHolder.clear();
                    }
                }
            });
            return newJobId;
        }

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

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

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

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

        /**
         * 删除定时任务
         *
         * @param propertyDTO 资产
         * @param scheduler   定时任务
         * @author yyt
         * @date 2024/3/14
         **/
        @Override
        @Transactional(rollbackFor = Exception.class)
        public void delete(PropertyDTO propertyDTO, OooRoomSchedulerJob scheduler) {
            String schedulerId = scheduler.getId();
            updateById(new OooRoomSchedulerJob().setId(schedulerId).setStatus(SchedulerCons.STATUS_DELETING)
                    .setSyncState(false));

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

        /**
         * 查询未删除的定时任务
         *
         * @param propertyId 资产 id
         * @param category   分类
         * @param id         排除自身
         * @return 定时任务
         * @author yyt
         * @date 2024/11/20
         **/
        @Override
        public List<OooRoomSchedulerJob> list(Integer propertyId, int category, String id) {
            return list(new QueryWrapper<OooRoomSchedulerJob>().lambda()
                    .eq(OooRoomSchedulerJob::getPropertyId, propertyId)
                    .eq(OooRoomSchedulerJob::getCategory, category)
                    .ne(OooRoomSchedulerJob::getStatus, SchedulerCons.STATUS_DELETING)
                    .ne(StringUtils.isNotEmpty(id) && !id.equals("0"), OooRoomSchedulerJob::getId, id));
        }

        /**
         * 检查分类下的定时任务是否超过限制数量
         *
         * @param propertyId 资产 id
         * @param category   分类
         * @param limitCount 限制数量
         * @author yyt
         * @date 2024/11/20
         **/
        @Override
        public void checkCount(Integer propertyId, Integer category, int limitCount) {
            long totalCount = count(new QueryWrapper<OooRoomSchedulerJob>().lambda()
                    .eq(OooRoomSchedulerJob::getPropertyId, propertyId)
                    .eq(OooRoomSchedulerJob::getCategory, category)
                    .ne(OooRoomSchedulerJob::getStatus, SchedulerCons.STATUS_DELETING));
            if (totalCount == limitCount) {
                throw new BadRequestException(CommonErrorI18nConstant.SCHEDULER_COUNT_TRANSFINITE,
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                        "Creating timing configuration rules exceeds number limit.");
            }
        }

    }