package com.buy507.mall.portal.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.buy507.mall.common.api.CommonResult;
import com.buy507.mall.mapper.OmsCartItemMapper;
import com.buy507.mall.mapper.PmsProductMapper;
import com.buy507.mall.mapper.PmsSkuStockMapper;
import com.buy507.mall.model.OmsCartItem;
import com.buy507.mall.model.OmsCartItemExample;
import com.buy507.mall.model.PmsProduct;
import com.buy507.mall.model.PmsSkuStock;
import com.buy507.mall.model.UmsMember;
import com.buy507.mall.portal.dao.PortalProductDao;
import com.buy507.mall.portal.domain.CartItemParam;
import com.buy507.mall.portal.domain.CartProduct;
import com.buy507.mall.portal.domain.CartPromotionItem;
import com.buy507.mall.portal.service.OmsCartItemService;
import com.buy507.mall.portal.service.OmsPromotionService;
import com.buy507.mall.portal.service.PortalCommonService;
import com.buy507.mall.portal.service.UmsMemberService;

/**
 * 购物车管理Service实现类
 */
@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 productMapper;
    
    @Autowired
    private PmsSkuStockMapper skuStockMapper;
    
    @Autowired
    private PortalCommonService commonService;

    @Override
    public CommonResult add(CartItemParam cartItemParam) {
    	
    	if(cartItemParam.getSkuId() == null) {
    		return CommonResult.validateFailed("商品SKU不能为空");
    	}
    	
    	PmsSkuStock skuStock = skuStockMapper.selectByPrimaryKey(cartItemParam.getSkuId());
		if(skuStock == null) {
			return CommonResult.validateFailed("未查询到商品信息");
		}
		
		if(cartItemParam.getQuantity() == null) {
			cartItemParam.setQuantity(1);
		}
		
		//根据商品id查询商品信息
		PmsProduct product = productMapper.selectByPrimaryKey(skuStock.getProductId());
		if(product == null) {
			return CommonResult.validateFailed("未查询到商品信息");
		}
		
		//判断是否参与分销结算，如果不参与，不能添加到购物车
    	if(product.getDistributionFlag().equals(0)) { //分销标志（0->不参与；1->参与）
    		return CommonResult.failed("该商品不能添加到购物车");
    	}
    	
        UmsMember currentMember = memberService.getCurrentMember();
        
        OmsCartItemExample example = new OmsCartItemExample();
        OmsCartItemExample.Criteria criteria = example.createCriteria();
        criteria.andMemberIdEqualTo(currentMember.getId());
        criteria.andProductSkuIdEqualTo(cartItemParam.getSkuId());
        
        OmsCartItem cartItem = null;
        Date date = new Date();
        BigDecimal discount = commonService.getDiscount(memberService.getById(currentMember.getId()).getId());
        List<OmsCartItem> cartItemList = cartItemMapper.selectByExample(example);
        if(cartItemList != null && !cartItemList.isEmpty()) {
        	cartItem = cartItemList.get(0);
        	cartItem.setQuantity(cartItem.getQuantity() + cartItemParam.getQuantity());
        	cartItem.setModifyDate(date);
        	if(discount != null) {
            	cartItem.setPrice(cartItem.getPrice().multiply(discount).setScale(2, BigDecimal.ROUND_HALF_UP));
            }
        	cartItemMapper.updateByPrimaryKey(cartItem);
        } else {
        	cartItem = new OmsCartItem();
        	cartItem.setProductId(skuStock.getProductId());
        	cartItem.setProductSkuId(skuStock.getId());
        	cartItem.setMemberId(currentMember.getId());
            cartItem.setMemberNickname(currentMember.getNickname());
            cartItem.setQuantity(cartItemParam.getQuantity());
            cartItem.setPrice(skuStock.getPrice());
            cartItem.setSp1(skuStock.getSp1());
            cartItem.setSp2(skuStock.getSp2());
            cartItem.setSp3(skuStock.getSp3());
            cartItem.setProductPic(skuStock.getPic());
            cartItem.setProductName(product.getName());
            cartItem.setProductSubTitle(product.getDetailTitle());
            cartItem.setProductSkuCode(skuStock.getSkuCode());
            cartItem.setCreateDate(date);
            cartItem.setProductCategoryId(product.getProductCategoryId());
            cartItem.setProductBrand(product.getBrandName());
            cartItem.setProductSn(product.getProductSn());
            cartItem.setDeleteStatus(0);
            if(discount != null) {
            	cartItem.setPrice(cartItem.getPrice().multiply(discount).setScale(2, BigDecimal.ROUND_HALF_UP));
            }
            cartItemMapper.insert(cartItem);
        }
        
        return CommonResult.success(null);
    }

    @Override
    public List<OmsCartItem> list(Long memberId) {
    	OmsCartItemExample example = new OmsCartItemExample();
    	example.createCriteria().andMemberIdEqualTo(memberId);
        return cartItemMapper.selectByExample(example);
    }

    @Override
    public List<CartPromotionItem> listPromotion(Long memberId) {
        List<OmsCartItem> cartItemList = list(memberId);
        List<CartPromotionItem> cartPromotionItemList = new ArrayList<>();
        if(!CollectionUtils.isEmpty(cartItemList)){
            cartPromotionItemList = promotionService.calcCartPromotion(cartItemList);
        }
        return cartPromotionItemList;
    }

    @Override
    public void updateQuantity(Long id, Long memberId, Integer quantity) {
    	OmsCartItem cartItem = cartItemMapper.selectByPrimaryKey(id);
    	if(cartItem.getMemberId().equals(memberId)) {
    		cartItem.setQuantity(quantity);
    		cartItemMapper.updateByPrimaryKey(cartItem);
    	}
    }

    @Override
    public void delete(Long memberId, List<Long> ids) {
    	OmsCartItemExample example = new OmsCartItemExample();
    	example.createCriteria().andMemberIdEqualTo(memberId);
    	List<OmsCartItem> cartItemList = cartItemMapper.selectByExample(example);
    	for(OmsCartItem cartItem : cartItemList) {
    		for(Long id : ids) {
    			if(cartItem.getId().equals(id)) {
    				cartItemMapper.deleteByPrimaryKey(cartItem.getId());
    			}
    		}
    	}
    }

    @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 void clear(Long memberId) {
    	OmsCartItemExample example = new OmsCartItemExample();
    	example.createCriteria().andMemberIdEqualTo(memberId);
    	List<OmsCartItem> cartItemList = cartItemMapper.selectByExample(example);
    	for(OmsCartItem cartItem : cartItemList) {
    		cartItemMapper.deleteByPrimaryKey(cartItem.getId());
    	}
    }
}
