# ScheduleSchedulerJobServiceImpl.java

    package cloud.wconnect.workperformance.service.schedule.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.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.workperformance.entity.schedule.ScheduleSchedulerJob;
    import cloud.wconnect.workperformance.mapper.schedule.ScheduleSchedulerJobMapper;
    import cloud.wconnect.workperformance.pojo.dto.schedule.ScheduleSchedulerDTO;
    import cloud.wconnect.workperformance.service.schedule.IScheduleSchedulerJobService;
    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-15
     */
    @Service
    @DS("work_performance")
    public class ScheduleSchedulerJobServiceImpl extends ServiceImpl<ScheduleSchedulerJobMapper, ScheduleSchedulerJob> implements IScheduleSchedulerJobService {

        @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;
        @Autowired
        private PropertyI18nRedisService propertyI18nRedisService;

        private static final String WORK_PERFORMANCE = "work_performance";

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

        /**
         * 保存定时任务
         *
         * @param propertyId   资产 id
         * @param schedulerDTO 定时任务
         * @param loginUserId  登录用户id
         * @return 定时任务 id
         * @author yyt
         * @date 2024/3/15
         **/
        @Override
        @Transactional(rollbackFor = Exception.class)
        public String save(Integer propertyId, ScheduleSchedulerDTO schedulerDTO, int loginUserId) {
            ScheduleSchedulerJob scheduler = beanMapper.map(schedulerDTO, ScheduleSchedulerJob.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, propertyI18nRedisService.get(propertyId), defaultTimezone);
                        //指定数据源
                        DynamicDataSourceContextHolder.push(WORK_PERFORMANCE);
                        //更新为已同步
                        updateSyncState(schedulerId, true);
                    } catch (Exception e) {
                        log.error("Launch schedule scheduler job[" + schedulerId + "] failed", e);
                    } finally {
                        DynamicDataSourceContextHolder.clear();
                    }
                });
            }

            return schedulerId;
        }

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

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

        /**
         * 修改定时任务
         *
         * @param propertyId   资产 id
         * @param scheduler    定时任务
         * @param schedulerDTO 定时任务修改内容
         * @param loginUserId  登录用户id
         * @return job id
         * @author yyt
         * @date 2024/3/15
         **/
        @Override
        @Transactional(rollbackFor = Exception.class)
        public String update(Integer propertyId, ScheduleSchedulerJob scheduler, ScheduleSchedulerDTO schedulerDTO, int loginUserId) {
            ScheduleSchedulerJob updateScheduler = beanMapper.map(schedulerDTO, ScheduleSchedulerJob.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, propertyI18nRedisService.get(propertyId), defaultTimezone);
                        //指定数据源
                        DynamicDataSourceContextHolder.push(WORK_PERFORMANCE);
                        //更新为已同步
                        updateSyncState(newJobId, true);
                    } catch (Exception e) {
                        log.error("Launch schedule scheduler job[" + newJobId + "] failed", e);
                    } finally {
                        DynamicDataSourceContextHolder.clear();
                    }
                } else {
                    try {
                        //调用内部接口删除任务
                        callInternalServiceDeleteJob(originJobId);
                        //指定数据源
                        DynamicDataSourceContextHolder.push(WORK_PERFORMANCE);
                        //更新为已同步
                        updateSyncState(newJobId, true);
                    } catch (Exception e) {
                        log.error("Delete schedule scheduler job[" + originJobId + "] failed", e);
                    } finally {
                        DynamicDataSourceContextHolder.clear();
                    }
                }
            });
            return newJobId;
        }

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

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

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

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

        /**
         * 查询未删除的定时任务
         *
         * @param propertyId 资产 id
         * @param category   类型（1：employee 报告缺失，3：history and forecast 报告缺失）
         * @return 定时任务
         * @author yyt
         * @date 2024/11/22
         **/
        @Override
        public List<ScheduleSchedulerJob> list(Integer propertyId, int category) {
            return list(new QueryWrapper<ScheduleSchedulerJob>().lambda()
                    .eq(ScheduleSchedulerJob::getPropertyId, propertyId)
                    .eq(ScheduleSchedulerJob::getCategory, category)
                    .ne(ScheduleSchedulerJob::getStatus, SchedulerCons.STATUS_DELETING));
        }

        /**
         * 查询未删除的定时任务
         *
         * @param propertyId 资产 id
         * @param category   类型（1：employee 报告缺失，3：history and forecast 报告缺失）
         * @return 定时任务
         * @author yyt
         * @date 2025/12/31
         **/
        @Override
        public List<ScheduleSchedulerDTO> listDTO(Integer propertyId, int category) {
            // 查询非删除中的定时任务
            List<ScheduleSchedulerJob> schedulers = list(propertyId, category);
            return beanMapper.mapList(schedulers, ScheduleSchedulerDTO.class);
        }

    }