package com.gyee.edge.loader.rocketmq.comuser;

import com.google.protobuf.InvalidProtocolBufferException;
import com.gyee.edge.loader.adapter.DataWrite;

import com.gyee.protocol.gyfp2.message.GYMessage;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Slf4j
@Component
public class BalanceComuser {

    @Value("${rocketmq.namesrvaddr}")
    String nameSrvAddr;

    @Autowired
    private DataWrite dataWrite;

    public void DataConsumer() throws Exception {
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("group_sonsumer");
        consumer.setNamesrvAddr(nameSrvAddr);
        consumer.subscribe("keyMessage", "*");
        consumer.setMessageModel(MessageModel.CLUSTERING);
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                try {
                    for (MessageExt msg : msgs) {
                        String topic = msg.getTopic();
                        String msgBody = new String(msg.getBody(), "utf-8");
                        String tags = msg.getTags();
                        try {
                            //反序列化
                            byte[] bytes = msg.getBody();
                            Date sTdate = new Date();
                            GYMessage gyMessage = GYMessage.toObject(bytes);
                            Date eNdate = new Date();
                            log.info("反序列化时间"+(eNdate.getTime()-sTdate.getTime()));
                            log.info("收到消息" + "topic" + topic + ",tags" + tags + ",msg" + gyMessage);
                            //数据写入
                            dataWrite.DataWriteGloden(gyMessage);
                        } catch (InvalidProtocolBufferException e) {
                            e.printStackTrace();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
        consumer.start();  //启动消费者
        log.info("Consumer STARTTED");
    }

}
