package com.seer.teach.mall.app.good.handler;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.seer.teach.mall.app.good.service.IAppGoodsSpecificationService;
import com.seer.teach.mall.entity.GoodsEntity;
import com.seer.teach.mall.entity.GoodsSpecificationEntity;
import com.seer.teach.mall.entity.OrderEntity;
import com.seer.teach.mall.entity.OrderGoodsEntity;
import com.seer.teach.mall.handler.OrderHandler;
import com.seer.teach.mall.service.IGoodsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import jakarta.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Component
public class SkuOrderHandler implements OrderHandler {

    @Resource
    private IGoodsService goodsService;

    @Resource
    private IAppGoodsSpecificationService appGoodsSpecificationService;

    @Transactional(rollbackFor = Exception.class, timeout = 120)
    @Override
    public void afterOrderCancel(OrderEntity order, List<OrderGoodsEntity> orderItems) {
        // 更新 SKU 库存
        orderItems.forEach(item -> {
            boolean updated = appGoodsSpecificationService.update(new LambdaUpdateWrapper<>(GoodsSpecificationEntity.class)
                    .eq(GoodsSpecificationEntity::getId, item.getSkuId()).setIncrBy(GoodsSpecificationEntity::getStock, item.getNumber()));
            log.info("订单取消，更新商品SKU {} 库存 {} 的结果是：{}", item.getSkuId(), item.getNumber(), updated);
        });
        
        // 按商品ID分组更新 SPU 库存
        Map<Integer, Integer> goodsStockMap = orderItems.stream()
                .collect(Collectors.groupingBy(OrderGoodsEntity::getGoodsId, 
                         Collectors.summingInt(OrderGoodsEntity::getNumber)));
        
        // 更新每个商品(SPU)的库存
        goodsStockMap.forEach((goodsId, stockIncrement) -> {
            boolean updated = goodsService.update(new LambdaUpdateWrapper<>(GoodsEntity.class)
                    .eq(GoodsEntity::getId, goodsId)
                    .setIncrBy(GoodsEntity::getStock, stockIncrement));
            log.info("订单取消，更新商品SPU {} 库存 {} 的结果是：{}", goodsId, stockIncrement, updated);
        });
    }
}