package com.ruoyi.mall.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.ruoyi.basic.domain.YjStore;
import com.ruoyi.basic.mapper.YjStoreMapper;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.SortUtil;
import com.ruoyi.mall.domain.MemberCart;
import com.ruoyi.mall.domain.Sku;
import com.ruoyi.mall.domain.form.UpdateMemberCartForm;
import com.ruoyi.mall.domain.order.OrderItem;
import com.ruoyi.mall.domain.query.MemberCartQuery;
import com.ruoyi.mall.domain.vo.MemberCartVO;
import com.ruoyi.mall.mapper.MemberCartMapper;
import com.ruoyi.mall.mapper.OrderItemMapper;
import com.ruoyi.mall.mapper.ProductMapper;
import com.ruoyi.mall.mapper.SkuMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 购物车Service业务层处理
 *
 * @author zcc
 */
@Service
public class MemberCartService extends ServiceImpl<MemberCartMapper, MemberCart> {
    @Autowired
    private MemberCartMapper memberCartMapper;
    @Autowired
    private SkuMapper skuMapper;
    @Autowired
    private YjStoreMapper storeMapper;
    @Autowired
    private ProductMapper productMapper;


    /**
     * 查询购物车
     *
     * @param id 购物车主键
     * @return 购物车
     */
    public MemberCart selectById(Long id) {
        return memberCartMapper.selectById(id);
    }

    /**
     * 查询购物车列表
     *
     * @param query 查询条件
     * @param page  分页条件
     * @return 购物车
     */
    public List<Map> selectList(MemberCartQuery query, Pageable page) {
        if (page != null) {
            PageHelper.startPage(page.getPageNumber() + 1, page.getPageSize(), SortUtil.sort2string(page.getSort(),"id desc"));
        }
        QueryWrapper<MemberCart> qw = new QueryWrapper<>();
        if (query.getMemberId() != null){
            qw.eq("member_id", query.getMemberId());
        }
        List<MemberCart> memberCartList = memberCartMapper.selectList(qw);
        if (CollectionUtil.isEmpty(memberCartList)){
            return Collections.emptyList();
        }
        //查sku
        List<Long> skuIdList = memberCartList.stream().map(MemberCart::getSkuId).collect(Collectors.toList());
        QueryWrapper<Sku> skuQw = new QueryWrapper<>();
        skuQw.in("id", skuIdList);
        Map<Long, Sku> skuMap = skuMapper.selectList(skuQw).stream().collect(Collectors.toMap(Sku::getId, it -> it));

        //查门店
        List<Long> storeIdList = memberCartList.stream().map(MemberCart::getStoreId).collect(Collectors.toList());

        List<YjStore> storeList = new ArrayList<>();
        for (Long aLong : storeIdList) {
           YjStore store= storeMapper.getOne(aLong);
           if (ObjectUtil.isNotEmpty(store) && !storeList.contains(store)){
               storeList.add(store);
            }
        }
        if (CollectionUtil.isEmpty(storeList)){
            return Collections.emptyList();
        }
        Map<Long, YjStore> storeMap = storeList.stream().collect(Collectors.toMap(YjStore::getId, it -> it));

        Map<Long, List<MemberCart>> storeCartMap = memberCartList.stream().collect(Collectors.groupingBy(MemberCart::getStoreId));

        List<Map> resList = new ArrayList<>();

        storeCartMap.forEach((storeId,cartList)->{
            Map<String,Object> resMap = new HashMap<>();
            List<MemberCartVO> list = new ArrayList<>();
            if (!storeMap.containsKey(storeId)){
                return;
            }
            resMap.put("storeName",storeMap.get(storeId).getStoreName());

                for (MemberCart item:cartList){
                    MemberCartVO memberCartVO = new MemberCartVO();
                    BeanUtils.copyProperties(item, memberCartVO);

                    //sku是否失效
                    if (!skuMap.containsKey(item.getSkuId())){
                        memberCartVO.setStatus(0);
                        memberCartVO.setSkuIfExist(0);
                    }else {
                        Sku sku = skuMap.get(item.getSkuId());
                        memberCartVO.setStock(sku.getStock());
                        memberCartVO.setPrice(sku.getPrice());
                        memberCartVO.setUnit(sku.getUnit());
                        memberCartVO.setSkuIfExist(1);
                    }
                    list.add(memberCartVO);
                }
            resMap.put("cartList",list);
            resList.add(resMap);
        });
        return resList;
    }

    /**
     * 新增购物车
     *
     * @param memberCart 购物车
     * @return 结果
     */
    public int insert(MemberCart memberCart) {

        memberCart.setMemberId(SecurityUtils.getAppLoginUser().getAppUserId());
        //判断cart是否存在
        QueryWrapper<MemberCart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("member_id",SecurityUtils.getAppLoginUser().getAppUserId());
        queryWrapper.eq("sku_id",memberCart.getSkuId());
        queryWrapper.eq("product_id",memberCart.getProductId());
        List<MemberCart> memberCarts = memberCartMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(memberCarts)) {
            memberCart.setStatus(1);
            memberCart.setCreateTime(LocalDateTime.now());
            memberCart.setCreateBy(SecurityUtils.getAppLoginUser().getAppUserId());
            return memberCartMapper.insert(memberCart);
        }
        MemberCart dbCart = memberCarts.get(0);
        dbCart.setUpdateTime(LocalDateTime.now());
        dbCart.setQuantity(dbCart.getQuantity() + memberCart.getQuantity());
        return memberCartMapper.updateById(dbCart);
    }

    /**
     * 修改购物车
     *
     * @param memberCart 购物车
     * @return 结果
     */
    public int update(MemberCart memberCart) {
        MemberCart cart = memberCartMapper.selectById(memberCart.getId());
        Sku sku = skuMapper.selectById(cart.getSkuId());
        if (cart == null){
            return 0;
        }
        if (cart.getQuantity()>sku.getStock()){
            throw new RuntimeException("库存数量："+sku.getStock());
        }
        cart.setQuantity(memberCart.getQuantity());
        cart.setUpdateTime(LocalDateTime.now());
        cart.setUpdateBy(SecurityUtils.getAppLoginUser().getAppUserId());
        return memberCartMapper.updateById(cart);
    }
    public int update(UpdateMemberCartForm form) {
        if (form.getNum() == null || form.getId() == null) {
            throw new BaseException("参数错误");
        }
        Long userId = SecurityUtils.getAppLoginUser().getAppUserId();
        LambdaQueryWrapper<MemberCart> qw = new LambdaQueryWrapper<>();
        qw.eq(MemberCart::getMemberId, userId);
        qw.eq(MemberCart::getId, form.getId());
        if (form.getNum() <= 0) {
            return memberCartMapper.delete(qw);
        }
        MemberCart e = new MemberCart();
        e.setQuantity(form.getNum());
        return memberCartMapper.update(e, qw);
    }

    /**
     * 删除购物车信息
     *
     * @param id 购物车主键
     * @return 结果
     */
    public int deleteById(Long id) {
        return memberCartMapper.deleteById(id);
    }

    /**
     * 删除购物车信息
     *
     * @param ids 购物车主键
     * @return 结果
     */
    public int deleteByIds(List<Long> ids) {
//        List<Long> idList = Arrays.stream(ids.split(",")).map(it -> Long.parseLong(it)).collect(Collectors.toList());
        return memberCartMapper.deleteBatchIds(ids);
    }

    public Integer mineCartNum() {
        Long userId = SecurityUtils.getAppLoginUser().getAppUserId();
        QueryWrapper<MemberCart> qw = new QueryWrapper<>();
        qw.eq("member_id", userId);
        qw.eq("status", 1);
        qw.select("count(quantity) quantity");
        MemberCart c = memberCartMapper.selectOne(qw);
        if (c == null) {
            return 0;
        }
        return c.getQuantity();
    }

    public List<Long> mineCartIds() {
        QueryWrapper<MemberCart> qw = new QueryWrapper<>();
        qw.eq("member_id", SecurityUtils.getAppLoginUser().getAppUserId());
        qw.eq("status", 1);
        qw.select("id");
        List<MemberCart> list = memberCartMapper.selectList(qw);
        return list.stream().map(MemberCart::getId).collect(Collectors.toList());
    }
}
