package com.heyu.api.listener;

import com.alibaba.fastjson.JSONObject;
import com.heyu.api.data.enums.DelayTypeEnums;
import com.heyu.api.data.dao.vv.VvPackageDao;
import com.heyu.api.data.dao.vv.VvTradeOrderLineDao;
import com.heyu.api.data.utils.SpringContextUtils;
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.Map;

@Component
@Slf4j
public class DelaySimpleRabbitListener {

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


    @Autowired
    private VvPackageDao vvPackageDao;


    @Autowired
    private VvTradeOrderLineDao vvTradeOrderLineDao;


    @RabbitHandler
    @RabbitListener(queues = "#{delayQueue.name}", containerFactory = "accountAmountQueueSimpleRabbitListenerContainerFactory")
    public void consumeMessage(@Payload String message, @Header(AmqpHeaders.DELIVERY_TAG) long delivertTag, Channel channel) {
        try {
            log.info("DeliveredDelaySimpleRabbitListener delayQueue :{} message:{}", delayQueue, message);
            Map<String, Object> map = JSONObject.parseObject(message, Map.class);
            String type = map.get("type") + "";

            DelayTypeEnums delayTypeEnums = DelayTypeEnums.getDelayTypeByType(type);

            if (delayTypeEnums == null) {
                log.info("DelaySimpleRabbitListener type is :{}", type);
                return;
            }

            BaseDelayedHandler baseDelayedHandler = SpringContextUtils.getBean(delayTypeEnums.getHandler());
            baseDelayedHandler.handler(message);
        } catch (Exception e) {
            log.error("DeliveredDelaySimpleRabbitListener handle", e);
        } finally {
            try {
                log.info("DeliveredDelaySimpleRabbitListener 消息{},消息确认完成", message);
                channel.basicAck(delivertTag, true);
            } catch (IOException e) {
                log.error("DeliveredDelaySimpleRabbitListener 消息确认异常", e);
            }
        }
    }
}