package com.gxwebsoft.shop.service.impl;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.gxwebsoft.common.core.utils.RequestUtil;
import com.gxwebsoft.common.system.entity.Dict;
import com.gxwebsoft.common.system.entity.DictData;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.shop.entity.*;
import com.gxwebsoft.shop.mapper.CartMapper;
import com.gxwebsoft.shop.service.*;
import com.gxwebsoft.shop.param.CartParam;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.shop.vo.CartShopVo;
import com.gxwebsoft.shop.vo.CartVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 购物车Service实现
 *
 * @author 科技小王子
 * @since 2024-07-29 21:02:39
 */
@Service
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements CartService {
    @Resource
    private GoodsService goodsService;
    @Resource
    private MerchantService merchantService;
    @Resource
    private ExpressTemplateService expressTemplateService;
    @Resource
    private UserAddressService userAddressService;

    @Autowired
    private RequestUtil requestUtil;

    @Override
    public PageResult<Cart> pageRel(CartParam param) {
        PageParam<Cart, CartParam> page = new PageParam<>(param);
        page.setDefaultOrder("create_time desc");
        List<Cart> list = baseMapper.selectPageRel(page, param);
        return new PageResult<>(list, page.getTotal());
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public CartVo listRel(CartParam param) {
        List<Cart> list = baseMapper.selectListRel(param);
        // 排序
        PageParam<Cart, CartParam> page = new PageParam<>();
        page.setDefaultOrder("create_time desc");
        List<Cart> carts = page.sortRecords(list);
        if (param.getId() != null) carts = list.stream().filter(d -> d.getId().equals(param.getId())).toList();
        System.out.println("carts = " + carts.size());
        // 整理数据
        final CartVo vo = new CartVo();
        // 计算单品总价
        User parentUser;
        if (param.getLoginUser() != null) {
            parentUser = requestUtil.getParent(param.getLoginUser().getUserId());
        } else {
            parentUser = null;
        }
        BigDecimal expressAmount = BigDecimal.ZERO;
        List<OrderGoods> orderGoodsList = new ArrayList<>();
        List<Cart> filterCartList = new ArrayList<>();
        for (Cart cart : carts) {
            cart.setTotalPrice(cart.getPrice().multiply(BigDecimal.valueOf(cart.getCartNum())));
            Goods goods = goodsService.getById(cart.getGoodsId());
            if (goods == null) {
                removeById(cart);
                continue;
            }
            filterCartList.add(cart);
            if (param.getLoginUser() != null) {
                BigDecimal originPrice = goods.getPrice();
                goods.setPrice(goods.getSalePrice());
                // 会员
//                if (parentUser != null) {
                if (goods.getPriceGift()) goods.setShowGift(true);
//                    goods.setPrice(originPrice);
//                }
                // 会员店
//                if (param.getLoginUser().getGradeId() > 30 && goods.getBuyingPriceOpen().equals(1)) {
//                    goods.setPrice(goods.getBuyingPrice());
////                    if (goods.getPriceGift()) goods.setShowGift(true);
//                }
            }
            OrderGoods orderGoods = new OrderGoods();
            orderGoods.setGoodsId(cart.getGoodsId());
            orderGoods.setGoods(goods);
            orderGoods.setTotalNum(cart.getCartNum());
            orderGoodsList.add(orderGoods);
            cart.setGoods(goods);
        }
        UserAddress userAddress;
        if (param.getAddressId() != null) userAddress = userAddressService.getById(param.getAddressId());
        else userAddress = userAddressService.getUserDefault(param.getLoginUser().getUserId());
//        if (userAddress != null) expressAmount = expressTemplateService.calExpressAmount(orderGoodsList, userAddress);
        // 计算购物车金额
        final Integer cartNum = filterCartList.stream().map(Cart::getCartNum).reduce(Integer::sum).orElse(0);
        final Integer selectNums = filterCartList.stream().filter(d -> d.getSelected().equals(true)).map(Cart::getCartNum).reduce(Integer::sum).orElse(0);
        final BigDecimal totalPrice = filterCartList.stream().filter(d -> d.getSelected().equals(true)).map(Cart::getTotalPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
        // 按店铺ID分组
        final Map<Integer, List<Cart>> collectCart = filterCartList.stream().collect(Collectors.groupingBy(Cart::getMerchantId));
        final ArrayList<CartShopVo> shops = new ArrayList<>();
        if (MapUtil.isNotEmpty(collectCart)) {
            for (Integer shopId : collectCart.keySet()) {
                final CartShopVo shopVo = new CartShopVo();
                shopVo.setShopId(shopId);
                shopVo.setCarts(collectCart.get(shopId));
                if (ObjectUtil.isNotEmpty(collectCart.get(shopId).get(0))) {
                    final Cart cart = collectCart.get(shopId).get(0);
                    shopVo.setShopName(cart.getMerchantName());
                    shopVo.setShopLogo(cart.getImage());
                }
                if (param.getWithMerchantInfo() != null) {
                    Merchant merchant = merchantService.getById(shopId);
                    shopVo.setMerchant(merchant);
                }
                shops.add(shopVo);
            }
        }

        vo.setShops(shops);
        vo.setTotalPrice(totalPrice);
        vo.setExpressAmount(expressAmount);
        vo.setTotalNums(Long.valueOf(cartNum));
        vo.setSelectNums(Long.valueOf(selectNums));
//    updateBatchById(carts);

        return vo;
    }

    @Override
    public Cart getByIdRel(Integer id) {
        CartParam param = new CartParam();
        param.setId(id);
        return param.getOne(baseMapper.selectListRel(param));
    }

    @Override
    public List<Cart> listRelMpj(CartParam param) {

        // 多表查询
        MPJLambdaWrapper<Cart> mpjLambdaWrapper = new MPJLambdaWrapper<>();
        mpjLambdaWrapper.selectAll(Cart.class)
                .select(Goods::getGoodsName)
                .select(Goods::getImage)
                .leftJoin(Goods.class, Goods::getGoodsId, Cart::getGoodsId).eq(Cart::getUserId, param.getUserId());

        // 查询选中状态
        if (param.getSelected() != null) {
            mpjLambdaWrapper.eq(Cart::getSelected, param.getSelected());
        }
        // 商品类型 0商城 1预定
        if (param.getType() != null) {
            mpjLambdaWrapper.eq(Cart::getType, param.getType());
        }
        // 是否为立即购买
        if (param.getIsNew() != null) {
            mpjLambdaWrapper.eq(Cart::getIsNew, param.getIsNew());
        }
        // 指定cartId
        if (param.getId() != null) {
            mpjLambdaWrapper.eq(Cart::getId, param.getId());
        }
        System.out.println("mpjLambdaWrapper = " + mpjLambdaWrapper);
        return baseMapper.selectJoinList(Cart.class, mpjLambdaWrapper);
    }

}
