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

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.cf.imes.framework.organ.core.context.OrganContextHolder;
import org.apache.rocketmq.client.hook.ConsumeMessageContext;
import org.apache.rocketmq.client.hook.ConsumeMessageHook;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.messaging.handler.invocation.InvocableHandlerMethod;

import java.util.List;

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

/**
 * RocketMQ 消息队列的多组织 {@link ConsumeMessageHook} 实现类
 *
 * Consumer 消费消息时，将消息的 Header 的组织编号，添加到 {@link OrganContextHolder} 中，通过 {@link InvocableHandlerMethod} 实现
 *
 * @author 晨丰科技
 */
public class OrganRocketMQConsumeMessageHook implements ConsumeMessageHook {

    @Override
    public String hookName() {
        return getClass().getSimpleName();
    }

    @Override
    public void consumeMessageBefore(ConsumeMessageContext context) {
        // 校验，消息必须是单条，不然设置组织可能不正确
        List<MessageExt> messages = context.getMsgList();
        Assert.isTrue(messages.size() == 1, "消息条数({})不正确", messages.size());
        // 设置组织编号
        String organId = messages.get(0).getUserProperty(HEADER_ORGAN_ID);
        if (StrUtil.isNotEmpty(organId)) {
            OrganContextHolder.setOrganId(Long.parseLong(organId));
        }
    }

    @Override
    public void consumeMessageAfter(ConsumeMessageContext context) {
        OrganContextHolder.clear();
    }

}
