// CartServiceImpl.java 文件中add()方法的的代码
package com.imooc.mall.service.impl;
import com.google.gson.Gson;
import com.imooc.mall.dao.ProductMapper;
import com.imooc.mall.enums.ProductStatusEnum;
import com.imooc.mall.enums.ResponseEnum;
import com.imooc.mall.form.CartAddForm;
import com.imooc.mall.pojo.Cart;
import com.imooc.mall.pojo.Product;
import com.imooc.mall.service.ICartService;
import com.imooc.mall.service.vo.CartProductVo;
import com.imooc.mall.service.vo.CartVo;
import com.imooc.mall.service.vo.ResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Service
public class CartServiceImpl implements ICartService {
@Autowired
private ProductMapper productMapper;
@Autowired
private StringRedisTemplate redisTemplate;
// 将对象转化成json字符串
private Gson gson = new Gson();
// 购物车id
private final static String CART_REDIS_KEY_TEMPLATE = "cart_%d";
// 向购物车中添加商品
@Override
public ResponseVo<CartVo> add(Integer uid, CartAddForm form) {
Integer quantity = 1;
Product product = productMapper.selectByPrimaryKey(form.getProductId());
// 1. 判断商品是否存在
if (product == null) {
return ResponseVo.error(ResponseEnum.PRODUCT_NOT_EXIST);
}
// 2. 判断商品是否在售
if (product.getStatus().equals(ProductStatusEnum.ON_SALE.getCode())) {
return ResponseVo.error(ResponseEnum.PRODUCT_OFF_SALE_OR_DELETE);
}
// 3. 判断商品的库存是否充足
if (product.getStock() <= 0) {
return ResponseVo.error(ResponseEnum.PRODUCT_STOCK_ERROR);
}
// 4. 校验完毕后,写入数据到 redis中
HashOperations<String, String, String> opsForHash = redisTemplate.opsForHash();
String redisKey = String.format(CART_REDIS_KEY_TEMPLATE, uid);
String value = opsForHash.get(redisKey, String.valueOf(product.getId()));
Cart cart;
if (StringUtils.isEmpty(value)) {
// 如果 value 为空,说明购物车中没有该商品,新增
cart = new Cart(product.getId(), quantity, form.getSelected());
} else {
// 如果存在, 则商品的数量 +1
cart = gson.fromJson(value, Cart.class);
cart.setQuantity(cart.getQuantity() + quantity);
}
opsForHash.put(redisKey, String.valueOf(product.getId()), gson.toJson(cart));
return list(uid);
}