package com.hzs.bonus.listener;

import com.hzs.bonus.bonus.service.IBonusSettleService;
import com.hzs.bonus.bonus.service.ICuMemberRetailLogService;
import com.hzs.common.core.constant.CountryConstants;
import com.hzs.common.core.constant.MagicNumberConstants;
import com.hzs.common.core.constant.RabbitMqConstants;
import com.hzs.common.core.enums.EYesNo;
import com.hzs.common.domain.member.bonus.CuMemberRetailLog;
import com.hzs.common.domain.sale.ext.SaOrderExt;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

/**
 * 订单秒接
 */
@Slf4j
@Component
public class SaOrderSecondListener {

    @Autowired
    private IBonusSettleService iBonusSettleService;
    @Autowired
    private ICuMemberRetailLogService iCuMemberRetailLogService;

    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = RabbitMqConstants.ORDER_SECOND_EXCHANGE, type = "topic"),
            value = @Queue(value = RabbitMqConstants.ORDER_SECOND_QUEUE, durable = "true", autoDelete = "false"),
            key = RabbitMqConstants.ORDER_SECOND_KEY))
    @RabbitHandler
    public void onMessage(Message<SaOrderExt> message, Channel channel) throws Exception {
        SaOrderExt saOrderExt = message.getPayload();
        log.info("秒结开始消费，接收到的参数：{}", saOrderExt.getOrderCode());

        Long deliveryTag = (Long) message.getHeaders().get(AmqpHeaders.DELIVERY_TAG);
        channel.basicAck(deliveryTag, false);

        CuMemberRetailLog cuMemberRetailLog = new CuMemberRetailLog();
        cuMemberRetailLog.setPkCountry(CountryConstants.CHINA_COUNTRY);
        cuMemberRetailLog.setPkCreator(MagicNumberConstants.PK_ADMIN);
        cuMemberRetailLog.setOrderCode(saOrderExt.getOrderCode());
        if (saOrderExt.getCancelBool() != null && saOrderExt.getCancelBool()) {
            cuMemberRetailLog.setCancelStatus(EYesNo.YES.getIntValue());
        }

        try {
            Thread.sleep(1000);
            iBonusSettleService.calculateCuMemberRetailRangeBonusBySaOrder(saOrderExt.getOrderCode());
        } catch (Exception e) {
            cuMemberRetailLog.setEnableStatus(EYesNo.NO.getIntValue());
            cuMemberRetailLog.setMsg(e.getMessage());
            e.printStackTrace();
        } finally {
            iCuMemberRetailLogService.save(cuMemberRetailLog);
        }
    }
}
