package com.hzs.third.mqcall.listener;

import cn.hutool.json.JSONUtil;
import com.hzs.common.core.constant.RabbitMqConstants;
import com.hzs.common.domain.sale.ext.SaOrderExt;
import com.hzs.scm.pub.IScmBillServiceApi;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

/**
 * 更新可用量,回退可用量
 */
@Slf4j
@Component
public class IcAvailableNumBackListener {

    @DubboReference
    IScmBillServiceApi scmBillServiceApi;

    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = RabbitMqConstants.AVAILABLE_NMU_BACK_EXCHANGE, type = "topic"),
            value = @Queue(value = RabbitMqConstants.AVAILABLE_NMU_BACK_QUEUE, durable = "true", autoDelete = "false"),
            key = RabbitMqConstants.AVAILABLE_NMU_BACK_KEY))
    @RabbitHandler
    public void onMessage(Message<SaOrderExt> message, Channel channel) throws Exception {
        SaOrderExt saOrderExt = message.getPayload();
        log.info("开始更新可用量，接收到的参数：{}", JSONUtil.toJsonStr(saOrderExt));
        try {
            Thread.sleep(1000);
            Long deliveryTag = (Long) message.getHeaders().get(AmqpHeaders.DELIVERY_TAG);
            channel.basicAck(deliveryTag, false);
            scmBillServiceApi.backSaOrderAvailable(saOrderExt);
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }
    }
}
