@ApiOperation(value = "从购物车中删除商品", notes = "从购物车中删除商品", httpMethod = "POST")
@PostMapping("/del")
public JSONResult del(
@RequestParam String userId,
@RequestParam String itemSpecId,
HttpServletRequest request,
HttpServletResponse response
) {
if (StringUtils.isBlank(userId) || StringUtils.isBlank(itemSpecId)) {
return JSONResult.errorMsg("参数不能为空");
}
// 用户在页面删除购物车中的商品数据,如果此时用户已经登录,则需要同步删除redis购物车中的商品
String shopcartJson = redisOperator.get(FOODIE_SHOPCART + ":" + userId);
if (StringUtils.isNotBlank(shopcartJson)) {
// redis中已经有购物车了
List<ShopcartBO> shopcartList = JsonUtils.jsonToList(shopcartJson, ShopcartBO.class);
// 判断购物车中是否存在已有商品,如果有的话则删除
for (ShopcartBO sc: shopcartList) {
String tmpSpecId = sc.getSpecId();
if (tmpSpecId.equals(itemSpecId)) {
shopcartList.remove(sc);
break;
}
}
// 覆盖现有redis中的购物车
redisOperator.set(FOODIE_SHOPCART + ":" + userId, JsonUtils.objectToJson(shopcartList));
}
return JSONResult.ok();
}
@ApiOperation(value = "用户下单", notes = "用户下单", httpMethod = "POST")
@PostMapping("/create")
public JSONResult create(
@RequestBody SubmitOrderBO submitOrderBO,
HttpServletRequest request,
HttpServletResponse response) {
if (submitOrderBO.getPayMethod() != PayMethod.WEIXIN.type
&& submitOrderBO.getPayMethod() != PayMethod.ALIPAY.type ) {
return JSONResult.errorMsg("支付方式不支持!");
}
// System.out.println(submitOrderBO.toString());
String shopcartJson = redisOperator.get(FOODIE_SHOPCART + ":" + submitOrderBO.getUserId());
if (StringUtils.isBlank(shopcartJson)) {
return JSONResult.errorMsg("购物数据不正确");
}
List<ShopcartBO> shopcartList = JsonUtils.jsonToList(shopcartJson, ShopcartBO.class);
// 1. 创建订单
OrderVO orderVO = orderService.createOrder(shopcartList, submitOrderBO);
String orderId = orderVO.getOrderId();
// 2. 创建订单以后,移除购物车中已结算(已提交)的商品
/**
* 1001
* 2002 -> 用户购买
* 3003 -> 用户购买
* 4004
*/
// 清理覆盖现有的redis汇总的购物数据
shopcartList.removeAll(orderVO.getToBeRemovedShopcatdList());
redisOperator.set(FOODIE_SHOPCART + ":" + submitOrderBO.getUserId(), JsonUtils.objectToJson(shopcartList));
// 整合redis之后,完善购物车中的已结算商品清除,并且同步到前端的cookie
CookieUtils.setCookie(request, response, FOODIE_SHOPCART, JsonUtils.objectToJson(shopcartList), true);
// 3. 向支付中心发送当前订单,用于保存支付中心的订单数据
MerchantOrdersVO merchantOrdersVO = orderVO.getMerchantOrdersVO();
merchantOrdersVO.setReturnUrl(payReturnUrl);
// 为了方便测试购买,所以所有的支付金额都统一改为1分钱
merchantOrdersVO.setAmount(1);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("UserId","");
headers.add("password","");
HttpEntity<MerchantOrdersVO> entity =
new HttpEntity<>(merchantOrdersVO, headers);
ResponseEntity<JSONResult> responseEntity =
restTemplate.postForEntity(paymentUrl,
entity,
JSONResult.class);
JSONResult paymentResult = responseEntity.getBody();
if (paymentResult.getStatus() != 200) {
logger.error("发送错误:{}", paymentResult.getMsg());
return JSONResult.errorMsg("支付中心订单创建失败,请联系管理员!");
}
return JSONResult.ok(orderId);
}
/**
* 用于创建订单相关信息
* @param submitOrderBO
*/
public OrderVO createOrder(List<ShopcartBO> shopcartList, SubmitOrderBO submitOrderBO);
@Transactional(propagation = Propagation.REQUIRED)
@Override
public OrderVO createOrder(List<ShopcartBO> shopcartList, SubmitOrderBO submitOrderBO) {
String userId = submitOrderBO.getUserId();
String addressId = submitOrderBO.getAddressId();
String itemSpecIds = submitOrderBO.getItemSpecIds();
Integer payMethod = submitOrderBO.getPayMethod();
String leftMsg = submitOrderBO.getLeftMsg();
// 包邮费用设置为0
Integer postAmount = 0;
String orderId = sid.nextShort();
UserAddress address = addressService.queryUserAddres(userId, addressId);
// 1. 新订单数据保存
Orders newOrder = new Orders();
newOrder.setId(orderId);
newOrder.setUserId(userId);
newOrder.setReceiverName(address.getReceiver());
newOrder.setReceiverMobile(address.getMobile());
newOrder.setReceiverAddress(address.getProvince() + " "
+ address.getCity() + " "
+ address.getDistrict() + " "
+ address.getDetail());
// newOrder.setTotalAmount();
// newOrder.setRealPayAmount();
newOrder.setPostAmount(postAmount);
newOrder.setPayMethod(payMethod);
newOrder.setLeftMsg(leftMsg);
newOrder.setIsComment(YesOrNo.NO.type);
newOrder.setIsDelete(YesOrNo.NO.type);
newOrder.setCreatedTime(new Date());
newOrder.setUpdatedTime(new Date());
// 2. 循环根据itemSpecIds保存订单商品信息表
String itemSpecIdArr[] = itemSpecIds.split(",");
Integer totalAmount = 0; // 商品原价累计
Integer realPayAmount = 0; // 优惠后的实际支付价格累计
List<ShopcartBO> toBeRemovedShopcatdList = new ArrayList<>();
for (String itemSpecId : itemSpecIdArr) {
ShopcartBO cartItem = getBuyCountsFromShopcart(shopcartList, itemSpecId);
// 整合redis后,商品购买的数量重新从redis的购物车中获取
int buyCounts = cartItem.getBuyCounts();
toBeRemovedShopcatdList.add(cartItem);
// 2.1 根据规格id,查询规格的具体信息,主要获取价格
ItemsSpec itemSpec = itemService.queryItemSpecById(itemSpecId);
totalAmount += itemSpec.getPriceNormal() * buyCounts;
realPayAmount += itemSpec.getPriceDiscount() * buyCounts;
// 2.2 根据商品id,获得商品信息以及商品图片
String itemId = itemSpec.getItemId();
Items item = itemService.queryItemById(itemId);
String imgUrl = itemService.queryItemMainImgById(itemId);
// 2.3 循环保存子订单数据到数据库
String subOrderId = sid.nextShort();
OrderItems subOrderItem = new OrderItems();
subOrderItem.setId(subOrderId);
subOrderItem.setOrderId(orderId);
subOrderItem.setItemId(itemId);
subOrderItem.setItemName(item.getItemName());
subOrderItem.setItemImg(imgUrl);
subOrderItem.setBuyCounts(buyCounts);
subOrderItem.setItemSpecId(itemSpecId);
subOrderItem.setItemSpecName(itemSpec.getName());
subOrderItem.setPrice(itemSpec.getPriceDiscount());
orderItemsMapper.insert(subOrderItem);
// 2.4 在用户提交订单以后,规格表中需要扣除库存
itemService.decreaseItemSpecStock(itemSpecId, buyCounts);
}
newOrder.setTotalAmount(totalAmount);
newOrder.setRealPayAmount(realPayAmount);
ordersMapper.insert(newOrder);
// 3. 保存订单状态表
OrderStatus waitPayOrderStatus = new OrderStatus();
waitPayOrderStatus.setOrderId(orderId);
waitPayOrderStatus.setOrderStatus(OrderStatusEnum.WAIT_PAY.type);
waitPayOrderStatus.setCreatedTime(new Date());
orderStatusMapper.insert(waitPayOrderStatus);
// 4. 构建商户订单,用于传给支付中心
MerchantOrdersVO merchantOrdersVO = new MerchantOrdersVO();
merchantOrdersVO.setMerchantOrderId(orderId);
merchantOrdersVO.setMerchantUserId(userId);
merchantOrdersVO.setAmount(realPayAmount + postAmount);
merchantOrdersVO.setPayMethod(payMethod);
// 5. 构建自定义订单vo
OrderVO orderVO = new OrderVO();
orderVO.setOrderId(orderId);
orderVO.setMerchantOrdersVO(merchantOrdersVO);
orderVO.setToBeRemovedShopcatdList(toBeRemovedShopcatdList);
return orderVO;
}
/**
* 从redis中的购物车里获取商品,目的:counts
* @param shopcartList
* @param specId
* @return
*/
private ShopcartBO getBuyCountsFromShopcart(List<ShopcartBO> shopcartList, String specId) {
for (ShopcartBO cart : shopcartList) {
if (cart.getSpecId().equals(specId)) {
return cart;
}
}
return null;
}