# HKRoomsRentedIndexListener.java

    package cloud.wconnect.workperformance.messagelistener.hkefficiency;

    import cloud.wconnect.commonlib.cons.BaseConstant;
    import cloud.wconnect.commonlib.cons.EventRedisKeyPrefixEnum;
    import cloud.wconnect.commonlib.cons.FunctionIdConstant;
    import cloud.wconnect.commonlib.cons.MoudleEventSubjectEnum;
    import cloud.wconnect.commonlib.pojo.ModuleEvent;
    import cloud.wconnect.commonlib.pojo.bo.m3.DailyOperatingStatisticsIndexBO;
    import cloud.wconnect.commonlib.pojo.bo.m3.DailyOperatingStatisticsIndexValueBO;
    import cloud.wconnect.commonlib.pojo.dto.PropertyDTO;
    import cloud.wconnect.commonlib.redis.PropertyI18nRedisService;
    import cloud.wconnect.commonlib.service.CommonService;
    import cloud.wconnect.commonlib.service.MailInternalService;
    import cloud.wconnect.commonlib.util.DateTimeUtils;
    import cloud.wconnect.commonlib.util.JsonUtils;
    import cloud.wconnect.commonlib.util.RateLimitUtils;
    import cloud.wconnect.workperformance.cons.BusinessEnum;
    import cloud.wconnect.workperformance.pojo.bo.hkefficiency.HkOperatingStatisticsListBO;
    import cloud.wconnect.workperformance.service.hkefficiency.IHkEfficiencyService;
    import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
    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.context.event.EventListener;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.scheduling.annotation.Async;
    import org.springframework.stereotype.Component;

    import java.text.MessageFormat;
    import java.time.LocalDate;
    import java.util.Collections;
    import java.util.List;
    import java.util.concurrent.TimeUnit;

    /**
     * 处理Room Rented指标监听器
     *
     * @author lichen
     * @date 2025/10/15
     */
    @Slf4j
    @Component
    public class HKRoomsRentedIndexListener {

        @Resource
        private IHkEfficiencyService housekeepingEfficiencyService;
        @Resource
        private ObjectMapper objectMapper;
        @Resource
        private MailInternalService mailInternalService;
        @Resource
        private RedisTemplate<String, Object> jsonRedisTemplate;
        @Resource
        private CommonService commonService;
        @Resource
        private PropertyI18nRedisService propertyI18nRedisService;

        private static final String SUBJECT = MoudleEventSubjectEnum.M3_OPERATING_STATISTICS_ROOMS_RENTED.getSubject();
        private static final String BUSINESS = BusinessEnum.HOUSEKEEPING_EFFICIENCY.getBusiness();

        /**
         * 异步监听事件处理
         *
         * @param event 事件体
         * @author lichen
         * @date 2025/10/15
         */
        @Async
        @EventListener
        public void handleRoomsRentedIndex(ModuleEvent event) {
            if (!StringUtils.equals(SUBJECT, event.getSubject())) {
                return;
            }
            if (!preventConcurrency(event.getMessageId())) {
                return;
            }
            log.info("HKRoomRentedIndexListener.handle start");
            if (StringUtils.isBlank(event.getBody())) {
                log.warn("HKRoomRentedIndexListener.handle end... event body is blank.");
                return;
            }
            String propertyAbbr = "";
            try {
                //消息转化为BO
                DailyOperatingStatisticsIndexBO dailyOperatingStatisticsIndexBO = JsonUtils.convertStringToObject(objectMapper, event.getBody(),
                        DailyOperatingStatisticsIndexBO.class);
                Integer propertyId = dailyOperatingStatisticsIndexBO.getPropertyId();
                List<DailyOperatingStatisticsIndexValueBO> indexValues = dailyOperatingStatisticsIndexBO.getIndexValues();
                if (CollectionUtils.isEmpty(indexValues)) {
                    log.warn("HKRoomRentedIndexListener.handle end... indexValues is empty.");
                    return;
                }

                PropertyDTO propertyDTO = propertyI18nRedisService.get(propertyId);
                propertyAbbr = propertyDTO.getAbbr();
                if (!propertyDTO.getStatus()) return;
                //校验是否开通功能
                if (!commonService.checkOpenFunction(propertyDTO, FunctionIdConstant.HOUSEKEEPING_EFFICIENCY)) {
                    log.warn("HKRoomRentedIndexListener.handle end... the property has not opened the Housekeeping efficiency function;property:{}", propertyAbbr);
                    return;
                }
                // 转化为BO
                List<HkOperatingStatisticsListBO> boList = indexValues.stream().map(indexValue -> {
                    HkOperatingStatisticsListBO bo = new HkOperatingStatisticsListBO();
                    bo.setProperty(propertyDTO.getAbbr());
                    bo.setRoomsRented(indexValue.getIndexValue().intValue());
                    //yyyyMMdd转换成yyyy-MM-dd
                    LocalDate localDate = DateTimeUtils.strToLocalDate(indexValue.getDate().toString(), BaseConstant.DATE_FORMAT_YYYYMMDD);
                    String theDay = DateTimeUtils.localDateToStr(localDate, BaseConstant.DATE_FORMAT_YYYY_MM_DD);
                    bo.setTheDay(theDay);
                    return bo;
                }).toList();

                //组装数据日期
                List<Integer> dateList = indexValues.stream().map(DailyOperatingStatisticsIndexValueBO::getDate).toList();
                Integer startDate = Collections.min(dateList);
                Integer endDate = Collections.max(dateList);

                //处理指标数据
                housekeepingEfficiencyService.handleHKOperatingStatisticsByM3Api(propertyDTO, boList, 0, startDate, endDate);
                log.info("HKRoomRentedIndexListener.handle end");
            } catch (Exception e) {
                log.error("HKRoomRentedIndexListener.handle end... error:{}", e.getMessage());
                //发送预警邮件
                if (RateLimitUtils.tryAcquire(this, propertyAbbr)) {
                    sendAlertEmail(propertyAbbr, e.getMessage());
                }
            }
        }

        /**
         * 防止并发操作
         *
         * @param messageId 消息事件 id
         * @return java.lang.Boolean
         * @author lichen
         * @date 2025/10/15
         */
        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 资产简称
         * @param exceptionMsg 报错内容
         * @author lichen
         * @date 2025/10/15
         */
        private void sendAlertEmail(String propertyAbbr, String exceptionMsg) {
            //主题
            String subject = "[Warning] - HK Efficiency Handle Room Rented Index exception.";

            //邮件内容
            String mailContent = MessageFormat.format("SNS Subject:{0}<br/>Business:{1}<br/>Property:{2}<br/>Content:{3}",
                    SUBJECT, BUSINESS, propertyAbbr, exceptionMsg);
            //发送alert
            mailInternalService.sendAlertEmail(subject, mailContent);
        }

    }