package com.hzs.third.mqcall.listener;

import cn.hutool.json.JSONUtil;
import com.hzs.activity.base.IActivityServiceApi;
import com.hzs.common.core.constant.RabbitMqConstants;
import com.hzs.common.core.domain.R;
import com.hzs.common.domain.sale.ext.SaOrderExt;
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 ActivityListener {

    @DubboReference
    IActivityServiceApi iActivityServiceApi;

    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = RabbitMqConstants.ACTIVITY_EXCHANGE, type = "topic"),
            value = @Queue(value = RabbitMqConstants.ACTIVITY_QUEUE, durable = "true", autoDelete = "false"),
            key = RabbitMqConstants.ACTIVITY_KEY))
    @RabbitHandler
    public void onMessage(Message<SaOrderExt> message, Channel channel) {
        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);
            R<Boolean> resultR = iActivityServiceApi.handleActivity(saOrderExt);
            if (!resultR.isSuccess()) {
                log.error("处理活动异常 {}", resultR.getMsg());
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }
    }
}
