# RateShopJobWorker.java

    package cloud.wconnect.rateshop.scheduler.rateshop;

    import cloud.wconnect.commonlib.cons.FunctionIdConstant;
    import cloud.wconnect.commonlib.cons.SchedulerCons;
    import cloud.wconnect.commonlib.service.CommonService;
    import cloud.wconnect.commonlib.service.MailInternalService;
    import cloud.wconnect.commonlib.util.RateLimitUtils;
    import cloud.wconnect.rateshop.businesstask.rateshop.*;
    import cloud.wconnect.rateshop.cons.rateshop.RateShopNotifyConfigTypeEnum;
    import cloud.wconnect.rateshop.entity.rateshop.RateShopScheduler;
    import cloud.wconnect.rateshop.service.AmazonSqsSchedulerService;
    import cloud.wconnect.rateshop.service.rateshop.IRateShopSchedulerService;
    import com.alibaba.fastjson.JSONObject;
    import jakarta.annotation.Resource;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.commons.collections.CollectionUtils;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.scheduling.annotation.Scheduled;
    import org.springframework.stereotype.Component;
    import software.amazon.awssdk.services.sqs.model.Message;

    import java.text.MessageFormat;
    import java.util.List;
    import java.util.Objects;

    @Slf4j
    @Component
    public class RateShopJobWorker {

        @Autowired
        private AmazonSqsSchedulerService amazonSqsSchedulerService;
        @Autowired
        private IRateShopSchedulerService schedulerService;
        @Autowired
        private MailInternalService mailInternalService;
        @Autowired
        private HistoryAndForecastServiceTask historyAndForecastServiceTask;
        @Autowired
        private GroupPickupServiceTask groupPickupServiceTask;
        @Autowired
        private RateShopOccupancySummaryServiceTask rateShopOccupancySummaryServiceTask;
        @Autowired
        private RateShopMarketSegmentSummaryServiceTask rateShopMarketSegmentSummaryServiceTask;
        @Resource
        private CommonService commonService;
        @Autowired
        private NotifyOccSnapshotForTheNextNDaysTask notifyOccSnapshotForTheNextNDaysTask;

        /**
         * 房价消息的队列url
         */
        @Value("${sqs.scheduler.queue-url.rate_shop_scheduler}")
        private String schedulerUrl;

        /**
         * 消费队列任务
         *
         * @author lichen
         * @date 2024/3/13
         */
        @Scheduled(cron = "0 0/1 * * * ?", zone = "${default.timezone}")
        public void run() {
            List<Message> messages = amazonSqsSchedulerService.getMessagesBatch(schedulerUrl);
            if (CollectionUtils.isNotEmpty(messages)) {
                for (Message message : messages) {
                    // message为json字符串：{"jobId": "894bd865a742c84d9a74c190b1e3cb92"}, 该jobId 为 rate_shop_scheduler表的id，该对应记录保存着任务的详细信息
                    // 警告: 执行任务的具体方法应该使用新的线程，而不是在本线程执行（要确保本线程不会被阻塞或异常退出）

                    RateShopScheduler schedulerJob = null;
                    try {
                        JSONObject jsonObject = JSONObject.parseObject(message.body());
                        String jobId = (String) jsonObject.get(SchedulerCons.JOB_ID);
                        schedulerJob = schedulerService.getById(jobId);

                        if(Objects.nonNull(schedulerJob)){
                            if (!commonService.checkPropertyEffectiveAndOpenFunction(schedulerJob.getPropertyId(), FunctionIdConstant.RATE_SHOP)) {
                                return;
                            }

                            //获取分类
                            Integer category = schedulerJob.getCategory();
                            if (category.equals(RateShopNotifyConfigTypeEnum.HISTORY_AND_FORECAST_REPORT_MISSED.getType())) {
                                historyAndForecastServiceTask.dataMissingCheck(schedulerJob);
                            } else if (category.equals(RateShopNotifyConfigTypeEnum.GROUP_PICKUP_REPORT_MISSED.getType())) {
                                groupPickupServiceTask.dataMissingCheck(schedulerJob);
                            } else if(category.equals(RateShopNotifyConfigTypeEnum.OCC_SNAPSHOT_FOR_THE_NEXT_N_DAYS.getType())){
                                notifyOccSnapshotForTheNextNDaysTask.notifyOccForecast(schedulerJob);
                            } else if (category.equals(RateShopNotifyConfigTypeEnum.OCCUPANCY_SUMMARY_REPORT_MISSED.getType())) {
                                rateShopOccupancySummaryServiceTask.dataMissingCheck(schedulerJob);
                            } else if (category.equals(RateShopNotifyConfigTypeEnum.MARKET_SEGMENT_SUMMARY_REPORT_MISSED.getType())) {
                                rateShopMarketSegmentSummaryServiceTask.dataMissingCheck(schedulerJob);
                            }
                            //任务执行次数加1
                            schedulerService.plusRunTimes(jobId);
                        }
                    } catch (Exception e) {
                        log.error("SQS consume error[RateShopJobWorker] - Message: {}; Exception: {}", message.body(), e.getMessage());
                        if (RateLimitUtils.tryAcquire(this)) {
                            sendAlertEmail(schedulerUrl, message.body(), schedulerJob, e.getMessage());
                        }
                    } finally {
                        // 删除消息
                        amazonSqsSchedulerService.deleteMessage(schedulerUrl, message.receiptHandle());
                    }
                }
                run();
            }
        }

        /**
         * 发送alertEmail
         *
         * @param schedulerUrl 定时任务调度URL
         * @param message      消息
         * @param schedulerJob 定时任务对象
         * @param exception    异常信息
         * @author lichen
         * @date 2024/3/15
         */
        public void sendAlertEmail(String schedulerUrl, String message, RateShopScheduler schedulerJob, String exception) {
            // 主题
            String subject = "[Warning] - process RateShopJobWorker";
            // 邮件内容
            String mailContent = MessageFormat.format("SQS url:{0}<br/>Message:{1}<br/>SchedulerJob:{2}<br/>Exception:{3}",
                    schedulerUrl, message, Objects.nonNull(schedulerJob) ? schedulerJob.toString() : "", exception);
            // 发送 alert
            mailInternalService.sendAlertEmail(subject, mailContent);
        }
    }