瀏覽代碼

开发模拟订单

wang 3 周之前
父節點
當前提交
a6ea839302

+ 40 - 42
yami-shop-api/src/main/java/com/yami/shop/api/controller/OrderController.java

@@ -70,7 +70,7 @@ public class OrderController {
     @PostMapping("/confirm")
     @ApiOperation(value = "结算,生成订单信息", notes = "传入下单所需要的参数进行下单")
     public ResponseEntity<ShopCartOrderMergerDto> confirm(@Valid @RequestBody OrderParam orderParam) {
-        if (orderParam.getOrderItem() == null){
+        if (orderParam.getOrderItem() == null) {
             orderParam.getBasketIds().forEach(basketId -> {
                 Basket byId = basketService.getById(basketId);
                 Sku byIdss = skuService.getById(byId);
@@ -82,15 +82,14 @@ public class OrderController {
                     throw new GlobalException("当前选择的规格库存不足!");
                 }
             });
-        }else {
+        } else {
             Sku byId = skuService.getById(orderParam.getOrderItem().getSkuId());
-            boolean skuStock = qnhService.getSkuStock(byId.getSkuCode(), byId.getProdId(),orderParam.getPlatform());
-            Product byId1 = productService.getById(byId.getProdId(),orderParam.getPlatform());
-            byId1.setTotalStocks(byId.getStocks());
+            boolean skuStock = qnhService.getSkuStock(byId.getSkuCode(), byId.getProdId(), orderParam.getPlatform());
+            Product byId1 = productService.getById(byId.getProdId(), orderParam.getPlatform());
             productService.updateById(byId1);
-//            if (skuStock && byId1.getTotalStocks() < orderParam.getOrderItem().getProdCount()) {
-//                throw new GlobalException("当前选择的规格库存不足!");
-//            }
+            if (skuStock && byId1.getTotalStocks() < orderParam.getOrderItem().getProdCount()) {
+                throw new GlobalException("当前选择的规格库存不足!");
+            }
         }
         String userId = SecurityUtils.getUser().getUserId();
         orderParam.setDvyType(1);
@@ -99,13 +98,14 @@ public class OrderController {
         UserAddr userAddr = userAddrService.getUserAddrByUserId(orderParam.getAddrId(), userId);
         UserAddrDto userAddrDto = mapperFacade.map(userAddr, UserAddrDto.class);
         // 组装获取用户提交的购物车商品项
+        //TODO wangjian 目前是写死的
         List<ShopCartItemDto> shopCartItems = basketService.getShopCartItemsByOrderItems(orderParam.getBasketIds(), orderParam.getOrderItem(), userId);
         if (CollectionUtil.isEmpty(shopCartItems)) {
             throw new GlobalException("请选择您需要的商品加入购物车");
         }
 
         // 根据店铺组装购车中的商品信息,返回每个店铺中的购物车商品信息
-        List<ShopCartDto> shopCarts = basketService.getShopCarts(shopCartItems,0L);
+        List<ShopCartDto> shopCarts = basketService.getShopCarts(shopCartItems, 0L);
 
         // 将要返回给前端的完整的订单信息
         ShopCartOrderMergerDto shopCartOrderMergerDto = new ShopCartOrderMergerDto();
@@ -127,15 +127,12 @@ public class OrderController {
 
 //        List<CouponOrderDto> coupons = new ArrayList<>();
         for (ShopCartDto shopCart : shopCarts) {
-
             // 每个店铺的订单信息
             ShopCartOrderDto shopCartOrder = new ShopCartOrderDto();
             shopCartOrder.setShopId(shopCart.getShopId());
             shopCartOrder.setShopName(shopCart.getShopName());
 
-
             List<ShopCartItemDiscountDto> shopCartItemDiscounts = shopCart.getShopCartItemDiscounts();
-
             // 店铺中的所有商品项信息
             List<ShopCartItemDto> shopAllShopCartItems = new ArrayList<>();
             for (ShopCartItemDiscountDto shopCartItemDiscount : shopCartItemDiscounts) {
@@ -145,7 +142,7 @@ public class OrderController {
 
             shopCartOrder.setShopCartItemDiscounts(shopCartItemDiscounts);
             allCartItem.addAll(shopAllShopCartItems);
-
+            // TODO wangjian 计算积分抵现和分摊,报错
             applicationContext.publishEvent(new ConfirmOrderEvent(shopCartOrder, orderParam, shopAllShopCartItems));
 
             total = Arith.add(total, shopCartOrder.getTotal());
@@ -157,32 +154,34 @@ public class OrderController {
             shopCartOrders.add(shopCartOrder);
         }
 
-        //根据价格进行店铺、满减、商品项的价格升序操作
-        for (int n = 0; n < shopCartOrders.size(); n++) {
-            shopCartOrders = shopCartOrders.stream().sorted(Comparator.comparing(ShopCartOrderDto::getActualTotal)).collect(Collectors.toList());
-            ShopCartOrderDto shopCartOrderDto = shopCartOrders.get(n);
-
-            List<ShopCartItemDiscountDto> shopCartItemDiscounts = shopCartOrderDto.getShopCartItemDiscounts();
-            for (ShopCartItemDiscountDto shopCartItemDiscount : shopCartItemDiscounts) {
-                List<ShopCartItemDto> sortShopCartItems = shopCartItemDiscount.getShopCartItems();
-                sortShopCartItems = sortShopCartItems.stream().sorted(Comparator.comparing(ProductItemDto::getActualTotal)).collect(Collectors.toList());
-                shopCartItemDiscount.setShopCartItems(sortShopCartItems);
-                double totalAmount = shopCartItemDiscount.getShopCartItems().stream().mapToDouble(ProductItemDto::getActualTotal).sum();
-                shopCartItemDiscount.setTotalAmount(totalAmount);
-            }
-            // 如果是折扣特别小的情况下,导致实际金额为0是,改变最小支付金额为0.01元,并且优惠金额减去0.01。
-            if (shopCartOrderDto.getActualTotal() <= 0) {
-                shopCartOrderDto.setActualTotal(0.01);
-                shopCartOrderDto.setShopReduce(Arith.sub(shopCartOrderDto.getShopReduce(), 0.01));
-                List<ShopCartItemDto> sortItems = shopCartItemDiscounts.get(shopCartItemDiscounts.size() - 1).getShopCartItems();
-                ShopCartItemDto shopCartItemDto = sortItems.get(sortItems.size() - 1);
-                shopCartItemDto.setActualTotal(0.01);
-                shopCartItemDto.setShareReduce(Arith.sub(shopCartItemDto.getShareReduce(), 0.01));
-            }
-            shopCartItemDiscounts = shopCartItemDiscounts.stream().sorted(Comparator.comparing(ShopCartItemDiscountDto::getTotalAmount)).collect(Collectors.toList());
-            shopCartOrders.get(n).setShopCartItemDiscounts(shopCartItemDiscounts);
-            actualTotal = Arith.add(actualTotal, shopCartOrderDto.getActualTotal());
-        }
+//        //根据价格进行店铺、满减、商品项的价格升序操作
+//        for (int n = 0; n < shopCartOrders.size(); n++) {
+//            shopCartOrders = shopCartOrders.stream().sorted(Comparator.comparing(ShopCartOrderDto::getActualTotal)).collect(Collectors.toList());
+//            ShopCartOrderDto shopCartOrderDto = shopCartOrders.get(n);
+//
+//            List<ShopCartItemDiscountDto> shopCartItemDiscounts = shopCartOrderDto.getShopCartItemDiscounts();
+//            for (ShopCartItemDiscountDto shopCartItemDiscount : shopCartItemDiscounts) {
+//                List<ShopCartItemDto> sortShopCartItems = shopCartItemDiscount.getShopCartItems();
+//                sortShopCartItems = sortShopCartItems.stream().sorted(Comparator.comparing(ProductItemDto::getActualTotal)).collect(Collectors.toList());
+//                shopCartItemDiscount.setShopCartItems(sortShopCartItems);
+//                double totalAmount = shopCartItemDiscount.getShopCartItems().stream().mapToDouble(ProductItemDto::getActualTotal).sum();
+//                //TODO 计算真实总库存
+//                shopCartItemDiscount.setTotalAmount(totalAmount);
+//            }
+//            // 如果是折扣特别小的情况下,导致实际金额为0是,改变最小支付金额为0.01元,并且优惠金额减去0.01。
+//            if (shopCartOrderDto.getActualTotal() <= 0) {
+//                shopCartOrderDto.setActualTotal(0.01);
+//                shopCartOrderDto.setShopReduce(Arith.sub(shopCartOrderDto.getShopReduce(), 0.01));
+//                List<ShopCartItemDto> sortItems = shopCartItemDiscounts.get(shopCartItemDiscounts.size() - 1).getShopCartItems();
+//                ShopCartItemDto shopCartItemDto = sortItems.get(sortItems.size() - 1);
+//                shopCartItemDto.setActualTotal(0.01);
+//                shopCartItemDto.setShareReduce(Arith.sub(shopCartItemDto.getShareReduce(), 0.01));
+//            }
+//            shopCartItemDiscounts = shopCartItemDiscounts.stream().sorted(Comparator.comparing(ShopCartItemDiscountDto::getTotalAmount)).collect(Collectors.toList());
+//            shopCartOrders.get(n).setShopCartItemDiscounts(shopCartItemDiscounts);
+//            //TODO 计算真实总库存
+//            actualTotal = Arith.add(actualTotal, shopCartOrderDto.getActualTotal());
+//        }
 
         shopCartOrderMergerDto.setActualTotal(actualTotal);
         shopCartOrderMergerDto.setTotal(total);
@@ -203,8 +202,6 @@ public class OrderController {
         allOrderReduce = 0.00;
         totalTransfee = 0.00;
         for (ShopCartOrderDto shopCartOrder : shopCartOrders) {
-
-
             //订单实际金额
             double orderActualTotal = 0.00;
             //商家优惠金额
@@ -222,7 +219,8 @@ public class OrderController {
                     orderPlatformAmount = Arith.add(orderPlatformAmount, shopCartItem.getPlatformShareReduce());
                 }
             }
-            shopCartOrder.setActualTotal(Arith.add(orderActualTotal, shopCartOrder.getTransfee()));
+//            shopCartOrder.setActualTotal(Arith.add(orderActualTotal, shopCartOrder.getTransfee()));
+            shopCartOrder.setActualTotal(100.0);
             //放入优惠金额
             shopCartOrder.setShopReduce(Arith.add(orderReduceAmount, shopCartOrder.getFreeTransfee()));
             //放入平台优惠金额,如果用户等级免自营店运费也要放进去

+ 21 - 19
yami-shop-api/src/main/java/com/yami/shop/api/listener/SubmitOrderListener.java

@@ -218,25 +218,25 @@ public class SubmitOrderListener {
             basketMapper.deleteShopCartItemsByBasketIds(userId, basketIds);
         }
 
-
+//TODO wangjia 修改本地库存
         // 更新sku库存
-        skuStocksMap.forEach((key, sku) -> {
-
-            if (skuMapper.updateStocks(sku) == 0) {
-                skuService.removeSkuCacheBySkuId(key, sku.getProdId());
-                productService.removeProductCacheByProdId(sku.getProdId());
-                throw new GlobalException("商品:[" + sku.getProdName() + "]库存不足");
-            }
-        });
+//        skuStocksMap.forEach((key, sku) -> {
+//
+//            if (skuMapper.updateStocks(sku) == 0) {
+//                skuService.removeSkuCacheBySkuId(key, sku.getProdId());
+//                productService.removeProductCacheByProdId(sku.getProdId());
+//                throw new GlobalException("商品:[" + sku.getProdName() + "]库存不足");
+//            }
+//        });
 
         // 更新商品库存
-        prodStocksMap.forEach((prodId, prod) -> {
-
-            if (productMapper.updateStocks(prod) == 0) {
-                productService.removeProductCacheByProdId(prodId);
-                throw new GlobalException("商品:[" + prod.getProdName() + "]库存不足");
-            }
-        });
+//        prodStocksMap.forEach((prodId, prod) -> {
+//
+//            if (productMapper.updateStocks(prod) == 0) {
+//                productService.removeProductCacheByProdId(prodId);
+//                throw new GlobalException("商品:[" + prod.getProdName() + "]库存不足");
+//            }
+//        });
 
     }
 
@@ -277,8 +277,10 @@ public class SubmitOrderListener {
 
     @SuppressWarnings({"Duplicates"})
     private Sku checkAndGetSku(Long skuId, ShopCartItemDto shopCartItem, Map<Long, Sku> skuStocksMap) {
+        //TODO wangjian 先让接口正常 shopCartItem
+        shopCartItem.setProdCount(9);
         // 获取sku信息
-        Sku sku = skuService.getSkuBySkuId(skuId);
+        Sku sku = skuService.getSkuBySkuId(skuId,1,158L);
         if (sku == null) {
             throw new GlobalException("购物车包含无法识别的商品");
         }
@@ -287,11 +289,11 @@ public class SubmitOrderListener {
             throw new GlobalException("商品[" + sku.getProdName() + "]已下架");
         }
         // -1为无限库存
-        if (sku.getStocks() != -1 && shopCartItem.getProdCount() > sku.getStocks()) {
+        if (sku.getActualStocks() != -1 && shopCartItem.getProdCount() > sku.getActualStocks()) {
             throw new GlobalException("商品:[" + sku.getProdName() + "]库存不足");
         }
 
-        if (sku.getStocks() != -1) {
+        if (sku.getActualStocks() != -1) {
             Sku mapSku = new Sku();
             mapSku.setProdId(sku.getProdId());
             // 这里的库存是改变的库存

+ 10 - 5
yami-shop-bean/src/main/java/com/yami/shop/bean/app/param/SubmitOrderParam.java

@@ -17,10 +17,15 @@ import io.swagger.annotations.ApiModelProperty;
 import lombok.Data;
 
 @Data
-@ApiModel(value= "提交订单参数")
+@ApiModel(value = "提交订单参数")
 public class SubmitOrderParam {
-	@ApiModelProperty(value = "每个店铺提交的订单信息",required=true)
-	private List<OrderShopParam> orderShopParam;
-	@ApiModelProperty(value = "每次订单提交时的uuid")
-	private String uuid;
+    @ApiModelProperty(value = "每个店铺提交的订单信息", required = true)
+    private List<OrderShopParam> orderShopParam;
+    @ApiModelProperty(value = "每次订单提交时的uuid")
+    private String uuid;
+    @ApiModelProperty(value = "渠道id")
+    private Integer platform;
+    @ApiModelProperty(value = "门店id")
+    private Long shopId;
+
 }

+ 20 - 16
yami-shop-service/src/main/java/com/yami/shop/dao/SkuMapper.java

@@ -22,28 +22,32 @@ import com.baomidou.mybatisplus.core.mapper.BaseMapper;
 
 public interface SkuMapper extends BaseMapper<Sku> {
 
-	/**
-	 * 批量插入sku
-	 * @param prodId 商品id
-	 * @param skuList sku列表
-	 */
-	void insertBatch(@Param("prodId") Long prodId, @Param("skuList") List<Sku> skuList);
+    /**
+     * 批量插入sku
+     *
+     * @param prodId  商品id
+     * @param skuList sku列表
+     */
+    void insertBatch(@Param("prodId") Long prodId, @Param("skuList") List<Sku> skuList);
 
-	List<Sku> listByProdId(@Param("prodId")Long prodId);
+    List<Sku> listByProdId(@Param("prodId") Long prodId);
 
-	List<Sku> listByProdIdAndPlatform(@Param("prodId")Long prodId,@Param("platform")Integer platform,@Param("shopId")Long shopId);
+    List<Sku> listByProdIdAndPlatform(@Param("prodId") Long prodId, @Param("platform") Integer platform, @Param("shopId") Long shopId);
 
-	int updateStocks(@Param("sku") Sku sku);
+    Sku listBySukIdAndPlatform(@Param("skuId") Long skuId, @Param("platform") Integer platform, @Param("shopId") Long shopId);
 
-	void deleteByProdId(@Param("prodId") Long prodId);
+    int updateStocks(@Param("sku") Sku sku);
 
-	void returnStock(@Param("skuCollect") Map<Long, Integer> skuCollect);
+    void deleteByProdId(@Param("prodId") Long prodId);
 
-	/**
-	 * 通过海博单品编码查询商品
-	 * @param hbSkuId 单品编码
-	 * @return 单品信息
-	 */
+    void returnStock(@Param("skuCollect") Map<Long, Integer> skuCollect);
+
+    /**
+     * 通过海博单品编码查询商品
+     *
+     * @param hbSkuId 单品编码
+     * @return 单品信息
+     */
     Sku selectByHbSkuId(@Param("hbSkuId") String hbSkuId);
 
 

+ 7 - 0
yami-shop-service/src/main/java/com/yami/shop/service/SkuService.java

@@ -43,6 +43,13 @@ public interface SkuService extends IService<Sku> {
      * @return
      */
     Sku getSkuBySkuId(Long skuId);
+    /**
+     * 根据skuId获取sku信息(将会被缓存起来)
+     *
+     * @param skuId
+     * @return
+     */
+    Sku getSkuBySkuId(Long skuId, Integer platform, Long shopId);
 
     void removeSkuCacheBySkuId(Long skuId, Long prodId);
 }

+ 3 - 9
yami-shop-service/src/main/java/com/yami/shop/service/impl/BasketServiceImpl.java

@@ -145,17 +145,13 @@ public class BasketServiceImpl extends ServiceImpl<BasketMapper, Basket> impleme
             List<ShopCartDto> shopCartDtos2 = Lists.newArrayList();
             //获取店铺的所有商品项
             List<ShopCartItemDto> shopCartItemDtoList2 = shopCartMap.get(shopId1);
-
             if(shopCartItemDtoList2 != null){
                 // 构建每个店铺的购物车信息
                 ShopCartDto shopCart2 = new ShopCartDto();
-
                 //店铺信息
                 shopCart2.setShopId(shopId1);
                 shopCart2.setShopName(shopCartItemDtoList2.get(0).getShopName());
-
                 applicationContext.publishEvent(new ShopCartEvent(shopCart2, shopCartItemDtoList2));
-
                 // 自营店的购物车位置是放在第一的
                 if (Objects.equals(1L, shopId1)) {
                     shopCartDtos2.add(0, shopCart2);
@@ -170,16 +166,12 @@ public class BasketServiceImpl extends ServiceImpl<BasketMapper, Basket> impleme
         for (Long shopId : shopCartMap.keySet()) {
             //获取店铺的所有商品项
             List<ShopCartItemDto> shopCartItemDtoList = shopCartMap.get(shopId);
-
             // 构建每个店铺的购物车信息
             ShopCartDto shopCart = new ShopCartDto();
-
             //店铺信息
             shopCart.setShopId(shopId);
             shopCart.setShopName(shopCartItemDtoList.get(0).getShopName());
-
             applicationContext.publishEvent(new ShopCartEvent(shopCart, shopCartItemDtoList));
-
             // 自营店的购物车位置是放在第一的
             if (Objects.equals(1L, shopId)) {
                 shopCartDtos.add(0, shopCart);
@@ -236,7 +228,9 @@ public class BasketServiceImpl extends ServiceImpl<BasketMapper, Basket> impleme
         shopCartItemDto.setCategoryId(prod.getCategoryId());
         shopCartItemDto.setPic(StrUtil.isBlank(sku.getPic()) ? prod.getPic() : sku.getPic());
         shopCartItemDto.setProdName(sku.getProdName());
-        shopCartItemDto.setProductTotalAmount(Arith.mul(sku.getPrice(), orderItem.getProdCount()));
+        //TODO wangjain 空指针 sku.getPrice(),需要去查sku_shop中的价格
+//        shopCartItemDto.setProductTotalAmount(Arith.mul(sku.getPrice(), orderItem.getProdCount()));
+        shopCartItemDto.setProductTotalAmount(Arith.mul(1, orderItem.getProdCount()));
         shopCartItemDto.setPrice(sku.getPrice());
         shopCartItemDto.setDistributionCardNo(orderItem.getDistributionCardNo());
         shopCartItemDto.setBasketDate(new Date());

+ 359 - 357
yami-shop-service/src/main/java/com/yami/shop/service/impl/CategoryServiceImpl.java

@@ -20,6 +20,7 @@ import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
 import com.google.common.collect.Lists;
 import com.yami.shop.bean.dto.ListCategoryDTO;
 import com.yami.shop.bean.model.Category;
+import com.yami.shop.bean.model.ShopCategory;
 import com.yami.shop.bean.param.CategoryScoreConfigParam;
 import com.yami.shop.bean.param.ScoreConfigParam;
 import com.yami.shop.bean.vo.ListCategoryForUserVO;
@@ -27,10 +28,7 @@ import com.yami.shop.bean.vo.ListCategoryVO;
 import com.yami.shop.common.config.Constant;
 import com.yami.shop.common.exception.GlobalException;
 import com.yami.shop.config.ShopConfig;
-import com.yami.shop.dao.CategoryBrandMapper;
-import com.yami.shop.dao.CategoryMapper;
-import com.yami.shop.dao.CategoryProdMapper;
-import com.yami.shop.dao.ProductMapper;
+import com.yami.shop.dao.*;
 import com.yami.shop.service.CategoryService;
 import com.yami.shop.service.SysConfigService;
 import lombok.AllArgsConstructor;
@@ -53,136 +51,137 @@ import static java.util.stream.Collectors.groupingBy;
  */
 @Service
 @AllArgsConstructor
-public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService{
+public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
 
-	private final CategoryMapper categoryMapper;
-	private final ShopConfig shopConfig;
+    private final CategoryMapper categoryMapper;
+    private final ShopConfig shopConfig;
 
-	private final CategoryBrandMapper categoryBrandMapper;
+    private final CategoryBrandMapper categoryBrandMapper;
 
-	private final CategoryProdMapper categoryPropMapper;
+    private final CategoryProdMapper categoryPropMapper;
+    private final ShopCategoryMapper shopCategoryMapper;
 
-	private final ProductMapper productMapper;
+    private final ProductMapper productMapper;
 
-	private SysConfigService sysConfigService;
+    private SysConfigService sysConfigService;
 
-	@Override
-	@Transactional(rollbackFor = Exception.class)
+    @Override
+    @Transactional(rollbackFor = Exception.class)
 //	@CacheEvict(cacheNames = "CategoryListByParentIdAndShopId", key = "#category.parentId + ':' + #category.shopId")
-	@Caching(evict = {
-			@CacheEvict(cacheNames = "CategoryListByParentIdAndShopId", key = "#category.parentId + ':' + #category.shopId"),
-			@CacheEvict(cacheNames = "CategoryListByShopId", key = "#category.shopId + ':category'")
-	})
-	public void saveCategroy(Category category) {
-		category.setRecTime(new Date());
-		// 保存分类信息
-		categoryMapper.insert(category);
-
-		insertBrandsAndAttributes(category);
-
-		if (Objects.equals(category.getParentId(),Constant.CATEGORY_ID) && Objects.equals(category.getShopId(),Constant.PLATFORM_SHOP_ID)){
-			this.changeScoreConfig();
-		}
-	}
-
-	@Override
-	@Transactional(rollbackFor = Exception.class)
+    @Caching(evict = {
+            @CacheEvict(cacheNames = "CategoryListByParentIdAndShopId", key = "#category.parentId + ':' + #category.shopId"),
+            @CacheEvict(cacheNames = "CategoryListByShopId", key = "#category.shopId + ':category'")
+    })
+    public void saveCategroy(Category category) {
+        category.setRecTime(new Date());
+        // 保存分类信息
+        categoryMapper.insert(category);
+
+        insertBrandsAndAttributes(category);
+
+        if (Objects.equals(category.getParentId(), Constant.CATEGORY_ID) && Objects.equals(category.getShopId(), Constant.PLATFORM_SHOP_ID)) {
+            this.changeScoreConfig();
+        }
+    }
+
+    @Override
+    @Transactional(rollbackFor = Exception.class)
 //	@CacheEvict(cacheNames = "CategoryListByParentIdAndShopId", key = "#category.parentId + ':' + #category.shopId")
-	@Caching(evict = {
-			@CacheEvict(cacheNames = "CategoryListByParentIdAndShopId", key = "#category.parentId + ':' + #category.shopId"),
-			@CacheEvict(cacheNames = "CategoryListByShopId", key = "#category.shopId + ':category'")
-	})
-	public void updateCategroy(Category category) {
-		Category categoryDB = categoryMapper.selectById(category.getCategoryId());
-		category.setUpdateTime(new Date());
-
-		// 保存分类信息
-		categoryMapper.updateById(category);
-
-		if (Objects.equals(categoryDB.getStatus(),1) && Objects.equals(category.getStatus(),0)){
-			if (Objects.equals(category.getParentId(), 0L)){
-				List<Category> categorieList = categoryMapper.selectList(new LambdaQueryWrapper<Category>().eq(Category::getParentId, category.getCategoryId()));
-				for (Category categoryByParentId: categorieList){
-					categoryByParentId.setStatus(0);
-					//从正常改为下线
-					productMapper.offlineProdByCategoryId(categoryByParentId.getCategoryId());
-				}
-				updateBatchById(categorieList);
-			}else {
-				//从正常改为下线
-				productMapper.offlineProdByCategoryId(category.getCategoryId());
-			}
-		}
-
-		//修改积分配置中的分类数据
-		if (!Objects.equals(category.getCategoryName(),category.getOldCategoryName())){
-			this.changeScoreConfig();
-		}
-		// 先删除后增加
-		deleteBrandsAndAttributes(category.getCategoryId());
-		insertBrandsAndAttributes(category);
-	}
-
-	@Override
-	@Transactional(rollbackFor = Exception.class)
+    @Caching(evict = {
+            @CacheEvict(cacheNames = "CategoryListByParentIdAndShopId", key = "#category.parentId + ':' + #category.shopId"),
+            @CacheEvict(cacheNames = "CategoryListByShopId", key = "#category.shopId + ':category'")
+    })
+    public void updateCategroy(Category category) {
+        Category categoryDB = categoryMapper.selectById(category.getCategoryId());
+        category.setUpdateTime(new Date());
+
+        // 保存分类信息
+        categoryMapper.updateById(category);
+
+        if (Objects.equals(categoryDB.getStatus(), 1) && Objects.equals(category.getStatus(), 0)) {
+            if (Objects.equals(category.getParentId(), 0L)) {
+                List<Category> categorieList = categoryMapper.selectList(new LambdaQueryWrapper<Category>().eq(Category::getParentId, category.getCategoryId()));
+                for (Category categoryByParentId : categorieList) {
+                    categoryByParentId.setStatus(0);
+                    //从正常改为下线
+                    productMapper.offlineProdByCategoryId(categoryByParentId.getCategoryId());
+                }
+                updateBatchById(categorieList);
+            } else {
+                //从正常改为下线
+                productMapper.offlineProdByCategoryId(category.getCategoryId());
+            }
+        }
+
+        //修改积分配置中的分类数据
+        if (!Objects.equals(category.getCategoryName(), category.getOldCategoryName())) {
+            this.changeScoreConfig();
+        }
+        // 先删除后增加
+        deleteBrandsAndAttributes(category.getCategoryId());
+        insertBrandsAndAttributes(category);
+    }
+
+    @Override
+    @Transactional(rollbackFor = Exception.class)
 //	@CacheEvict(cacheNames = "CategoryListByParentIdAndShopId", key = "#category.parentId + ':' + #category.shopId")
-	@Caching(evict = {
-			@CacheEvict(cacheNames = "CategoryListByParentIdAndShopId", key = "#category.parentId + ':' + #category.shopId"),
-			@CacheEvict(cacheNames = "CategoryListByShopId", key = "#category.shopId + ':category'")
-	})
-	public void deleteCategroy(Category category) {
-		categoryMapper.deleteById(category.getCategoryId());
-		//修改积分配置中的分类数据
-		if (Objects.equals(category.getParentId(),Constant.CATEGORY_ID)){
-			this.changeScoreConfig();
-		}
-		deleteBrandsAndAttributes(category.getCategoryId());
-	}
-
-	@Override
-	public Category getCategoryByCategoryIdAndShopId(Long categoryId, Long shopId) {
-		Category category = categoryMapper.selectOne(new LambdaQueryWrapper<Category>().eq(Category::getCategoryId, categoryId).eq(Category::getShopId, shopId));
-		if (category == null) {
-			throw new GlobalException("无法获取分类信息");
-		}
-		return category;
-	}
+    @Caching(evict = {
+            @CacheEvict(cacheNames = "CategoryListByParentIdAndShopId", key = "#category.parentId + ':' + #category.shopId"),
+            @CacheEvict(cacheNames = "CategoryListByShopId", key = "#category.shopId + ':category'")
+    })
+    public void deleteCategroy(Category category) {
+        categoryMapper.deleteById(category.getCategoryId());
+        //修改积分配置中的分类数据
+        if (Objects.equals(category.getParentId(), Constant.CATEGORY_ID)) {
+            this.changeScoreConfig();
+        }
+        deleteBrandsAndAttributes(category.getCategoryId());
+    }
+
+    @Override
+    public Category getCategoryByCategoryIdAndShopId(Long categoryId, Long shopId) {
+        Category category = categoryMapper.selectOne(new LambdaQueryWrapper<Category>().eq(Category::getCategoryId, categoryId).eq(Category::getShopId, shopId));
+        if (category == null) {
+            throw new GlobalException("无法获取分类信息");
+        }
+        return category;
+    }
 
     @Override
 //    @Cacheable(cacheNames = "CategoryListByParentIdAndShopId", key = "#parentId + ':' + #shopId")
     public IPage<Category> listByParentIdAndShopId(Long parentId, Long shopId, Integer current, Integer size) {
-		if (Objects.isNull(shopId)) {
-			IPage<Category> page = page(new Page<>(current, size), new LambdaQueryWrapper<Category>()
-					.eq(Category::getParentId, parentId)
-					.eq(Category::getStatus, 1)
-					.orderByDesc(Category::getSeq)
-					.orderByDesc(Category::getCategoryId));
-			List<Category> categories = page.getRecords();
-			if (CollectionUtil.isNotEmpty(categories)) {
-				for (Category category : categories) {
-					List<Category> son = categoryMapper.selectList(new LambdaQueryWrapper<Category>()
-							.eq(Category::getParentId, category.getCategoryId())
-							.eq(Category::getStatus, 1)
-							.orderByDesc(Category::getSeq));
-					category.setCategories(son);
-					if (CollectionUtil.isNotEmpty(son)) {
-						for (Category item : son) {
-							List<Category> third = categoryMapper.selectList(new LambdaQueryWrapper<Category>()
-									.eq(Category::getParentId, item.getCategoryId())
-									.eq(Category::getStatus, 1)
-									.orderByDesc(Category::getSeq));
-							item.setCategories(third);
-						}
-					}
-				}
-			}
-			Page res = new Page();
-			BeanUtils.copyProperties(page, res);
-			res.setRecords(categories);
-			return res;
-		}
-	    // 如果是平台分类,则特殊处理
-	    if(shopId == 0) {
+        if (Objects.isNull(shopId)) {
+            IPage<Category> page = page(new Page<>(current, size), new LambdaQueryWrapper<Category>()
+                    .eq(Category::getParentId, parentId)
+                    .eq(Category::getStatus, 1)
+                    .orderByDesc(Category::getSeq)
+                    .orderByDesc(Category::getCategoryId));
+            List<Category> categories = page.getRecords();
+            if (CollectionUtil.isNotEmpty(categories)) {
+                for (Category category : categories) {
+                    List<Category> son = categoryMapper.selectList(new LambdaQueryWrapper<Category>()
+                            .eq(Category::getParentId, category.getCategoryId())
+                            .eq(Category::getStatus, 1)
+                            .orderByDesc(Category::getSeq));
+                    category.setCategories(son);
+                    if (CollectionUtil.isNotEmpty(son)) {
+                        for (Category item : son) {
+                            List<Category> third = categoryMapper.selectList(new LambdaQueryWrapper<Category>()
+                                    .eq(Category::getParentId, item.getCategoryId())
+                                    .eq(Category::getStatus, 1)
+                                    .orderByDesc(Category::getSeq));
+                            item.setCategories(third);
+                        }
+                    }
+                }
+            }
+            Page res = new Page();
+            BeanUtils.copyProperties(page, res);
+            res.setRecords(categories);
+            return res;
+        }
+        // 如果是平台分类,则特殊处理
+        if (shopId == 0) {
 //            List<Category> categoriesTwo = categoryMapper.listByParentId(parentId);
 //            List<Category> categoriesThree = categoryMapper.listThreeByParentId(parentId);
 //            for (Category category : categoriesThree) {
@@ -200,136 +199,137 @@ public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> i
 //                }
 //            }
 //            return categoriesTwo;
-			return new Page<>();
-        }else {
-			IPage<Category> page2 = page(new Page<>(current, size), new LambdaQueryWrapper<Category>()
-					.eq(Category::getShopId,shopId)
-					.eq(Category::getParentId,parentId)
-					.eq(Category::getStatus, 1)
-					.orderByDesc(Category::getSeq)
-					.orderByDesc(Category::getCategoryId));
+            return new Page<>();
+        } else {
+            IPage<Category> page2 = page(new Page<>(current, size), new LambdaQueryWrapper<Category>()
+                    .eq(Category::getShopId, shopId)
+                    .eq(Category::getParentId, parentId)
+                    .eq(Category::getStatus, 1)
+                    .orderByDesc(Category::getSeq)
+                    .orderByDesc(Category::getCategoryId));
             return page2;
         }
     }
 
-	@Override
-	@Cacheable(cacheNames = "CategoryListByShopId", key = "#shopId + ':category'")
-	public List<Category> listByShopId(Long shopId) {
-		return categoryMapper.selectList(new LambdaQueryWrapper<Category>().eq(Category::getShopId,shopId));
-	}
-
-	@Override
-	public IPage<ListCategoryVO> listCategory(ListCategoryDTO listCategoryDTO) {
-		IPage<ListCategoryVO> listCategoryVOIPage = categoryMapper.listCategory(new Page<>(listCategoryDTO.getCurrent(), listCategoryDTO.getSize()), listCategoryDTO);
-		listCategoryVOIPage.getRecords().forEach(listCategoryVO -> {
-			listCategoryVO.setGrade(0);
-			if(listCategoryVO.getResource() == null){
-				listCategoryVO.setResource("");
-			}else {
-				listCategoryVO.setResource(listCategoryVO.getResource() + "个商品");
-			}
-			listCategoryVO.setProductBeBound(0);
-			listCategoryVO.setChildren(categoryMapper.listCategoryChildren(new ListCategoryDTO().setParentId(listCategoryVO.getCategoryID())));
-			listCategoryVO.getChildren().forEach(listCategoryVO1 -> {
-				listCategoryVO1.setGrade(1);
-				if(listCategoryVO1.getResource() == null){
-					listCategoryVO1.setResource("");
-				}else {
-					listCategoryVO1.setResource(listCategoryVO1.getResource() + "个商品");
-				}
-				List<ListCategoryVO> listCategoryVOS = categoryMapper.listCategoryChildren(new ListCategoryDTO().setParentId(listCategoryVO1.getCategoryID()));
-				if (listCategoryVOS.isEmpty()){
-					listCategoryVO1.setProductBeBound(1);
-					listCategoryVO1.setChildren(new ArrayList<>());
-				}else {
-					listCategoryVO1.setProductBeBound(0);
-					listCategoryVO1.setChildren(listCategoryVOS);
-					listCategoryVO1.getChildren().forEach(listCategoryVO2 -> {
-						listCategoryVO2.setGrade(2);
-						if(listCategoryVO2.getResource() == null){
-							listCategoryVO2.setResource("");
-						}else {
-							listCategoryVO2.setResource(listCategoryVO2.getResource() + "个商品");
-						}
-						listCategoryVO2.setProductBeBound(1);
-						listCategoryVO2.setChildren(new ArrayList<>());
-					});
-				}
-			});
-		});
-		return listCategoryVOIPage;
-	}
-
-	@Override
-	@Transactional(rollbackFor = Exception.class)
-	public Integer parseCategoryFile(MultipartFile excelFile, Long shopId) throws Exception {
-		// 1. 校验并解析Excel
-		List<List<String>> dataRows = validateAndParseExcel(excelFile);
-
-		// 2. 保存分类层级(若允许放宽主键依赖,可开启批量插入)
-		saveCategoryHierarchy(dataRows, shopId);
-
-		// 3. 返回成功导入的行数(每行对应一组三级分类)
-		return dataRows.size();
-	}
-
-	@Override
-	public List<ListCategoryForUserVO> listCategoryForUser(Long shopId) {
-		List<Category> categories = categoryMapper.selectList(
-				new LambdaQueryWrapper<Category>()
-						.eq(Category::getShopId, shopId)
-						.eq(Category::getStatus, 1)
-						.orderByDesc(Category::getSeq)
-		);
-		if (CollectionUtil.isEmpty(categories)) {
-			return Collections.emptyList();
-		}
-
-		Map<Long, List<Category>> parentMap = categories.stream()
-				.collect(Collectors.groupingBy(Category::getParentId));
-
-		// 初始层级为一级分类(grade = 1)
-		return buildCategoryTree(parentMap.getOrDefault(0L, Collections.emptyList()), parentMap, 0);
-	}
-
-	private List<ListCategoryForUserVO> buildCategoryTree(List<Category> categories, Map<Long, List<Category>> parentMap, int currentLevel) {
-		if (CollectionUtil.isEmpty(categories)) return Collections.emptyList();
-		return categories.stream()
-				.map(category -> {
-					ListCategoryForUserVO vo = new ListCategoryForUserVO();
-					BeanUtil.copyProperties(category, vo);
-					vo.setCategoryId(category.getCategoryId());
-
-					// 动态计算当前分类的等级(1: 一级, 2: 二级, 3: 三级)
-					int grade = currentLevel;
-					vo.setGrade(grade); // 如果 VO 类中需要保留 grade 字段,可保留此行
-
-					// 判断是否为二级或三级分类,并设置 productBeBound 字段
-					int productBeBound = 0;
-					if (grade == 1 || grade == 2) {
-						// 三级分类直接绑定商品
-						if (grade == 2) {
-							productBeBound = 1;
-						}
-						// 二级分类若无子分类(三级分类),则允许绑定商品
-						else if (grade == 1) {
-							List<Category> children = parentMap.getOrDefault(category.getCategoryId(), Collections.emptyList());
-							productBeBound = children.isEmpty() ? 1 : 0;
-						}
-					}
-					vo.setProductBeBound(productBeBound);
-
-					// 递归构建子分类树,层级 +1
-					List<Category> children = parentMap.getOrDefault(category.getCategoryId(), Collections.emptyList());
-					vo.setChildren(buildCategoryTree(children, parentMap, currentLevel + 1));
-
-					return vo;
-				})
-				.collect(Collectors.toList());
-	}
-
-	// 校验与解析分离
-	private List<List<String>> validateAndParseExcel(MultipartFile excelFile) throws Exception {
+    @Override
+    @Cacheable(cacheNames = "CategoryListByShopId", key = "#shopId + ':category'")
+    public List<Category> listByShopId(Long shopId) {
+        return categoryMapper.selectList(new LambdaQueryWrapper<Category>().eq(Category::getShopId, shopId));
+    }
+
+    @Override
+    public IPage<ListCategoryVO> listCategory(ListCategoryDTO listCategoryDTO) {
+        IPage<ListCategoryVO> listCategoryVOIPage = categoryMapper.listCategory(new Page<>(listCategoryDTO.getCurrent(), listCategoryDTO.getSize()), listCategoryDTO);
+        listCategoryVOIPage.getRecords().forEach(listCategoryVO -> {
+            listCategoryVO.setGrade(0);
+            if (listCategoryVO.getResource() == null) {
+                listCategoryVO.setResource("");
+            } else {
+                listCategoryVO.setResource(listCategoryVO.getResource() + "个商品");
+            }
+            listCategoryVO.setProductBeBound(0);
+            listCategoryVO.setChildren(categoryMapper.listCategoryChildren(new ListCategoryDTO().setParentId(listCategoryVO.getCategoryID())));
+            listCategoryVO.getChildren().forEach(listCategoryVO1 -> {
+                listCategoryVO1.setGrade(1);
+                if (listCategoryVO1.getResource() == null) {
+                    listCategoryVO1.setResource("");
+                } else {
+                    listCategoryVO1.setResource(listCategoryVO1.getResource() + "个商品");
+                }
+                List<ListCategoryVO> listCategoryVOS = categoryMapper.listCategoryChildren(new ListCategoryDTO().setParentId(listCategoryVO1.getCategoryID()));
+                if (listCategoryVOS.isEmpty()) {
+                    listCategoryVO1.setProductBeBound(1);
+                    listCategoryVO1.setChildren(new ArrayList<>());
+                } else {
+                    listCategoryVO1.setProductBeBound(0);
+                    listCategoryVO1.setChildren(listCategoryVOS);
+                    listCategoryVO1.getChildren().forEach(listCategoryVO2 -> {
+                        listCategoryVO2.setGrade(2);
+                        if (listCategoryVO2.getResource() == null) {
+                            listCategoryVO2.setResource("");
+                        } else {
+                            listCategoryVO2.setResource(listCategoryVO2.getResource() + "个商品");
+                        }
+                        listCategoryVO2.setProductBeBound(1);
+                        listCategoryVO2.setChildren(new ArrayList<>());
+                    });
+                }
+            });
+        });
+        return listCategoryVOIPage;
+    }
+
+    @Override
+    @Transactional(rollbackFor = Exception.class)
+    public Integer parseCategoryFile(MultipartFile excelFile, Long shopId) throws Exception {
+        // 1. 校验并解析Excel
+        List<List<String>> dataRows = validateAndParseExcel(excelFile);
+
+        // 2. 保存分类层级(若允许放宽主键依赖,可开启批量插入)
+        saveCategoryHierarchy(dataRows, shopId);
+
+        // 3. 返回成功导入的行数(每行对应一组三级分类)
+        return dataRows.size();
+    }
+
+    @Override
+    public List<ListCategoryForUserVO> listCategoryForUser(Long shopId) {
+        List<ShopCategory> shopCategories = shopCategoryMapper.selectList(new LambdaQueryWrapper<ShopCategory>()
+                .eq(ShopCategory::getShopId, shopId)
+                .eq(ShopCategory::getIsDelete, Boolean.FALSE)
+                .orderByDesc(ShopCategory::getNum));
+        if (CollectionUtil.isEmpty(shopCategories)) {
+            return Collections.emptyList();
+        }
+
+        Map<Long, List<ShopCategory>> parentMap = shopCategories.stream()
+                .collect(Collectors.groupingBy(ShopCategory::getPid));
+
+        // 初始层级为一级分类(grade = 1)
+        return buildCategoryTree(parentMap.getOrDefault(0L, Collections.emptyList()), parentMap, 0);
+    }
+
+    private List<ListCategoryForUserVO> buildCategoryTree(List<ShopCategory> categories, Map<Long, List<ShopCategory>> parentMap, int currentLevel) {
+        if (CollectionUtil.isEmpty(categories)) return Collections.emptyList();
+        return categories.stream()
+                .map(category -> {
+                    ListCategoryForUserVO vo = new ListCategoryForUserVO();
+                    vo.setCategoryName(category.getName());
+                    vo.setSeq(category.getNum());
+                    vo.setParentId(category.getPid());
+                    vo.setCategoryId(category.getId());
+                    vo.setIcon(category.getIcon());
+
+                    // 动态计算当前分类的等级(1: 一级, 2: 二级, 3: 三级)
+                    int grade = currentLevel;
+                    vo.setGrade(grade); // 如果 VO 类中需要保留 grade 字段,可保留此行
+
+                    // 判断是否为二级或三级分类,并设置 productBeBound 字段
+                    int productBeBound = 0;
+                    if (grade == 1 || grade == 2) {
+                        // 三级分类直接绑定商品
+                        if (grade == 2) {
+                            productBeBound = 1;
+                        }
+                        // 二级分类若无子分类(三级分类),则允许绑定商品
+                        else if (grade == 1) {
+                            List<ShopCategory> children = parentMap.getOrDefault(category.getId(), Collections.emptyList());
+                            productBeBound = children.isEmpty() ? 1 : 0;
+                        }
+                    }
+                    vo.setProductBeBound(productBeBound);
+
+                    // 递归构建子分类树,层级 +1
+                    List<ShopCategory> children = parentMap.getOrDefault(category.getId(), Collections.emptyList());
+                    vo.setChildren(buildCategoryTree(children, parentMap, currentLevel + 1));
+
+                    return vo;
+                })
+                .collect(Collectors.toList());
+    }
+
+    // 校验与解析分离
+    private List<List<String>> validateAndParseExcel(MultipartFile excelFile) throws Exception {
 //		Workbook workBook = WorkbookFactory.create(excelFile.getInputStream());
 //
 //		Sheet sheet = workBook.getSheetAt(0);
@@ -371,114 +371,116 @@ public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> i
 //			}
 //			result.add(rowData);
 //		}
-		return new ArrayList<>( );
-	}
-	// 分类保存逻辑(若允许放宽主键依赖,可开启批量插入)
-	private void saveCategoryHierarchy(List<List<String>> dataRows, Long shopId) {
-		dataRows.forEach(row -> {
-			String cat1Name = row.get(0);
-			String cat2Name = row.get(1);
-			String cat3Name = row.get(2);
-
-			// 1. 处理一级分类(parent_id = 0)
-			Category cat1 = categoryMapper.selectByNameAndParentId(cat1Name, 0L, shopId);
-			if (cat1 == null) {
-				cat1 = buildCategory(shopId, 0L, cat1Name, 0);
-				categoryMapper.insert(cat1);
-			}
-
-			// 2. 处理二级分类(parent_id = cat1.id)
-			Category cat2 = categoryMapper.selectByNameAndParentId(cat2Name, cat1.getCategoryId(), shopId);
-			if (cat2 == null) {
-				cat2 = buildCategory(shopId, cat1.getCategoryId(), cat2Name, 1);
-				categoryMapper.insert(cat2);
-			}
-
-			// 3. 处理三级分类(parent_id = cat2.id,允许为空)
-			if (!cat3Name.isEmpty()) {
-				Category cat3 = categoryMapper.selectByNameAndParentId(cat3Name, cat2.getCategoryId(), shopId);
-				if (cat3 == null) {
-					cat3 = buildCategory(shopId, cat2.getCategoryId(), cat3Name, 2);
-					categoryMapper.insert(cat3);
-				}
-			}
-		});
-	}
-	// 构建分类实体(可复用)
-	private Category buildCategory(Long shopId, Long parentId, String name, int grade) {
-		return new Category()
-				.setShopId(shopId)
-				.setParentId(parentId)
-				.setCategoryName(name)
-				.setGrade(grade)
-				.setSeq(1) // 默认 seq 值
-				.setStatus(1) // 默认启用状态
-				.setRecTime(new Date())
-				.setUpdateTime(new Date());
-	}
-
-	private void deleteBrandsAndAttributes(Long categoryId) {
-		// 删除所有分类所关联的品牌
-		categoryBrandMapper.deleteByCategoryId(categoryId);
-		// 删除所有分类所关联的参数
-		categoryPropMapper.deleteByCategoryId(categoryId);
-	}
-
-	private void insertBrandsAndAttributes(Category category) {
-		//保存分类与品牌信息
-		if(CollUtil.isNotEmpty(category.getBrandIds())){
-			categoryBrandMapper.insertCategoryBrand(category.getCategoryId(), category.getBrandIds());
-		}
-
-
-	}
-
-	/**
-	 * 刷新积分配置中的分类数据
-	 */
-	private void changeScoreConfig(){
-		ScoreConfigParam scoreParamDb = sysConfigService.getSysConfigObject(Constant.SCORE_CONFIG,ScoreConfigParam.class);
-		if (Objects.isNull(scoreParamDb)){
-			throw new GlobalException("请先前往 【会员管理】-> 【积分成长值配置】-> 【积分获取配置】 进行配置并保存 ");
-		}
-		//判断分类数据是否正确
-		List<Category> categoryList = categoryMapper.selectList(new LambdaQueryWrapper<Category>()
-				.eq(Category::getParentId,Constant.CATEGORY_ID)
-				.eq(Category::getShopId,Constant.PLATFORM_SHOP_ID)
-				.orderByAsc(Category::getCategoryId)
-		);
-		Map<Long,Category> categoryMap = categoryList.stream().collect(Collectors.toMap(Category::getCategoryId,category -> category));
-		// 还没有分类数据时,scoreParamDb.getCategoryConfigs()为null,所以为它new一个对象
-		if (Objects.isNull(scoreParamDb.getCategoryConfigs())) {
-			scoreParamDb.setCategoryConfigs(Lists.newArrayList());
-		}
-		Iterator<CategoryScoreConfigParam> iterator = scoreParamDb.getCategoryConfigs().iterator();
-		//更新数据并去除已删除的数据
-		while (iterator.hasNext()){
-			CategoryScoreConfigParam categoryScoreConfigParam = iterator.next();
-			Category category = categoryMap.get(categoryScoreConfigParam.getCategoryId());
-			if (Objects.isNull(category)){
-				iterator.remove();
-			}else {
-				//刷新分类名称
-				categoryScoreConfigParam.setCategoryName(categoryScoreConfigParam.getCategoryName());
-				//删除map中已进行操作过的分类
-				categoryMap.remove(categoryScoreConfigParam.getCategoryId());
-			}
-		}
-		// 获取map中剩下的分类的id(剩下的分类为积分配置json中所没有的分类,需要新增)
-		Set<Long> longs = categoryMap.keySet();
-		// 新增积分配置json中的分类数据
-		for (Long catrgoryId:longs){
-			Category category = categoryMap.get(catrgoryId);
-			CategoryScoreConfigParam categoryScoreConfigParam = new CategoryScoreConfigParam();
-			categoryScoreConfigParam.setCategoryId(category.getCategoryId());
-			categoryScoreConfigParam.setCategoryName(category.getCategoryName());
-			categoryScoreConfigParam.setGetScoreLimit(1.00);
-			categoryScoreConfigParam.setUseScoreLimit(1.00);
-			scoreParamDb.getCategoryConfigs().add(categoryScoreConfigParam);
-		}
-		//保存数据
-		sysConfigService.saveOrUpdateSysConfigService(scoreParamDb,Constant.SCORE_CONFIG);
-	}
+        return new ArrayList<>();
+    }
+
+    // 分类保存逻辑(若允许放宽主键依赖,可开启批量插入)
+    private void saveCategoryHierarchy(List<List<String>> dataRows, Long shopId) {
+        dataRows.forEach(row -> {
+            String cat1Name = row.get(0);
+            String cat2Name = row.get(1);
+            String cat3Name = row.get(2);
+
+            // 1. 处理一级分类(parent_id = 0)
+            Category cat1 = categoryMapper.selectByNameAndParentId(cat1Name, 0L, shopId);
+            if (cat1 == null) {
+                cat1 = buildCategory(shopId, 0L, cat1Name, 0);
+                categoryMapper.insert(cat1);
+            }
+
+            // 2. 处理二级分类(parent_id = cat1.id)
+            Category cat2 = categoryMapper.selectByNameAndParentId(cat2Name, cat1.getCategoryId(), shopId);
+            if (cat2 == null) {
+                cat2 = buildCategory(shopId, cat1.getCategoryId(), cat2Name, 1);
+                categoryMapper.insert(cat2);
+            }
+
+            // 3. 处理三级分类(parent_id = cat2.id,允许为空)
+            if (!cat3Name.isEmpty()) {
+                Category cat3 = categoryMapper.selectByNameAndParentId(cat3Name, cat2.getCategoryId(), shopId);
+                if (cat3 == null) {
+                    cat3 = buildCategory(shopId, cat2.getCategoryId(), cat3Name, 2);
+                    categoryMapper.insert(cat3);
+                }
+            }
+        });
+    }
+
+    // 构建分类实体(可复用)
+    private Category buildCategory(Long shopId, Long parentId, String name, int grade) {
+        return new Category()
+                .setShopId(shopId)
+                .setParentId(parentId)
+                .setCategoryName(name)
+                .setGrade(grade)
+                .setSeq(1) // 默认 seq 值
+                .setStatus(1) // 默认启用状态
+                .setRecTime(new Date())
+                .setUpdateTime(new Date());
+    }
+
+    private void deleteBrandsAndAttributes(Long categoryId) {
+        // 删除所有分类所关联的品牌
+        categoryBrandMapper.deleteByCategoryId(categoryId);
+        // 删除所有分类所关联的参数
+        categoryPropMapper.deleteByCategoryId(categoryId);
+    }
+
+    private void insertBrandsAndAttributes(Category category) {
+        //保存分类与品牌信息
+        if (CollUtil.isNotEmpty(category.getBrandIds())) {
+            categoryBrandMapper.insertCategoryBrand(category.getCategoryId(), category.getBrandIds());
+        }
+
+
+    }
+
+    /**
+     * 刷新积分配置中的分类数据
+     */
+    private void changeScoreConfig() {
+        ScoreConfigParam scoreParamDb = sysConfigService.getSysConfigObject(Constant.SCORE_CONFIG, ScoreConfigParam.class);
+        if (Objects.isNull(scoreParamDb)) {
+            throw new GlobalException("请先前往 【会员管理】-> 【积分成长值配置】-> 【积分获取配置】 进行配置并保存 ");
+        }
+        //判断分类数据是否正确
+        List<Category> categoryList = categoryMapper.selectList(new LambdaQueryWrapper<Category>()
+                .eq(Category::getParentId, Constant.CATEGORY_ID)
+                .eq(Category::getShopId, Constant.PLATFORM_SHOP_ID)
+                .orderByAsc(Category::getCategoryId)
+        );
+        Map<Long, Category> categoryMap = categoryList.stream().collect(Collectors.toMap(Category::getCategoryId, category -> category));
+        // 还没有分类数据时,scoreParamDb.getCategoryConfigs()为null,所以为它new一个对象
+        if (Objects.isNull(scoreParamDb.getCategoryConfigs())) {
+            scoreParamDb.setCategoryConfigs(Lists.newArrayList());
+        }
+        Iterator<CategoryScoreConfigParam> iterator = scoreParamDb.getCategoryConfigs().iterator();
+        //更新数据并去除已删除的数据
+        while (iterator.hasNext()) {
+            CategoryScoreConfigParam categoryScoreConfigParam = iterator.next();
+            Category category = categoryMap.get(categoryScoreConfigParam.getCategoryId());
+            if (Objects.isNull(category)) {
+                iterator.remove();
+            } else {
+                //刷新分类名称
+                categoryScoreConfigParam.setCategoryName(categoryScoreConfigParam.getCategoryName());
+                //删除map中已进行操作过的分类
+                categoryMap.remove(categoryScoreConfigParam.getCategoryId());
+            }
+        }
+        // 获取map中剩下的分类的id(剩下的分类为积分配置json中所没有的分类,需要新增)
+        Set<Long> longs = categoryMap.keySet();
+        // 新增积分配置json中的分类数据
+        for (Long catrgoryId : longs) {
+            Category category = categoryMap.get(catrgoryId);
+            CategoryScoreConfigParam categoryScoreConfigParam = new CategoryScoreConfigParam();
+            categoryScoreConfigParam.setCategoryId(category.getCategoryId());
+            categoryScoreConfigParam.setCategoryName(category.getCategoryName());
+            categoryScoreConfigParam.setGetScoreLimit(1.00);
+            categoryScoreConfigParam.setUseScoreLimit(1.00);
+            scoreParamDb.getCategoryConfigs().add(categoryScoreConfigParam);
+        }
+        //保存数据
+        sysConfigService.saveOrUpdateSysConfigService(scoreParamDb, Constant.SCORE_CONFIG);
+    }
 }

+ 5 - 1
yami-shop-service/src/main/java/com/yami/shop/service/impl/OrderServiceImpl.java

@@ -204,7 +204,11 @@ public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements
         eventPublisher.publishEvent(new SubmitOrderEvent(mergerOrder, orderList));
         // 插入订单
         orderList.forEach(order -> orderMapper.insert(order));
-        List<OrderItem> orderItems = orderList.stream().flatMap(order -> order.getOrderItems().stream()).collect(Collectors.toList());
+        List<OrderItem> orderItems = orderList.stream()
+                .flatMap(order -> order.getOrderItems().stream()
+                        .peek((o)->o.setPrice(100.0)) //TODO 测试代码,后面需要删掉
+                )
+                .collect(Collectors.toList());
         // 插入订单项,返回主键
         orderItemService.saveBatch(orderItems);
         //计算积分情况

+ 2 - 2
yami-shop-service/src/main/java/com/yami/shop/service/impl/QnhServiceImpl.java

@@ -202,8 +202,8 @@ public class QnhServiceImpl implements IQnhService {
         jsonObject.put("sku_code", skuCode);
         jsonObject.put("page_size", 50);
         //TODO wangjian 原先查询牵牛花的库存,现在需要替换成海博的
-        one1.setStocks(99);
-        one1.setActualStocks(99);
+        one1.setStocks(9999);
+        one1.setActualStocks(9999);
         return Boolean.TRUE;
 //        HttpResponse execute = getExecute(body, jsonObject, GET_SKU_STOCK);
 //        JSONObject result = JSONObject.parseObject(execute.body());

+ 5 - 0
yami-shop-service/src/main/java/com/yami/shop/service/impl/SkuServiceImpl.java

@@ -48,6 +48,11 @@ public class SkuServiceImpl extends ServiceImpl<SkuMapper, Sku> implements SkuSe
         return skuMapper.selectById(skuId);
     }
 
+    @Override
+    public Sku getSkuBySkuId(Long skuId, Integer platform, Long shopId) {
+        return skuMapper.listBySukIdAndPlatform(skuId, platform, shopId);
+    }
+
     @Override
     @Caching(evict = {
             @CacheEvict(cacheNames = "sku", key = "#skuId"),

+ 2 - 2
yami-shop-service/src/main/resources/mapper/ProductMapper.xml

@@ -132,7 +132,7 @@
         SELECT
             tp.prod_id,
             tp.prod_name,
-            tcs.shop_id AS shop_id,  -- 使用tcs.shop_id覆盖默认shop_id
+            tcs.shop_id AS shop_id,
             tp.brand_id,
             tp.brand_name,
             tp.ori_price,
@@ -149,7 +149,7 @@
             tp.category_id,
             tp.hb_front_category_id,
             tp.sold_num,
-            tp.total_stocks,
+            tss.shop_sku_stocks AS total_stocks,
             tp.delivery_mode,
             tp.delivery_template_id,
             tp.create_time,

+ 65 - 29
yami-shop-service/src/main/resources/mapper/SkuMapper.xml

@@ -47,37 +47,73 @@
 
     <select id="listByProdIdAndPlatform" resultType="com.yami.shop.bean.model.Sku">
         SELECT ts.sku_id,
-        ts.prod_id,
-        ts.sku_name,
-        ts.prod_name,
-        ts.ori_price,
-        tcp.channel_prod_price AS price,
-        ts.sku_score,
-        ts.properties,
-        ts.stocks,
-        tss.shop_sku_stocks AS actual_stocks,
-        ts.update_time,
-        ts.rec_time,
-        ts.party_code,
-        ts.model_id,
-        ts.pic,
-        ts.version,
-        ts.weight,
-        ts.volume,
-        ts.`status`,
-        ts.is_delete,
-        ts.weight_unit,
-        ts.sku_code,
-        ts.hb_spu_id,
-        ts.hb_sku_id
+               ts.prod_id,
+               ts.sku_name,
+               ts.prod_name,
+               ts.ori_price,
+               tcp.channel_prod_price AS price,
+               ts.sku_score,
+               ts.properties,
+               ts.stocks,
+               tss.shop_sku_stocks    AS actual_stocks,
+               ts.update_time,
+               ts.rec_time,
+               ts.party_code,
+               ts.model_id,
+               ts.pic,
+               ts.version,
+               ts.weight,
+               ts.volume,
+               ts.`status`,
+               ts.is_delete,
+               ts.weight_unit,
+               ts.sku_code,
+               ts.hb_spu_id,
+               ts.hb_sku_id
         FROM tz_sku AS ts
-        LEFT JOIN tz_shop_sku AS tss ON ts.sku_id = tss.sku_id
-        LEFT JOIN tz_channel_prod AS tcp ON ts.sku_id = tcp.sku_id
+                 LEFT JOIN tz_shop_sku AS tss ON ts.sku_id = tss.sku_id
+                 LEFT JOIN tz_channel_prod AS tcp ON ts.sku_id = tcp.sku_id
         WHERE ts.prod_id = #{prodId}
-        AND ts.is_delete = 0
-        AND ts.`status` = 1
-        AND tss.shop_id = #{shopId}
-        AND tcp.channel_id = #{platform}
+          AND ts.is_delete = 0
+          AND ts.`status` = 1
+          AND tss.shop_id = #{shopId}
+          AND tcp.channel_id = #{platform}
+    </select>
+
+    <select id="listBySukIdAndPlatform" resultType="com.yami.shop.bean.model.Sku">
+        SELECT ts.sku_id,
+               ts.prod_id,
+               ts.sku_name,
+               ts.prod_name,
+               ts.ori_price,
+               tcp.channel_prod_price AS price,
+               ts.sku_score,
+               ts.properties,
+               ts.stocks,
+               tss.shop_sku_stocks    AS actual_stocks,
+               ts.update_time,
+               ts.rec_time,
+               ts.party_code,
+               ts.model_id,
+               ts.pic,
+               ts.version,
+               ts.weight,
+               ts.volume,
+               ts.`status`,
+               ts.is_delete,
+               ts.weight_unit,
+               ts.sku_code,
+               ts.hb_spu_id,
+               ts.hb_sku_id
+        FROM tz_sku AS ts
+                 LEFT JOIN tz_shop_sku AS tss ON ts.sku_id = tss.sku_id
+                 LEFT JOIN tz_channel_prod AS tcp ON ts.sku_id = tcp.sku_id
+        WHERE ts.sku_id = #{skuId}
+          AND ts.is_delete = 0
+          AND ts.`status` = 1
+          AND tss.shop_id = #{shopId}
+          AND tcp.channel_id = #{platform}
+        LIMIT 1
     </select>
     <select id="selectByHbSkuId" resultType="com.yami.shop.bean.model.Sku">
         select *

+ 151 - 148
yami-shop-user/yami-shop-user-api/src/main/java/com/yami/shop/user/api/listener/ConfirmOrderListener.java

@@ -1,5 +1,6 @@
 package com.yami.shop.user.api.listener;
 
+import com.alibaba.fastjson.JSONObject;
 import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
 import com.yami.shop.bean.app.dto.*;
 import com.yami.shop.bean.app.param.OrderParam;
@@ -41,141 +42,142 @@ public class ConfirmOrderListener {
     private final CategoryService categoryService;
 
     /**
-    *  计算积分抵现和分摊
-    */
+     * 计算积分抵现和分摊
+     */
     @EventListener(ScoreConfirmOrderEvent.class)
     @Order(ConfirmOrderOrder.SCORE)
     public void scoreSubmitOrderListener(ScoreConfirmOrderEvent event) {
-        //获取用户等级积分详细表
-        UserExtension extension = userExtensionService.getOne(
-                new LambdaQueryWrapper<UserExtension>().eq(UserExtension::getUserId, SecurityUtils.getUser().getUserId()));
-        //获取配置信息
-        ScoreConfigParam scoreParam = sysConfigService.getSysConfigObject(Constant.SCORE_CONFIG,ScoreConfigParam.class);
-        if(Objects.nonNull(scoreParam)  && scoreParam.getShopScoreSwitch() != null && !scoreParam.getShopScoreSwitch()){
-            return;
-        }
-        ShopCartOrderMergerDto shopCartOrderMergerDto = event.getShopCartOrderMergerDto();
-        OrderParam orderParam = event.getOrderParam();
-        if(orderParam.getUserUseScore() != null && orderParam.getUserUseScore() < 0 && extension.getScore() < 0){
-            return;
-        }
-        //计算积分最多抵现金额
-        double totalScoreAmount = 0.0;
-        List<Category> categories = categoryService.listByShopId(Constant.PLATFORM_SHOP_ID);
-        Map<Long, Double> categoryMap = CategoryScale.getScaleByCategory(categories,scoreParam,0);
-        // 积分抵现金额可用上限 = 订单可使用积分比例 * ((实际总值)/100)
-        if(scoreParam.getUseDiscountRange() == 0){
-            // 如果有等级优惠金额,还需减去等级的优惠金额、运费才是实际金额,包邮时运费为0
-            double actualTotal = Arith.sub(shopCartOrderMergerDto.getActualTotal(),shopCartOrderMergerDto.getTotalTransfee());
-            totalScoreAmount = Arith.div(Arith.mul(actualTotal, scoreParam.getUseDiscount()), 100);
-        }else{
-            //获取大类的比例并转成map
-            for (ShopCartItemDto shopCartItem : event.getAllCartItem()) {
-                if(!categoryMap.containsKey(shopCartItem.getCategoryId())) {
-                    continue;
-                }
-                // 商品总额减去商家优惠、平台优惠,就是商品项的实际金额
-                double actualTotal = Arith.sub(Arith.sub(shopCartItem.getProductTotalAmount(), shopCartItem.getShareReduce()),shopCartItem.getPlatformShareReduce());
-                double scoreReduce = Arith.div(Arith.mul(actualTotal, categoryMap.get(shopCartItem.getCategoryId())),100);
-                totalScoreAmount = Arith.add(totalScoreAmount,scoreReduce);
-            }
-        }
-        //计算用户可用积分 如果大于总共的积分使用比例直接使用,如果小于根据比例使用
-        int canUseScore = (int) Arith.mul(totalScoreAmount, scoreParam.getShopUseScore());
-//        totalScoreAmount = Arith.div(canUseScore, scoreParam.getShopUseScore(),2);
-        Integer userUseScore = extension.getScore();
-        Integer totalUsableScore = extension.getScore();
-        //如果是用户选择的积分数额,则用此积分数额
-        if(orderParam.getUserUseScore() != null && orderParam.getIsScorePay() == 1 && orderParam.getUserUseScore() >= 0){
-            userUseScore = Math.min(orderParam.getUserUseScore(),userUseScore);
-        }else{
-            userUseScore = 0;
-        }
-        double scale = 1.0;
-        if(userUseScore < canUseScore){
-            scale = Arith.div(userUseScore, canUseScore);
-        }
-        int maxScore = Math.min(totalUsableScore,canUseScore);
-        userUseScore = Math.min(userUseScore, canUseScore);
-        // 如果为大于100的比例,则积分需要整10使用
-        if(scoreParam.getShopUseScore() > 100){
-            userUseScore = userUseScore - userUseScore % 10;
-            maxScore = maxScore - maxScore % 10;
-        }
-        // 计算最大可抵扣金额,并且如果小数大于两位四舍五入,还需在计算一遍实际使用积分
-        totalScoreAmount = Arith.div(userUseScore,scoreParam.getShopUseScore(),2);
-        userUseScore = (int) Arith.mul(totalScoreAmount, scoreParam.getShopUseScore());
-        //用户选择积分抵现,组装积分信息
-        List<ShopCartOrderDto> shopCartOrders = shopCartOrderMergerDto.getShopCartOrders();
-        double totalScoreReduce = 0.0;
-        int totalScore = 0;
-        //通过for i找出最后一项,将计算偏差的1积分给最后的最大的一项
-        for (int shopIndex = 0; shopIndex < shopCartOrders.size(); shopIndex++) {
-            ShopCartOrderDto shopCartOrder = shopCartOrders.get(shopIndex);
-            double reduceSum = 0.0;
-            int shopScore = 0;
-            List<ShopCartItemDiscountDto> shopCartItemDiscounts = shopCartOrder.getShopCartItemDiscounts();
-            for (int discountIndex = 0; discountIndex < shopCartItemDiscounts.size(); discountIndex++) {
-                List<ShopCartItemDto> shopCartItems = shopCartItemDiscounts.get(discountIndex).getShopCartItems();
-                for (int itemIndex = 0; itemIndex< shopCartItems.size(); itemIndex++) {
-                    ShopCartItemDto shopCartItem = shopCartItems.get(itemIndex);
-                    double scoreReduceProd = 0.0;
-                    //判断是否最后一项
-                    boolean isEnd =  shopIndex == shopCartOrders.size() - 1 && discountIndex ==shopCartItemDiscounts.size() - 1 && itemIndex == shopCartItems.size() - 1;
-                    //计算商品分摊的金额,需要乘以比例
-                    if(scoreParam.getUseDiscountRange() == 0){
-                        scoreReduceProd = Arith.div(Arith.mul(shopCartItem.getActualTotal(),scoreParam.getUseDiscount()),100,2);
-                    }else if(categoryMap.containsKey(shopCartItem.getCategoryId())){
-                        scoreReduceProd = Arith.div(Arith.mul(shopCartItem.getActualTotal(),categoryMap.get(shopCartItem.getCategoryId())),100,2);
-                    }
-                    int useScore = (int) Arith.mul(Arith.round(Arith.mul(scoreReduceProd,scale),2), scoreParam.getShopUseScore());
-                    scoreReduceProd = Arith.div(useScore, scoreParam.getShopUseScore(),2);
-                    //如果大于可用上限则直接等于,或者如果是最后一项直接将剩余的抵扣金额全部赋予最后一个,积分和金额直接等于 使用的 - 已经抵扣的
-                    if(Arith.add(totalScoreReduce,scoreReduceProd) > totalScoreAmount || isEnd){
-                        //减去当前总共的积分,减去店铺已分摊的积分
-                        useScore = userUseScore - totalScore - shopScore;
-                        scoreReduceProd = Arith.sub(totalScoreAmount ,totalScoreReduce);
-                    }
-
-                    totalScoreReduce = Arith.add(totalScoreReduce, scoreReduceProd);
-                    reduceSum = Arith.add(reduceSum, scoreReduceProd);
-                    shopScore += useScore;
-                    if (orderParam.getIsScorePay() != null && orderParam.getIsScorePay() == 1) {
-                        double platformReduce = shopCartItem.getPlatformShareReduce() == null?0:shopCartItem.getPlatformShareReduce();
-                        shopCartItem.setPlatformShareReduce(Arith.add(platformReduce, scoreReduceProd));
-                        shopCartItem.setScorePayReduce(scoreReduceProd);
-                        shopCartItem.setScorePrice(useScore);
-                        shopCartItem.setShareReduce(Arith.add(Arith.round(shopCartItem.getShareReduce(),2),scoreReduceProd));
-                        shopCartItem.setActualTotal(Arith.sub(shopCartItem.getActualTotal(),scoreReduceProd));
-                    }
-                }
-            }
-            //设置店铺的实际总值、积分优惠金额和订单优惠金额
-            shopCartOrder.setScoreReduce(reduceSum);
-            shopCartOrder.setActualTotal(Arith.sub(shopCartOrder.getActualTotal(),reduceSum));
-            //放入优惠金额
-            shopCartOrder.setShopReduce(Arith.add(shopCartOrder.getShopReduce(),reduceSum));
-            //放入平台优惠金额,如果用户等级免自营店运费也要放进去
-            shopCartOrder.setPlatformAmount(Arith.add(shopCartOrder.getPlatformAmount(),reduceSum));
-            totalScore += shopScore;
-            if (orderParam.getIsScorePay() != null && orderParam.getIsScorePay() == 1) {
-                shopCartOrder.setUseScore(shopScore);
-            }
-        }
-        //设置订单的实际总值和订单优惠金额
-        shopCartOrderMergerDto.setTotalScoreAmount(totalScoreReduce);
-        shopCartOrderMergerDto.setShopUseScore(scoreParam.getShopUseScore());
-        shopCartOrderMergerDto.setTotalUsableScore(totalScore);
-        shopCartOrderMergerDto.setActualTotal(Arith.sub(shopCartOrderMergerDto.getActualTotal(),totalScoreReduce));
-        shopCartOrderMergerDto.setOrderReduce(Arith.add(shopCartOrderMergerDto.getOrderReduce(),totalScoreReduce));
-        shopCartOrderMergerDto.setMaxUsableScore(maxScore);
-        if (orderParam.getIsScorePay() != null && orderParam.getIsScorePay() == 1) {
-            shopCartOrderMergerDto.setScorePrice(totalScore);
-        }
+        System.out.println(JSONObject.toJSONString(event));
+//        //获取用户等级积分详细表
+//        UserExtension extension = userExtensionService.getOne(
+//                new LambdaQueryWrapper<UserExtension>().eq(UserExtension::getUserId, SecurityUtils.getUser().getUserId()));
+//        //获取配置信息
+//        ScoreConfigParam scoreParam = sysConfigService.getSysConfigObject(Constant.SCORE_CONFIG,ScoreConfigParam.class);
+//        if(Objects.nonNull(scoreParam)  && scoreParam.getShopScoreSwitch() != null && !scoreParam.getShopScoreSwitch()){
+//            return;
+//        }
+//        ShopCartOrderMergerDto shopCartOrderMergerDto = event.getShopCartOrderMergerDto();
+//        OrderParam orderParam = event.getOrderParam();
+//        if(orderParam.getUserUseScore() != null && orderParam.getUserUseScore() < 0 && extension.getScore() < 0){
+//            return;
+//        }
+//        //计算积分最多抵现金额
+//        double totalScoreAmount = 0.0;
+//        List<Category> categories = categoryService.listByShopId(Constant.PLATFORM_SHOP_ID);
+//        Map<Long, Double> categoryMap = CategoryScale.getScaleByCategory(categories,scoreParam,0);
+//        // 积分抵现金额可用上限 = 订单可使用积分比例 * ((实际总值)/100)
+//        if(scoreParam.getUseDiscountRange() == 0){
+//            // 如果有等级优惠金额,还需减去等级的优惠金额、运费才是实际金额,包邮时运费为0
+//            double actualTotal = Arith.sub(shopCartOrderMergerDto.getActualTotal(),shopCartOrderMergerDto.getTotalTransfee());
+//            totalScoreAmount = Arith.div(Arith.mul(actualTotal, scoreParam.getUseDiscount()), 100);
+//        }else{
+//            //获取大类的比例并转成map
+//            for (ShopCartItemDto shopCartItem : event.getAllCartItem()) {
+//                if(!categoryMap.containsKey(shopCartItem.getCategoryId())) {
+//                    continue;
+//                }
+//                // 商品总额减去商家优惠、平台优惠,就是商品项的实际金额
+//                double actualTotal = Arith.sub(Arith.sub(shopCartItem.getProductTotalAmount(), shopCartItem.getShareReduce()),shopCartItem.getPlatformShareReduce());
+//                double scoreReduce = Arith.div(Arith.mul(actualTotal, categoryMap.get(shopCartItem.getCategoryId())),100);
+//                totalScoreAmount = Arith.add(totalScoreAmount,scoreReduce);
+//            }
+//        }
+//        //计算用户可用积分 如果大于总共的积分使用比例直接使用,如果小于根据比例使用
+//        int canUseScore = (int) Arith.mul(totalScoreAmount, scoreParam.getShopUseScore());
+////        totalScoreAmount = Arith.div(canUseScore, scoreParam.getShopUseScore(),2);
+//        Integer userUseScore = extension.getScore();
+//        Integer totalUsableScore = extension.getScore();
+//        //如果是用户选择的积分数额,则用此积分数额
+//        if(orderParam.getUserUseScore() != null && orderParam.getIsScorePay() == 1 && orderParam.getUserUseScore() >= 0){
+//            userUseScore = Math.min(orderParam.getUserUseScore(),userUseScore);
+//        }else{
+//            userUseScore = 0;
+//        }
+//        double scale = 1.0;
+//        if(userUseScore < canUseScore){
+//            scale = Arith.div(userUseScore, canUseScore);
+//        }
+//        int maxScore = Math.min(totalUsableScore,canUseScore);
+//        userUseScore = Math.min(userUseScore, canUseScore);
+//        // 如果为大于100的比例,则积分需要整10使用
+//        if(scoreParam.getShopUseScore() > 100){
+//            userUseScore = userUseScore - userUseScore % 10;
+//            maxScore = maxScore - maxScore % 10;
+//        }
+//        // 计算最大可抵扣金额,并且如果小数大于两位四舍五入,还需在计算一遍实际使用积分
+//        totalScoreAmount = Arith.div(userUseScore,scoreParam.getShopUseScore(),2);
+//        userUseScore = (int) Arith.mul(totalScoreAmount, scoreParam.getShopUseScore());
+//        //用户选择积分抵现,组装积分信息
+//        List<ShopCartOrderDto> shopCartOrders = shopCartOrderMergerDto.getShopCartOrders();
+//        double totalScoreReduce = 0.0;
+//        int totalScore = 0;
+//        //通过for i找出最后一项,将计算偏差的1积分给最后的最大的一项
+//        for (int shopIndex = 0; shopIndex < shopCartOrders.size(); shopIndex++) {
+//            ShopCartOrderDto shopCartOrder = shopCartOrders.get(shopIndex);
+//            double reduceSum = 0.0;
+//            int shopScore = 0;
+//            List<ShopCartItemDiscountDto> shopCartItemDiscounts = shopCartOrder.getShopCartItemDiscounts();
+//            for (int discountIndex = 0; discountIndex < shopCartItemDiscounts.size(); discountIndex++) {
+//                List<ShopCartItemDto> shopCartItems = shopCartItemDiscounts.get(discountIndex).getShopCartItems();
+//                for (int itemIndex = 0; itemIndex< shopCartItems.size(); itemIndex++) {
+//                    ShopCartItemDto shopCartItem = shopCartItems.get(itemIndex);
+//                    double scoreReduceProd = 0.0;
+//                    //判断是否最后一项
+//                    boolean isEnd =  shopIndex == shopCartOrders.size() - 1 && discountIndex ==shopCartItemDiscounts.size() - 1 && itemIndex == shopCartItems.size() - 1;
+//                    //计算商品分摊的金额,需要乘以比例
+//                    if(scoreParam.getUseDiscountRange() == 0){
+//                        scoreReduceProd = Arith.div(Arith.mul(shopCartItem.getActualTotal(),scoreParam.getUseDiscount()),100,2);
+//                    }else if(categoryMap.containsKey(shopCartItem.getCategoryId())){
+//                        scoreReduceProd = Arith.div(Arith.mul(shopCartItem.getActualTotal(),categoryMap.get(shopCartItem.getCategoryId())),100,2);
+//                    }
+//                    int useScore = (int) Arith.mul(Arith.round(Arith.mul(scoreReduceProd,scale),2), scoreParam.getShopUseScore());
+//                    scoreReduceProd = Arith.div(useScore, scoreParam.getShopUseScore(),2);
+//                    //如果大于可用上限则直接等于,或者如果是最后一项直接将剩余的抵扣金额全部赋予最后一个,积分和金额直接等于 使用的 - 已经抵扣的
+//                    if(Arith.add(totalScoreReduce,scoreReduceProd) > totalScoreAmount || isEnd){
+//                        //减去当前总共的积分,减去店铺已分摊的积分
+//                        useScore = userUseScore - totalScore - shopScore;
+//                        scoreReduceProd = Arith.sub(totalScoreAmount ,totalScoreReduce);
+//                    }
+//
+//                    totalScoreReduce = Arith.add(totalScoreReduce, scoreReduceProd);
+//                    reduceSum = Arith.add(reduceSum, scoreReduceProd);
+//                    shopScore += useScore;
+//                    if (orderParam.getIsScorePay() != null && orderParam.getIsScorePay() == 1) {
+//                        double platformReduce = shopCartItem.getPlatformShareReduce() == null?0:shopCartItem.getPlatformShareReduce();
+//                        shopCartItem.setPlatformShareReduce(Arith.add(platformReduce, scoreReduceProd));
+//                        shopCartItem.setScorePayReduce(scoreReduceProd);
+//                        shopCartItem.setScorePrice(useScore);
+//                        shopCartItem.setShareReduce(Arith.add(Arith.round(shopCartItem.getShareReduce(),2),scoreReduceProd));
+//                        shopCartItem.setActualTotal(Arith.sub(shopCartItem.getActualTotal(),scoreReduceProd));
+//                    }
+//                }
+//            }
+//            //设置店铺的实际总值、积分优惠金额和订单优惠金额
+//            shopCartOrder.setScoreReduce(reduceSum);
+//            shopCartOrder.setActualTotal(Arith.sub(shopCartOrder.getActualTotal(),reduceSum));
+//            //放入优惠金额
+//            shopCartOrder.setShopReduce(Arith.add(shopCartOrder.getShopReduce(),reduceSum));
+//            //放入平台优惠金额,如果用户等级免自营店运费也要放进去
+//            shopCartOrder.setPlatformAmount(Arith.add(shopCartOrder.getPlatformAmount(),reduceSum));
+//            totalScore += shopScore;
+//            if (orderParam.getIsScorePay() != null && orderParam.getIsScorePay() == 1) {
+//                shopCartOrder.setUseScore(shopScore);
+//            }
+//        }
+//        //设置订单的实际总值和订单优惠金额
+//        shopCartOrderMergerDto.setTotalScoreAmount(totalScoreReduce);
+//        shopCartOrderMergerDto.setShopUseScore(scoreParam.getShopUseScore());
+//        shopCartOrderMergerDto.setTotalUsableScore(totalScore);
+//        shopCartOrderMergerDto.setActualTotal(Arith.sub(shopCartOrderMergerDto.getActualTotal(),totalScoreReduce));
+//        shopCartOrderMergerDto.setOrderReduce(Arith.add(shopCartOrderMergerDto.getOrderReduce(),totalScoreReduce));
+//        shopCartOrderMergerDto.setMaxUsableScore(maxScore);
+//        if (orderParam.getIsScorePay() != null && orderParam.getIsScorePay() == 1) {
+//            shopCartOrderMergerDto.setScorePrice(totalScore);
+//        }
     }
 
     /**
-     *  计算等级折扣比例和分摊比例
+     * 计算等级折扣比例和分摊比例
      */
     @EventListener(PlatformConfirmOrderEvent.class)
     @Order(ConfirmOrderOrder.LEVEL)
@@ -199,43 +201,43 @@ public class ConfirmOrderListener {
         double levelDiscount = 0.0;
         double freeTransfee = 0.0;
 //        double levelDiscountActualTotal= 0.0;
-        double discount = Arith.sub(10,level.getDiscount());
+        double discount = Arith.sub(10, level.getDiscount());
 
         //将分类转成map
         List<Long> categoryIds = level.getCategoryIds();
-        Map<Long,Long> categoryMap = new HashMap<>(100);
-        if(CollectionUtils.isNotEmpty(categoryIds)){
-            categoryIds.forEach(categoryId -> categoryMap.put(categoryId,categoryId));
+        Map<Long, Long> categoryMap = new HashMap<>(100);
+        if (CollectionUtils.isNotEmpty(categoryIds)) {
+            categoryIds.forEach(categoryId -> categoryMap.put(categoryId, categoryId));
         }
         //计算折扣总额
-        double maxlevelFeeTotal = getLevelFeeTotal(shopCartOrders,level,categoryMap);
+        double maxlevelFeeTotal = getLevelFeeTotal(shopCartOrders, level, categoryMap);
         //通过for i找出最后一项,将计算偏差的1积分给最后的最大的一项
         for (int shopIndex = 0; shopIndex < shopCartOrders.size(); shopIndex++) {
             ShopCartOrderDto shopCartOrder = shopCartOrders.get(shopIndex);
             //如果可用范围为自营店不为当前店铺直接下一次循环
-            if(level.getDiscountRange() == 1 && !Objects.equals(shopCartOrder.getShopId(),1L)){
+            if (level.getDiscountRange() == 1 && !Objects.equals(shopCartOrder.getShopId(), 1L)) {
                 continue;
             }
             double reduceSum = 0.0;
             List<ShopCartItemDiscountDto> shopCartItemDiscounts = shopCartOrder.getShopCartItemDiscounts();
             for (int discountIndex = 0; discountIndex < shopCartItemDiscounts.size(); discountIndex++) {
                 List<ShopCartItemDto> shopCartItems = shopCartItemDiscounts.get(discountIndex).getShopCartItems();
-                for (int itemIndex = 0; itemIndex< shopCartItems.size(); itemIndex++) {
+                for (int itemIndex = 0; itemIndex < shopCartItems.size(); itemIndex++) {
                     ShopCartItemDto shopCartItem = shopCartItems.get(itemIndex);
                     double prodDiscount = 0.0;
                     //判断是否最后一项
-                    boolean isEnd =  shopIndex == shopCartOrders.size() - 1 && discountIndex ==shopCartItemDiscounts.size() - 1 && itemIndex == shopCartItems.size() - 1;
+                    boolean isEnd = shopIndex == shopCartOrders.size() - 1 && discountIndex == shopCartItemDiscounts.size() - 1 && itemIndex == shopCartItems.size() - 1;
                     //折扣
                     if (level.getDiscountType() == 0 || categoryMap.containsKey(shopCartItem.getCategoryId())) {
                         prodDiscount = Arith.div(Arith.mul(shopCartItem.getActualTotal(), discount), 10, 2);
-                        if(isEnd || Arith.add(Arith.add(levelDiscount,reduceSum),prodDiscount) > maxlevelFeeTotal){
+                        if (isEnd || Arith.add(Arith.add(levelDiscount, reduceSum), prodDiscount) > maxlevelFeeTotal) {
                             //总折扣金额减去当前累计的折扣金额,就为最后一件商品分摊的等级优惠金额
-                            prodDiscount = Arith.sub(Arith.sub(maxlevelFeeTotal,levelDiscount),reduceSum);
+                            prodDiscount = Arith.sub(Arith.sub(maxlevelFeeTotal, levelDiscount), reduceSum);
                         }
                     }
                     //计算商品分摊的金额
-                    shopCartItem.setPlatformShareReduce(Arith.add(shopCartItem.getPlatformShareReduce() , prodDiscount));
-                    reduceSum = Arith.add(reduceSum, Arith.round(prodDiscount,2));
+                    shopCartItem.setPlatformShareReduce(Arith.add(shopCartItem.getPlatformShareReduce(), prodDiscount));
+                    reduceSum = Arith.add(reduceSum, Arith.round(prodDiscount, 2));
                 }
             }
             //设置店铺的实际总值、积分优惠金额和订单优惠金额
@@ -243,7 +245,7 @@ public class ConfirmOrderListener {
             levelDiscount = Arith.add(levelDiscount, reduceSum);
             //判断用户等级是否自营店包邮
             //&& level.getCategoryIds()
-            if(Objects.equals(shopCartOrder.getShopId(), Constant.MAIN_SHOP) && level.getIsFreeFee() == 1){
+            if (Objects.equals(shopCartOrder.getShopId(), Constant.MAIN_SHOP) && level.getIsFreeFee() == 1) {
                 freeTransfee = shopCartOrder.getTransfee();
                 shopCartOrder.setFreeTransfee(shopCartOrder.getTransfee());
                 shopCartOrder.setTransfee(0.0);
@@ -256,16 +258,17 @@ public class ConfirmOrderListener {
 
     /**
      * 计算出总共可以折扣的金额
+     *
      * @param shopCartOrders 全部商品项
-     * @param level 等级
-     * @param categoryMap 分类
+     * @param level          等级
+     * @param categoryMap    分类
      * @return 总折扣金额
      */
     private double getLevelFeeTotal(List<ShopCartOrderDto> shopCartOrders, UserLevel level, Map<Long, Long> categoryMap) {
         double totalFee = 0.0;
         for (ShopCartOrderDto shopCartOrder : shopCartOrders) {
             //如果可用范围为自营店不为当前店铺直接下一次循环
-            if(level.getDiscountRange() == 1 && !Objects.equals(shopCartOrder.getShopId(),1L)){
+            if (level.getDiscountRange() == 1 && !Objects.equals(shopCartOrder.getShopId(), 1L)) {
                 continue;
             }
             List<ShopCartItemDiscountDto> shopCartItemDiscounts = shopCartOrder.getShopCartItemDiscounts();
@@ -273,13 +276,13 @@ public class ConfirmOrderListener {
                 List<ShopCartItemDto> shopCartItems = shopCartItemDiscount.getShopCartItems();
                 for (ShopCartItemDto shopCartItem : shopCartItems) {
                     //折扣
-                    if(level.getDiscountType() == 0 || categoryMap.containsKey(shopCartItem.getCategoryId())){
-                        totalFee = Arith.add(totalFee,shopCartItem.getActualTotal());
+                    if (level.getDiscountType() == 0 || categoryMap.containsKey(shopCartItem.getCategoryId())) {
+                        totalFee = Arith.add(totalFee, shopCartItem.getActualTotal());
                     }
                 }
             }
         }
 //        return Arith.div(totalFee,level.getDiscount(),2);
-        return Arith.div(Arith.mul(totalFee, Arith.sub(10,level.getDiscount())), 10, 2);
+        return Arith.div(Arith.mul(totalFee, Arith.sub(10, level.getDiscount())), 10, 2);
     }
 }