# HotelKpIBudgetDatabaseListener.java

    package cloud.wconnect.workperformance.messagelistener.hotelkpi.modelevent;

    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.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.JsonUtils;
    import cloud.wconnect.commonlib.util.RateLimitUtils;
    import cloud.wconnect.workperformance.cons.BusinessEnum;
    import cloud.wconnect.workperformance.cons.hotelkpi.HotelKpiMetricsEnum;
    import cloud.wconnect.workperformance.cons.hotelkpi.HotelKpiTriggerTypeCons;
    import cloud.wconnect.workperformance.pojo.bo.modelevent.budgetdb.BudgetDatabaseBO;
    import cloud.wconnect.workperformance.service.hotelkpi.IHotelKpiBudgetDatabaseService;
    import cloud.wconnect.workperformance.service.hotelkpi.IHotelKpiCommonSummaryService;
    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.Service;

    import java.text.MessageFormat;
    import java.util.List;
    import java.util.Objects;
    import java.util.concurrent.TimeUnit;

    /**
     * 事件监听：Budget Database
     *
     * @author zc
     * @date 2025/08/26
     */
    @Slf4j
    @Service
    public class HotelKpIBudgetDatabaseListener {
        @Resource
        private IHotelKpiBudgetDatabaseService budgetDatabaseService;
        @Resource
        private IHotelKpiCommonSummaryService commonSummaryService;
        @Resource
        private MailInternalService mailInternalService;
        @Resource
        private PropertyI18nRedisService propertyI18nRedisService;
        @Resource
        private RedisTemplate<String, Object> jsonRedisTemplate;
        @Resource
        private ObjectMapper objectMapper;
        @Resource
        private CommonService commonService;

        private static final String SUBJECT = MoudleEventSubjectEnum.BUDGET_DATABASE.getSubject();
        private static final String BUSINESS = BusinessEnum.HOTEL_KPI.getBusiness();

        /**
         * 异步监听事件处理
         *
         * @param event 事件体
         * @author zc
         * @date 2025/8/26
         */
        @Async
        @EventListener
        public void handle(ModuleEvent event) {
            if (!StringUtils.equals(SUBJECT, event.getSubject())) {
                return;
            }

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

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

            // body 转换为对象
            BudgetDatabaseBO eventBO = JsonUtils.convertStringToObject(objectMapper,
                    event.getBody(), BudgetDatabaseBO.class);

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

            try {
                // 保存数据
                budgetDatabaseService.save(eventBO);
                // 处理数据
                handleData(propertyDTO, eventBO.getYear());

                log.info("HotelKpBudgetDatabaseListener.handle end...");
            } catch (Exception e) {
                String propertyAbbr = propertyDTO.getAbbr();
                if (RateLimitUtils.tryAcquire(this, propertyAbbr)) {
                    sendAlertEmail(propertyAbbr, e.getMessage(), event.getBody());
                }
                log.error("HotelKpBudgetDatabaseListener.handle end... Process error.", e);
            }
        }

        /**
         * 处理数据
         *
         * @param propertyDTO 资产
         * @param year        年份(yyyy)
         * @author zc
         * @date 2025/8/26
         */
        public void handleData(PropertyDTO propertyDTO, int year) {
            List<Integer> metricsTypeList = List.of(HotelKpiMetricsEnum.OCC.getMetricsType(),
                    HotelKpiMetricsEnum.ADR.getMetricsType(), HotelKpiMetricsEnum.RGI.getMetricsType(),
                    HotelKpiMetricsEnum.RM_REVENUE.getMetricsType(), HotelKpiMetricsEnum.FB_RESTAURANT.getMetricsType(),
                    HotelKpiMetricsEnum.FB_BANQUET.getMetricsType(), HotelKpiMetricsEnum.FB_REVENUE.getMetricsType(),
                    HotelKpiMetricsEnum.OTHER_REVENUE.getMetricsType(), HotelKpiMetricsEnum.TOTAL_REVENUE.getMetricsType(),
                    HotelKpiMetricsEnum.RM_OTHER.getMetricsType());
            for (int metricsType : metricsTypeList) {
                commonSummaryService.triggerSetMetricsData(propertyDTO, HotelKpiTriggerTypeCons.BUDGET_DATABASE,
                        year, year, metricsType);
            }
        }

        /**
         * 获取有效的资产数据
         *
         * @param propertyId 资产 id
         * @return PropertyDTO
         * @author zc
         * @date 2025/8/23
         */
        private PropertyDTO getEffectiveProperty(int propertyId) {
            PropertyDTO propertyDTO = propertyI18nRedisService.get(propertyId);
            if (Objects.isNull(propertyDTO)) {
                log.warn("HotelKpBudgetDatabaseListener.handle end... The property:{} is not exist", propertyId);
                return null;
            }
            if (!propertyDTO.getStatus()) {
                log.warn("HotelKpBudgetDatabaseListener.handle end...  The property:{} is closed", propertyId);
                return null;
            }
            if (!commonService.checkOpenFunction(propertyDTO, FunctionIdConstant.HOTEL_KPI)) {
                log.warn("HotelKpBudgetDatabaseListener.handle end... The property:{} has not opened hotel kpi function", propertyId);
                return null;
            }
            return propertyDTO;
        }

        /**
         * 发送预警邮件
         *
         * @param propertyAbbr     资产简称
         * @param exceptionMessage 异常信息
         * @param eventBody        事件体
         * @author zc
         * @date 2025/8/23
         */
        private void sendAlertEmail(String propertyAbbr, String exceptionMessage, String eventBody) {
            String subject = "[Warning] - Handle [W-connect Budget Database] data error";
            String content = "Process error: " + exceptionMessage;
            String mailContent = MessageFormat.format("Module SNS Subject:{0}<br/>Business:{1}<br/>Property:{2}<br/>Content:{3}<br/>EventBody:{4}",
                    SUBJECT, BUSINESS, propertyAbbr, content, eventBody);
            mailInternalService.sendAlertEmail(subject, mailContent);
        }

        /**
         * 防止并发操作
         *
         * @param messageId 消息事件 id
         * @return boolean true：未并发，当前线程可以执行；false：检测到并发，当前线程应放弃执行
         * @author zc
         * @date 2025/8/23
         */
        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);
        }
    }