# AdjUserCloseListener.java

    package cloud.wconnect.frontoffice.messagelistener.adjustment;

    import cloud.wconnect.commonlib.cons.FunctionIdConstant;
    import cloud.wconnect.commonlib.cons.MoudleEventSubjectEnum;
    import cloud.wconnect.commonlib.pojo.ModuleEvent;
    import cloud.wconnect.commonlib.pojo.bo.UserBO;
    import cloud.wconnect.commonlib.pojo.dto.PropertyBasicInfoDTO;
    import cloud.wconnect.commonlib.pojo.dto.PropertyDTO;
    import cloud.wconnect.commonlib.pojo.dto.UserDTO;
    import cloud.wconnect.commonlib.redis.PropertyI18nRedisService;
    import cloud.wconnect.commonlib.service.CommonService;
    import cloud.wconnect.commonlib.service.MailInternalService;
    import cloud.wconnect.commonlib.service.TenantInternalService;
    import cloud.wconnect.commonlib.service.UserInternalService;
    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.List;
    import java.util.Objects;
    import java.util.concurrent.TimeUnit;

    /**
     * 用户关闭事件
     *
     * @author yyt
     * @date 2023/9/26
     */
    @Slf4j
    @Service
    public class AdjUserCloseListener {

        @Autowired
        private RedisTemplate<String, Object> redisTemplate;
        @Autowired
        private ObjectMapper objectMapper;
        @Autowired
        private MailInternalService mailInternalService;
        @Autowired
        private PropertyI18nRedisService propertyI18nRedisService;
        @Autowired
        private UserInternalService userInternalService;
        @Autowired
        private IAdjEventReceiveHandleService adjListenerService;
        @Autowired
        private TenantInternalService tenantInternalService;
        @Autowired
        private CommonService commonService;

        /**
         * 事件主题
         */
        private static final String SUBJECT = MoudleEventSubjectEnum.USER_CLOSE.getSubject();

        /**
         * 业务名称
         */
        private static final String BUSINESS = BusinessEnum.ADJUSTMENT_REQUESTS.getBusiness();

        /**
         * 异步监听事件处理
         *
         * @param event 事件体
         * @author yyt
         * @date 2026/3/20
         */
        @Async
        @EventListener
        public void handleAdjustment(ModuleEvent event) {
            if (!StringUtils.equals(SUBJECT, event.getSubject())) {
                return;
            }
            log.info("AdjUserCloseListener.handle start...");
            if (!preventConcurrency(event.getMessageId())) {
                return;
            }
            if (StringUtils.isBlank(event.getBody())) {
                log.warn("AdjUserCloseListener.handle end... event body is blank.");
                return;
            }
            String tenantName = "";
            try {
                String body = event.getBody();
                UserBO userBO = JsonUtils.convertStringToObject(objectMapper, body, UserBO.class);
                Integer tenantId = userBO.getTenantId();
                Integer userId = userBO.getUserId();
                if (Objects.isNull(tenantId) || Objects.isNull(userId)) return;

                UserDTO user = userInternalService.getOne(tenantId, userId);
                if (user.getStatus()) {
                    log.warn("AdjUserCloseListener.handle end... user is effective.");
                    return;
                }
                List<Integer> propertyIds = user.getProperties().stream().map(PropertyBasicInfoDTO::getId).toList();
                List<PropertyDTO> effectiveProperties = propertyI18nRedisService.list(propertyIds).stream().filter(PropertyDTO::getStatus).toList();
                if (CollectionUtils.isEmpty(effectiveProperties)) {
                    log.warn("AdjUserCloseListener.handle end... property is not effective.");
                    return;
                }

                tenantName = tenantInternalService.getTenantById(tenantId).getName();

                for (PropertyDTO propertyDTO : effectiveProperties) {
                    //校验是否开通功能
                    if (!commonService.checkOpenFunction(propertyDTO, FunctionIdConstant.ADJUSTMENT_REQUESTS)) {
                        log.warn("AdjUserCloseListener.end... the property has not opened the adjustment function;property:{}", propertyDTO.getAbbr());
                        return;
                    }

                    adjListenerService.userLose(propertyDTO, userId);
                }
            } catch (Exception e) {
                log.error("handle user close exception", e);
                //发送预警邮件
                if (RateLimitUtils.tryAcquire(this, tenantName)) {
                    sendAlertEmail(tenantName, e.getMessage());
                }
            }
            log.info("AdjUserCloseListener.handle end...");
        }

        /**
         * 防止并发操作
         *
         * @param messageId 消息事件 id
         * @return boolean true：未并发，当前线程可以执行；false：检测到并发，当前线程应放弃执行
         * @author yyt
         * @date 2026/3/20
         */
        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 tenantName   租户名称
         * @param exceptionMsg 报错内容
         * @author yyt
         * @date 2026/3/20
         */
        private void sendAlertEmail(String tenantName, String exceptionMsg) {
            //主题
            String subject = "[Warning] - Handle User Close Event Exception.";
            //邮件内容
            String mailContent = MessageFormat.format("SNS Subject:{0}<br/>Business:{1}<br/>Tenant:{2}<br/>Content:{3}",
                    SUBJECT, BUSINESS, tenantName, exceptionMsg);
            //发送alert
            mailInternalService.sendAlertEmail(subject, mailContent);
        }

    }