package com.izouma.dingdong.service.user;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.izouma.dingdong.domain.OrderGoodsSpec;
import com.izouma.dingdong.domain.OrderInfo;
import com.izouma.dingdong.domain.user.ShoppingCart;
import com.izouma.dingdong.domain.merchant.FullReduction;
import com.izouma.dingdong.domain.merchant.Goods;
import com.izouma.dingdong.domain.merchant.MerchantSettings;
import com.izouma.dingdong.exception.BusinessException;
import com.izouma.dingdong.repo.OrderGoodsSpecRepo;
import com.izouma.dingdong.repo.OrderInfoRepo;
import com.izouma.dingdong.repo.user.ShoppingCartRepo;
import com.izouma.dingdong.repo.UserRepo;
import com.izouma.dingdong.repo.merchant.FullReductionRepo;
import com.izouma.dingdong.repo.merchant.GoodsRepo;
import com.izouma.dingdong.repo.merchant.MerchantSettingsRepo;
import com.izouma.dingdong.service.merchant.GoodsService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Comparator;
import java.util.List;

@Service
@AllArgsConstructor
public class ShoppingCartService {

    private ShoppingCartRepo shoppingCartRepo;
    private GoodsRepo goodsRepo;
    private UserRepo userRepo;
    private OrderInfoRepo orderInfoRepo;
    private MerchantSettingsRepo merchantSettingsRepo;
    private FullReductionRepo fullReductionRepo;
    private OrderGoodsSpecRepo orderGoodsSpecRepo;
    private GoodsService goodsService;

    /*
    创建购物车
     */
    public ShoppingCart save(Long userId, OrderGoodsSpec orderGoodsSpec) {
        Goods goods = goodsRepo.findById(orderGoodsSpec.getGoodsId()).orElseThrow(new BusinessException("无商品"));

        //查看商品库存是否足够
        //Goods goods = goodsService.buy(orderGoodsSpec.getGoodsId(), orderGoodsSpec.getNum());

        //按商家创建购物车
        Long merchantId = goods.getMerchantId();

        //商家信息
        MerchantSettings merchant = merchantSettingsRepo.findByMerchantId(merchantId).orElseThrow(new BusinessException("无商户"));

        //查找是不是第一次购买
        userRepo.findById(userId).orElseThrow(new BusinessException("无用户"));

        //购物车中是否已有
        ShoppingCart shoppingCart = shoppingCartRepo.findByUserIdAndMerchantId(userId, merchantId);

        //加规格
        List<OrderGoodsSpec> specs = CollUtil.newArrayList();
        specs.add(orderGoodsSpec);

        //减的金额
        BigDecimal sub = orderGoodsSpec.getGoodsPrice().subtract(orderGoodsSpec.getGoodsRealPrice()).multiply(BigDecimal.valueOf(orderGoodsSpec.getNum()));

        //包装费

        BigDecimal packingPrice = BigDecimal.ZERO;

        if (ObjectUtil.isNotNull(goods.getPackingPrice())) {
            packingPrice = goods.getPackingPrice().multiply(BigDecimal.valueOf(orderGoodsSpec.getNum()));
        }

        if (ObjectUtil.isNull(shoppingCart)) {
            shoppingCart = ShoppingCart.builder()
                    .merchantId(goods.getMerchantId())
                    .userId(userId)
                    .goodsTotal(orderGoodsSpec.getGoodsPrice().multiply(BigDecimal.valueOf(orderGoodsSpec.getNum())))
                    .reducedAmount(sub)
                    .orderGoodsSpecs(specs)
                    .packingPrice(packingPrice)
                    .fullReduction(BigDecimal.ZERO)
                    .build();
        } else {
            //商品总价(原价)
            shoppingCart.setGoodsTotal(shoppingCart.getGoodsTotal().add(orderGoodsSpec.getGoodsPrice().multiply(BigDecimal.valueOf(orderGoodsSpec.getNum()))));
            //折扣的差价
            shoppingCart.setReducedAmount(shoppingCart.getReducedAmount().add(sub));
            specs.addAll(shoppingCart.getOrderGoodsSpecs());
            shoppingCart.setOrderGoodsSpecs(specs);
            //包装费
            shoppingCart.setPackingPrice(shoppingCart.getPackingPrice().add(packingPrice));
        }

        //查找是不是第一次购买
        List<OrderInfo> userOrders = orderInfoRepo.findAllByUserId(userId);
        List<OrderInfo> userOrdersMerchant = orderInfoRepo.findAllByUserIdAndMerchantId(userId, merchantId);
        //是新用户也是首单
        if (CollUtil.isEmpty(userOrders)) {
//            shoppingCart.setNewUser(merchant.getNewUser());
            shoppingCart.setFirstBuy(merchant.getFirstOrder());
        } else {
            //首单
            if (CollUtil.isEmpty(userOrdersMerchant)) {
                shoppingCart.setNewUser(BigDecimal.ZERO);
                shoppingCart.setFirstBuy(merchant.getFirstOrder());
            } else {
                //非首单设置为0
                shoppingCart.setNewUser(BigDecimal.ZERO);
                shoppingCart.setFirstBuy(BigDecimal.ZERO);
            }
        }


        //获取配送费
        shoppingCart.setDeliveryAmount(BigDecimal.TEN);


        boolean flag = true;
        //满减
        if (!goods.getIsFullReduction()) {
            flag = false;
        }
        if (flag) {
            //参与满减
            List<FullReduction> fullReductions = fullReductionRepo.findAllByMerchantId(merchantId);
            fullReductions.sort(Comparator.comparing(FullReduction::getFullAmount));
            for (FullReduction f : fullReductions) {
                if (f.getFullAmount().compareTo(shoppingCart.getGoodsTotal()) <= 0) {
                    shoppingCart.setFullReduction(f.getMinusAmount());
                    //不是折扣是满减，就置为减去的金额
                    shoppingCart.setReducedAmount(f.getMinusAmount());
                }
            }
        }

        //商品总价+配送费+包装费
        BigDecimal total = shoppingCart.getGoodsTotal().add(shoppingCart.getDeliveryAmount()).add(shoppingCart.getPackingPrice());

        //需要减去的金额=首单+新用户+折扣/满减
        BigDecimal sub2 = shoppingCart.getFirstBuy().add(shoppingCart.getNewUser()).add(shoppingCart.getReducedAmount());
        //总价-首单-新用户-满减
        BigDecimal real = total.subtract(sub2);

        shoppingCart.setRealAmount(real);
        shoppingCart.setReducedAmount(sub2);

        shoppingCart = shoppingCartRepo.save(shoppingCart);

        orderGoodsSpec.setShoppingCartId(shoppingCart.getId());

        orderGoodsSpecRepo.save(orderGoodsSpec);

        return shoppingCart;
    }


}
