package com.heyu.api.listener;

import com.alibaba.fastjson.JSONObject;
import com.heyu.api.data.dao.vv.VvRequestLogDao;
import com.heyu.api.data.entity.vv.VvRequestLogEntity;
import com.heyu.api.data.utils.DateUtils;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;

@Component
@Slf4j
public class VVUrlQueueSimpleRabbitListener {

    @Value("${eb.config.rabbitQueue.urlStatisticQueue}")
    private String urlStatisticQueue;


    @Autowired
    private VvRequestLogDao vvRequestLogDao;


    @RabbitHandler
    @RabbitListener(queues = "#{urlStatisticQueue.name}", containerFactory = "accountAmountQueueSimpleRabbitListenerContainerFactory")
    public void consumeMessage(@Payload String message, @Header(AmqpHeaders.DELIVERY_TAG) long delivertTag, Channel channel) {
        try {
            VvRequestLogEntity vvRequestLogEntity = JSONObject.parseObject(message, VvRequestLogEntity.class);
            vvRequestLogEntity.setCreateTimestamp(System.currentTimeMillis());

            vvRequestLogEntity.setCreateDay(DateUtils.formatDate(new Date(), DateUtils.YYYY_MM_DD));
            vvRequestLogDao.insert(vvRequestLogEntity);
        } catch (Exception e) {
            log.error("urlStatisticQueue handle", e);
        } finally {
            try {
                log.info("urlStatisticQueue消息{},消息确认完成", message);
                channel.basicAck(delivertTag, true);
            } catch (IOException e) {
                log.error("urlStatisticQueue消息确认异常", e);
            }
        }
    }
}