# RevenueHistoryAndForecastNextMonthListener.java

    package cloud.wconnect.rateshop.messagelistener.revenue;

    import cloud.wconnect.commonlib.cons.*;
    import cloud.wconnect.commonlib.exception.ListenerException;
    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.BusinessDateUtil;
    import cloud.wconnect.commonlib.util.DateTimeUtils;
    import cloud.wconnect.commonlib.util.JsonUtils;
    import cloud.wconnect.commonlib.util.RateLimitUtils;
    import cloud.wconnect.rateshop.cons.BusinessEnum;
    import cloud.wconnect.rateshop.cons.EventSubjectEnum;
    import cloud.wconnect.rateshop.cons.revenue.RevenueImportCons;
    import cloud.wconnect.rateshop.pojo.bo.revenue.OtbAndTransientGroupBO;
    import cloud.wconnect.rateshop.service.AmazonS3Service;
    import cloud.wconnect.rateshop.service.revenue.IRevenueImportLogService;
    import cloud.wconnect.rateshop.service.revenue.IRevenueImportService;
    import cloud.wconnect.rateshop.service.revenue.historyandforecast.IHistoryAndForecastListenerFileParse;
    import cloud.wconnect.rateshop.service.revenue.report.IRevenueReportCommonService;
    import cloud.wconnect.sns.http.entity.SnsHttpEvent;
    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.lang3.StringUtils;
    import org.springframework.beans.factory.annotation.Autowired;
    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.InputStream;
    import java.text.MessageFormat;
    import java.time.format.DateTimeFormatter;
    import java.util.List;
    import java.util.Map;
    import java.util.Objects;
    import java.util.concurrent.TimeUnit;

    /**
     * History And Forecast Next Month
     *
     * @author yyt
     * 2023/10/31
     */
    @Slf4j
    @Component
    public class RevenueHistoryAndForecastNextMonthListener {

        @Resource
        private ObjectMapper objectMapper;
        @Resource
        private RedisTemplate<String, Object> jsonRedisTemplate;
        @Resource
        private PropertyInternalService propertyInternalService;
        @Resource
        private ApplicationContext applicationContext;
        @Resource
        private AmazonS3Service amazonS3Service;
        @Resource
        private MailInternalService mailInternalService;
        @Resource
        private IRevenueImportService revenueImportService;
        @Resource
        private IRevenueImportLogService revenueImportLogService;
        @Resource
        private CommonService commonService;
        @Autowired
        private IRevenueReportCommonService revenueReportCommonService;

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

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

        private static final String BUSINESS = BusinessEnum.REVENUE.getBusiness();

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

            Integer id = null;
            Integer uid = null;
            boolean importResult = true;
            boolean crossMonth = true;
            String targetDate = null;
            Long startDate = null;
            Long endDate = null;

            EventBodyDTO eventBodyDTO = JsonUtils.convertStringToObject(objectMapper, event.getBody(), EventBodyDTO.class);
            String path = eventBodyDTO.getPath();
            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("RevenueHistoryAndForecastNextMonthListener.end... the property is not exist;property:{}", propertyAbbrName);
                return;
            }
            if (!property.getStatus()) {
                log.warn("RevenueHistoryAndForecastNextMonthListener.end... the property is closed;property:{}", propertyAbbrName);
                return;
            }
            if (!commonService.checkOpenFunction(property, FunctionIdConstant.REVENUE)) {
                log.warn("RevenueHistoryAndForecastNextMonthListener.end... the property has not opened the daily revenue function;property:{}", propertyAbbrName);
                return;
            }
            String source = (String) parameter.get(EventBodyParamEnum.SOURCE.getDesc());
            if (!source.equals(property.getPmsType())) {
                log.info("RevenueHistoryAndForecastNextMonthListener.end... pms is not supported;property:{},propertyPms:{},eventPms:{}", propertyAbbrName, property.getPmsType(), source);
                return;
            }

            try {
                uid = (Integer) parameter.get(EventBodyParamEnum.UID.getDesc());
                uid = Objects.isNull(uid) ? 0 : uid;
                id = Objects.isNull(parameter.get(EventBodyParamEnum.ID.getDesc())) ? null :
                        Integer.parseInt(parameter.get(EventBodyParamEnum.ID.getDesc()).toString());

                String timezone = property.getTimezone();
                DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(BaseConstant.DATE_FORMAT_YYYY_MM_DD);
                if (Objects.isNull(id)) {
                    // 系统自动导入的，判断是否跨月，未跨月，不处理
                    // 计算未来第17天的日期
                    crossMonth = revenueImportService.checkCrossMonth(property.getTimezone());
                    if (!crossMonth) {
                        // 未跨月，不处理
                        log.info("RevenueHistoryAndForecastNextMonthListener.end... don't need to handle report");
                        return;
                    }

                    targetDate = DateTimeUtils.dateNow(timezone).format(dateTimeFormatter);
                    List<Long> dates = revenueImportService.listImportHistoryAndForecastNextMonthDateRange(timezone);
                    startDate = dates.get(0);
                    endDate = dates.get(1);
                } else {
                    Object dateObj = parameter.get(EventBodyParamEnum.DATE.getDesc());
                    Object startDateObj = parameter.get(EventBodyParamEnum.START_DATE.getDesc());
                    Object endDateObj = parameter.get(EventBodyParamEnum.END_DATE.getDesc());
                    if (Objects.isNull(dateObj) || Objects.isNull(startDateObj) || Objects.isNull(endDateObj)) {
                        log.warn("RevenueHistoryAndForecastNextMonthListener.end... the date、startDate、endDate is null, no processing required;property:{}", propertyAbbrName);
                        return;
                    }
                    targetDate = DateTimeUtils.toZonedDateTime(Long.parseLong(dateObj.toString()), timezone).format(dateTimeFormatter);
                    startDate = Long.parseLong(startDateObj.toString());
                    endDate = Long.parseLong(endDateObj.toString());
                }

                revenueReportCommonService.toS3(path);

                // 解析文件
                log.info("RevenueHistoryAndForecastNextMonthListener: report parsing begin - {}", propertyAbbrName);
                OtbAndTransientGroupBO otbAndTransientGroupBO = parseReport(property, eventBodyDTO, startDate, endDate);
                log.info("RevenueHistoryAndForecastNextMonthListener: report parsing end - {}", propertyAbbrName);
                // 保存文件数据
                revenueImportService.saveOtbAndTransientGroupNextMonthData(property, targetDate, otbAndTransientGroupBO, uid);
            } catch (Exception e) {
                importResult = false;
                if (RateLimitUtils.tryAcquire(this, propertyAbbrName)) {
                    sendAlertEmail(propertyAbbrName, e.getMessage(), eventBodyDTO.getPath());
                }
                log.error("RevenueHistoryAndForecastNextMonthListener.end... handle import history and forecast next month report error.", e);
            } finally {
                if (crossMonth) {
                    // 自动导入报告时插入处理时机，用于定时检查报告缺失逻辑
                    if (Objects.nonNull(uid) && uid == 0) {
                        updateLastTime(propertyAbbrName);
                    }

                    if (Objects.isNull(id)) {
                        // 生成导入记录
                        String timezone = property.getTimezone();
                        List<Long> dates = revenueImportService.listImportHistoryAndForecastNextMonthDateRange(timezone);
                        revenueImportLogService.handleSaveSystemImportRecord(property, RevenueImportCons.HISTORY_FORECAST_NEXT_MONTH,
                                DateTimeUtils.localDateToLong(BusinessDateUtil.getBusinessDate(timezone), timezone), dates.get(0), dates.get(1),
                                importResult ? ReportImportResultCons.IMPORT_RESULT_SUCCESS : ReportImportResultCons.IMPORT_RESULT_FAIL, path);
                    } else {
                        String eventBusiness = parameter.get(EventBodyParamEnum.ORIGINATE_FROM.getDesc()).toString();
                        if (BUSINESS.equals(eventBusiness)) {
                            // 修改导入记录状态
                            revenueImportLogService.updateLogStatus(id, importResult, path, uid);
                        } else {
                            if (Objects.nonNull(targetDate) && Objects.nonNull(startDate) && Objects.nonNull(endDate)) {
                                revenueImportLogService.saveRecord(property.getId(), RevenueImportCons.HISTORY_FORECAST_NEXT_MONTH,
                                        DateTimeUtils.dateStrToEpochSecond(targetDate, BaseConstant.DATE_FORMAT_YYYY_MM_DD, property.getTimezone()),
                                        startDate, endDate, importResult ? ReportImportResultCons.IMPORT_RESULT_SUCCESS :
                                                ReportImportResultCons.IMPORT_RESULT_FAIL, path, uid);
                            }
                        }
                    }
                    log.info("RevenueHistoryAndForecastNextMonthListener.end...");
                }
            }
        }

        /**
         * 解析报告数据
         *
         * @param property     资产
         * @param eventBodyDTO 事件体
         * @param startDate    开始日期
         * @param endDate      结束日期
         * @return Otb And TransientGroup
         * @author yyt
         * @date 2023/11/1
         */
        private OtbAndTransientGroupBO parseReport(PropertyDTO property, EventBodyDTO eventBodyDTO, Long startDate, Long endDate) {
            Map<String, Object> parameter = eventBodyDTO.getParameter();
            String source = (String) parameter.get(EventBodyParamEnum.SOURCE.getDesc());
            String path = eventBodyDTO.getPath();
            OtbAndTransientGroupBO otbAndTransientGroupBO = null;
            Map<String, IHistoryAndForecastListenerFileParse> beansOfType = applicationContext.getBeansOfType(IHistoryAndForecastListenerFileParse.class);
            for (IHistoryAndForecastListenerFileParse bean : beansOfType.values()) {
                if (bean.supports(source)) {
                    try (InputStream inputStream = amazonS3Service.getFile(path)) {
                        otbAndTransientGroupBO = bean.parseReport(property.getId(), property.getTimezone(), inputStream,
                                startDate, endDate);
                        break;
                    } catch (Exception e) {
                        throw new ListenerException("parse history and forecast next month report error", e);
                    }
                }
            }
            if (Objects.isNull(otbAndTransientGroupBO)) {
                throw new ListenerException("the source is not exist; source: " + source);
            }

            return otbAndTransientGroupBO;
        }

        /**
         * 发送预警邮件
         *
         * @param abbrName property abbr
         * @param content  邮件内容
         * @param path     文件路径
         * @author yyt
         * @date 2023/11/1
         */
        private void sendAlertEmail(String abbrName, String content, String path) {
            String subject = "[Warning] - Handle History And Forecast Next Month 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);
        }

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

        /**
         * 防止并发操作
         *
         * @param messageId 消息事件 id
         * @return true / false
         * @author yyt
         * @date 2023/11/1
         */
        private Boolean preventConcurrency(String messageId) {
            return jsonRedisTemplate.opsForValue().setIfAbsent(
                    EventRedisKeyPrefixEnum.KEY_PREFIX_FOR_MESSAGE.getDesc() +
                            StringUtils.join(Lists.newArrayList(SUBJECT, BUSINESS, messageId), "."),
                    0L, 1, TimeUnit.DAYS);
        }

    }