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.OrderReturnedBO;
import com.xingxi.common.mq.constant.OrderMqKey;
import com.xingxi.common.mq.core.AbstractRabbitConsumer;
import com.xingxi.common.utils.DateUtils;
import com.xingxi.mq.entity.OrderDetail;
import com.xingxi.mq.server.order.service.IOrderDetailVoService;
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.Date;
import java.util.List;

/**
 * 退货确认消息
 * 将退货数量从订单信息的售后中数量减少，增加只已退货数量中
 */
@Slf4j
@Component
public class OrderReturnedConsumer extends AbstractRabbitConsumer {

    @Resource
    private IOrderDetailVoService orderDetailVoService;

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

    @RabbitListener(queues = OrderMqKey.EDIT_QUEUE_ORDER_FOR_RETURNED)
    @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);
        Date nowDate = DateUtils.getNowDate();

        // json对象转换
        List<OrderReturnedBO> returnList = JSON.parseArray(body, OrderReturnedBO.class);

        for (OrderReturnedBO orbo : returnList) {
            int returnQty = 0;
            if (orbo.getStockQty() != null) {
                returnQty = returnQty + orbo.getStockQty();
            }
            if (orbo.getScrapQty() != null) {
                returnQty = returnQty + orbo.getScrapQty();
            }
            int afterQty = returnQty;
            if (orbo.getRejectQty() != null) {
                afterQty = afterQty + orbo.getRejectQty();
            }
            OrderDetail uod = new OrderDetail();
            uod.setOrderId(orbo.getOrderId());
            uod.setOrderDetailId(orbo.getOrderDetailId());
            uod.setSuiteId(orbo.getSuiteId());
            uod.setAfterQty(afterQty);
            uod.setReturnQty(returnQty);
            uod.setUpdateUser("订单退货完成MQ");
            uod.setUpdateTime(nowDate);

            orderDetailVoService.updateReturnQty(uod);
        }

        log.info("订单退货完成MQ,推送的订单数据处理完成.");
        return true;
    }
}
