
package com.tmerclub.cloud.product.listener;

import cn.hutool.core.collection.CollUtil;
import com.tmerclub.cloud.api.product.vo.SkuStockVO;
import com.tmerclub.cloud.common.order.bo.RefundReductionStockBO;
import com.tmerclub.cloud.common.order.bo.RefundStockOperateBO;
import com.tmerclub.cloud.common.rocketmq.config.RocketMqConstant;
import com.tmerclub.cloud.product.manager.StockManager;
import com.tmerclub.cloud.product.mapper.SpuMapper;
import com.tmerclub.cloud.product.service.StockBillLogService;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 解锁库存的监听
 *
 * @author tmerclub
 */
@Component
@RocketMQMessageListener(topic = RocketMqConstant.ORDER_REFUND_SUCCESS_STOCK_TOPIC, consumerGroup = RocketMqConstant.ORDER_REFUND_SUCCESS_STOCK_TOPIC)
public class OrderRefundSuccessStockConsumer implements RocketMQListener<RefundStockOperateBO> {

    @Autowired
    private StockManager stockManager;
    @Autowired
    private SpuMapper spuMapper;
    @Autowired
    private StockBillLogService stockBillLogService;

    /**
     * 订单退款导致待发货订单取消，需要还原优惠券和库存
     */
    @Override
    public void onMessage(RefundStockOperateBO refundStockOperateBO) {
        // 保存退款还原库存的日志
        stockBillLogService.generateStockLogOfRefundOrderList(refundStockOperateBO);

        List<SkuStockVO> skuStockLocks = new ArrayList<>(refundStockOperateBO.getRefundReductionStockList().size());
        refundStockOperateBO.getRefundReductionStockList().forEach(refundStockOperateDTO -> {
            // 解锁库存
            SkuStockVO skuStockVO = new SkuStockVO(refundStockOperateDTO.getSkuId(), refundStockOperateDTO.getCount());
            skuStockVO.setStockPointId(refundStockOperateDTO.getStockPointId());
            skuStockLocks.add(skuStockVO);
        });

        if (CollUtil.isNotEmpty(skuStockLocks)) {
            // 减少销量，增加sku库存数量 - 这里报错没有关系，mq会重试
            stockManager.increaseStock(skuStockLocks);
        }
        List<RefundReductionStockBO> stockBillLogItems = refundStockOperateBO.getRefundReductionStockList();
        // 如果供应商商品不用添加记录，只需要扣库存
        if (!Objects.equals(stockBillLogItems.get(0).getSupplierProd(), 1)) {
            return;
        }
        List<Long> supplierSpuIds = stockBillLogItems.stream().map(RefundReductionStockBO::getSpuId).toList();
        List<Long> spuIds = spuMapper.batchSupIdListBySupplierId(supplierSpuIds);
        spuIds.addAll(supplierSpuIds);
        spuMapper.updateSpuUpdateTime(spuIds, null, null, null);
    }
}
