# RevenueSchedulerJobServiceImpl.java

    package cloud.wconnect.rateshop.service.revenue.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.revenue.RevenueSchedulerJob;
    import cloud.wconnect.rateshop.mapper.revenue.RevenueSchedulerJobMapper;
    import cloud.wconnect.rateshop.pojo.dto.revenue.RevenueSchedulerDTO;
    import cloud.wconnect.rateshop.service.revenue.IRevenueSchedulerJobService;
    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.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.*;
    import java.util.concurrent.Executor;

    /**
     * <p>
     * 服务实现类
     * </p>
     *
     * @author yyt
     * @since 2024-03-16
     */
    @Service
    @DS("rate_shop")
    public class RevenueSchedulerJobServiceImpl extends ServiceImpl<RevenueSchedulerJobMapper, RevenueSchedulerJob> implements IRevenueSchedulerJobService {

        @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;

        /**
         * 校验分类下最大可配置调度任务的数量
         *
         * @param propertyId 资产 id
         * @param category   分类
         * @param maxNum     最大数量
         * @author yyt
         * @date 2024/3/14
         **/
        @Override
        public void checkMaxNum(Integer propertyId, Integer category, Integer maxNum) {
            long count = count(new QueryWrapper<RevenueSchedulerJob>().lambda()
                    .eq(RevenueSchedulerJob::getPropertyId, propertyId)
                    .eq(RevenueSchedulerJob::getCategory, category)
                    .ne(RevenueSchedulerJob::getStatus, SchedulerCons.STATUS_DELETING));
            if (count >= maxNum) {
                throw new BadRequestException(CommonErrorI18nConstant.SCHEDULER_COUNT_TRANSFINITE,
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                        MessageFormat.format("The RevenueSchedulerJob maximum configuration:{0}, propertyId{1}, category:{2}",
                                maxNum, propertyId, 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, RevenueSchedulerDTO schedulerDTO, Integer userId) {
            Integer propertyId = propertyDTO.getId();
            RevenueSchedulerJob scheduler = beanMapper.map(schedulerDTO, RevenueSchedulerJob.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);
                        //指定数据源
                        appointDataSource();
                        //更新为已同步
                        updateSyncState(schedulerId, true);
                    } catch (Exception e) {
                        log.error("Launch revenue 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, RevenueSchedulerJob scheduler, PropertyDTO propertyDTO, String defaultTimezone) throws JsonProcessingException {
            JobBodyDTO task = new JobBodyDTO()
                    .setJobId(scheduler.getId()).setOriginJobId(originJobId)
                    .setModuleId(MoudleIdConstant.RATE_SHOP).setFunctionId(FunctionIdConstant.REVENUE)
                    .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 RevenueSchedulerJob().setId(scheduleId).setSyncState(syncState));
        }

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

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

        /**
         * 更新调度任务和生成新的 job id
         *
         * @param schedulerJob 调度任务
         * @author zc
         * @date 2024/5/27
         */
        private void updateAndGenerateNewJobId(RevenueSchedulerJob schedulerJob) {
            String newJobId = CommonUtils.randomUuidWithoutDashes();
            update(schedulerJob, new LambdaUpdateWrapper<RevenueSchedulerJob>()
                    .set(RevenueSchedulerJob::getId, newJobId)
                    .eq(RevenueSchedulerJob::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 2024/3/14
         */
        private void callInternalServiceDeleteJob(String schedulerId) {
            schedulerInternalService.deleteJob(new JobBodyDTO().setJobId(schedulerId)
                    .setModuleId(MoudleIdConstant.RATE_SHOP).setFunctionId(FunctionIdConstant.REVENUE));
        }

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

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

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

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

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

            JobParameterDTO jobParameterDTO = JsonUtils.convertStringToObject(objectMapper, parameters, JobParameterDTO.class);
            //解析日期表达式
            return JobParameterUtils.parseDateRange(jobParameterDTO.getDateRange(), jobParameterDTO.getDateRangeUnit(), propertyDTO.getTimezone(), null);
        }

        /**
         * 获取指定日期需要的日期区间
         *
         * @param propertyDTO 资产DTO
         * @param type        邮件配置类型
         * @param theDate     指定日期
         * @return 日期区间
         * @author yyt
         * @date 2024/5/25
         */
        @Override
        public Map<String, Long> getDateRange(PropertyDTO propertyDTO, int type, Long theDate) {
            RevenueSchedulerJob schedulerJob = getOne(new LambdaQueryWrapper<RevenueSchedulerJob>().eq(RevenueSchedulerJob::getPropertyId, propertyDTO.getId())
                    .eq(RevenueSchedulerJob::getCategory, type));

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

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

            JobParameterDTO jobParameterDTO = JsonUtils.convertStringToObject(objectMapper, parameters, JobParameterDTO.class);
            //解析日期表达式
            return JobParameterUtils.parseDateRange(theDate, jobParameterDTO.getDateRange(), jobParameterDTO.getDateRangeUnit(), propertyDTO.getTimezone(), null);
        }

        /**
         * 删除任务
         *
         * @param schedulerJob 调度任务
         * @author zc
         * @date 2024/4/24
         */
        @Override
        @Transactional(rollbackFor = Exception.class)
        public void delete(RevenueSchedulerJob schedulerJob) {
            // 更新为未同步 删除中
            schedulerJob.setSyncState(false).setStatus(SchedulerCons.STATUS_DELETING);
            updateById(schedulerJob);

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

        /**
         * 查询非删除中的定时任务
         *
         * @param propertyId 资产 id
         * @param category 分类 (1:History and Forecast,2:Business Block,3:Reservation Statistics,4:Reservation Forecast,
         *                 5:Reservation Forecast Next Month,6:History Forecast Next Month,7:History Forecast Last Year,
         *                 8: Reservations Forecast Next 14 days,9:History and Forecast Next 90 days,10:Market Code,
         *                 11:Occ jump alert，12：History and Forecast this month（future），13：History and Forecast next month（future），
         *                 14：History and Forecast the month after next，15：History and Forecast last year next 90 days，
         *                 16：Reservation Forecast next 90 days，17：History and Forecast Business Block next 90 days,
         *                 19：Manager flash,20：Detailed Availability 未来14天报告缺失,21：Rate Review 通知,
         *                 22: Group Pickup)
         * @return 定时任务
         * @author yyt
         * @date 2024/12/2
         **/
        @Override
        public List<RevenueSchedulerJob> list(Integer propertyId, int category) {
            return list(new QueryWrapper<RevenueSchedulerJob>().lambda()
                    .eq(RevenueSchedulerJob::getPropertyId, propertyId)
                    .eq(RevenueSchedulerJob::getCategory, category)
                    .ne(RevenueSchedulerJob::getStatus, SchedulerCons.STATUS_DELETING));
        }

    }