# RevenueManagerFlashMTDYesterdayListener.java

    package cloud.wconnect.rateshop.messagelistener.revenue;

    import cloud.wconnect.commonlib.cons.EventBodyParamEnum;
    import cloud.wconnect.commonlib.cons.FunctionIdConstant;
    import cloud.wconnect.commonlib.cons.ReportImportResultCons;
    import cloud.wconnect.commonlib.exception.ListenerException;
    import cloud.wconnect.commonlib.exception.ParseReportException;
    import cloud.wconnect.commonlib.pojo.dto.EventBodyDTO;
    import cloud.wconnect.commonlib.pojo.dto.PropertyDTO;
    import cloud.wconnect.commonlib.pojo.dto.scheduler.JobParameterDTO;
    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.KeyPrefixEnum;
    import cloud.wconnect.rateshop.cons.S3BucketFunctionCons;
    import cloud.wconnect.rateshop.cons.revenue.RevenueImportCons;
    import cloud.wconnect.rateshop.pojo.bo.revenue.ManagerFlashBO;
    import cloud.wconnect.rateshop.pojo.dto.revenue.ManagerFlashDTO;
    import cloud.wconnect.rateshop.service.AmazonS3Service;
    import cloud.wconnect.rateshop.service.revenue.IRevenueDailySummaryManagerFlashService;
    import cloud.wconnect.rateshop.service.revenue.IRevenueImportLogService;
    import cloud.wconnect.rateshop.service.revenue.IRevenueSchedulerJobService;
    import cloud.wconnect.rateshop.service.revenue.managerflash.IManagerFlashParse;
    import cloud.wconnect.sns.http.entity.SnsHttpEvent;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.google.common.collect.Lists;
    import com.google.common.collect.Maps;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.commons.collections.MapUtils;
    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.Service;

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

    /**
     * 报告处理：manager-flash/service-mtd--1d
     *
     * @author lichen
     * @date 2025/1/10
     */
    @Slf4j
    @Service
    public class RevenueManagerFlashMTDYesterdayListener {

        @Autowired
        private MailInternalService mailInternalService;
        @Autowired
        private ObjectMapper objectMapper;
        @Autowired
        private PropertyInternalService propertyInternalService;
        @Autowired
        private RedisTemplate<String, Object> redisTemplate;
        @Autowired
        private ApplicationContext applicationContext;
        @Value("${default.timezone}")
        private String defaultTimezone;
        @Autowired
        private AmazonS3Service amazonS3Service;
        @Autowired
        private IRevenueImportLogService revenueImportLogService;
        @Autowired
        private IRevenueSchedulerJobService schedulerJobService;
        @Autowired
        private IRevenueDailySummaryManagerFlashService revenueDailySummaryManagerFlashService;
        @Autowired
        private CommonService commonService;

        /**
         * subject
         */
        private final String SUBJECT = EventSubjectEnum.MANAGER_FLASH.getSubject();
        /**
         * 业务名称
         */
        private final String BUSINESS = BusinessEnum.REVENUE.getBusiness();

        /**
         * 异步监听事件处理
         *
         * @param event 事件对象
         * @author lichen
         * @date 2025/1/10
         */
        @Async
        @EventListener
        public void handle(SnsHttpEvent event) {
            if (!StringUtils.equals(SUBJECT, event.getSubject())) {
                return;
            }

            log.info("RevenueManagerFlashMTDYesterdayListener.handle start...");

            if (!preventConcurrency(event.getMessageId())) {
                log.warn("RevenueManagerFlashMTDYesterdayListener.handle end... A machine has been executed");
                return;
            }
            if (StringUtils.isBlank(event.getBody())) {
                log.warn("RevenueManagerFlashMTDYesterdayListener.handle end... event body is blank.");
                return;
            }

            // 解析事件体内容
            EventBodyDTO eventBodyDTO = JsonUtils.convertStringToObject(objectMapper, event.getBody(), EventBodyDTO.class);
            Map<String, Object> parameter = eventBodyDTO.getParameter();
            // 获取租户标识
            String tenantSymbol = (String) parameter.get(EventBodyParamEnum.TENANT_SYMBOL.getDesc());
            // 资产标识
            List<String> abbrNameList = (List<String>) parameter.get(EventBodyParamEnum.PROPERTY_ABBR.getDesc());
            String propertyAbbr = abbrNameList.get(0);

            // 获取有效的资产数据
            PropertyDTO propertyDTO = getEffectiveProperty(tenantSymbol, propertyAbbr);
            if (Objects.isNull(propertyDTO)) {
                return;
            }

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

            IManagerFlashParse parser = getParser(source);
            if (Objects.isNull(parser)) {
                log.warn("RevenueManagerFlashMTDYesterdayListener.handle end... parser is null, property:{}, source:{}",
                        propertyAbbr, source);
                return;
            }

            //获取操作用户id
            Integer uid = (Integer) parameter.get(EventBodyParamEnum.UID.getDesc());
            //获取日志id
            Long logId = Objects.isNull(parameter.get(EventBodyParamEnum.ID.getDesc())) ? null :
                    Long.parseLong(parameter.get(EventBodyParamEnum.ID.getDesc()).toString());
            //获取报告数据范围
            Map<String, Long> dateRange = getDateRange(propertyDTO, parameter, logId);
            if (MapUtils.isEmpty(dateRange)) {
                log.warn("RevenueManagerFlashMTDYesterdayListener.handle end... The dateRante is empty, property:{}", propertyAbbr);
                return;
            }
            boolean importResult = true;
            try (InputStream fileInputStream = amazonS3Service.getFile(eventBodyDTO.getPath())) {
                //上传文件到功能对应的桶中
                amazonS3Service.uploadFile(S3BucketFunctionCons.REVENUE_IMPORT_RECORD, fileInputStream, eventBodyDTO.getPath());

                //报告中的数据
                ManagerFlashDTO managerFlashDTO = parseReport(eventBodyDTO, propertyDTO, parser);
                if (Objects.isNull(managerFlashDTO)) return;

                List<ManagerFlashBO> managerFlashBOS = dateRange.values().stream().distinct()
                        .map(date -> ManagerFlashBO.builder()
                                .theDate(date)
                                .noShow(managerFlashDTO.getNoShow())
                                .cancelled(managerFlashDTO.getCancelled())
                                .adr(managerFlashDTO.getAdr())
                                .build()).toList();
                revenueDailySummaryManagerFlashService.saveOrUpdate(propertyDTO, managerFlashBOS);
                log.info("RevenueManagerFlashMTDYesterdayListener.end...");
            } catch (Exception e) {
                importResult = false;
                if (RateLimitUtils.tryAcquire(this, propertyAbbr)) {
                    sendAlertEmail(propertyAbbr, e.getMessage(), eventBodyDTO.getPath());
                }
                log.error("RevenueManagerFlashMTDYesterdayListener.end... Process error.", e);
            } finally {
                if (uid == 0) {
                    updateLastTime(propertyAbbr);
                }

                if (Objects.isNull(logId)) {//自动下发
                    // 生成导入记录
                    String timezone = propertyDTO.getTimezone();
                    revenueImportLogService.handleSaveSystemImportRecord(propertyDTO, RevenueImportCons.MANAGER_FLASH,
                            DateTimeUtils.localDateToLong(BusinessDateUtil.getBusinessDate(timezone), timezone), dateRange.get(JobParameterDTO.START_DATE), dateRange.get(JobParameterDTO.END_DATE),
                            importResult ? ReportImportResultCons.IMPORT_RESULT_SUCCESS : ReportImportResultCons.IMPORT_RESULT_FAIL,
                            eventBodyDTO.getPath());
                } else {
                    String eventBusiness = (String) parameter.get(EventBodyParamEnum.ORIGINATE_FROM.getDesc());
                    if (BUSINESS.equals(eventBusiness)) {
                        // 修改导入记录状态
                        revenueImportLogService.updateLogStatus(logId, importResult, eventBodyDTO.getPath(), uid);
                    } else {
                        // 生成导入记录
                        ZonedDateTime dateNow = DateTimeUtils.dateNow(propertyDTO.getTimezone());
                        revenueImportLogService.handleSaveSystemImportRecord(propertyDTO, RevenueImportCons.MANAGER_FLASH,
                                dateNow.toEpochSecond(), dateRange.get(JobParameterDTO.START_DATE), dateRange.get(JobParameterDTO.END_DATE),
                                importResult ? ReportImportResultCons.IMPORT_RESULT_SUCCESS : ReportImportResultCons.IMPORT_RESULT_FAIL,
                                eventBodyDTO.getPath());
                    }
                }
            }
        }

        /**
         * 解析报告
         *
         * @param eventBodyDTO 事件体
         * @param propertyDTO  资产DTO
         * @param parser       解析器
         * @return java.lang.Integer
         * @author lichen
         * @date 2025/1/10
         */
        private ManagerFlashDTO parseReport(EventBodyDTO eventBodyDTO, PropertyDTO propertyDTO, IManagerFlashParse parser) throws ParseReportException {
            try (InputStream inputStream = amazonS3Service.getFile(eventBodyDTO.getPath())) {
                return parser.parse(inputStream, propertyDTO);
            } catch (Exception e) {
                throw new ListenerException("parse Manager flash report error", e);
            }
        }

        /**
         * 解析报告
         *
         * @param source 来源
         * @return cloud.wconnect.rateshop.service.revenue.managerflash.IManagerFlashParse
         * @author lichen
         * @date 2026/1/26
         */
        private IManagerFlashParse getParser(String source) throws ParseReportException {
            IManagerFlashParse parser = null;
            Map<String, IManagerFlashParse> beansOfType = applicationContext.getBeansOfType(IManagerFlashParse.class);
            for (IManagerFlashParse bean : beansOfType.values()) {
                if (bean.supports(source)) {
                    parser = bean;
                    break;
                }
            }
            return parser;
        }

        /**
         * 发送邮件
         *
         * @param propertyAbbr 资产标识
         * @param exceptionMsg 异常消息
         * @param s3Key        文件S3Key
         * @return void
         * @author lichen
         * @date 2025/1/10
         */
        private void sendAlertEmail(String propertyAbbr, String exceptionMsg, String s3Key) {
            String subject = "[Warning] - Handle Manager Flash/Service Report error";
            //邮件内容
            String mailContent = MessageFormat.format("SNS Subject:{0}<br/>Business:{1}<br/>Property:{2}<br/>Content:{3}<br/>S3Key:{4}",
                    SUBJECT, BUSINESS, propertyAbbr, exceptionMsg, s3Key);
            //发送alert
            mailInternalService.sendAlertEmail(subject, mailContent);
        }

        /**
         * 防止并发操作
         *
         * @param messageId 消息事件 id
         * @return java.lang.Boolean
         * @author lichen
         * @date 2025/1/10
         */
        private Boolean preventConcurrency(String messageId) {
            return redisTemplate.opsForValue().setIfAbsent(
                    KeyPrefixEnum.KEY_PREFIX_FOR_MESSAGE.getDesc() + StringUtils.join(Lists.newArrayList(SUBJECT, BUSINESS, messageId), "."),
                    0L, 1, TimeUnit.DAYS);
        }

        /**
         * 保存事件最近处理时刻
         *
         * @param abbrName 资产标识
         * @return void
         * @author lichen
         * @date 2025/1/10
         */
        private void updateLastTime(String abbrName) {
            //DateTimeUtils.nowTimestamp() 返回long 类型，存储进redis后，再获取是Integer类型。两边类型不一致，所以直接存储String类型
            redisTemplate.opsForValue().set(
                    KeyPrefixEnum.KEY_PREFIX_FOR_PROCESSING.getDesc() + StringUtils.join(Lists.newArrayList(SUBJECT, BUSINESS, abbrName), "."),
                    String.valueOf(DateTimeUtils.dateTimeNowOfSecond(defaultTimezone)));
        }

        /**
         * 获取报告数据日期范围
         *
         * @param propertyDTO 资产
         * @param parameter   事件体参数
         * @param logId       日志 id
         * @return java.util.Map<java.lang.String, java.lang.Long>
         * @author lichen
         * @date 2025/1/10
         */
        private Map<String, Long> getDateRange(PropertyDTO propertyDTO, Map<String, Object> parameter, Long logId) {
            // 自动下发
            if (Objects.isNull(logId)) {
                //报告数据日期
                return schedulerJobService.getDateRange(propertyDTO, RevenueImportCons.MANAGER_FLASH);
            }
            // 手动导入
            Map<String, Long> dateRange = Maps.newHashMap();
            Object startDateObj = parameter.get(EventBodyParamEnum.START_DATE.getDesc());
            Object endDateObj = parameter.get(EventBodyParamEnum.END_DATE.getDesc());
            if (Objects.nonNull(startDateObj) && Objects.nonNull(endDateObj)) {
                dateRange.put(EventBodyParamEnum.START_DATE.getDesc(), Long.parseLong(startDateObj.toString()));
                dateRange.put(EventBodyParamEnum.END_DATE.getDesc(), Long.parseLong(endDateObj.toString()));
            }
            return dateRange;
        }

        /**
         * 获取有效的资产数据
         *
         * @param tenantSymbol 租户标识
         * @param propertyAbbr 资产标识
         * @return cloud.wconnect.commonlib.pojo.dto.PropertyDTO
         * @author lichen
         * @date 2025/1/10
         */
        private PropertyDTO getEffectiveProperty(String tenantSymbol, String propertyAbbr) {
            PropertyDTO propertyDTO = propertyInternalService.getOne(propertyAbbr, tenantSymbol);
            if (Objects.isNull(propertyDTO)) {
                log.warn("RevenueManagerFlashMTDYesterdayListener.handle end... The property:{} is not exist", propertyAbbr);
                return null;
            }
            if (!propertyDTO.getStatus()) {
                log.warn("RevenueManagerFlashMTDYesterdayListener.handle end...  The property:{} is closed", propertyAbbr);
                return null;
            }

            if (!commonService.checkOpenFunction(propertyDTO, FunctionIdConstant.REVENUE)) {
                log.warn("RevenueManagerFlashMTDYesterdayListener.handle end... The property:{} has not opened daily revenue function", propertyAbbr);
                return null;
            }
            return propertyDTO;
        }
    }