package com.hzs.third.mqcall.listener;

import cn.hutool.core.collection.CollectionUtil;
import com.hzs.activity.base.IActivityServiceApi;
import com.hzs.activity.dto.AcRecommendUpgradeDTO;
import com.hzs.common.core.constant.RabbitMqConstants;
import com.hzs.common.core.enums.EOrderOperateStatus;
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;

import java.util.List;

/**
 * 撤销订单，回退活活动公共的监听方法, 用于处理活动
 */
@Slf4j
@Component
public class ActivityBackListener {

    @DubboReference
    IActivityServiceApi activityServiceApi;

    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = RabbitMqConstants.ORDER_CANCEL_EXCHANGE, type = "topic"),
            value = @Queue(value = RabbitMqConstants.ORDER_CANCEL_ACTIVITY_BACK_QUEUE, durable = "true", autoDelete = "false"),
            key = RabbitMqConstants.ORDER_CANCEL_KEY))
    @RabbitHandler
    public void onMessage(Message<List<SaOrderExt>> message, Channel channel) throws Exception {
        try {
            Long deliveryTag = (Long) message.getHeaders().get(AmqpHeaders.DELIVERY_TAG);
            channel.basicAck(deliveryTag, false);

            // 第一单为撤单订单，此处改为订单列表因为合并撤单时，后面的订单有部分活动也需要进行处理
            List<SaOrderExt> saOrderExtList = message.getPayload();
            log.info("撤单活动回退处理参数：{}", saOrderExtList);

            if (CollectionUtil.isNotEmpty(saOrderExtList)) {
                SaOrderExt saOrderExt = saOrderExtList.get(0);

                // 处理抽奖
                activityServiceApi.backGiveMemberDrawNum(saOrderExt);

                if (EOrderType.REGISTER_ORDER.getValue() == saOrderExt.getOrderType()
                        || EOrderType.UPGRADE_ORDER.getValue() == saOrderExt.getOrderType()
                        || EOrderType.SPECIAL_REGISTER_ORDER.getValue() == saOrderExt.getOrderType()
                        || EOrderType.SPECIAL_UPGRADE_ORDER.getValue() == saOrderExt.getOrderType()) {
                    // 处理直推升级
                    activityServiceApi.invokeRecommendUpgrade(AcRecommendUpgradeDTO.builder().saOrderExt(saOrderExt).orderOperateStatus(EOrderOperateStatus.CANCEL).build());
                }
            }
        } catch (Exception e) {
            log.error("撤单MQ异步处理营销活动异常，msg:{} ", e.getMessage(), e);
        }
    }

}
