# RevenueHistoryAndForecastBusinessBlocksListener.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.TransientGroupAdrBO;
    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.historyandforecastbusinessblocks.IHistoryAndForecastBusinessBlocksFileParse;
    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 Business Blocks
     *
     * @author yyt
     * 2023/11/2
     */
    @Slf4j
    @Component
    public class RevenueHistoryAndForecastBusinessBlocksListener {

        @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_BUSINESS_BLOCK_NEXT_FOURTEEN_DAY.getSubject();

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

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

            Integer id = null;
            int uid = 0;
            boolean importResult = 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("RevenueHistoryAndForecastBusinessBlocksListener.end... the property is not exist;property:{}", propertyAbbrName);
                return;
            }
            if (!property.getStatus()) {
                log.warn("RevenueHistoryAndForecastBusinessBlocksListener.end... the property is closed;property:{}", propertyAbbrName);
                return;
            }
            if (!commonService.checkOpenFunction(property, FunctionIdConstant.REVENUE)) {
                log.warn("RevenueHistoryAndForecastBusinessBlocksListener.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("RevenueHistoryAndForecastBusinessBlocksListener.end... pms is not supported;property:{},propertyPms:{},eventPms:{}", propertyAbbrName, property.getPmsType(), source);
                return;
            }

            try {
                uid = (Integer) parameter.get(EventBodyParamEnum.UID.getDesc());
                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)) {
                    targetDate = DateTimeUtils.dateNow(timezone).format(dateTimeFormatter);
                    List<Long> dates = revenueImportService.listImportHistoryAndForecastBusinessBlockDateRange(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("RevenueHistoryAndForecastBusinessBlocksListener.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);

                // 解析文件
                List<TransientGroupAdrBO> transientGroupAdrs = parseReport(property, eventBodyDTO, startDate, endDate);
                // 保存文件数据
                revenueImportService.saveTransientGroupAdrData(property, targetDate, transientGroupAdrs, uid);
            } catch (Exception e) {
                importResult = false;
                if (RateLimitUtils.tryAcquire(this, propertyAbbrName)) {
                    sendAlertEmail(propertyAbbrName, e.getMessage(), eventBodyDTO.getPath());
                }
                log.error("RevenueHistoryAndForecastBusinessBlocksListener.end... handle import history and forecast business blocks report error.", e);
            } finally {
                // 自动导入报告时插入处理时机，用于定时检查报告缺失逻辑
                if (uid == 0) {
                    updateLastTime(propertyAbbrName);
                }

                if (Objects.isNull(id)) {
                    // 生成导入记录
                    String timezone = property.getTimezone();
                    List<Long> dates = revenueImportService.listImportHistoryAndForecastBusinessBlockDateRange(timezone);
                    revenueImportLogService.handleSaveSystemImportRecord(property, RevenueImportCons.HISTORY_FORECAST_BUSINESS_BLOCK,
                            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_BUSINESS_BLOCK,
                                    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("RevenueHistoryAndForecastBusinessBlocksListener.end...");
        }

        /**
         * 解析报告 Transient Group Adr 数据
         *
         * @param property     资产
         * @param eventBodyDTO 事件体
         * @param startDate    开始日期
         * @param endDate      结束日期
         * @return Transient Group Last Year
         * @author yyt
         * @date 2023/11/2
         */
        private List<TransientGroupAdrBO> 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();
            List<TransientGroupAdrBO> transientGroupAdrs = null;
            Map<String, IHistoryAndForecastBusinessBlocksFileParse> beansOfType =
                    applicationContext.getBeansOfType(IHistoryAndForecastBusinessBlocksFileParse.class);
            Integer propertyId = property.getId();
            String timezone = property.getTimezone();
            for (IHistoryAndForecastBusinessBlocksFileParse bean : beansOfType.values()) {
                if (bean.supports(source)) {
                    try (InputStream inputStream = amazonS3Service.getFile(path)) {
                        transientGroupAdrs = bean.parseReportForTransientGroupAdr(propertyId, timezone, inputStream,
                                startDate, endDate);
                        break;
                    } catch (Exception e) {
                        throw new ListenerException("parse history and forecast business blocks report error", e);
                    }
                }
            }
            if (Objects.isNull(transientGroupAdrs)) {
                throw new ListenerException("the source is not exist; source: " + source);
            }

            return transientGroupAdrs;
        }

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

    }