# BlackListListener.java

    package cloud.wconnect.frontoffice.messagelistener.badguest;

    import cloud.wconnect.commonlib.component.BeanMapper;
    import cloud.wconnect.commonlib.cons.FunctionIdConstant;
    import cloud.wconnect.commonlib.cons.MoudleEventSubjectEnum;
    import cloud.wconnect.commonlib.cons.OperationBlackCons;
    import cloud.wconnect.commonlib.pojo.ModuleEvent;
    import cloud.wconnect.commonlib.pojo.bo.black.BlackBO;
    import cloud.wconnect.commonlib.pojo.bo.black.OperationBlackBO;
    import cloud.wconnect.commonlib.pojo.dto.PropertyDTO;
    import cloud.wconnect.commonlib.service.CommonService;
    import cloud.wconnect.commonlib.service.MailInternalService;
    import cloud.wconnect.commonlib.service.PropertyInternalService;
    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.entity.badguest.BadGuest;
    import cloud.wconnect.frontoffice.mapper.badguest.BadGuestMapper;
    import cloud.wconnect.frontoffice.service.badguest.IBadGuestService;
    import com.baomidou.dynamic.datasource.annotation.DS;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.google.common.collect.Lists;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.commons.collections.CollectionUtils;
    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.Component;

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

    /**
     * 接收module-event发送的主题：save_black 消息
     *
     * @author lichen
     * @date 2023/9/25
     */
    @Slf4j
    @Component
    @DS("logbook")
    public class BlackListListener {

        @Autowired
        private MailInternalService mailInternalService;
        @Autowired
        private PropertyInternalService propertyInternalService;
        @Autowired
        private RedisTemplate<String, Object> redisTemplate;
        @Autowired
        private ObjectMapper objectMapper;
        @Autowired
        private IBadGuestService badGuestService;
        @Autowired
        private BadGuestMapper badGuestMapper;
        @Autowired
        private BeanMapper beanMapper;
        @Autowired
        private CommonService commonService;

        /**
         * 事件主题
         */
        private static final String SUBJECT = MoudleEventSubjectEnum.SAVE_BLACK.getSubject();
        /**
         * 业务名称
         */
        private static final String BUSINESS = BusinessEnum.GUESTS_BLACKLIST.getBusiness();

        /**
         * 异步监听事件处理
         *
         * @param event 事件体
         * @return void
         * @author lichen
         * @date 2023/9/25
         */
        @Async
        @EventListener
        public void saveBlackList(ModuleEvent event) {
            if (!StringUtils.equals(SUBJECT, event.getSubject())) {
                return;
            }
            log.warn("BlackListListener.handle start...");
            if (!preventConcurrency(event.getMessageId())) {
                return;
            }
            if (StringUtils.isBlank(event.getBody())) {
                log.warn("BlackListListener.handle end... event body is blank.");
                return;
            }
            String propertyAbbr = "";
            try {
                // body 转换为对象
                OperationBlackBO operationBlackBO = JsonUtils.convertStringToObject(objectMapper, event.getBody(), OperationBlackBO.class);
                List<BlackBO> blackBOS = operationBlackBO.getBlacks();
                if (CollectionUtils.isEmpty(blackBOS)) return;

                //查询资产
                Integer propertyId = operationBlackBO.getPropertyId();
                PropertyDTO propertyDTO = propertyInternalService.getOne(propertyId);
                if (!propertyDTO.getStatus()) return;
                propertyAbbr = propertyDTO.getAbbr();
                //校验是否开通功能
                if (!commonService.checkOpenFunction(propertyDTO, FunctionIdConstant.GUEST_BLACK_LIST)) {
                    log.warn("BlackListListener.end... the property has not opened the DNR(Do Not Rent) function;property:{}", propertyAbbr);
                    return;
                }

                //转化为黑名单数据
                List<BadGuest> badGuests = beanMapper.mapList(blackBOS, BadGuest.class, (bo, entity) -> {
                    entity.setCaseReason(bo.getActualReason());
                });

                if (OperationBlackCons.ADD == operationBlackBO.getOperationType()) {
                    //保存chargeback来源的数据
                    badGuestService.saveBatchByChargeback(propertyDTO, blackBOS, badGuests);
                } else {
                    //根据客人姓名、入住日期、caseNumber查询chargeback来源的黑名单
                    List<BadGuest> alreadyBadGuests = badGuestMapper.listByGuestNameAndCheckInDateAndCaseNumber(propertyId, badGuests);
                    if (CollectionUtils.isNotEmpty(alreadyBadGuests)) {
                        //批量作废黑名单
                        badGuestService.batchCancellation(propertyDTO, alreadyBadGuests.stream().map(BadGuest::getId).toList());
                    }
                }
            } catch (Exception e) {
                // 发送预警邮件通知解析报告异常
                if (RateLimitUtils.tryAcquire(this, propertyAbbr)) {
                    sendAlertEmail(propertyAbbr, e.getMessage());
                }
                log.error("Handle BlackList data exception", e);
            }
        }

        /**
         * 防止并发操作
         *
         * @param messageId 消息事件 id
         * @return boolean true：未并发，当前线程可以执行；false：检测到并发，当前线程应放弃执行
         * @author zc
         * @date 2023/9/13
         */
        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 Do Not Rent data error";
            //邮件内容
            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);
        }

    }