package cn.axzo.msg.center.mq;

import cn.axzo.framework.rocketmq.Event;
import cn.axzo.framework.rocketmq.EventProducer;
import cn.axzo.msg.center.api.mq.MqMessage;
import cn.axzo.msg.center.common.utils.BizAssertions;
import cn.axzo.msg.center.service.enums.MqMessageType;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @author yanglin
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class MqProducer {

    private final EventProducer<MqMessage> producer;

    public <Message extends MqMessage> void send(MqMessageRecord<Message> record) {
        BizAssertions.assertNotNull(record.getMessageType(), "消息类型不能为空");
        BizAssertions.assertNotNull(record.getMessage(), "消息体不能为空");
        log.info("开始 - 发送消息. messageRecord={}", record);
        try {
            sendImpl(record);
            log.info("结束 - 发送消息. messageRecord={}", record);
        } catch (Exception e) {
            log.warn("异常 - 发送消息. messageRecord={}", record, e);
            // 由调用方决定怎么处理异常
            throw e;
        }
    }

    private <Message extends MqMessage> void sendImpl(MqMessageRecord<Message> record) {
        MqMessageType messageType = record.getMessageType();
        producer.send(Event.builder()
                .shardingKey(record.getShardingKey())
                .targetId(record.getMessageKey())
                .targetType(messageType.getEventModel())
                .eventCode(messageType.getEventCode())
                .eventModule(messageType.getEventModel())
                .eventName(messageType.getTag(record.getTagInfo()))
                .operatorId(record.getOperatorId())
                .operatorType(record.getOperatorType())
                .data(record.getMessage())
                .build());
    }

}