# ChargeAdjustmentListener.java

    package cloud.wconnect.finance.messagelistener.chargeback;

    import cloud.wconnect.commonlib.cons.EventRedisKeyPrefixEnum;
    import cloud.wconnect.commonlib.cons.MoudleEventSubjectEnum;
    import cloud.wconnect.commonlib.pojo.ModuleEvent;
    import cloud.wconnect.commonlib.pojo.bo.adj.AdjBO;
    import cloud.wconnect.commonlib.pojo.bo.adj.BatchAdjBO;
    import cloud.wconnect.commonlib.pojo.dto.PropertyDTO;
    import cloud.wconnect.commonlib.redis.PropertyI18nRedisService;
    import cloud.wconnect.commonlib.service.MailInternalService;
    import cloud.wconnect.commonlib.util.JsonUtils;
    import cloud.wconnect.commonlib.util.RateLimitUtils;
    import cloud.wconnect.finance.cons.BusinessEnum;
    import cloud.wconnect.finance.service.chargeback.ICbCaseIwcAdRequestService;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.google.common.collect.Lists;
    import lombok.RequiredArgsConstructor;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.commons.collections4.CollectionUtils;
    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.util.List;
    import java.util.concurrent.TimeUnit;

    /**
     * 处理Adjustment事件
     *
     * @author lichen
     * @date 2026/2/9
     */
    @Slf4j
    @Component
    @RequiredArgsConstructor
    public class ChargeAdjustmentListener {

        private final ObjectMapper objectMapper;
        private final RedisTemplate<String, Object> redisTemplate;
        private final PropertyI18nRedisService propertyI18nRedisService;
        private final ICbCaseIwcAdRequestService cbCaseIwcAdRequestService;
        private final MailInternalService mailInternalService;
        private static final String SUBJECT = MoudleEventSubjectEnum.ADJUSTMENT_AMOUNT.getSubject();
        private static final String BUSINESS = BusinessEnum.CHARGEBACK_JOURNAL.getBusiness();

        /**
         * 处理Adjustment数据
         *
         * @param event 事件
         * @author lichen
         * @date 2026/2/9
         */
        @Async
        @EventListener
        public void handleAdjustment(ModuleEvent event) {
            if (!StringUtils.equals(SUBJECT, event.getSubject())) {
                return;
            }
            log.info("ChargeAdjustmentListener.handle start...");
            if (!preventConcurrency(event.getMessageId())) {
                return;
            }
            if (StringUtils.isBlank(event.getBody())) {
                log.warn("ChargeAdjustmentListener.handle end... event body is blank.");
                return;
            }

            // body 转换为对象
            BatchAdjBO batchAdjBO = JsonUtils.convertStringToObject(objectMapper, event.getBody(), BatchAdjBO.class);
            if (CollectionUtils.isEmpty(batchAdjBO.getData())) {
                log.warn("ChargeAdjustmentListener.handle end... adj data is empty.");
                return;
            }
            PropertyDTO propertyDTO = propertyI18nRedisService.get(batchAdjBO.getPropertyId());

            try {
                List<AdjBO> adjBOList = batchAdjBO.getData();
                if (batchAdjBO.getActionType() == BatchAdjBO.ACTION_TYPE_SAVE) {
                    // 保存数据
                    cbCaseIwcAdRequestService.save(propertyDTO.getId(), adjBOList, batchAdjBO.getUpdateTime());
                } else {
                    // 删除数据
                    cbCaseIwcAdRequestService.delete(propertyDTO.getId(), adjBOList);
                }
            } catch (Exception e) {
                if (RateLimitUtils.tryAcquire(this, propertyDTO.getAbbr())) {
                    sendAlertEmail(propertyDTO.getAbbr(), e.getMessage(), event.getBody());
                }
                log.error("ChargeAdjustmentListener.handle error: {}", e.getMessage());
            }
        }

        /**
         * 防止并发操作
         *
         * @param messageId 消息事件 id
         * @return boolean true：未并发，当前线程可以执行；false：检测到并发，当前线程应放弃执行
         * @author lichen
         * @date 2026/2/9
         */
        private Boolean preventConcurrency(String messageId) {
            String key = EventRedisKeyPrefixEnum.KEY_PREFIX_FOR_MESSAGE.getDesc() +
                    StringUtils.join(Lists.newArrayList(SUBJECT, BUSINESS, messageId), ".");
            return redisTemplate.opsForValue().setIfAbsent(key, 0L, 1, TimeUnit.DAYS);
        }

        /**
         * 发送预警邮件
         *
         * @param abbrName property abbr
         * @param content  报错信息
         * @param body     消息体
         * @author lichen
         * @date 2026/2/14
         */
        private void sendAlertEmail(String abbrName, String content, String body) {
            String subject = "[Warning] - Handle Adjustment Exception";
            String mailContent = MessageFormat.format("SNS Subject:{0}<br/>Business:{1}<br/>Property:{2}<br/>Content:{3}<br/>MessageBody:{4}",
                    SUBJECT, BUSINESS, abbrName, content, body);
            mailInternalService.sendAlertEmail(subject, mailContent);
        }

    }