# ClcJobWorker.java

    package cloud.wconnect.frontoffice.scheduler.clc;

    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.frontoffice.businesstask.clc.ArrivalTask;
    import cloud.wconnect.frontoffice.businesstask.clc.GuestInHouseTask;
    import cloud.wconnect.frontoffice.businesstask.clc.SiteDataTask;
    import cloud.wconnect.frontoffice.entity.clc.ClcSchedulerJob;
    import cloud.wconnect.frontoffice.pojo.dto.clc.ClcSchedulerDTO;
    import cloud.wconnect.frontoffice.service.AmazonSqsService;
    import cloud.wconnect.frontoffice.service.clc.IClcSchedulerService;
    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;

    /**
     * @author yyt
     * 2024-03-13
     */
    @Slf4j
    @Component
    public class ClcJobWorker {

        @Autowired
        private AmazonSqsService amazonSqsService;
        @Autowired
        private MailInternalService mailInternalService;
        @Autowired
        private IClcSchedulerService clcSchedulerService;
        @Autowired
        private ArrivalTask arrivalTask;
        @Autowired
        private GuestInHouseTask guestInHouseTask;
        @Autowired
        private SiteDataTask siteDataTask;
        @Resource
        private CommonService commonService;

        /**
         * 定时消息的队列 url
         */
        @Value("${sqs.queue-url.clc_scheduler}")
        private String schedulerUrl;

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

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

                        if (Objects.nonNull(schedulerJob)) {
                            //获取分类
                            Integer propertyId = schedulerJob.getPropertyId();
                            if (!commonService.checkPropertyEffectiveAndOpenFunction(propertyId, FunctionIdConstant.CLC)) {
                                return;
                            }

                            Integer category = schedulerJob.getCategory();
                            if (category.equals(ClcSchedulerDTO.MISSING_ARRIVAL_REPORT)) {
                                arrivalTask.reportMissCheck(schedulerJob);
                            } else if (category.equals(ClcSchedulerDTO.MISSING_GUEST_IN_HOUSE_REPORT)) {
                                guestInHouseTask.reportMissCheck(schedulerJob);
                            } else if (category.equals(ClcSchedulerDTO.MISSING_NOTIFY)) {
                                arrivalTask.notifyMissingClc(propertyId);
                            } else if (category.equals(ClcSchedulerDTO.NOTIFY_HANDLE_CHECK_OUT)) {
                                siteDataTask.notifyHandleCheckOut(propertyId);
                            }

                            //任务执行次数加1
                            clcSchedulerService.plusRunTimes(jobId);
                        }
                    } catch (Exception e) {
                        log.error("SQS consume error[ClcJobWorker] - Message: {}; Exception: {}", message.body(), e.getMessage());
                        if (RateLimitUtils.tryAcquire(this)) {
                            sendAlertEmail(schedulerUrl, message.body(), schedulerJob, e.getMessage());
                        }
                    } finally {
                        // 删除消息
                        amazonSqsService.deleteMessage(schedulerUrl, message.receiptHandle());
                    }
                }
            }
        }

        /**
         * 发送alertEmail
         *
         * @param schedulerUrl 定时任务调度URL
         * @param message      消息
         * @param schedulerJob 定时任务对象
         * @param exception    异常信息
         * @author yyt
         * @date 2024/3/13
         */
        public void sendAlertEmail(String schedulerUrl, String message, ClcSchedulerJob schedulerJob, String exception) {
            // 主题
            String subject = "[Warning] - process ClcJobWorker";
            // 邮件内容
            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);
        }
    }