package com.qmth.exam.reserve.mq;

import com.qmth.exam.reserve.bean.apply.ApplyRecordCacheBean;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class ExamReserveMQProducer implements MQConstants {

    private static final Logger log = LoggerFactory.getLogger(ExamReserveMQProducer.class);

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @Value("${rocketmq.producer.send-message-timeout:3000}")
    private Integer mqSendMessageTimeout;

    @Value("${rocketmq.topic}")
    private String mqTopic;

    public void sendMessage(ApplyRecordCacheBean bean) {
        // 按考点ID分区队列（同个考点下消息按顺序执行）
        String hashKey = String.valueOf(bean.getExamSiteId());

        // 主题:分类
        String destination = mqTopic + ":" + TAG_STUDENT_APPLY;

        // MQ消息延迟级别3 = 10秒
        int delayLevel = 3;

        Message<ApplyRecordCacheBean> message = MessageBuilder.withPayload(bean).build();

        SendResult result = rocketMQTemplate.syncSendOrderly(destination, message, hashKey, mqSendMessageTimeout, delayLevel);
        log.info("【考生预约队列】消息推送{}！{}_{}_{}_{} bizId:{} msgId:{}", result.getSendStatus(), bean.getStudentId(),
                bean.getExamSiteId(), bean.getTimePeriodId(), bean.getCancel(), bean.getBizId(), result.getMsgId());
    }

}
