package com.peanut.modules.book.controller; import java.math.BigDecimal; import java.util.*; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.stream.Collectors; import com.alibaba.fastjson.JSONObject; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.toolkit.IdWorker; import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.peanut.modules.book.entity.*; import com.peanut.modules.book.service.*; import lombok.extern.slf4j.Slf4j; import lombok.var; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.peanut.common.utils.PageUtils; import com.peanut.common.utils.R; /** * 订单表 * * @author yl * @email yl328572838@163.com * @date 2022-08-29 15:27:44 */ @Slf4j @RestController @RequestMapping("book/buyorder") public class BuyOrderController { @Autowired private BuyOrderService buyOrderService; @Autowired private ShopProductService shopProductService; @Autowired private BuyOrderDetailService buyOrderDetailService; @Autowired private CouponService couponService; @Autowired private CouponHistoryService couponHistoryService; @Autowired private OrderCartService orderCartService; @Autowired private MyUserService myUserService; @Autowired private TransactionDetailsService transactionDetailsService; @Autowired private AuthorService authorService; @Autowired private UserEbookBuyService userEbookBuyService; @Autowired private BookService bookService; @Autowired private BookShelfService bookShelfService; @Autowired private UserRecordService userRecordService; @Autowired private UserFollowUpService userFollowUpService; @Autowired private PayWechatOrderService payWechatOrderService; @Autowired private PayZfbOrderService payZfbOrderService; /** * 订单状态 - 待支付 */ private static final String ORDER_STATUS_TO_BE_PAID = "0"; /** * 订单状态 - 待发货 */ private static final String ORDER_STATUS_TO_BE_SHIPPED = "1"; /** * 订单状态 - 待收货 */ private static final String ORDER_STATUS_TO_BE_RECEIVED = "2"; /** * 支付方式 - 支付宝 */ private static final String PAYMENT_METHOD_ALI_PAY = "1"; /** * 支付方式 */ private static final String PAYMENT_METHOD_WECHAT_PAY = "2"; /** * 支付方式 */ private static final String PAYMENT_METHOD_IOS = "3"; /** * 支付方式 */ private static final String PAYMENT_METHOD_VIRTUAL = "4"; /** * 购买方式 - 直接购买 */ private static final String BUY_TYPE_REDIRECT = "0"; /** * 购买方式 - 购物车 */ private static final String BUY_TYPE_CART = "1"; @Autowired private ShopProudictBookService shopProudictBookService; /** * 列表 */ @RequestMapping("/list") public R list(@RequestParam Map params) throws Exception { if ("all".equals(params.get("orderStatus"))) { params.remove("orderStatus"); } PageUtils page = buyOrderService.queryPage(params); return R.ok().put("page", page); } /** * @param params * @return 听书未购买页面展示 * (销量最多的书,最先放最前面展示。最新上线的书,预售的书,放最前面展示 * @throws Exception */ @RequestMapping("/lists") public R lists(@RequestParam Map params) throws Exception { if ("all".equals(params.get("orderStatus"))) { params.remove("orderStatus"); } PageUtils page = buyOrderService.queryPages(params); return R.ok().put("page", page); } /** * 信息 */ @RequestMapping("/info/{orderId}") public R info(@PathVariable("orderId") Integer orderId) { BuyOrderEntity buyOrder = buyOrderService.getById(orderId); return R.ok().put("buyOrder", buyOrder); } /** * 下单 */ @RequestMapping("/buySave") @Transactional public R buySave(@RequestBody BuyOrderEntity buyOrder) { BigDecimal realMoney; // 根据订单获取订单详情 List products = buyOrder.getProducts(); // ? BigDecimal totalPrice = new BigDecimal(0); List list = new ArrayList<>(); // 遍历商品 查询价格 for (BuyOrderDetailEntity buyOrderDetail : products) { BuyOrderDetailEntity buyOrderDetailEntity = new BuyOrderDetailEntity(); Integer productId = buyOrderDetail.getProductId(); ShopProductEntity product = shopProductService.getById(productId); BigDecimal activityPrice = product.getActivityPrice(); // 实际执行价格 BigDecimal price; if (activityPrice == null || activityPrice.equals(BigDecimal.ZERO)) { price = product.getPrice(); } else { price = product.getActivityPrice(); } int quantity = buyOrderDetail.getQuantity(); totalPrice = totalPrice.add(price.multiply(BigDecimal.valueOf(quantity))); if (product.getProductStock() - quantity < 0) { return R.error(500, "库存不足"); } // 更新商品库存 product.setProductStock(product.getProductStock() - quantity); product.setSumSales(product.getSumSales() + quantity); shopProductService.updateById(product); BeanUtils.copyProperties(buyOrderDetail, buyOrderDetailEntity); buyOrderDetailEntity.setProductName(product.getProductName()); buyOrderDetailEntity.setProductPrice(product.getPrice()); buyOrderDetailEntity.setAddressId(buyOrder.getAddressId()); buyOrderDetailEntity.setProductUrl(product.getProductImages()); buyOrderDetailEntity.setOrderStatus(ORDER_STATUS_TO_BE_PAID); list.add(buyOrderDetailEntity); } Integer couponId = buyOrder.getCouponId(); if (couponId != null) { CouponHistoryEntity couponHistory = couponHistoryService.getById(couponId); CouponEntity coupon = couponService.getById(couponHistory.getCouponId()); BigDecimal amount = coupon.getCouponAmount(); totalPrice = totalPrice.subtract(amount); } if (buyOrder.getShippingMoney() != null) { totalPrice = totalPrice.add(buyOrder.getShippingMoney()); } // 减去优惠券金额 realMoney = buyOrder.getRealMoney(); if (totalPrice.compareTo(realMoney) == 0) { //特定格式的时间ID String timeId = IdWorker.getTimeId().substring(0, 32); buyOrder.setOrderSn(timeId); if (PAYMENT_METHOD_VIRTUAL.equals(buyOrder.getPaymentMethod())) { buyOrder.setOrderStatus(ORDER_STATUS_TO_BE_SHIPPED); } buyOrder.setPaymentDate(new Date()); buyOrderService.save(buyOrder); for (BuyOrderDetailEntity buyOrderDetailEntity : list) { buyOrderDetailEntity.setOrderId(buyOrder.getOrderId()); buyOrderDetailEntity.setUserId(buyOrder.getUserId()); // 判断结算状态 String buyType = buyOrder.getBuyType(); if (buyType.equals(BUY_TYPE_CART)) { // 更改购物车 状态 List orderCartList = orderCartService.getBaseMapper().selectList(new QueryWrapper() .eq("user_id", buyOrder.getUserId()).eq("product_id", buyOrderDetailEntity.getProductId())); if (orderCartList.size() > 0) { List collect = orderCartList.stream().map(orderCartEntity -> { Integer cartId = orderCartEntity.getCartId(); return cartId; }).collect(Collectors.toList()); orderCartService.removeByIds(collect); } } } buyOrderDetailService.saveBatch(list); if (couponId != null) { //更改优惠券状态 CouponHistoryEntity one = couponHistoryService.getById(couponId); one.setUseStatus(1); one.setUseTime(new Date()); one.setOrderId(Long.valueOf(buyOrder.getOrderId())); one.setOrderSn(buyOrder.getOrderSn()); couponHistoryService.updateById(one); } if ("4".equals(buyOrder.getPaymentMethod())) { MyUserEntity user = this.myUserService.getById(buyOrder.getUserId()); if (user.getPeanutCoin().compareTo(realMoney) >= 0) { user.setPeanutCoin(user.getPeanutCoin().subtract(realMoney)); this.myUserService.updateById(user); // 添加消费信息 TransactionDetailsEntity transactionDetailsEntity = new TransactionDetailsEntity(); transactionDetailsEntity.setRemark("购买健康超市用品!订单编号为《 " + buyOrder.getOrderSn() + "》"); transactionDetailsEntity.setUserId(user.getId()); transactionDetailsEntity.setUserName(user.getNickname()); transactionDetailsEntity.setChangeAmount(realMoney.negate()); transactionDetailsEntity.setUserBalance(user.getPeanutCoin()); transactionDetailsEntity.setTel(user.getTel()); transactionDetailsEntity.setOrderType("购买健康超市用品!"); transactionDetailsService.save(transactionDetailsEntity); //购买成功后,添加书到个人表中 List pros = products.stream().map(BuyOrderDetailEntity::getProductId).collect(Collectors.toList()); for (Integer s : pros) { List collect = shopProudictBookService.getBaseMapper().selectList(new LambdaQueryWrapper() .eq(ShopProudictBookEntity::getProudictId, s) .eq(ShopProudictBookEntity::getDelFlag, 0)).stream().map(ShopProudictBookEntity::getBookId).collect(Collectors.toList()); userEbookBuyService.addBookForUser(buyOrder.getUserId(), collect); } } else { return R.error("余额不足!"); } } } return R.ok().put("orderSn", buyOrder.getOrderSn()).put("money", realMoney); } /** * 修改 */ @RequestMapping("/update") // @RequiresPermissions("book:buyorder:update") public R update(@RequestBody BuyOrderEntity buyOrder) { buyOrderService.updateById(buyOrder); return R.ok(); } /** * 删除 */ @RequestMapping("/delete") // @RequiresPermissions("book:buyorder:delete") public R delete(@RequestBody Integer[] orderIds) { buyOrderService.removeByIds(Arrays.asList(orderIds)); return R.ok(); } /** * 列表 */ @RequestMapping("/appUserGetlist") // @RequiresPermissions("book:buyorder:list") public R appUserGetlist(@RequestParam Map params) { PageUtils page = buyOrderService.queryPage1(params); return R.ok().put("page", page); } /** * app 端 取消订单 */ @RequestMapping("/appDelete") // @RequiresPermissions("book:buyorder:delete") @Transactional public R appDelete(@RequestParam("orderId") Integer orderId) { //1. 判断订单状态 BuyOrderEntity byId = buyOrderService.getById(orderId); if (byId != null) { //2. 判断当前订单是否存在优惠券 进行 回显 Integer couponId = byId.getCouponId(); if (couponId != null) { CouponHistoryEntity byId1 = couponHistoryService.getById(couponId); byId1.setUseStatus(0); couponHistoryService.updateById(byId1); } // 库存回滚 List buyOrderDetailEntities = buyOrderDetailService.getBaseMapper().selectList(new QueryWrapper() .eq("order_id", byId.getOrderId())); for (BuyOrderDetailEntity buyOrderDetailEntity : buyOrderDetailEntities) { Integer productId = buyOrderDetailEntity.getProductId(); ShopProductEntity product = shopProductService.getById(productId); product.setProductStock(product.getProductStock() + buyOrderDetailEntity.getQuantity()); shopProductService.updateById(product); } // //3. 恢复当前订单 的 购物车商品 // // List products = buyOrderDetailService.getBaseMapper().selectList(new QueryWrapper() // .eq("order_id", orderId)); // // for (BuyOrderDetailEntity product : products) { // // Integer productId = product.getProductId(); // // OrderCartEntity byId1 = orderCartService.getDeteleOrderCarts(byId.getUserId(),productId); // // byId1.setDelFlag(0); // // orderCartService.updateById(byId1); // // } buyOrderService.removeById(orderId); } return R.ok(); } @RequestMapping("/randomOrderCode") @Transactional public R randomOrderCode(@RequestBody BuyOrderEntity buyOrder) { // String re= String.valueOf(buyOrderService.randomOrderCode(buyOrder)); // buyOrderService.save(re); return R.ok(); } /** * 充值专用订单生成接口 */ @RequestMapping("/rechargeSave") @Transactional public R rechargeSave(@RequestBody BuyOrderEntity buyOrder) { String timeId = IdWorker.getTimeId().substring(0, 32); buyOrder.setOrderSn(timeId); buyOrderService.save(buyOrder); return R.ok().put("orderSn", timeId); } /** * 信息 */ @RequestMapping("/appGetOrderInfo/{type}") public R appGetOrderInfo(@PathVariable String type, @RequestParam("orderId") Integer orderId) { BuyOrderEntity buyOrder = buyOrderService.getById(orderId); List orderDetail = null; if ("1".equals(type)) { orderDetail = buyOrderDetailService.getBaseMapper().selectList(new QueryWrapper() .eq("order_id", orderId)); } else { orderDetail = buyOrderDetailService.getBaseMapper().selectList(new QueryWrapper() .eq("order_id", orderId)); //TODO 根据shipping_sn快递单号分组,订单下无快递单号,我的订单同时无法显示,暂时注释 //.groupBy("shipping_sn") } for (BuyOrderDetailEntity buyOrderDetailEntity : orderDetail) { ShopProductEntity prod = shopProductService.getById(buyOrderDetailEntity.getProductId()); if (prod != null) { buyOrderDetailEntity.setImage(prod.getProductImages()); } } List resultOrder = new ArrayList(); Set sn_no = new HashSet(); for (BuyOrderDetailEntity buyOrderDetailEntity : orderDetail) { resultOrder.add(buyOrderDetailEntity); sn_no.add(buyOrderDetailEntity.getShippingSn()); } UserRecordEntity userRecordEntity = userRecordService.getBaseMapper().selectOne(new QueryWrapper() .eq("orderSn", buyOrder.getOrderSn()) .eq("userid", buyOrder.getUserId()) .eq("orderdid", buyOrder.getOrderId()) .last("LIMIT 1")); Integer id = null; if (userRecordEntity != null) { id = userRecordEntity.getId(); } buyOrder.setProducts(resultOrder); Date createDate = buyOrder.getCreateTime(); return R.ok().put("buyOrder", buyOrder).put("CreateTime", createDate).put("userRecordid", id); } /** * 计算快递费用 */ @RequestMapping("/getTransPrice/{area}") public R getTransPrice(@PathVariable String area, @RequestParam Map productMap) { Map params = new HashMap<>(); params.put("kdCode", "YD"); params.put("area", area); int price = this.buyOrderService.getProductGoodsType(params, productMap); return R.ok().put("price", price); } /** * 后台发货按钮 * * @Param shipperCode 快递公司编码 * @Param sendType 0:订单列表发货 1:商品列表发货 * @Param type 合并发货/拆分发货 * @Param ids 订单id串 */ @RequestMapping("/delivery/{shipperCode}") public R delivery(@PathVariable("shipperCode") String shipperCode, @RequestParam("shipperName") String shipperName, @RequestBody Integer[] ids) { buyOrderService.sendFMS(ids, shipperCode, shipperName); return R.ok(); } /** * 及时查询快递信息 */ @RequestMapping("/queryFMS") public R queryFMS(@RequestParam Map params) { List detailList = this.buyOrderDetailService.getBaseMapper().selectList(new QueryWrapper().eq("order_id", params.get("orderId"))); List jsonList = new ArrayList<>(); JSONObject jsonObj = null; for (BuyOrderDetailEntity detail : detailList) { jsonObj = buyOrderService.queryFMS(detail.getShipperCode(), detail.getShippingSn()); if (Objects.isNull(jsonObj)) { return R.ok("暂未查到物流信息!"); } jsonObj.put("ShipperName", detail.getShipperName()); jsonList.add(jsonObj); } return R.ok().put("rntStr", jsonList); } /** * 检查可合并的订单信息 * * @return */ @RequestMapping("/checkOrder") public R checkOrder(@RequestParam Map params) { Page page = buyOrderService.checkOrder(params); return R.ok().put("page", page); } /** * 检查传来的orderId 是否有可合并的其他订单信息 * * @param orderIds * @return */ @RequestMapping("/checkMerge") public R checkMerge(@RequestBody Integer[] orderIds) { List list = buyOrderService.checkOrder(orderIds); return R.ok().put("list", list); } /** * 批量发货功能 * * @param orderDetailIds 订单详情 * @return */ @RequestMapping("/blendSendFMS/{shipperCode}") public R blendSendFMS(@PathVariable("shipperCode") String shipperCode, @RequestParam("shipperName") String shipperName, @RequestBody Integer[] orderDetailIds) { buyOrderService.blendSendFMS(orderDetailIds, shipperCode, shipperName); return R.ok(); } /** * 后台取消订单接口 */ @RequestMapping("/cancelFMS") public R cancelFMS(@RequestParam Map params) { buyOrderService.cancelFMS(params.get("orderSn").toString(), params.get("shipperCode").toString(), params.get("expNo").toString()); // return R.ok() return R.ok().put("paramsTEXT", params); } /** * 去重查询可打印面单 * * @param params * @return */ @RequestMapping("/querySheetPage") public R querySheetPage(@RequestParam Map params) { PageUtils page = buyOrderDetailService.querySheet(params); return R.ok().put("page", page); } }