package com.xingxi.mq.consumer.order;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.rabbitmq.client.Channel;
import com.xingxi.common.mq.bo.order.OrderBO;
import com.xingxi.common.mq.constant.OrderMqKey;
import com.xingxi.common.mq.core.AbstractRabbitConsumer;
import com.xingxi.common.mq.publisher.order.OrderUnPaidMqPublisher;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Component
public class OrderCreatedConsumer extends AbstractRabbitConsumer {

    @Resource
    private OrderUnPaidMqPublisher orderUnPaidMqPublisher;

    @Bean(OrderMqKey.EDIT_QUEUE_ORDER_FOR_CREATED)
    @Override
    protected List<Binding> getBindingList() {
        return Lists.newArrayList(
                this.bind(OrderMqKey.EDIT_EXCHANGE,
                        OrderMqKey.EDIT_QUEUE_ORDER_FOR_CREATED,
                        OrderMqKey.EDIT_ROUTE_FOR_CREATED));
    }

    @RabbitListener(queues = OrderMqKey.EDIT_QUEUE_ORDER_FOR_CREATED)
    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        this.convertMessage(message, channel);
    }


    @Override
    public boolean execute(String body, Channel channel, Message message) throws Exception {
        log.info("订单生成后推送至延迟队列MQ,处理推送的订单数据【{}】.", body);

        // 消息转发至延迟队列
        OrderBO orderBO = JSON.parseObject(body, OrderBO.class);
        if(orderBO == null) {
            return true;
        }
        orderUnPaidMqPublisher.sendMessage(orderBO);

        log.info("订单生成后推送至延迟队列MQ,订单【{}】数据处理完成.", orderBO.getOrderNo());
        return true;
    }
}
