package com.yonge.cooleshow.portal.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.yonge.cooleshow.mbg.mapper.OmsCartItemMapper;
import com.yonge.cooleshow.mbg.mapper.PmsProductMapper;
import com.yonge.cooleshow.mbg.mapper.PmsSkuStockMapper;
import com.yonge.cooleshow.mbg.model.*;
import com.yonge.cooleshow.portal.dao.PortalProductDao;
import com.yonge.cooleshow.portal.domain.CartProduct;
import com.yonge.cooleshow.portal.domain.CartPromotionItem;
import com.yonge.cooleshow.portal.service.OmsCartItemService;
import com.yonge.cooleshow.portal.service.OmsPromotionService;
import com.yonge.cooleshow.portal.service.UmsMemberService;
import com.yonge.toolset.base.exception.BizException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

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

/**
 * 购物车管理Service实现类
 * Created by macro on 2018/8/2.
 */
@Service
public class OmsCartItemServiceImpl implements OmsCartItemService {
    @Autowired
    private OmsCartItemMapper cartItemMapper;
    @Autowired
    private PortalProductDao productDao;
    @Autowired
    private OmsPromotionService promotionService;
    @Autowired
    private UmsMemberService memberService;

    @Autowired
    private PmsProductMapper pmsProductMapper;

    @Autowired
    private PmsSkuStockMapper skuStockMapper;

    @Override
    public OmsCartItem add(OmsCartItem cartItem) {
        UmsMember currentMember =memberService.getCurrentMember();
        cartItem.setMemberId(currentMember.getId());
        cartItem.setMemberNickname(currentMember.getNickname());
        cartItem.setDeleteStatus(0);
        OmsCartItem existCartItem = getCartItem(cartItem);
        if (cartItem.getHidden() == null) {
            cartItem.setHidden(0);
        } else if (cartItem.getHidden() == 1) {
            existCartItem = null;
        }

        PmsSkuStock pmsSkuStock = skuStockMapper.selectByPrimaryKey(cartItem.getProductSkuId());
        if (pmsSkuStock == null) {
            throw new BizException("商品规格不存在");
        }
        if (existCartItem == null) {
            PmsProduct pmsProduct = pmsProductMapper.selectByPrimaryKey(cartItem.getProductId());

            if (pmsProduct == null) {
                throw new BizException("商品不存在");
            }
            cartItem.setPrice(pmsProduct.getPrice());
            cartItem.setProductPic(pmsProduct.getPic());
            cartItem.setProductName(pmsProduct.getName());
            cartItem.setProductSubTitle(pmsProduct.getSubTitle());
            cartItem.setProductCategoryId(pmsProduct.getProductCategoryId());
            cartItem.setProductBrand(pmsProduct.getName());
            cartItem.setProductSn(pmsProduct.getProductSn());
            if (cartItem.getProductSkuId() != null) {
                if (pmsSkuStock.getStock() - pmsSkuStock.getLockStock() < cartItem.getQuantity()) {
                    throw new BizException("库存不足");
                }
                cartItem.setProductSkuCode(pmsSkuStock.getSkuCode());
                cartItem.setProductAttr(pmsSkuStock.getSpData());
                cartItem.setPrice(pmsSkuStock.getPrice());
            }

            cartItem.setCreateDate(new Date());
            cartItemMapper.insert(cartItem);
            return cartItem;
        } else {
            if (cartItem.getPromoterId() != null) {
                existCartItem.setPromoterId(cartItem.getPromoterId());
            }
            if (pmsSkuStock.getStock() - pmsSkuStock.getLockStock() < existCartItem.getQuantity() + cartItem.getQuantity()) {
                throw new BizException("库存不足");
            }
            if(existCartItem.getQuantity() + cartItem.getQuantity() > 200) {
                existCartItem.setQuantity(200);
            } else {
                existCartItem.setQuantity(cartItem.getQuantity() + existCartItem.getQuantity());
            }
            cartItem.setModifyDate(new Date());
            cartItemMapper.updateByPrimaryKey(existCartItem);
        }
        return existCartItem;
    }

    /**
     * 根据会员id,商品id和规格获取购物车中商品
     */
    private OmsCartItem getCartItem(OmsCartItem cartItem) {
        OmsCartItemExample example = new OmsCartItemExample();
        OmsCartItemExample.Criteria criteria = example.createCriteria().andMemberIdEqualTo(cartItem.getMemberId())
                .andProductIdEqualTo(cartItem.getProductId()).andDeleteStatusEqualTo(0).andHiddenEqualTo(0);
        if (!StringUtils.isEmpty(cartItem.getProductSkuId())) {
            criteria.andProductSkuIdEqualTo(cartItem.getProductSkuId());
        }
        List<OmsCartItem> cartItemList = cartItemMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(cartItemList)) {
            return cartItemList.get(0);
        }
        return null;
    }

    @Override
    public List<OmsCartItem> list(Long memberId) {
        OmsCartItemExample example = new OmsCartItemExample();
        example.createCriteria().andDeleteStatusEqualTo(0).andMemberIdEqualTo(memberId).andHiddenEqualTo(0);
        List<OmsCartItem> omsCartItems = cartItemMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(omsCartItems)) {
            return omsCartItems;
        }
        List<Long> skuIds = omsCartItems.stream().map(OmsCartItem::getProductSkuId).collect(Collectors.toList());
        PmsSkuStockExample skuExample = new PmsSkuStockExample();
        skuExample.createCriteria().andIdIn(skuIds);
        List<PmsSkuStock> pmsSkuStocks = skuStockMapper.selectByExample(skuExample);
        Map<Long, List<PmsSkuStock>> collect =
                pmsSkuStocks.stream().collect(Collectors.groupingBy(PmsSkuStock::getId));
        for (OmsCartItem omsCartItem : omsCartItems) {
            List<PmsSkuStock> pmsSkuStocks1 = collect.get(omsCartItem.getProductSkuId());
            if (!CollectionUtils.isEmpty(pmsSkuStocks1)) {
                omsCartItem.setStock(pmsSkuStocks1.get(0).getStock());
                omsCartItem.setLockStock(pmsSkuStocks1.get(0).getLockStock());
            }
        }
        return omsCartItems;
    }

    @Override
    public List<CartPromotionItem> listPromotion(Long memberId, List<Long> cartIds, boolean del) {
        List<OmsCartItem> cartItemList;
        if (!del) {
            cartItemList = list(memberId);
            if (CollUtil.isNotEmpty(cartIds)) {
                cartItemList = cartItemList.stream().filter(item -> cartIds.contains(item.getId())).collect(Collectors.toList());
            }
        } else {
            OmsCartItemExample example = new OmsCartItemExample();
            example.createCriteria().andMemberIdEqualTo(memberId).andIdIn(cartIds);
            cartItemList  = cartItemMapper.selectByExample(example);
        }
        List<CartPromotionItem> cartPromotionItemList = new ArrayList<>();
        if(!CollectionUtils.isEmpty(cartItemList)){
            cartPromotionItemList = promotionService.calcCartPromotion(cartItemList);
        }
        return cartPromotionItemList;
    }

    @Override
    public int updateQuantity(Long id, Long memberId, Integer quantity) {
        OmsCartItem cartItem = new OmsCartItem();
        cartItem.setQuantity(quantity);
        OmsCartItem omsCartItem = cartItemMapper.selectByPrimaryKey(id);

        if (omsCartItem.getProductSkuId() == null) {
            throw new BizException("商品已售空");
        }

        PmsSkuStock pmsSkuStock = skuStockMapper.selectByPrimaryKey(omsCartItem.getProductSkuId());

        if (pmsSkuStock.getStock() - pmsSkuStock.getLockStock() < quantity) {
            return pmsSkuStock.getStock() - pmsSkuStock.getLockStock();
        }

        OmsCartItemExample example = new OmsCartItemExample();
        example.createCriteria().andDeleteStatusEqualTo(0)
                .andIdEqualTo(id).andMemberIdEqualTo(memberId);
        cartItemMapper.updateByExampleSelective(cartItem, example);
        return pmsSkuStock.getStock() - pmsSkuStock.getLockStock();
    }

    @Override
    public int delete(Long memberId, List<Long> ids) {
        OmsCartItem record = new OmsCartItem();
        record.setDeleteStatus(1);
        OmsCartItemExample example = new OmsCartItemExample();
        example.createCriteria().andIdIn(ids).andMemberIdEqualTo(memberId);
        return cartItemMapper.updateByExampleSelective(record, example);
    }

    @Override
    public CartProduct getCartProduct(Long productId) {
        return productDao.getCartProduct(productId);
    }

    @Override
    public int updateAttr(OmsCartItem cartItem) {
        //删除原购物车信息
        OmsCartItem updateCart = new OmsCartItem();
        updateCart.setId(cartItem.getId());
        updateCart.setModifyDate(new Date());
        updateCart.setDeleteStatus(1);
        cartItemMapper.updateByPrimaryKeySelective(updateCart);
        cartItem.setId(null);
        add(cartItem);
        return 1;
    }

    @Override
    public int clear(Long memberId) {
        OmsCartItem record = new OmsCartItem();
        record.setDeleteStatus(1);
        OmsCartItemExample example = new OmsCartItemExample();
        example.createCriteria().andMemberIdEqualTo(memberId);
        return cartItemMapper.updateByExampleSelective(record,example);
    }

    @Override
    public OmsCartItem get(Long id) {
        return cartItemMapper.selectByPrimaryKey(id);
    }
}
