package cn.reghao.tnb.content.app.mall.service;

import cn.reghao.file.api.dto.BuyDto;
import cn.reghao.file.api.iface.NewOrderService;
import cn.reghao.tnb.common.auth.UserContext;
import cn.reghao.tnb.content.app.mall.db.mapper.ProductMapper;
import cn.reghao.tnb.content.app.mall.db.repository.MallRepository;
import cn.reghao.tnb.content.app.mall.model.dto.BuyItem;
import cn.reghao.tnb.content.app.mall.model.dto.BuyProductDto;
import cn.reghao.tnb.content.app.mall.model.po.Product;
import cn.reghao.tnb.content.app.mall.model.po.ProductSnapshot;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author reghao
 * @date 2025-02-24 15:00:52
 */
@Service
public class BuyService {
    @DubboReference(check = false)
    private NewOrderService newOrderService;

    private final CartService cartService;
    private final ProductMapper productMapper;
    private final MallRepository mallRepository;

    public BuyService(CartService cartService, ProductMapper productMapper, MallRepository mallRepository) {
        this.cartService = cartService;
        this.productMapper = productMapper;
        this.mallRepository = mallRepository;
    }

    public long buyProduct(BuyProductDto buyProductDto) {
        long deliveryId = buyProductDto.getDeliveryId();
        BuyItem buyItem = buyProductDto.getItems().get(0);
        long productId = buyItem.getItemId();
        int amount = buyItem.getNum();
        Product product = productMapper.findByItemId(productId);
        int stock = product.getStock();
        if (amount > stock) {
            // 库存不足
            return -1;
        }

        double price = product.getPrice();
        BuyDto buyDto = new BuyDto(productId, price, amount, deliveryId, UserContext.getUserId());

        // TODO 创建订单和修改库存是一个分布式事务
        long orderId = newOrderService.createOrder(buyDto);
        ProductSnapshot productSnapshot = new ProductSnapshot(orderId, product);
        mallRepository.updateProduct(amount, productSnapshot);
        return orderId;
    }

    public long buyCartItems(BuyProductDto buyProductDto) {
        long deliveryId = buyProductDto.getDeliveryId();
        // shop -> products
        Map<Long, List<BuyItem>> map = buyProductDto.getItems().stream().collect(Collectors.groupingBy(BuyItem::getShopId));
        map.forEach((shopId, items) -> {
            items.forEach(item -> {
                long orderId = 1L;
                Product product = mallRepository.getProduct(item.getItemId());
            });
        });

        long loginUser = UserContext.getUserId();
        map.forEach((shopId, items) -> {
            items.forEach(item -> {
                long itemId = item.getItemId();
                cartService.deleteCartItem(loginUser, itemId);
            });
        });

        return 0;
    }
}
