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

import cn.hutool.core.util.ReflectUtil;
import com.cf.imes.framework.organ.core.context.OrganContextHolder;
import org.apache.kafka.clients.producer.ProducerInterceptor;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;
import org.apache.kafka.common.header.Headers;
import org.springframework.messaging.handler.invocation.InvocableHandlerMethod;

import java.util.Map;

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

/**
 * Kafka 消息队列的多组织 {@link ProducerInterceptor} 实现类
 *
 * 1. Producer 发送消息时，将 {@link OrganContextHolder} 组织编号，添加到消息的 Header 中
 * 2. Consumer 消费消息时，将消息的 Header 的组织编号，添加到 {@link OrganContextHolder} 中，通过 {@link InvocableHandlerMethod} 实现
 *
 * @author 晨丰科技
 */
public class OrganKafkaProducerInterceptor implements ProducerInterceptor<Object, Object> {

    @Override
    public ProducerRecord<Object, Object> onSend(ProducerRecord<Object, Object> record) {
        Long organId = OrganContextHolder.getOrganId();
        if (organId != null) {
            Headers headers = (Headers) ReflectUtil.getFieldValue(record, "headers"); // private 属性，没有 get 方法，智能反射
            headers.add(HEADER_ORGAN_ID, organId.toString().getBytes());
        }
        return record;
    }

    @Override
    public void onAcknowledgement(RecordMetadata metadata, Exception exception) {
        // onAcknowledgement
    }

    @Override
    public void close() {
        // close
    }

    @Override
    public void configure(Map<String, ?> configs) {
        // configure
    }

}
