package com.hai.goods.service.impl;

import com.hai.dao.GoodsShoppingCartMapper;
import com.hai.entity.GoodsShoppingCart;
import com.hai.entity.GoodsShoppingCartExample;
import com.hai.goods.service.ShoppingCartService;
import org.apache.commons.collections4.MapUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Service("shoppingCartService")
public class ShoppingCartServiceImpl implements ShoppingCartService {

    @Resource
    private GoodsShoppingCartMapper shoppingCartMapper;

    @Override
    public void insertShoppingCart(GoodsShoppingCart shoppingCart) {
        shoppingCartMapper.insert(shoppingCart);
    }

    @Override
    public void updateShoppingCart(GoodsShoppingCart shoppingCart) {
        shoppingCartMapper.updateByPrimaryKey(shoppingCart);
    }

    @Override
    public List<GoodsShoppingCart> getShoppingCartList(Map<String, Object> map) {
        GoodsShoppingCartExample example = new GoodsShoppingCartExample();
        GoodsShoppingCartExample.Criteria criteria = example.createCriteria();

        if (MapUtils.getLong(map, "userId") != null) {
            criteria.andUserIdEqualTo(MapUtils.getLong(map, "userId"));
        }

        return shoppingCartMapper.selectByExample(example);
    }

    @Override
    public GoodsShoppingCart findShoppingCartById(Long id) {
        return shoppingCartMapper.selectByPrimaryKey(id);
    }

    @Override
    public GoodsShoppingCart findShoppingCartByMap(Map<String, Object> map) {
        GoodsShoppingCartExample example = new GoodsShoppingCartExample();
        GoodsShoppingCartExample.Criteria criteria = example.createCriteria();

        if (MapUtils.getLong(map, "userId") != null) {
            criteria.andUserIdEqualTo(MapUtils.getLong(map, "userId"));
        }
        if (MapUtils.getString(map, "sku") != null) {
            criteria.andSkuEqualTo(MapUtils.getString(map, "sku"));
        }
        if (MapUtils.getLong(map, "goodsId") != null) {
            criteria.andGoodsIdEqualTo(MapUtils.getLong(map, "goodsId"));
        }

        List<GoodsShoppingCart> list = shoppingCartMapper.selectByExample(example);

        if (list.size() > 0 ) {
            return list.get(0);
        }

        return null;
    }

    @Override
    public void deleteShoppingCart(Long id) {
        shoppingCartMapper.deleteByPrimaryKey(id);
    }
}
