package com.hzs.third.mqcall.listener;

import com.hzs.activity.base.IActivityServiceApi;
import com.hzs.common.core.constant.RabbitMqConstants;
import com.hzs.common.core.domain.R;
import com.hzs.common.core.enums.EOrderType;
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 ActivityBackListener {

    @DubboReference
    IActivityServiceApi iActivityServiceApi;

    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = RabbitMqConstants.ACTIVITY_BACK_EXCHANGE, type = "topic"),
            value = @Queue(value = RabbitMqConstants.ACTIVITY_BACK_QUEUE, durable = "true", autoDelete = "false"),
            key = RabbitMqConstants.ACTIVITY_BACK_KEY))
    @RabbitHandler
    public void onMessage(Message<SaOrderExt> message, Channel channel) {
        SaOrderExt saOrderExt = message.getPayload();
        // 赠送抽奖次数
        try {
            Long deliveryTag = (Long) message.getHeaders().get(AmqpHeaders.DELIVERY_TAG);
            channel.basicAck(deliveryTag, false);

            log.info("撤单活动MQ异步处理 third：{}", saOrderExt);

            iActivityServiceApi.backGiveMemberDrawNum(saOrderExt);
            if (EOrderType.REGISTER_ORDER.getValue() == saOrderExt.getOrderType()) {
                // 注册订单处理
                // 直推赠送政策币
                R backOrderPolicyR = iActivityServiceApi.backGiveOrderPolicy(saOrderExt);
                if (!backOrderPolicyR.isSuccess()) {
                    log.error(backOrderPolicyR.getMsg());
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }
    }
}
