# PastReservationSchedulerJobServiceImpl.java

    package cloud.wconnect.frontoffice.service.pastreservation.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.CronRuleUtil;
    import cloud.wconnect.commonlib.util.TransactionUtils;
    import cloud.wconnect.commonlib.util.UpdateLogUtil;
    import cloud.wconnect.frontoffice.entity.pastreservation.PastReservationSchedulerJob;
    import cloud.wconnect.frontoffice.mapper.pastreservation.PastReservationSchedulerJobMapper;
    import cloud.wconnect.frontoffice.pojo.dto.pastreservation.PastReservationSchedulerDTO;
    import cloud.wconnect.frontoffice.service.pastreservation.IPastReservationSchedulerJobService;
    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.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-10-01
     */
    @Service
    @DS("logbook")
    public class PastReservationSchedulerJobServiceImpl extends ServiceImpl<PastReservationSchedulerJobMapper, PastReservationSchedulerJob> implements IPastReservationSchedulerJobService {

        @Autowired
        private BeanMapper beanMapper;
        @Autowired
        private UpdateLogUtil updateLogUtil;
        @Autowired
        private Executor executor;
        @Value("${default.timezone}")
        private String defaultTimezone;
        @Autowired
        private ObjectMapper objectMapper;
        @Autowired
        private SchedulerInternalService schedulerInternalService;

        private static final String DATASOURCE_LOGBOOK = "logbook";

        /**
         * 校验数量超过限制
         *
         * @param propertyId 资产 id
         * @param category   分类
         * @param limitCount 限制数量
         * @author yyt
         * @date 2024/10/2
         **/
        @Override
        public void checkCountLimit(Integer propertyId, Integer category, int limitCount) {
            long totalCount = count(new QueryWrapper<PastReservationSchedulerJob>().lambda()
                    .eq(PastReservationSchedulerJob::getPropertyId, propertyId)
                    .eq(PastReservationSchedulerJob::getCategory, category)
                    .ne(PastReservationSchedulerJob::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.");
            }
        }

        /**
         * 检查存在
         *
         * @param id 定时任务 id
         * @return 定时任务
         * @author yyt
         * @date 2024/10/2
         **/
        @Override
        public PastReservationSchedulerJob checkExist(String id) {
            PastReservationSchedulerJob 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 propertyDTO  资产
         * @param schedulerDTO 定时任务
         * @param userId       操作人
         * @return 定时任务 id
         * @author yyt
         * @date 2024/10/2
         **/
        @Override
        @Transactional(rollbackFor = Exception.class)
        public String save(PropertyDTO propertyDTO, PastReservationSchedulerDTO schedulerDTO, int userId) {
            Integer propertyId = propertyDTO.getId();
            PastReservationSchedulerJob scheduler = beanMapper.map(schedulerDTO, PastReservationSchedulerJob.class);
            scheduler.setPropertyId(propertyId).setRunTimes(BaseConstant.ZERO).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(DATASOURCE_LOGBOOK);
                        //更新为已同步
                        updateSyncState(schedulerId, true);
                    } catch (Exception e) {
                        log.error("Launch continuous stay monitor scheduler job[" + schedulerId + "] failed", e);
                    } finally {
                        DynamicDataSourceContextHolder.clear();
                    }
                });
            }

            return schedulerId;
        }

        /**
         * 修改定时任务
         *
         * @param propertyDTO  资产
         * @param scheduler    定时任务
         * @param schedulerDTO 定时任务修改内容
         * @param userId       操作人
         * @return job id
         * @author yyt
         * @date 2024/10/2
         **/
        @Override
        @Transactional(rollbackFor = Exception.class)
        public String update(PropertyDTO propertyDTO, PastReservationSchedulerJob scheduler, PastReservationSchedulerDTO schedulerDTO, int userId) {
            PastReservationSchedulerJob updateScheduler = beanMapper.map(schedulerDTO, PastReservationSchedulerJob.class);
            updateScheduler.setId(scheduler.getId());
            updateScheduler.setRunTimes(BaseConstant.ZERO);
            updateScheduler.setUpdateLog(updateLogUtil.append(scheduler.getUpdateLog(), userId));
            // 设为未同步
            updateScheduler.setSyncState(false);
            updateById(updateScheduler);

            String jobId = scheduler.getId();

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

        /**
         * 调用内部接口保存任务
         *
         * @param originJobId     原调度任务 id
         * @param scheduler       调度任务对象
         * @param propertyDTO     资产
         * @param defaultTimezone 默认时区
         * @author yyt
         * @date 2024/10/2
         */
        private void callInternalServiceLaunchJob(String originJobId, PastReservationSchedulerJob scheduler, PropertyDTO propertyDTO, String defaultTimezone) throws JsonProcessingException {
            JobBodyDTO task = new JobBodyDTO()
                    .setJobId(scheduler.getId()).setOriginJobId(originJobId)
                    .setModuleId(MoudleIdConstant.FRONT_OFFICE).setFunctionId(FunctionIdConstant.PAST_RESERVATION)
                    .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/10/2
         **/
        @Override
        public void updateSyncState(String scheduleId, boolean syncState) {
            updateById(new PastReservationSchedulerJob().setId(scheduleId).setSyncState(syncState));
        }

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

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

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

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

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

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

    }