# RevenueDailySummaryMarketCodeListener.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.RoomDayBO;
    import cloud.wconnect.rateshop.service.AmazonS3Service;
    import cloud.wconnect.rateshop.service.revenue.IRevenueDailySummaryTaService;
    import cloud.wconnect.rateshop.service.revenue.IRevenueImportLogService;
    import cloud.wconnect.rateshop.service.revenue.IRevenueSchedulerJobService;
    import cloud.wconnect.rateshop.service.revenue.marketcode.IMarketCodeFileParse;
    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.Component;

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

    /**
     * 处理Market Code报告
     * 下发规则：5AM 前一日数据
     *
     * @author lichen
     * @date 2024/3/27
     */
    @Slf4j
    @Component
    public class RevenueDailySummaryMarketCodeListener {

        @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 IRevenueDailySummaryTaService taService;
        @Autowired
        private CommonService commonService;
        /**
         * subject
         */
        private final String SUBJECT = EventSubjectEnum.MARKET_CODE.getSubject();
        /**
         * 业务名称
         */
        private final String BUSINESS = BusinessEnum.REVENUE.getBusiness();

        /**
         * 处理报告监听器
         *
         * @param event 事件对象
         * @return void
         * @author lichen
         * @date 2024/3/27
         */
        @Async
        @EventListener
        public void handle(SnsHttpEvent event) {
            if (!StringUtils.equals(SUBJECT, event.getSubject())) {
                return;
            }
            log.info("Revenue Process MarketCode.start...");
            if (!preventConcurrency(event.getMessageId())) {
                log.warn("Revenue Process MarketCode.end... A machine has been executed");
                return;
            }
            if (StringUtils.isBlank(event.getBody())) {
                log.warn("Revenue Process MarketCode.end... event body is blank.");
                return;
            }

            EventBodyDTO eventBodyDTO = JsonUtils.convertStringToObject(objectMapper, event.getBody(), EventBodyDTO.class);
            Map<String, Object> parameter = eventBodyDTO.getParameter();
            List<String> abbrNameList = (List<String>) parameter.get(EventBodyParamEnum.PROPERTY_ABBR.getDesc());
            String propertyAbbr = abbrNameList.get(0);
            //获取租户标识
            String tenantSymbol = (String) parameter.get(EventBodyParamEnum.TENANT_SYMBOL.getDesc());
            //获取资产
            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("RevenueDailySummaryMarketCodeListener.handle end... property not support this pms type, propertyId:{}, supportPmsType:{}, currentPmsType:{}",
                        propertyDTO.getId(), propertyDTO.getPmsType(), 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("RevenueDailySummaryMarketCodeListener.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());

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

                List<RoomDayBO> roomDayBOS = dateRange.values().stream().distinct().map(date -> new RoomDayBO(date, roomDay)).toList();
                taService.saveOrUpdate(propertyDTO, roomDayBOS);
                log.info("Revenue Process MarketCode.end...");
            } catch (Exception e) {
                importResult = false;
                if (RateLimitUtils.tryAcquire(this, propertyAbbr)) {
                    sendAlertEmail(propertyAbbr, e.getMessage(), eventBodyDTO.getPath());
                }
                log.error("Revenue Process MarketCode.end... Process error.", e);
            } finally {
                if (uid == 0) {
                    updateLastTime(propertyAbbr);
                }

                if (Objects.isNull(logId)) {//自动下发
                    // 生成导入记录
                    String timezone = propertyDTO.getTimezone();
                    revenueImportLogService.handleSaveSystemImportRecord(propertyDTO, RevenueImportCons.MARKET_CODE,
                            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.MARKET_CODE,
                                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
         * @return java.lang.Integer
         * @author lichen
         * @date 2024/3/27
         */
        private Integer parseReport(EventBodyDTO eventBodyDTO, PropertyDTO propertyDTO) throws ParseReportException{
            String source = (String) eventBodyDTO.getParameter().get(EventBodyParamEnum.SOURCE.getDesc());
            Map<String, IMarketCodeFileParse> beansOfType = applicationContext.getBeansOfType(IMarketCodeFileParse.class);
            Collection<IMarketCodeFileParse> parsers = beansOfType.values();
            for (IMarketCodeFileParse parser : parsers) {
                if (parser.supports(source)) {
                    try (InputStream inputStream = amazonS3Service.getFile(eventBodyDTO.getPath())) {
                        return parser.parse(inputStream, propertyDTO);
                    } catch (Exception e) {
                        throw new ListenerException("parse market code report error", e);
                    }
                }
            }
            throw new ListenerException("Not found report parser");
        }

        /**
         * 发送预警邮件
         *
         * @param propertyAbbr 资产简称
         * @param exceptionMsg 报错内容
         * @param s3Key        s3路径
         * @return void
         * @author lichen
         * @date 2024/3/26
         */
        private void sendAlertEmail(String propertyAbbr, String exceptionMsg, String s3Key) {
            String subject = "[Warning] - Handle Market Code 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 2024/3/27
         */
        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 2024/3/27
         */
        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 数据日期范围
         * @author lichen
         * @date 2024/6/1
         */
        private Map<String, Long> getDateRange(PropertyDTO propertyDTO, Map<String, Object> parameter, Long logId) {
            // 自动下发
            if (Objects.isNull(logId)) {
                //报告数据日期
                return schedulerJobService.getDateRange(propertyDTO, RevenueImportCons.MARKET_CODE);
            }
            // 手动导入
            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 PropertyDTO
         * @author lichen
         * @date 2024/6/1
         */
        private PropertyDTO getEffectiveProperty(String tenantSymbol, String propertyAbbr) {
            PropertyDTO propertyDTO = propertyInternalService.getOne(propertyAbbr, tenantSymbol);
            if (Objects.isNull(propertyDTO)) {
                log.warn("RevenueDailySummaryMarketCodeListener.handle end... The property:{} is not exist", propertyAbbr);
                return null;
            }
            if (!propertyDTO.getStatus()) {
                log.warn("RevenueDailySummaryMarketCodeListener.handle end...  The property:{} is closed", propertyAbbr);
                return null;
            }

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

    }