# FdProcedureCheckSchedulerServiceImpl.java

    package cloud.wconnect.workperformance.service.fdprocedurecheck.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.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.workperformance.entity.fdprocedurecheck.FdProcedureCheckScheduler;
    import cloud.wconnect.workperformance.mapper.fdprocedurecheck.FdProcedureCheckSchedulerMapper;
    import cloud.wconnect.workperformance.pojo.dto.fdprocedurecheck.scheduler.FdSchedulerDTO;
    import cloud.wconnect.workperformance.service.fdprocedurecheck.IFdProcedureCheckSchedulerService;
    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.update.LambdaUpdateWrapper;
    import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
    import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
    import com.fasterxml.jackson.core.JsonProcessingException;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import jakarta.annotation.Resource;
    import org.apache.commons.collections.CollectionUtils;
    import org.apache.commons.lang3.StringUtils;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.lang.Nullable;
    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>
     * fd procedure check 功能的调度数据 服务实现类
     * </p>
     *
     * @author zc
     * @since 2024-03-15
     */
    @Service
    @DS("work_performance")
    public class FdProcedureCheckSchedulerServiceImpl extends ServiceImpl<FdProcedureCheckSchedulerMapper, FdProcedureCheckScheduler> implements IFdProcedureCheckSchedulerService {
        @Resource
        private SchedulerInternalService schedulerInternalService;
        @Resource
        private UpdateLogUtil updateLogUtil;
        @Resource
        private BeanMapper beanMapper;
        @Resource
        private Executor executor;
        @Resource
        private ObjectMapper objectMapper;
        @Value("${default.timezone}")
        private String defaultTimezone;

        private final static Integer MODULE_ID = MoudleIdConstant.WORK_PERFORMANCE;
        private final static Integer FUNCTION_ID = FunctionIdConstant.FD_PROCEDURE_CHECK;

        /**
         * 查询调度任务的配置
         *
         * @param propertyId 资产ID
         * @param category   分类
         * @return 调度任务
         * @author zc
         * @date 2024/3/15
         */
        @Override
        public List<FdProcedureCheckScheduler> list(int propertyId, int category) {
            return list(new LambdaQueryWrapper<FdProcedureCheckScheduler>()
                    .eq(FdProcedureCheckScheduler::getPropertyId, propertyId)
                    .ne(FdProcedureCheckScheduler::getStatus, SchedulerCons.STATUS_DELETING)
                    .eq(FdProcedureCheckScheduler::getCategory, category));
        }

        /**
         * 校验是否存在
         *
         * @param id 调度任务 id
         * @return FdProcedureCheckScheduler
         * @author zc
         * @date 2024/3/15
         */
        @Override
        public FdProcedureCheckScheduler checkExist(String id) {
            FdProcedureCheckScheduler scheduler = getById(id);
            if (Objects.isNull(scheduler)) {
                throw new BadRequestException(CommonErrorI18nConstant.DATA_NOT_FOUND,
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                        "The FdProcedureCheckScheduler is not found, id = " + id);
            }
            return scheduler;
        }

        /**
         * 校验归属
         *
         * @param propertyId 资产 id
         * @param scheduler  调度任务
         * @author zc
         * @date 2024/3/15
         */
        @Override
        public void checkBelong(int propertyId, FdProcedureCheckScheduler scheduler) {
            if (!scheduler.getPropertyId().equals(propertyId)) {
                throw new ForbiddenException(BaseErrorCodeEnum.DATA_FORBIDDEN.getI18nCode(),
                        BaseErrorCodeEnum.DATA_FORBIDDEN.getCode(),
                        MessageFormat.format("The FdProcedureCheckScheduler not belong current property," +
                                        "schedulerId:{0},schedulerBelongPropertyId:{1},currentPropertyId:{2}",
                                scheduler.getId(), scheduler.getPropertyId(), propertyId));
            }
        }

        /**
         * 创建调度任务
         *
         * @param schedulerDTO 调度任务DTO
         * @param propertyDTO  资产DTO
         * @param operatorId   操作人 id
         * @return 调度任务id
         * @author zc
         * @date 2024/3/15
         */
        @Override
        @Transactional(rollbackFor = Exception.class)
        public String save(FdSchedulerDTO schedulerDTO, PropertyDTO propertyDTO, int operatorId) {
            FdProcedureCheckScheduler scheduler = beanMapper.map(schedulerDTO, FdProcedureCheckScheduler.class, item -> {
                item.setRunTimes(BaseConstant.ZERO);
                item.setSyncState(schedulerDTO.getStatus() == SchedulerCons.STATUS_STOP);
                item.setUpdateLog(updateLogUtil.get(operatorId));
            });
            // 保存调度任务
            save(scheduler);
            String jobId = scheduler.getId();

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

        /**
         * 更新同步状态
         *
         * @param id        主键ID
         * @param syncState 同步状态
         * @author zc
         * @date 2024/3/15
         */
        @Override
        public void updateSyncState(String id, boolean syncState) {
            updateById(new FdProcedureCheckScheduler().setId(id).setSyncState(syncState));
        }

        /**
         * 修改调度任务
         *
         * @param propertyDTO     资产DTO
         * @param originScheduler 修改前的调度任务
         * @param schedulerDTO    修改后的调度任务DTO
         * @param operatorId      操作人 id
         * @return job id
         * @author zc
         * @date 2024/3/15
         */
        @Override
        @Transactional(rollbackFor = Exception.class)
        public String update(PropertyDTO propertyDTO, FdProcedureCheckScheduler originScheduler,
                             FdSchedulerDTO schedulerDTO, int operatorId) {
            FdProcedureCheckScheduler scheduler = beanMapper.map(schedulerDTO, FdProcedureCheckScheduler.class, item -> {
                item.setRunTimes(BaseConstant.ZERO);
                item.setSyncState(Boolean.FALSE);
                item.setUpdateLog(updateLogUtil.append(originScheduler.getUpdateLog(), operatorId));
            });

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

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

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

        /**
         * 校验分类下最大可配置调度任务的数量
         *
         * @param propertyId 资产Id
         * @param category   分类
         * @param maxNum     最大数量
         * @author zc
         * @date 2024/3/15
         */
        @Override
        public void checkMaxNum(int propertyId, int category, int maxNum) {
            long count = count(new LambdaQueryWrapper<FdProcedureCheckScheduler>()
                    .eq(FdProcedureCheckScheduler::getPropertyId, propertyId)
                    .eq(FdProcedureCheckScheduler::getCategory, category)
                    .ne(FdProcedureCheckScheduler::getStatus, SchedulerCons.STATUS_DELETING));
            if (count >= maxNum) {
                throw new BadRequestException(CommonErrorI18nConstant.DATA_EXISTED,
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                        MessageFormat.format("The FdProcedureCheckSchedulerJob maximum configuration:{0}, propertyId{1}, category:{2}",
                                maxNum, propertyId, category));
            }
        }

        /**
         * 刷新调度任务同步状态为已同步
         *
         * @param ids 调度任务ID集合
         * @author zc
         * @date 2024/3/15
         */
        @Override
        public void refreshSyncStateByIds(List<String> ids) {
            update(new UpdateWrapper<FdProcedureCheckScheduler>().lambda()
                    .in(FdProcedureCheckScheduler::getId, ids)
                    .set(FdProcedureCheckScheduler::getSyncState, Boolean.TRUE));
        }

        /**
         * 调度任务执行次数递增
         *
         * @param jobId 主键ID
         * @author zc
         * @date 2024/3/15
         */
        @Override
        public void plusRunTimes(String jobId) {
            baseMapper.plusRunTimes(jobId);
        }

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

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

        /**
         * 校验 scheduler 参数不能与同 category 的相同
         *
         * @param schedulerDTO 调度任务DTO
         * @param ignoreId     忽略的调度任务 id
         * @author zc
         * @date 2024/3/19
         */
        @Override
        public void checkSchedulerRepeat(FdSchedulerDTO schedulerDTO, @Nullable String ignoreId) {
            List<FdProcedureCheckScheduler> schedulerList = list(new LambdaQueryWrapper<FdProcedureCheckScheduler>()
                    .eq(FdProcedureCheckScheduler::getPropertyId, schedulerDTO.getPropertyId())
                    .eq(FdProcedureCheckScheduler::getCategory, schedulerDTO.getCategory())
                    .ne(FdProcedureCheckScheduler::getStatus, SchedulerCons.STATUS_DELETING)
                    .ne(StringUtils.isNotBlank(ignoreId), FdProcedureCheckScheduler::getId, ignoreId));
            if (CollectionUtils.isEmpty(schedulerList)) {
                return;
            }
            // 判断 scheduler 参数是否重复
            CronRuleUtil.checkSchedulerRepeat(objectMapper, schedulerList.stream().map(FdProcedureCheckScheduler::getScheduler).toList(),
                    schedulerDTO.getScheduler());
        }

        /**
         * 调用内部接口删除任务
         *
         * @param jobId 任务ID
         * @author zc
         * @date 2024/3/15
         */
        private void callInternalServiceDeleteJob(String jobId) {
            schedulerInternalService.deleteJob(new JobBodyDTO().setJobId(jobId)
                    .setModuleId(MODULE_ID).setFunctionId(FUNCTION_ID));
        }

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

        /**
         * 设置数据源
         *
         * @author zc
         * @date 2024/3/16
         */
        private void pushDynamicDataSource() {
            DynamicDataSourceContextHolder.push("work_performance");
        }
    }