# PastReservationJobChecker.java

    package cloud.wconnect.frontoffice.scheduler.pastreservation;

    import cloud.wconnect.commonlib.cons.FunctionIdConstant;
    import cloud.wconnect.commonlib.cons.MoudleIdConstant;
    import cloud.wconnect.commonlib.cons.SchedulerCons;
    import cloud.wconnect.commonlib.pojo.dto.PropertyDTO;
    import cloud.wconnect.commonlib.pojo.dto.scheduler.JobBodyDTO;
    import cloud.wconnect.commonlib.service.PropertyInternalService;
    import cloud.wconnect.commonlib.service.SchedulerInternalService;
    import cloud.wconnect.commonlib.util.CronRuleUtil;
    import cloud.wconnect.frontoffice.entity.pastreservation.PastReservationSchedulerJob;
    import cloud.wconnect.frontoffice.service.pastreservation.IPastReservationSchedulerJobService;
    import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.scheduling.annotation.Scheduled;
    import org.springframework.stereotype.Component;

    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import java.util.stream.Collectors;

    /**
     * @author: yyt
     * 2024-10-4
     */
    @Slf4j
    @Component
    public class PastReservationJobChecker {

        private final IPastReservationSchedulerJobService pastReservationSchedulerJobService;
        private final SchedulerInternalService schedulerInternalService;
        private final PropertyInternalService propertyInternalService;
        private final ObjectMapper objectMapper;
        private final String defaultTimezone;

        public PastReservationJobChecker(IPastReservationSchedulerJobService pastReservationSchedulerJobService, SchedulerInternalService schedulerInternalService,
                                         PropertyInternalService propertyInternalService, ObjectMapper objectMapper, @Value("${default.timezone}") String defaultTimezone){
            this.pastReservationSchedulerJobService = pastReservationSchedulerJobService;
            this.schedulerInternalService = schedulerInternalService;
            this.propertyInternalService = propertyInternalService;
            this.objectMapper = objectMapper;
            this.defaultTimezone = defaultTimezone;
        }

        /**
         * 每小时检查一次未同步的数据，将未同步的数据同步到调度中心
         *
         * @author yyt
         * @date 2024/10/4
         **/
        @Scheduled(cron = "${schedule.cron.sync-scheduler-job}", zone = "${default.timezone}")
        public void checkSchedulerJob() {
            //查询未同步的定时任务
            List<PastReservationSchedulerJob> unSyncJobs = pastReservationSchedulerJobService.list(new LambdaQueryWrapper<PastReservationSchedulerJob>()
                    .eq(PastReservationSchedulerJob::getSyncState, false));
            if (unSyncJobs.isEmpty()) {
                return;
            }

            List<Integer> propertyIds = unSyncJobs.stream().map(PastReservationSchedulerJob::getPropertyId).distinct().toList();
            Map<Integer, String> propertyIdToTimezoneMapping = propertyInternalService.getProperty(propertyIds)
                    .stream().collect(Collectors.toMap(PropertyDTO::getId, PropertyDTO::getTimezone));

            List<String> updateJobIds = new ArrayList<>();
            List<String> deleteJobIds = new ArrayList<>();
            unSyncJobs.forEach(job -> {
                if (job.getStatus() == SchedulerCons.STATUS_START) {//开启
                    try {
                        JobBodyDTO task = new JobBodyDTO()
                                .setJobId(job.getId()).setModuleId(MoudleIdConstant.FRONT_OFFICE).setFunctionId(FunctionIdConstant.PAST_RESERVATION)
                                .setStartDate(job.getStartDate())
                                .setCronRule(CronRuleUtil.generateCronRuleForScheduler(objectMapper.readValue(job.getScheduler(), HashMap.class),
                                        job.getStartDate(), propertyIdToTimezoneMapping.get(job.getPropertyId()), defaultTimezone));
                        schedulerInternalService.launchJob(task);
                        updateJobIds.add(job.getId());
                    } catch (Exception e) {
                        log.error("Launch past reservation scheduler job[" + job.getId() + "] failed", e);
                    }
                } else {//关闭 or 删除中
                    try {
                        schedulerInternalService.deleteJob(new JobBodyDTO().setJobId(job.getId())
                                .setModuleId(MoudleIdConstant.FRONT_OFFICE).setFunctionId(FunctionIdConstant.PAST_RESERVATION));
                        if (job.getStatus() == SchedulerCons.STATUS_STOP) {
                            updateJobIds.add(job.getId());
                        } else {
                            deleteJobIds.add(job.getId());
                        }
                    } catch (Exception e) {
                        log.error("Delete past reservation scheduler job[" + job.getId() + "] failed", e);
                    }
                }
            });

            if (!updateJobIds.isEmpty()) {
                pastReservationSchedulerJobService.refreshSyncStateByIds(updateJobIds);
            }

            if (!deleteJobIds.isEmpty()) {
                pastReservationSchedulerJobService.removeByIds(deleteJobIds);
            }
        }

    }