package cn.gintone.config;


import cn.gintone.dto.WebLogInfo;
import cn.gintone.iotdbUtils.MyIotDbUtils;
import cn.gintone.service.VisitInfoService;
import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 消费者类
 */
@Component
public class MyConsumer {

    @Autowired
    private IotDbConfig iotDbConfig;

    @Autowired
    private VisitInfoService visitInfoService;

    /**
     * 监听队列---当队列中有消息，则监听器工作，处理接受到的消息
     */
    @RabbitListener(queues = "my_boot_fanout_queue1")
    public void receive1(Message message) {
        byte[] body = message.getBody();
        System.out.printf("receive1接受到的消息" + new String(body));
    }

    @RabbitListener(queues = "my_boot_topic_queue")
    public void receive2(Message message, Channel channel) throws IOException {
        byte[] body = message.getBody();
        String receivedRoutingKey = message.getMessageProperties().getReceivedRoutingKey();
        if (receivedRoutingKey.contains("weblog")) {
            System.out.println(iotDbConfig);
            System.out.println(channel);
            String jsonStr = new String(body);
            WebLogInfo webLogInfo = null;
            try {
                webLogInfo = JSON.parseObject(JSON.parse(jsonStr).toString(), WebLogInfo.class);
                MyIotDbUtils.inserOne(iotDbConfig, webLogInfo);
                visitInfoService.checkWebLogInfo(webLogInfo);
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                return;
            }
        }


        // 手动ack，告知broker要签收的消息的id（deliveryTag）
//        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }
}
