package com.hzs.third.mqcall.listener;

import cn.hutool.json.JSONUtil;
import com.hzs.common.core.constant.RabbitMqConstants;
import com.hzs.common.domain.scm.ic.IcAvailableNum;
import com.hzs.common.domain.scm.ic.ext.IcAvailableNumExt;
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;

import java.util.List;

/**
 * 更新可用量
 */
@Slf4j
@Component
public class IcAvailableNumListener {

    @DubboReference
    IScmBillServiceApi scmBillServiceApi;

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