# ScheduleHistoryAndForecastListener.java

    package cloud.wconnect.workperformance.messagelistener.schedule;

    import cloud.wconnect.commonlib.cons.EventBodyParamEnum;
    import cloud.wconnect.commonlib.cons.EventRedisKeyPrefixEnum;
    import cloud.wconnect.commonlib.cons.FunctionIdConstant;
    import cloud.wconnect.commonlib.cons.ReportImportResultCons;
    import cloud.wconnect.commonlib.pojo.dto.EventBodyDTO;
    import cloud.wconnect.commonlib.pojo.dto.PropertyDTO;
    import cloud.wconnect.commonlib.service.CommonService;
    import cloud.wconnect.commonlib.service.MailInternalService;
    import cloud.wconnect.commonlib.service.PropertyInternalService;
    import cloud.wconnect.commonlib.util.DateTimeUtils;
    import cloud.wconnect.commonlib.util.JsonUtils;
    import cloud.wconnect.commonlib.util.RateLimitUtils;
    import cloud.wconnect.sns.http.entity.SnsHttpEvent;
    import cloud.wconnect.workperformance.cons.BusinessEnum;
    import cloud.wconnect.workperformance.cons.EventSubjectEnum;
    import cloud.wconnect.workperformance.entity.schedule.ScheduleHistoryAndForecastImportLog;
    import cloud.wconnect.workperformance.pojo.bo.schedule.ScheduleHistoryAndForecastBO;
    import cloud.wconnect.workperformance.service.AmazonS3Service;
    import cloud.wconnect.workperformance.service.schedule.IScheduleHistoryAndForecastImportLogService;
    import cloud.wconnect.workperformance.service.schedule.IScheduleHistoryAndForecastService;
    import cloud.wconnect.workperformance.service.schedule.IScheduleWorkDayService;
    import cloud.wconnect.workperformance.service.schedule.historyandforecast.IHistoryAndForecastFileParse;
    import cloud.wconnect.workperformance.service.schedule.impl.ScheduleWorkDayServiceImpl;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.google.common.collect.Lists;
    import jakarta.annotation.Resource;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.commons.collections.CollectionUtils;
    import org.apache.commons.lang3.StringUtils;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.event.EventListener;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.scheduling.annotation.Async;
    import org.springframework.stereotype.Component;

    import java.io.IOException;
    import java.io.InputStream;
    import java.text.MessageFormat;
    import java.util.List;
    import java.util.Map;
    import java.util.Objects;
    import java.util.concurrent.TimeUnit;

    /**
     * History And Forecast 报告事件处理
     *
     * @author yyt
     * 2023/7/4
     */
    @Slf4j
    @Component
    public class ScheduleHistoryAndForecastListener {

        @Resource
        private ObjectMapper objectMapper;
        @Resource
        private ApplicationContext applicationContext;
        @Resource
        private RedisTemplate<String, Object> jsonRedisTemplate;
        @Resource
        private PropertyInternalService propertyInternalService;
        @Resource
        private MailInternalService mailInternalService;
        @Resource
        private IScheduleWorkDayService scheduleWorkDayService;
        @Resource
        private AmazonS3Service amazonS3Service;
        @Resource
        private IScheduleHistoryAndForecastImportLogService scheduleHistoryAndForecastImportLogService;
        @Resource
        private IScheduleHistoryAndForecastService scheduleHistoryAndForecastService;
        @Resource
        private CommonService commonService;

        @Value("${default.timezone}")
        private String defaultTimezone;

        private static final String SUBJECT = EventSubjectEnum.HISTORY_AND_FORECAST_SERVICE_YESTERDAY_NINETY_DAY.getSubject();

        private final String BUSINESS = BusinessEnum.SCHEDULE_HISTORY_AND_FORECAST.getBusiness();

        /**
         * 监听 history and forecast 报告
         *
         * @param event 事件
         * @author yyt
         * @date 2023/7/4
         */
        @Async
        @EventListener
        public void handle(SnsHttpEvent event) {
            // 校验 subject
            if (!StringUtils.equals(event.getSubject(), SUBJECT)) {
                return;
            }
            log.info("ScheduleHistoryAndForecastListener.start...");
            // 防止并发
            if (!preventConcurrency(event.getMessageId())) {
                log.warn("ScheduleHistoryAndForecastListener.end... a machine has been executed.");
                return;
            }
            // 校验 事件体 信息
            if (StringUtils.isBlank(event.getBody())) {
                log.warn("ScheduleHistoryAndForecastListener.end... event body is blank.");
                return;
            }

            EventBodyDTO eventBodyDTO = JsonUtils.convertStringToObject(objectMapper, event.getBody(), EventBodyDTO.class);
            Map<String, Object> parameter = eventBodyDTO.getParameter();

            List<String> propertyAbbrNames = (List<String>) parameter.get(EventBodyParamEnum.PROPERTY_ABBR.getDesc());
            String propertyAbbrName = propertyAbbrNames.get(0);
            String tenantAbbrName = (String) parameter.get(EventBodyParamEnum.TENANT_SYMBOL.getDesc());
            PropertyDTO property = propertyInternalService.getOne(propertyAbbrName, tenantAbbrName);
            if (Objects.isNull(property)) {
                log.warn("ScheduleHistoryAndForecastListener.end... the property is not exist;property:{}", propertyAbbrName);
                return;
            }
            if (!property.getStatus()) {
                log.warn("ScheduleHistoryAndForecastListener.end... the property is closed;property:{}", propertyAbbrName);
                return;
            }

            String source = (String) parameter.get(EventBodyParamEnum.SOURCE.getDesc());
            if(!property.getPmsType().equals(source)){
                log.warn("ScheduleHistoryAndForecastListener.handle end... property not support this pms type, propertyId:{}, supportPmsType:{}, currentPmsType:{}",
                        property.getId(), property.getPmsType(), source);
                return;
            }

            if (!commonService.checkOpenFunction(property, FunctionIdConstant.SCHEDULE)) {
                log.warn("ScheduleHistoryAndForecastListener.end... the property has not opened schedule function;property:{}", propertyAbbrName);
                return;
            }

            Integer uid = (Integer) parameter.get(EventBodyParamEnum.UID.getDesc());
            uid = Objects.isNull(uid) ? 0 : uid;
            Integer id = (Integer) parameter.get(EventBodyParamEnum.ID.getDesc());
            // 处理数据日期范围
            Long startDate = null;
            Long endDate = null;
            int importResult = ScheduleHistoryAndForecastImportLog.IMPORT_RESULT_SUCCESS;

            /**
             * 处理数据日期范围：
             * 1、自动导入报告时，取调度配置的数据日期范围
             * 2、手动导入报告（解决异常、手动导入）时，取事件体的日期范围
             */
            if (uid == 0) {
                Map<String, Long> dateRangeMap = scheduleWorkDayService.calculateValidDateRange(property);
                startDate = dateRangeMap.get(ScheduleWorkDayServiceImpl.START_DATE);
                endDate = dateRangeMap.get(ScheduleWorkDayServiceImpl.END_DATE);
            } else {
                startDate = Objects.isNull(parameter.get(EventBodyParamEnum.START_DATE.getDesc())) ? null :
                        (long) Integer.parseInt(parameter.get(EventBodyParamEnum.START_DATE.getDesc()).toString());
                endDate = Objects.isNull(parameter.get(EventBodyParamEnum.END_DATE.getDesc())) ? null :
                        (long) Integer.parseInt(parameter.get(EventBodyParamEnum.END_DATE.getDesc()).toString());
            }
            if (Objects.isNull(startDate) && Objects.isNull(endDate)) {
                log.info("ScheduleHistoryAndForecastListener.end... the startDate and endDate is null,no need handle.");
                return;
            }

            // 解析报告数据
            List<ScheduleHistoryAndForecastBO> historyAndForecasts = null;
            try {
                historyAndForecasts = parseReport(startDate, endDate, eventBodyDTO, property);
            } catch (IOException e) {
                sendAlertEmail(propertyAbbrName, "parse report error " + e.getMessage(), eventBodyDTO.getPath());
                log.error("ScheduleHistoryAndForecastListener.end... parse report error.");
            }
            if (Objects.isNull(historyAndForecasts)) {
                return;
            }

            try {
                // 处理数据
                if (CollectionUtils.isNotEmpty(historyAndForecasts)) {
                    scheduleHistoryAndForecastService.handleHistoryAndForecastData(property, historyAndForecasts);
                }
            } catch (Exception e) {
                importResult = ScheduleHistoryAndForecastImportLog.IMPORT_RESULT_FAIL;
                if (RateLimitUtils.tryAcquire(this, propertyAbbrName)) {
                    sendAlertEmail(propertyAbbrName, e.getMessage(), eventBodyDTO.getPath());
                }
                log.error("ScheduleHistoryAndForecastListener.end... parse report error.");
            } finally {
                // 自动导入报告时插入处理时机，用于定时检查报告缺失逻辑
                if (uid == 0) {
                    updateLastTime(propertyAbbrName);
                }

                long now = DateTimeUtils.nowTimestamp();
                // 系统自动导入
                if (Objects.isNull(id)) {
                    // 插入导入记录
                    scheduleHistoryAndForecastImportLogService.saveRecord(property.getId(),
                            DateTimeUtils.dateNowTimestamp(property.getTimezone()), startDate, endDate, importResult, uid);
                } else {
                    String eventBusiness = parameter.get(EventBodyParamEnum.ORIGINATE_FROM.getDesc()).toString();
                    if (BUSINESS.equals(eventBusiness)) {
                        // 修改导入记录状态
                        ScheduleHistoryAndForecastImportLog update = new ScheduleHistoryAndForecastImportLog().setId(id)
                                .setImportResult(importResult);

                        ScheduleHistoryAndForecastImportLog importLog = scheduleHistoryAndForecastImportLogService.getById(id);
                        if (importLog.getImportResult() == ReportImportResultCons.IMPORT_RESULT_REPAIRING) {
                            update.setResolvedBy(importResult == ScheduleHistoryAndForecastImportLog.IMPORT_RESULT_SUCCESS ? uid : 0)
                                    .setResolvedTime(importResult == ScheduleHistoryAndForecastImportLog.IMPORT_RESULT_SUCCESS ? now : 0);
                        }
                        scheduleHistoryAndForecastImportLogService.updateById(update);
                    } else {
                        if (Objects.nonNull(startDate) && Objects.nonNull(endDate)) {
                            scheduleHistoryAndForecastImportLogService.saveRecord(property.getId(),
                                    DateTimeUtils.dateNowTimestamp(property.getTimezone()), startDate, endDate, importResult, uid);
                        }
                    }
                }
            }

            log.info("ScheduleHistoryAndForecastListener.end...");
        }

        /**
         * 解析报告数据
         *
         * @param startDate    开始日期
         * @param endDate      结束日期
         * @param eventBodyDTO 事件体
         * @param propertyDTO     时区
         * @return history and forecast
         * @author yyt
         * @date 2023/7/4
         */
        private List<ScheduleHistoryAndForecastBO> parseReport(Long startDate, Long endDate, EventBodyDTO eventBodyDTO,
                                                               PropertyDTO propertyDTO) throws IOException {
            Map<String, Object> parameter = eventBodyDTO.getParameter();
            String source = (String) parameter.get(EventBodyParamEnum.SOURCE.getDesc());
            String path = eventBodyDTO.getPath();

            List<ScheduleHistoryAndForecastBO> historyAndForecasts = null;
            Map<String, IHistoryAndForecastFileParse> beansOfType = applicationContext.getBeansOfType(IHistoryAndForecastFileParse.class);
            for (IHistoryAndForecastFileParse bean : beansOfType.values()) {
                if (bean.supports(source)) {
                    try (InputStream inputStream = amazonS3Service.getFile(path)) {
                        historyAndForecasts = bean.parsReport(startDate, endDate, inputStream, propertyDTO);
                    }
                    break;
                }
            }
            if (Objects.isNull(historyAndForecasts)) {
                log.info(MessageFormat.format("ScheduleHistoryAndForecastListener.end... do not handle this source for the time being; property:{0}, source:{1}", propertyDTO.getAbbr(), source));

                return null;
            }

            return historyAndForecasts;
        }

        /**
         * 防止并发操作
         *
         * @param messageId 消息事件 id
         * @return boolean true：未并发，当前线程可以执行；false：检测到并发，当前线程应放弃执行
         * @author yyt
         * @date 2023/7/4
         */
        private Boolean preventConcurrency(String messageId) {
            String key = EventRedisKeyPrefixEnum.KEY_PREFIX_FOR_MESSAGE.getDesc() +
                    StringUtils.join(Lists.newArrayList(SUBJECT, BUSINESS, messageId), ".");
            return jsonRedisTemplate.opsForValue().setIfAbsent(key, 0L, 1, TimeUnit.DAYS);
        }

        /**
         * 保存事件最近处理时刻
         *
         * @param propertyAbbr 资产标识
         * @author yyt
         * @date 2023/7/5
         */
        private void updateLastTime(String propertyAbbr) {
            String key = EventRedisKeyPrefixEnum.KEY_PREFIX_FOR_PROCESSING.getDesc() +
                    StringUtils.join(Lists.newArrayList(SUBJECT, BUSINESS, propertyAbbr), ".");
            String value = String.valueOf(DateTimeUtils.dateTimeNow(defaultTimezone).toEpochSecond());
            jsonRedisTemplate.opsForValue().set(key, value);
        }

        /**
         * 发送预警邮件
         *
         * @param abbrName property abbr
         * @param content  邮件内容
         * @param path     文件路径
         * @author yyt
         * @date 2023/7/5
         */
        private void sendAlertEmail(String abbrName, String content, String path) {
            String subject = "[Warning] - Handle History And Forecast Report Exception";
            String mailContent = MessageFormat.format("SNS Subject:{0}<br/>Business:{1}<br/>Property:{2}<br/>Content:{3}<br/>S3Key:{4}",
                    SUBJECT, BUSINESS, abbrName, content, path);
            mailInternalService.sendAlertEmail(subject, mailContent);
        }

    }