# ChargebackAdjustmentListener.java

    package cloud.wconnect.frontoffice.messagelistener.adjustment;

    import cloud.wconnect.commonlib.cons.FunctionIdConstant;
    import cloud.wconnect.commonlib.cons.MoudleEventSubjectEnum;
    import cloud.wconnect.commonlib.cons.OperationAdjCons;
    import cloud.wconnect.commonlib.pojo.ModuleEvent;
    import cloud.wconnect.commonlib.pojo.bo.adj.chargeback.ChargebackBatchAdjBO;
    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.frontoffice.cons.BusinessEnum;
    import cloud.wconnect.frontoffice.cons.KeyPrefixEnum;
    import cloud.wconnect.frontoffice.service.adjustment.IAdjEventReceiveHandleService;
    import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.google.common.collect.Lists;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.commons.lang3.StringUtils;
    import org.springframework.beans.factory.annotation.Autowired;
    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.concurrent.TimeUnit;

    /**
     * 消费主题：adj 的事件
     *
     * @author lichen
     * @date 2023/9/26
     */
    @Slf4j
    @Service
    public class ChargebackAdjustmentListener {

        @Autowired
        private RedisTemplate<String, Object> redisTemplate;
        @Autowired
        private ObjectMapper objectMapper;
        @Autowired
        private MailInternalService mailInternalService;
        @Autowired
        private PropertyI18nRedisService propertyI18nRedisService;
        @Autowired
        private IAdjEventReceiveHandleService adjListenerService;
        @Autowired
        private CommonService commonService;
        /**
         * 事件主题
         */
        private static final String SUBJECT = MoudleEventSubjectEnum.CHARGEBACK_ADJ.getSubject();
        /**
         * 业务名称
         */
        private static final String BUSINESS = BusinessEnum.ADJUSTMENT_REQUESTS.getBusiness();

        /**
         * 异步监听事件处理
         *
         * @param event 事件体
         * @author lichen
         * @date 2023/9/25
         */
        @Async
        @EventListener
        public void handleAdjustment(ModuleEvent event) {
            if (!StringUtils.equals(SUBJECT, event.getSubject())) {
                return;
            }
            log.info("ChargebackAdjustmentListener.handle start...");
            if (!preventConcurrency(event.getMessageId())) {
                return;
            }
            if (StringUtils.isBlank(event.getBody())) {
                log.warn("ChargebackAdjustmentListener.handle end... event body is blank.");
                return;
            }
            String propertyAbbr = "";
            try {
                // body 转换为对象
                String body = event.getBody();
                log.info("ChargebackAdjustmentListener.handle receive adj,body:{}", body);

                ChargebackBatchAdjBO chargebackBatchAdjBO = JsonUtils.convertStringToObject(objectMapper, body, ChargebackBatchAdjBO.class);
                if (CollectionUtils.isEmpty(chargebackBatchAdjBO.getAdjs())) return;

                PropertyDTO propertyDTO = propertyI18nRedisService.get(chargebackBatchAdjBO.getPropertyId());
                propertyAbbr = propertyDTO.getAbbr();
                if (!propertyDTO.getStatus()) return;
                //校验是否开通功能
                if (!commonService.checkOpenFunction(propertyDTO, FunctionIdConstant.ADJUSTMENT_REQUESTS)) {
                    log.warn("ChargebackAdjustmentListener.end... the property has not opened the adjustment function;property:{}", propertyAbbr);
                    return;
                }
                Integer operationType = chargebackBatchAdjBO.getOperationType();
                if (operationType == OperationAdjCons.SAVE) {
                    adjListenerService.save(chargebackBatchAdjBO, propertyDTO);
                } else if (operationType == OperationAdjCons.APPROVED) {
                    adjListenerService.approved(chargebackBatchAdjBO, propertyDTO);
                } else if (operationType == OperationAdjCons.DELETE) {
                    adjListenerService.delete(chargebackBatchAdjBO, propertyDTO);
                } else if (operationType == OperationAdjCons.COMMENT) {
                    adjListenerService.updateComment(chargebackBatchAdjBO, propertyDTO);
                }else if (operationType == OperationAdjCons.BIND) {
                    adjListenerService.bind(chargebackBatchAdjBO, propertyDTO);
                }else if (operationType == OperationAdjCons.UNBIND){
                    adjListenerService.unbind(chargebackBatchAdjBO, propertyDTO);
                }
            } catch (Exception e) {
                log.error("Handle Chargeback Adjustment data exception", e);
                //发送预警邮件
                if (RateLimitUtils.tryAcquire(this, propertyAbbr)) {
                    sendAlertEmail(propertyAbbr, e.getMessage());
                }
            }
        }

        /**
         * 防止并发操作
         *
         * @param messageId 消息事件 id
         * @return boolean true：未并发，当前线程可以执行；false：检测到并发，当前线程应放弃执行
         * @author lichen
         * @date 2023/9/26
         */
        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 propertyAbbr 资产简称
         * @param exceptionMsg 报错内容
         * @return void
         * @author lichen
         * @date 2024/2/22
         */
        private void sendAlertEmail(String propertyAbbr, String exceptionMsg) {
            //主题
            String subject = "[Warning] - Handle the Chargeback Adjustment Request data is 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);
        }
    }