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;
private
Gson gson =
new
Gson();
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());
if
(product ==
null
) {
return
ResponseVo.error(ResponseEnum.PRODUCT_NOT_EXIST);
}
if
(product.getStatus().equals(ProductStatusEnum.ON_SALE.getCode())) {
return
ResponseVo.error(ResponseEnum.PRODUCT_OFF_SALE_OR_DELETE);
}
if
(product.getStock() <=
0
) {
return
ResponseVo.error(ResponseEnum.PRODUCT_STOCK_ERROR);
}
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)) {
cart =
new
Cart(product.getId(), quantity, form.getSelected());
}
else
{
cart = gson.fromJson(value, Cart.
class
);
cart.setQuantity(cart.getQuantity() + quantity);
}
opsForHash.put(redisKey, String.valueOf(product.getId()), gson.toJson(cart));
return
list(uid);
}