package com.cf.imes.framework.organ.core.mq.redis;

import cn.hutool.core.util.StrUtil;
import com.cf.imes.framework.mq.redis.core.interceptor.RedisMessageInterceptor;
import com.cf.imes.framework.mq.redis.core.message.AbstractRedisMessage;
import com.cf.imes.framework.organ.core.context.OrganContextHolder;

import static com.cf.imes.framework.web.core.util.WebFrameworkUtils.HEADER_ORGAN_ID;

/**
 * 多组织 {@link AbstractRedisMessage} 拦截器
 *
 * 1. Producer 发送消息时，将 {@link OrganContextHolder} 组织编号，添加到消息的 Header 中
 * 2. Consumer 消费消息时，将消息的 Header 的组织编号，添加到 {@link OrganContextHolder} 中
 *
 * @author 晨丰科技
 */
public class OrganRedisMessageInterceptor implements RedisMessageInterceptor {

    @Override
    public void sendMessageBefore(AbstractRedisMessage message) {
        Long organId = OrganContextHolder.getOrganId();
        if (organId != null) {
            message.addHeader(HEADER_ORGAN_ID, organId.toString());
        }
    }

    @Override
    public void consumeMessageBefore(AbstractRedisMessage message) {
        String organIdStr = message.getHeader(HEADER_ORGAN_ID);
        if (StrUtil.isNotEmpty(organIdStr)) {
            OrganContextHolder.setOrganId(Long.valueOf(organIdStr));
        }
    }

    @Override
    public void consumeMessageAfter(AbstractRedisMessage message) {
        // 注意，Consumer 是一个逻辑的入口，所以不考虑原本上下文就存在组织编号的情况
        OrganContextHolder.clear();
    }

}
