浏览代码

Merge branch 'zx_saas_goods' of http://git.dayaedu.com/yonge/mec into dev

zouxuan 1 年之前
父节点
当前提交
0384d2d04f
共有 100 个文件被更改,包括 4160 次插入2040 次删除
  1. 9 30
      mec-application/src/main/java/com/ym/mec/student/controller/RepairController.java
  2. 1 31
      mec-application/src/main/java/com/ym/mec/student/controller/StudentOrderController.java
  3. 2 2
      mec-application/src/main/java/com/ym/mec/teacher/controller/GoodsController.java
  4. 46 23
      mec-application/src/main/java/com/ym/mec/web/controller/APIController.java
  5. 54 8
      mec-application/src/main/java/com/ym/mec/web/controller/GoodsController.java
  6. 13 1
      mec-application/src/main/java/com/ym/mec/web/controller/ImportController.java
  7. 12 0
      mec-application/src/main/java/com/ym/mec/web/controller/MusicGroupCalenderRefundPeriodController.java
  8. 3 0
      mec-application/src/main/java/com/ym/mec/web/controller/ReplacementInstrumentActivityController.java
  9. 1 20
      mec-application/src/main/java/com/ym/mec/web/controller/StudentPaymentRouteOrderController.java
  10. 2 1
      mec-application/src/main/java/com/ym/mec/web/controller/StudentRepairController.java
  11. 5 2
      mec-application/src/main/java/com/ym/mec/web/controller/TaskController.java
  12. 34 10
      mec-application/src/main/java/com/ym/mec/web/controller/education/EduRepairController.java
  13. 21 0
      mec-application/src/main/resources/columnMapper.ini
  14. 4 0
      mec-biz/src/main/java/com/ym/mec/biz/dal/dao/GoodsDao.java
  15. 2 0
      mec-biz/src/main/java/com/ym/mec/biz/dal/dao/MusicGroupCalenderRefundPeriodDao.java
  16. 9 0
      mec-biz/src/main/java/com/ym/mec/biz/dal/dao/MusicGroupPaymentCalenderAddressDao.java
  17. 9 0
      mec-biz/src/main/java/com/ym/mec/biz/dal/dao/MusicGroupPaymentCalenderGoodsDao.java
  18. 7 0
      mec-biz/src/main/java/com/ym/mec/biz/dal/dao/MusicGroupPaymentCalenderRepairDao.java
  19. 5 0
      mec-biz/src/main/java/com/ym/mec/biz/dal/dao/SellOrderDao.java
  20. 2 0
      mec-biz/src/main/java/com/ym/mec/biz/dal/dao/StudentPaymentOrderDao.java
  21. 2 0
      mec-biz/src/main/java/com/ym/mec/biz/dal/dao/StudentPaymentRouteOrderDao.java
  22. 2 0
      mec-biz/src/main/java/com/ym/mec/biz/dal/dao/StudentRepairDao.java
  23. 2 0
      mec-biz/src/main/java/com/ym/mec/biz/dal/dao/SubjectGoodsMapperDao.java
  24. 2 0
      mec-biz/src/main/java/com/ym/mec/biz/dal/dao/SysAreaDao.java
  25. 14 0
      mec-biz/src/main/java/com/ym/mec/biz/dal/dto/ComplementGoodsDto.java
  26. 3 95
      mec-biz/src/main/java/com/ym/mec/biz/dal/dto/CooperationCalenderRefundDto.java
  27. 26 0
      mec-biz/src/main/java/com/ym/mec/biz/dal/dto/CooperationCalenderRefundUpdateDto.java
  28. 20 0
      mec-biz/src/main/java/com/ym/mec/biz/dal/dto/GoodsNameDto.java
  29. 1 0
      mec-biz/src/main/java/com/ym/mec/biz/dal/dto/GoodsOrderItemVO.java
  30. 8 192
      mec-biz/src/main/java/com/ym/mec/biz/dal/dto/MusicGroupPaymentBaseCalender.java
  31. 22 0
      mec-biz/src/main/java/com/ym/mec/biz/dal/dto/OutOrderInfoDto.java
  32. 10 0
      mec-biz/src/main/java/com/ym/mec/biz/dal/dto/ReplacementInstrumentActivityStatDto.java
  33. 22 0
      mec-biz/src/main/java/com/ym/mec/biz/dal/dto/WaitSendMessageDto.java
  34. 14 2
      mec-biz/src/main/java/com/ym/mec/biz/dal/entity/Goods.java
  35. 49 0
      mec-biz/src/main/java/com/ym/mec/biz/dal/entity/GoodsSub.java
  36. 11 96
      mec-biz/src/main/java/com/ym/mec/biz/dal/entity/MusicGroupCalenderRefundPeriod.java
  37. 1 1
      mec-biz/src/main/java/com/ym/mec/biz/dal/entity/MusicGroupPaymentCalender.java
  38. 73 0
      mec-biz/src/main/java/com/ym/mec/biz/dal/entity/MusicGroupPaymentCalenderAddress.java
  39. 0 1
      mec-biz/src/main/java/com/ym/mec/biz/dal/entity/MusicGroupPaymentCalenderCourseSettings.java
  40. 66 0
      mec-biz/src/main/java/com/ym/mec/biz/dal/entity/MusicGroupPaymentCalenderGoods.java
  41. 11 1
      mec-biz/src/main/java/com/ym/mec/biz/dal/entity/ReplacementInstrument.java
  42. 3 0
      mec-biz/src/main/java/com/ym/mec/biz/dal/entity/SellOrder.java
  43. 36 1
      mec-biz/src/main/java/com/ym/mec/biz/dal/entity/StudentGoodsSell.java
  44. 4 0
      mec-biz/src/main/java/com/ym/mec/biz/dal/entity/StudentPaymentOrder.java
  45. 56 0
      mec-biz/src/main/java/com/ym/mec/biz/dal/entity/StudentPaymentOrderAddress.java
  46. 1 0
      mec-biz/src/main/java/com/ym/mec/biz/dal/enums/MessageTypeEnum.java
  47. 1 0
      mec-biz/src/main/java/com/ym/mec/biz/dal/enums/OrderTypeEnum.java
  48. 1 0
      mec-biz/src/main/java/com/ym/mec/biz/dal/enums/TemplateTypeEnum.java
  49. 25 0
      mec-biz/src/main/java/com/ym/mec/biz/dal/mapper/GoodsSubMapper.java
  50. 27 0
      mec-biz/src/main/java/com/ym/mec/biz/dal/mapper/StudentPaymentOrderAddressMapper.java
  51. 10 0
      mec-biz/src/main/java/com/ym/mec/biz/dal/page/GoodsQuery.java
  52. 33 0
      mec-biz/src/main/java/com/ym/mec/biz/dal/page/GoodsQueryInfo.java
  53. 63 0
      mec-biz/src/main/java/com/ym/mec/biz/dal/wrapper/GoodsSubWrapper.java
  54. 256 0
      mec-biz/src/main/java/com/ym/mec/biz/dal/wrapper/GoodsWrapper.java
  55. 71 0
      mec-biz/src/main/java/com/ym/mec/biz/dal/wrapper/MusicGroupCalenderRefundPeriodWrapper.java
  56. 67 0
      mec-biz/src/main/java/com/ym/mec/biz/dal/wrapper/MusicGroupPaymentCalenderAddressWrapper.java
  57. 63 0
      mec-biz/src/main/java/com/ym/mec/biz/dal/wrapper/StudentPaymentOrderAddressWrapper.java
  58. 3 0
      mec-biz/src/main/java/com/ym/mec/biz/service/CooperationOrganService.java
  59. 43 9
      mec-biz/src/main/java/com/ym/mec/biz/service/GoodsService.java
  60. 15 0
      mec-biz/src/main/java/com/ym/mec/biz/service/GoodsSubService.java
  61. 3 0
      mec-biz/src/main/java/com/ym/mec/biz/service/MusicGroupCalenderRefundPeriodService.java
  62. 13 0
      mec-biz/src/main/java/com/ym/mec/biz/service/MusicGroupPaymentCalenderAddressService.java
  63. 14 0
      mec-biz/src/main/java/com/ym/mec/biz/service/MusicGroupPaymentCalenderGoodsService.java
  64. 2 0
      mec-biz/src/main/java/com/ym/mec/biz/service/MusicGroupPaymentCalenderRepairService.java
  65. 1 0
      mec-biz/src/main/java/com/ym/mec/biz/service/SchoolService.java
  66. 25 6
      mec-biz/src/main/java/com/ym/mec/biz/service/SellOrderService.java
  67. 43 0
      mec-biz/src/main/java/com/ym/mec/biz/service/StudentPaymentOrderAddressService.java
  68. 5 5
      mec-biz/src/main/java/com/ym/mec/biz/service/StudentPaymentOrderDetailService.java
  69. 4 0
      mec-biz/src/main/java/com/ym/mec/biz/service/StudentPaymentOrderService.java
  70. 5 0
      mec-biz/src/main/java/com/ym/mec/biz/service/StudentPaymentRouteOrderService.java
  71. 2 1
      mec-biz/src/main/java/com/ym/mec/biz/service/SysAreaService.java
  72. 2 0
      mec-biz/src/main/java/com/ym/mec/biz/service/SysUserCashAccountService.java
  73. 3 3
      mec-biz/src/main/java/com/ym/mec/biz/service/impl/ActivityUserMapperServiceImpl.java
  74. 3 2
      mec-biz/src/main/java/com/ym/mec/biz/service/impl/ClassGroupServiceImpl.java
  75. 12 0
      mec-biz/src/main/java/com/ym/mec/biz/service/impl/CooperationOrganServiceImpl.java
  76. 2 2
      mec-biz/src/main/java/com/ym/mec/biz/service/impl/CourseScheduleStudentPaymentServiceImpl.java
  77. 3 2
      mec-biz/src/main/java/com/ym/mec/biz/service/impl/EduPracticeGroupServiceImpl.java
  78. 58 22
      mec-biz/src/main/java/com/ym/mec/biz/service/impl/ExportServiceImpl.java
  79. 820 53
      mec-biz/src/main/java/com/ym/mec/biz/service/impl/GoodsServiceImpl.java
  80. 23 0
      mec-biz/src/main/java/com/ym/mec/biz/service/impl/GoodsSubServiceImpl.java
  81. 54 3
      mec-biz/src/main/java/com/ym/mec/biz/service/impl/MusicGroupCalenderRefundPeriodServiceImpl.java
  82. 22 0
      mec-biz/src/main/java/com/ym/mec/biz/service/impl/MusicGroupPaymentCalenderAddressServiceImpl.java
  83. 80 0
      mec-biz/src/main/java/com/ym/mec/biz/service/impl/MusicGroupPaymentCalenderGoodsServiceImpl.java
  84. 28 4
      mec-biz/src/main/java/com/ym/mec/biz/service/impl/MusicGroupPaymentCalenderRepairServiceImpl.java
  85. 373 39
      mec-biz/src/main/java/com/ym/mec/biz/service/impl/MusicGroupPaymentCalenderServiceImpl.java
  86. 3 2
      mec-biz/src/main/java/com/ym/mec/biz/service/impl/MusicGroupPaymentStudentCourseDetailServiceImpl.java
  87. 1 1
      mec-biz/src/main/java/com/ym/mec/biz/service/impl/MusicGroupServiceImpl.java
  88. 18 20
      mec-biz/src/main/java/com/ym/mec/biz/service/impl/PayServiceImpl.java
  89. 30 32
      mec-biz/src/main/java/com/ym/mec/biz/service/impl/ReplacementInstrumentActivityServiceImpl.java
  90. 18 0
      mec-biz/src/main/java/com/ym/mec/biz/service/impl/ReplacementInstrumentServiceImpl.java
  91. 1 0
      mec-biz/src/main/java/com/ym/mec/biz/service/impl/SchoolServiceImpl.java
  92. 470 375
      mec-biz/src/main/java/com/ym/mec/biz/service/impl/SellOrderServiceImpl.java
  93. 12 7
      mec-biz/src/main/java/com/ym/mec/biz/service/impl/StudentGoodsSellServiceImpl.java
  94. 6 0
      mec-biz/src/main/java/com/ym/mec/biz/service/impl/StudentInstrumentServiceImpl.java
  95. 65 0
      mec-biz/src/main/java/com/ym/mec/biz/service/impl/StudentPaymentOrderAddressServiceImpl.java
  96. 118 51
      mec-biz/src/main/java/com/ym/mec/biz/service/impl/StudentPaymentOrderDetailServiceImpl.java
  97. 175 153
      mec-biz/src/main/java/com/ym/mec/biz/service/impl/StudentPaymentOrderServiceImpl.java
  98. 143 164
      mec-biz/src/main/java/com/ym/mec/biz/service/impl/StudentPaymentRouteOrderServiceImpl.java
  99. 37 137
      mec-biz/src/main/java/com/ym/mec/biz/service/impl/StudentRegistrationServiceImpl.java
  100. 85 430
      mec-biz/src/main/java/com/ym/mec/biz/service/impl/StudentRepairServiceImpl.java

+ 9 - 30
mec-application/src/main/java/com/ym/mec/student/controller/RepairController.java

@@ -1,7 +1,6 @@
 package com.ym.mec.student.controller;
 
 
-import com.ym.mec.auth.api.client.SysUserFeignService;
 import com.ym.mec.auth.api.entity.SysUser;
 import com.ym.mec.biz.dal.entity.StudentGoodsSell;
 import com.ym.mec.biz.dal.entity.StudentPaymentOrder;
@@ -34,7 +33,7 @@ import java.util.Optional;
 public class RepairController extends BaseController {
 
     @Autowired
-    private SysUserFeignService sysUserFeignService;
+    private SysUserService sysUserService;
     @Autowired
     private StudentRepairService studentRepairService;
     @Autowired
@@ -50,11 +49,7 @@ public class RepairController extends BaseController {
     @PostMapping(value = "/addGoodsSellOrder")
     public HttpResponseResult addGoodsSellOrder(@RequestBody StudentGoodsSell studentGoodsSell) throws Exception {
         if(studentGoodsSell.getUserId() == null){
-            SysUser sysUser = sysUserFeignService.queryUserInfo();
-            if (sysUser == null) {
-                throw new BizException("请登录");
-            }
-            studentGoodsSell.setUserId(sysUser.getId());
+            studentGoodsSell.setUserId(sysUserService.getUserId());
         }
         if (studentGoodsSell.getIsRepeatPay() == false) {
             List<StudentPaymentOrder> list = studentPaymentOrderService.queryByCondition(GroupType.GOODS_SELL, null, studentGoodsSell.getUserId(), DealStatusEnum.ING,
@@ -94,11 +89,7 @@ public class RepairController extends BaseController {
     @ApiOperation("获取维修记录")
     @GetMapping(value = "/getStudentRepairList")
     public HttpResponseResult getStudentRepairList(RepairStudentQueryInfo queryInfo) {
-        SysUser sysUser = sysUserFeignService.queryUserInfo();
-        if (sysUser == null) {
-            return failed("用户信息获取失败");
-        }
-        queryInfo.setStudentId(sysUser.getId());
+        queryInfo.setStudentId(sysUserService.getUserId());
         queryInfo.setPayStatus(2);
         return succeed(studentRepairService.queryPage(queryInfo));
     }
@@ -107,7 +98,7 @@ public class RepairController extends BaseController {
     @GetMapping(value = "/getRepairInfo")
     public HttpResponseResult getRepairInfo(Integer id,Integer studentId) {
         Optional.ofNullable(studentId)
-                .map(sysUserFeignService::queryUserById)
+                .map(sysUserService::queryUserById)
                 .orElseThrow(() -> new BizException("用户信息获取失败"));
 
         StudentRepair repairInfo = studentRepairService.getRepairInfo(id);
@@ -120,31 +111,23 @@ public class RepairController extends BaseController {
     @ApiOperation("支付维修单")
     @PostMapping(value = "/payRepair")
     public HttpResponseResult payRepair(@RequestBody StudentRepair repairInfo) throws Exception {
-        SysUser sysUser = sysUserFeignService.queryUserInfo();
-        if (sysUser == null) {
-            return failed(HttpStatus.FORBIDDEN, "请登录");
-        }
+        sysUserService.getUser();
         return succeed(studentRepairService.payRepair(repairInfo));
     }
 
     @ApiOperation("获取维修技师信息")
     @PostMapping(value = "/getRepairer")
     public HttpResponseResult getRepairer() {
-        SysUser sysUser = sysUserFeignService.queryUserInfo();
-        if (sysUser == null) {
-            return failed(HttpStatus.FORBIDDEN, "请登录");
-        }
+        SysUser sysUser = sysUserService.getUser();
         return succeed(studentRepairService.getStudentRepairer(sysUser.getId(),sysUser.getOrganId()));
     }
 
     @ApiOperation(value = "分页查询商品(教材、辅件)列表")
     @GetMapping("/queryGoodsPage")
     public Object queryPage(GoodsQueryInfo queryInfo){
-        SysUser sysUser = sysUserFeignService.queryUserInfo();
-        if(sysUser == null){
-            throw new BizException("请先登录");
-        }
+        SysUser sysUser = sysUserService.getUser();
         queryInfo.setStudentShowOrganId(sysUser.getOrganId().toString());
+        queryInfo.setTenantId(sysUser.getTenantId());
         return succeed(goodsService.queryPage(queryInfo));
     }
 
@@ -157,11 +140,7 @@ public class RepairController extends BaseController {
     @ApiOperation(value = "分页查询学员商品订单")
     @GetMapping("/queryStudentGoodsOrders")
     public Object queryStudentGoodsOrders(GoodsSellQueryInfo queryInfo) {
-        SysUser sysUser = sysUserFeignService.queryUserInfo();
-        if (sysUser == null) {
-            return failed(HttpStatus.FORBIDDEN, "请登录");
-        }
-        queryInfo.setStudentId(sysUser.getId());
+        queryInfo.setStudentId(sysUserService.getUserId());
         return succeed(studentGoodsSellService.queryStudentGoodsOrders(queryInfo));
     }
 

+ 1 - 31
mec-application/src/main/java/com/ym/mec/student/controller/StudentOrderController.java

@@ -97,8 +97,6 @@ public class StudentOrderController extends BaseController {
     @Autowired
     private VipGroupActivityService vipGroupActivityService;
     @Autowired
-    private SellOrderService sellOrderService;
-    @Autowired
     private TenantOrderRecordService tenantOrderRecordService;
     @Autowired
     private OrderPayOpsService orderPayOpsService;
@@ -477,7 +475,7 @@ public class StudentOrderController extends BaseController {
     @GetMapping("/setSuccessStatus")
     public HttpResponseResult setSuccessStatus(String orderNo) throws Exception {
         if (!profiles.equals("dev") && !profiles.equals("test")) {
-            return failed("非法操作");
+//            return failed("非法操作");
         }
         List<StudentPaymentOrder> payingOrders = studentPaymentOrderService.findOrdersByStatus(DealStatusEnum.ING);
 
@@ -888,34 +886,6 @@ public class StudentOrderController extends BaseController {
         return succeed(musicGroupRegCalender);
     }
 
-    @GetMapping("fixSellOrder")
-    public HttpResponseResult<List<SellOrder>> fixSellOrder(String orderNo) {
-        StudentPaymentOrder order = studentPaymentOrderService.findOrderByOrderNo(orderNo);
-        List<SellOrder> sellOrders = new ArrayList<>();
-        if (order == null || !order.getStatus().equals(DealStatusEnum.SUCCESS) || !order.getType().equals(OrderTypeEnum.APPLY)) {
-            return succeed(sellOrders);
-        }
-
-        List<StudentPaymentOrderDetail> orderDetails = studentPaymentOrderDetailService.getOrderGoodsDetail(order.getId());
-        //销售订单详情
-        if (orderDetails.size() > 0) {
-            MusicGroup musicGroup = musicGroupService.get(order.getMusicGroupId());
-            BigDecimal couponRemitFee = order.getCouponRemitFee();
-            if (couponRemitFee.compareTo(BigDecimal.ZERO) > 0) {
-                BigDecimal musicFee = orderDetails.stream().filter(o -> o.getType().getCode().equals("MUSICAL")
-                                || o.getType().getCode().equals("ACCESSORIES") || o.getType().getCode().equals("TEACHING"))
-                        .map(o -> o.getPrice()).reduce(BigDecimal.ZERO, BigDecimal::add);
-                BigDecimal expectAmount = order.getExpectAmount();
-                //获取比例
-                BigDecimal ratioAmount = musicFee.divide(expectAmount, 6, BigDecimal.ROUND_HALF_UP);
-                //获取分配的减免金额
-                couponRemitFee = couponRemitFee.multiply(ratioAmount).setScale(2, BigDecimal.ROUND_HALF_UP);
-            }
-            sellOrders = sellOrderService.addOrderDetail2SellOrder(orderDetails, order, musicGroup, couponRemitFee);
-        }
-        return succeed(sellOrders);
-
-    }
 
     @ApiImplicitParams({
             @ApiImplicitParam(name = "queryDate", dataType = "String", value = "年月"),

+ 2 - 2
mec-application/src/main/java/com/ym/mec/teacher/controller/GoodsController.java

@@ -1,7 +1,7 @@
 package com.ym.mec.teacher.controller;
 
-import com.ym.mec.biz.dal.entity.Goods;
 import com.ym.mec.biz.dal.entity.GoodsCategory;
+import com.ym.mec.biz.dal.wrapper.GoodsWrapper;
 import com.ym.mec.biz.service.GoodsCategoryService;
 import com.ym.mec.biz.service.GoodsService;
 import com.ym.mec.common.controller.BaseController;
@@ -29,7 +29,7 @@ public class GoodsController extends BaseController {
     @ApiOperation(value = "根据商品(教材、辅件)编号查询商品(教材、辅件)")
     @GetMapping("/get/{id}")
     public Object get(@ApiParam(value = "商品(教材、辅件)编号", required = true) @PathVariable("id") Integer id) {
-        Goods goods = goodsService.getDetail(id);
+        GoodsWrapper.Goods goods = goodsService.getDetail(id);
         GoodsCategory goodsCategory = goodsCategoryService.get(goods.getGoodsCategoryId());
         if (Objects.nonNull(goodsCategory)) {
             goods.setGoodsCategoryName(goodsCategory.getName());

+ 46 - 23
mec-application/src/main/java/com/ym/mec/web/controller/APIController.java

@@ -10,18 +10,16 @@ import com.ym.mec.biz.dal.entity.*;
 import com.ym.mec.biz.dal.page.StudentVipGroupQueryInfo;
 import com.ym.mec.biz.service.*;
 import com.ym.mec.common.controller.BaseController;
-import com.ym.mec.common.entity.HttpResponseResult;
-import com.ym.mec.common.entity.MallCreateOrderModel;
-import com.ym.mec.common.entity.OrderCancelModel;
-import com.ym.mec.common.entity.RefundModel;
+import com.ym.mec.common.dto.SchoolDto;
+import com.ym.mec.common.entity.*;
 import com.ym.mec.thirdparty.adapay.entity.BaseResult;
 import io.swagger.annotations.Api;
 import io.swagger.annotations.ApiOperation;
 import org.apache.commons.lang3.StringUtils;
-import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.util.CollectionUtils;
 import org.springframework.web.bind.annotation.*;
 
+import javax.annotation.Resource;
 import java.math.BigDecimal;
 import java.util.HashMap;
 import java.util.List;
@@ -31,32 +29,34 @@ import java.util.Map;
 @Api(tags = "对外接口")
 @RestController
 public class APIController extends BaseController {
-	@Autowired
+	@Resource
 	private SysUserCashAccountDao sysUserCashAccountDao;
-	@Autowired
+	@Resource
 	private TeacherDao teacherDao;
-	@Autowired
+	@Resource
 	private EmployeeDao employeeDao;
-	@Autowired
+	@Resource
 	private PracticeLessonApplyService practiceLessonApplyService;
-	@Autowired
+	@Resource
 	private PracticeGroupService practiceGroupService;
-	@Autowired
+	@Resource
 	private ImGroupService imGroupService;
-	@Autowired
+	@Resource
 	private SysUserFeignService sysUserFeignService;
-	@Autowired
+	@Resource
 	private SysTenantConfigService sysTenantConfigService;
-	@Autowired
+	@Resource
 	private SysUserService sysUserService;
-	@Autowired
+	@Resource
 	private VipGroupService vipGroupService;
-
-	@Autowired
+	@Resource
 	private SysConfigService sysConfigService;
-
-	@Autowired
+	@Resource
 	private StudentPaymentOrderService studentPaymentOrderService;
+	@Resource
+	private GoodsService goodsService;
+	@Resource
+	private CooperationOrganService cooperationOrganService;
 
 	@GetMapping("/createCashAccount")
 	public Boolean createCashAccount(Integer userId,Integer tenantId) {
@@ -146,24 +146,30 @@ public class APIController extends BaseController {
 	// 商城订单优惠券金额
 	@PostMapping("/couponAmount")
 	public HttpResponseResult<Map> couponAmount(@RequestBody MallCreateOrderModel model) {
-			return succeed(studentPaymentOrderService.couponAmount(model));
+		return succeed(studentPaymentOrderService.couponAmount(model));
 	}
 
 	// 商城保存订单详情数据
 	@PostMapping("/mallSaveOrderInfo")
 	public HttpResponseResult<Map> mallSaveOrderInfo(@RequestBody MallCreateOrderModel model) {
-			studentPaymentOrderService.mallSaveOrderInfo(model);
-			return succeed();
+		studentPaymentOrderService.mallSaveOrderInfo(model);
+		return succeed();
 	}
 
 	// 商城支付成功/失败修改订单状态
 	@PostMapping("/updateOrder")
 	public HttpResponseResult updateOrder(@RequestBody Map map) throws Exception {
-
 		studentPaymentOrderService.updateOrder(map);
 		return succeed();
 	}
 
+	// 同步商城订单发货状态
+	@PostMapping("/updateShippedStatus")
+	public HttpResponseResult updateShippedStatus(@RequestBody List<OrderSkuSync> orderSkuSyncs) throws Exception {
+		studentPaymentOrderService.updateShippedStatus(orderSkuSyncs);
+		return succeed();
+	}
+
 
 	/**
 	 * 商城取消订单接口
@@ -229,4 +235,21 @@ public class APIController extends BaseController {
 
 		return succeed(balance);
 	}
+
+	// 组合商品状态同步
+	@PostMapping("/goodsStatusSynchronize")
+	public HttpResponseResult<Boolean> goodsStatusSynchronize(@RequestBody List<GoodsSubModel> goodsSubModelList) {
+		return succeed(goodsService.goodsStatusSynchronize(goodsSubModelList));
+	}
+
+	// 组合商品库存同步
+	@PostMapping("/goodsStockCountSynchronize")
+	public HttpResponseResult<Boolean> goodsStockCountSynchronize(@RequestBody List<GoodsSubStockModel> goodsSubStockModels) {
+		return succeed(goodsService.goodsStockCountSynchronize(goodsSubStockModels));
+	}
+
+	@PostMapping("/schoolListByIds")
+	public HttpResponseResult<List<SchoolDto>> coopListByIds(@RequestBody List<Integer> coopIds) {
+		return succeed(cooperationOrganService.coopListByIds(coopIds));
+	}
 }

+ 54 - 8
mec-application/src/main/java/com/ym/mec/web/controller/GoodsController.java

@@ -8,6 +8,7 @@ import com.ym.mec.biz.dal.entity.GoodsProcurement;
 import com.ym.mec.biz.dal.enums.YesOrNoEnum;
 import com.ym.mec.biz.dal.page.GoodsQuery;
 import com.ym.mec.biz.dal.page.GoodsQueryInfo;
+import com.ym.mec.biz.dal.wrapper.GoodsWrapper;
 import com.ym.mec.biz.service.GoodsCategoryService;
 import com.ym.mec.biz.service.GoodsService;
 import com.ym.mec.biz.service.SysUserService;
@@ -18,10 +19,20 @@ import io.swagger.annotations.ApiParam;
 import org.apache.commons.lang3.StringUtils;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.security.access.prepost.PreAuthorize;
-import org.springframework.web.bind.annotation.*;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
 
+import java.util.Arrays;
+import java.util.Collections;
 import java.util.Date;
+import java.util.List;
+import java.util.Map;
 import java.util.Objects;
+import java.util.stream.Collectors;
 
 @RequestMapping("${app-config.url.web:}/goods")
 @Api(tags = "商品(教材、辅件)服务")
@@ -40,19 +51,27 @@ public class GoodsController extends BaseController {
     @ApiOperation(value = "新增商品(教材、辅件)")
     @PostMapping("/add")
     @PreAuthorize("@pcs.hasPermissions('goods/add')")
-    public Object add(Goods goods){
-        goodsService.addGoods(goods,sysUserService.getUserId());
+    public Object add(@RequestBody GoodsWrapper.Goods goods) {
+        goodsService.addGoods(Collections.singletonList(goods), sysUserService.getUserId());
         return succeed();
     }
 
-    @ApiOperation(value = "新增商品清单")
+    @ApiOperation(value = "新增商品(教材、辅件)")
+    @PostMapping("/addBatch")
+    @PreAuthorize("@pcs.hasPermissions('goods/addBatch')")
+    public Object addBatch(@RequestBody List<GoodsWrapper.Goods> goodsList) {
+        goodsService.addGoods(goodsList, sysUserService.getUserId());
+        return succeed();
+    }
+
+/*    @ApiOperation(value = "新增商品清单")
     @PostMapping("/addGoodsProcurement")
     @PreAuthorize("@pcs.hasPermissions('goods/addGoodsProcurement')")
     public Object addGoodsProcurement(GoodsProcurement goodsProcurement){
         goodsProcurement.setOperatorId(sysUserService.getUserId());
         goodsService.addGoodsProcurement(goodsProcurement);
         return succeed();
-    }
+    }*/
 
     @ApiOperation(value = "删除商品(教材、辅件)")
     @PostMapping("/del/{id}")
@@ -79,16 +98,16 @@ public class GoodsController extends BaseController {
     @ApiOperation(value = "修改商品(教材、辅件)")
     @PostMapping("/update")
     @PreAuthorize("@pcs.hasPermissions('goods/update')")
-    public Object update(Goods goods){
+    public Object update(@RequestBody GoodsWrapper.Goods goods){
         goods.setUpdateTime(new Date());
-        goodsService.update(goods);
+        goodsService.updateGoods(goods);
         return succeed();
     }
 
     @ApiOperation(value = "根据商品(教材、辅件)编号查询商品(教材、辅件)")
     @GetMapping("/get/{id}")
     public Object get(@ApiParam(value = "商品(教材、辅件)编号", required = true) @PathVariable("id") Integer id){
-        Goods goods = goodsService.getDetail(id);
+        GoodsWrapper.Goods goods = goodsService.getDetail(id);
         GoodsCategory goodsCategory = goodsCategoryService.get(goods.getGoodsCategoryId());
         if(Objects.nonNull(goodsCategory)){
             goods.setGoodsCategoryName(goodsCategory.getName());
@@ -120,4 +139,31 @@ public class GoodsController extends BaseController {
     public Object findGoodsBySubId(GoodsQuery goodsQuery){
         return succeed(goodsService.findGoodsBySubId(goodsQuery));
     }
+
+
+    @ApiOperation(value = "查询商城商品列表分页")
+    @GetMapping("/queryGoodsSubByPage")
+//    @PreAuthorize("@pcs.hasPermissions('goods/queryGoodsSubByPage')")
+    public Object queryGoodsSubByPage(GoodsWrapper.GoodsSubQuery query) {
+        return succeed(goodsService.queryGoodsSubByPage(query));
+
+    }
+
+    @ApiOperation(value = "查询商品类型")
+    @GetMapping("/queryGoodsTypeList")
+    public Object queryGoodsTypeList() {
+        return succeed(goodsService.queryGoodsTypeList());
+    }
+
+    @ApiOperation(value = "查询商品分类")
+    @GetMapping("/queryGoodsCategoryList")
+    public Object queryGoodsCategoryList() {
+        return succeed(goodsService.queryGoodsCategoryList());
+    }
+
+    @ApiOperation(value = "查询商品品牌")
+    @GetMapping("/queryGoodsBrandList")
+    public Object queryGoodsBrandList() {
+        return succeed(goodsService.queryGoodsBrandList());
+    }
 }

+ 13 - 1
mec-application/src/main/java/com/ym/mec/web/controller/ImportController.java

@@ -60,11 +60,23 @@ public class ImportController extends BaseController {
     private StudentVisitService studentVisitService;
 
 
-    @ApiOperation(value = "导入商品")
+/*    @ApiOperation(value = "导入商品")
     @PostMapping(value = "goods")
     @PreAuthorize("@pcs.hasPermissions('import/goods')")
     public HttpResponseResult<List<Goods>> importGoods(@RequestParam("file") MultipartFile file) throws Exception {
         return succeed(goodsService.importGoods(file, sysUserService.getUserId()));
+    }*/
+
+    @ApiOperation(value = "导入商品")
+    @PostMapping(value = "goodsV2")
+//    @PreAuthorize("@pcs.hasPermissions('import/goodsV2')")
+    public HttpResponseResult<String> importGoodsV2(@RequestParam("file") MultipartFile file) throws Exception {
+        String errFile = goodsService.importGoodsV2(file, sysUserService.getUserId());
+        if (StringUtils.isEmpty(errFile)) {
+            return succeed();
+        } else {
+            return failed(errFile);
+        }
     }
 
     @ApiOperation(value = "导入财务支出")

+ 12 - 0
mec-application/src/main/java/com/ym/mec/web/controller/MusicGroupCalenderRefundPeriodController.java

@@ -1,6 +1,8 @@
 package com.ym.mec.web.controller;
 
 import com.ym.mec.biz.dal.dto.CooperationCalenderRefundDto;
+import com.ym.mec.biz.dal.dto.CooperationCalenderRefundUpdateDto;
+import com.ym.mec.biz.dal.entity.MusicGroupCalenderRefundPeriod;
 import com.ym.mec.biz.dal.page.CooperationRefundQueryInfo;
 import com.ym.mec.biz.service.MusicGroupCalenderRefundPeriodService;
 import com.ym.mec.biz.service.OrganizationService;
@@ -18,6 +20,7 @@ import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RestController;
 
 import java.util.HashMap;
+import java.util.List;
 
 @RequestMapping("${app-config.url.web:}/musicGroupCalenderRefundPeriod")
 @Api(tags = "学校缴费项目缴费周期")
@@ -49,4 +52,13 @@ public class MusicGroupCalenderRefundPeriodController extends BaseController {
         queryInfo.setOrganId(organizationService.getEmployeeOrgan(queryInfo.getOrganId()));
         return succeed(musicGroupCalenderRefundPeriodService.queryCoopCalender(queryInfo));
     }
+
+    @ApiOperation(value = "批量修改")
+    @PostMapping("/batchUpdate")
+    @PreAuthorize("@pcs.hasPermissions('musicGroupCalenderRefundPeriod/batchUpdate')")
+    @AuditLogAnnotation(operateName = "批量修改")
+    public HttpResponseResult batchUpdate(@RequestBody List<CooperationCalenderRefundUpdateDto> refundPeriods) {
+        musicGroupCalenderRefundPeriodService.batchUpdate(refundPeriods);
+        return succeed();
+    }
 }

+ 3 - 0
mec-application/src/main/java/com/ym/mec/web/controller/ReplacementInstrumentActivityController.java

@@ -1,5 +1,6 @@
 package com.ym.mec.web.controller;
 
+import com.beust.jcommander.internal.Lists;
 import com.ym.mec.auth.api.client.SysUserFeignService;
 import com.ym.mec.biz.dal.dao.ReplacementInstrumentActivityDao;
 import com.ym.mec.biz.dal.dao.SysConfigDao;
@@ -89,6 +90,7 @@ public class ReplacementInstrumentActivityController extends BaseController {
         ReplacementInstrumentCooperation byCooperationId = replacementInstrumentCooperationService.get(oldReplacementInstrumentActivity.getReplacementInstrumentCooperationId());
         if (byCooperationId.getOpenPay().equals(YesOrNoEnum.YES) && oldReplacementInstrumentActivity.getInstrumentsId() == null && replacementInstrumentActivity.getInstrumentsId() != null) {
             Goods goods = goodsService.get(replacementInstrumentActivity.getInstrumentsId());
+            goods.setBrand(goodsService.getBrandMap().getOrDefault(goods.getBrand(),goods.getBrand()));
             Map<Integer, String> userMap = new HashMap<>();
             Map<Integer, String> userPhoneMap = new HashMap<>();
             Integer userId = oldReplacementInstrumentActivity.getUserId();
@@ -126,6 +128,7 @@ public class ReplacementInstrumentActivityController extends BaseController {
         }
         if (openFlag == 1) {
             Goods goods = goodsService.get(replacementInstrumentActivity.getInstrumentsId());
+            goods.setBrand(goodsService.getBrandMap().getOrDefault(goods.getBrand(),goods.getBrand()));
             Map<Integer, String> userMap = new HashMap<>();
             Map<Integer, String> userPhoneMap = new HashMap<>();
             Integer userId = replacementInstrumentActivity.getUserId();

+ 1 - 20
mec-application/src/main/java/com/ym/mec/web/controller/StudentPaymentRouteOrderController.java

@@ -1,13 +1,9 @@
 package com.ym.mec.web.controller;
 
-import com.ym.mec.biz.dal.dao.SellOrderDao;
 import com.ym.mec.biz.dal.dao.StudentPaymentOrderDao;
-import com.ym.mec.biz.dal.dao.StudentPaymentRouteOrderDao;
 import com.ym.mec.biz.dal.dto.BasicUserDto;
 import com.ym.mec.biz.dal.dto.OutOrderInfoDto;
 import com.ym.mec.biz.dal.dto.StudentPaymentRouteOrderDto;
-import com.ym.mec.biz.dal.entity.SellOrder;
-import com.ym.mec.biz.dal.entity.StudentPaymentOrder;
 import com.ym.mec.biz.dal.entity.StudentPaymentRouteOrder;
 import com.ym.mec.biz.dal.enums.AuditStatusEnum;
 import com.ym.mec.biz.dal.page.StudentPaymentOrderQueryInfo;
@@ -43,10 +39,6 @@ public class StudentPaymentRouteOrderController extends BaseController {
     private OrganizationService organizationService;
     @Autowired
     private StudentPaymentOrderDao studentPaymentOrderDao;
-    @Autowired
-    private SellOrderDao sellOrderDao;
-    @Autowired
-    private StudentPaymentRouteOrderDao studentPaymentRouteOrderDao;
 
     @ApiOperation(value = "财务订单列表")
     @GetMapping("/finance")
@@ -143,18 +135,7 @@ public class StudentPaymentRouteOrderController extends BaseController {
     @GetMapping("/getOrderInfo")
     @PreAuthorize("@pcs.hasPermissions('routeOrder/getOrderInfo')")
     public HttpResponseResult<OutOrderInfoDto> getOrderInfo(Long orderId) {
-        OutOrderInfoDto outOrderInfoDto = new OutOrderInfoDto();
-        StudentPaymentOrder order = studentPaymentOrderDao.get(orderId);
-        outOrderInfoDto.setStudentPaymentOrder(order);
-        StudentPaymentRouteOrder routeOrder = studentPaymentRouteOrderDao.getByOrderNo(order.getOrderNo());
-        outOrderInfoDto.setCalenderId(routeOrder.getCalenderId());
-        List<SellOrder> sellOrders = sellOrderDao.getOrderSellOrder(orderId);
-        BigDecimal goodsAmount = sellOrders.stream().map(SellOrder::getActualAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
-        BigDecimal serviceAmount = outOrderInfoDto.getStudentPaymentOrder().getActualAmount().subtract(goodsAmount);
-        outOrderInfoDto.setServiceAmount(serviceAmount);
-        outOrderInfoDto.setGoodsAmount(goodsAmount);
-        outOrderInfoDto.setSellOrders(sellOrders);
-        return succeed(outOrderInfoDto);
+        return succeed(studentPaymentRouteOrderService.getRouteOrder(orderId));
     }
 
     @ApiOperation(value = "删除订单")

+ 2 - 1
mec-application/src/main/java/com/ym/mec/web/controller/StudentRepairController.java

@@ -27,6 +27,7 @@ import javax.servlet.http.HttpServletResponse;
 import java.io.IOException;
 import java.io.OutputStream;
 import java.math.BigDecimal;
+import java.math.RoundingMode;
 import java.util.Date;
 import java.util.List;
 import java.util.stream.Collectors;
@@ -88,7 +89,7 @@ public class StudentRepairController extends BaseController {
             }
             List<RepairGoodsDto> repairGoodsDtos = JSONObject.parseArray(row.getGoodsJson(), RepairGoodsDto.class);
             BigDecimal repairGoodsAmount = repairGoodsDtos.stream().map(RepairGoodsDto::getGroupPurchasePrice).reduce(BigDecimal.ZERO, BigDecimal::add);
-            BigDecimal goodsRouteAmount = (row.getAmount().add(repairGoodsAmount).subtract(row.getExemptionAmount())).multiply(repairGoodsAmount).divide(row.getAmount().add(repairGoodsAmount), 2, BigDecimal.ROUND_DOWN);
+            BigDecimal goodsRouteAmount = (row.getAmount().add(repairGoodsAmount).subtract(row.getExemptionAmount())).multiply(repairGoodsAmount).divide(row.getAmount().add(repairGoodsAmount), 2, RoundingMode.DOWN);
             BigDecimal repairRouteAmount = row.getAmount().add(repairGoodsAmount).subtract(row.getExemptionAmount()).subtract(goodsRouteAmount);
             String goodiesStr = repairGoodsDtos.stream().map(RepairGoodsDto::getName).collect(Collectors.joining(","));
             row.setGoodsJson(goodiesStr);

+ 5 - 2
mec-application/src/main/java/com/ym/mec/web/controller/TaskController.java

@@ -140,9 +140,10 @@ public class TaskController extends BaseController {
     private DegreeService degreeService;
 	@Autowired
 	private ImPluginContext imPluginContext;
-
     @Autowired
     private UserMusicService userMusicService;
+    @Autowired
+    private MusicGroupPaymentCalenderRepairService musicGroupPaymentCalenderRepairService;
 
 	@GetMapping(value = "/initSysMusicCompareDayData")
 	public void initSysMusicCompareDayData(){
@@ -234,9 +235,11 @@ public class TaskController extends BaseController {
 	}
 
 	@GetMapping(value = "/pushWaitSendMessageTask")
-	// 每天9点推送前一天22点之后的推送消息
 	public void pushWaitSendMessageTask(){
+		// 每天9点推送前一天22点之后的推送消息
 		sysMessageService.pushWaitSendMessageTask();
+		// 学校缴费回款提醒
+		musicGroupPaymentCalenderRepairService.pushWaitSendMessageTask();
 	}
 
 	@GetMapping(value = "/repertoryWarn")

+ 34 - 10
mec-application/src/main/java/com/ym/mec/web/controller/education/EduRepairController.java

@@ -1,6 +1,9 @@
 package com.ym.mec.web.controller.education;
 
 
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONArray;
+import com.alibaba.fastjson.JSONObject;
 import com.ym.mec.auth.api.entity.SysUser;
 import com.ym.mec.biz.dal.dao.EmployeeDao;
 import com.ym.mec.biz.dal.dao.StudentInstrumentDao;
@@ -12,21 +15,26 @@ import com.ym.mec.biz.dal.enums.OrderTypeEnum;
 import com.ym.mec.biz.dal.page.*;
 import com.ym.mec.biz.service.*;
 import com.ym.mec.common.controller.BaseController;
+import com.ym.mec.common.dto.BrandDto;
 import com.ym.mec.common.entity.HttpResponseResult;
 import com.ym.mec.common.page.PageInfo;
 import com.ym.mec.common.page.QueryInfo;
+import com.ym.mec.mall.MallFeignService;
 import com.ym.mec.util.date.DateUtil;
 import io.swagger.annotations.Api;
 import io.swagger.annotations.ApiOperation;
+import org.apache.commons.lang.math.NumberUtils;
 import org.apache.commons.lang3.StringUtils;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.http.HttpStatus;
 import org.springframework.web.bind.annotation.*;
 
+import javax.annotation.Resource;
 import java.util.Date;
 import java.util.List;
 import java.util.Map;
 import java.util.Objects;
+import java.util.stream.Collectors;
 
 @RequestMapping("${app-config.url.web:}/eduRepair")
 @Api(tags = "教务维修服务")
@@ -53,17 +61,20 @@ public class EduRepairController extends BaseController {
     private StudentInstrumentService studentInstrumentService;
     @Autowired
     private StudentInstrumentDao studentInstrumentDao;
+    @Resource
+    private MallFeignService mallFeignService;
 
     @ApiOperation("获取学生列表")
     @GetMapping(value = "/getStudents")
     public HttpResponseResult<PageInfo<BasicUserDto>> getStudents(RepairStudentQueryInfo queryInfo) {
-        Integer userId = sysUserService.getUserId();
-        Employee employee = employeeDao.get(userId);
+        SysUser user = sysUserService.getUser();
+        Employee employee = employeeDao.get(user.getId());
         if (Objects.isNull(employee)) {
             return failed(HttpStatus.NOT_ACCEPTABLE, "员工信息不存在");
         }
-        queryInfo.setEmployeeId(userId);
+        queryInfo.setEmployeeId(user.getId());
         queryInfo.setOrganIdList(employee.getOrganIdList());
+        queryInfo.setTenantId(user.getTenantId());
         return succeed(studentRepairService.getStudents(queryInfo));
     }
 
@@ -99,12 +110,6 @@ public class EduRepairController extends BaseController {
         SysUser sysUser = sysUserService.getUser();
         repairInfo.setEmployeeId(sysUser.getId());
         repairInfo.setEmployeeName(sysUser.getRealName());
-//        if(repairInfo.getSendType().equals(1)){
-//            Employee employee = employeeDao.get(sysUser.getId());
-//            if(StringUtils.isBlank(employee.getContactAddress())){
-//                return failed("联系地址为空,请联系相关人员在\"员工管理\"完善");
-//            }
-//        }
         return succeed(studentRepairService.addRepair(repairInfo));
     }
 
@@ -113,7 +118,26 @@ public class EduRepairController extends BaseController {
     public HttpResponseResult getStudentRepairList(RepairStudentQueryInfo queryInfo) {
         queryInfo.setEmployeeId(sysUserService.getUserId());
         queryInfo.setPayStatus(2);
-        return succeed(studentRepairService.queryPage(queryInfo));
+        PageInfo<StudentRepair> repairPageInfo = studentRepairService.queryPage(queryInfo);
+        List<StudentRepair> rows = repairPageInfo.getRows();
+        if (!rows.isEmpty()) {
+            Map<Long, String> brandIdNameMap = mallFeignService.getList().stream().collect(Collectors.toMap(BrandDto::getId, BrandDto::getName));
+            rows.forEach(row -> {
+                String goodsJson = row.getGoodsJson();
+                if (StringUtils.isNotEmpty(goodsJson)) {
+                    JSONArray goods = JSON.parseArray(goodsJson);
+                    for (Object good : goods) {
+                        JSONObject goodObject = (JSONObject) good;
+                        String brand = goodObject.getString("brand");
+                        if (Objects.nonNull(brand) && NumberUtils.isNumber(brand)) {
+                            goodObject.put("brandName", brandIdNameMap.getOrDefault(Long.valueOf(brand), ""));
+                        }
+                    }
+                    row.setGoodsJson(JSON.toJSONString(goods));
+                }
+            });
+        }
+        return succeed(repairPageInfo);
     }
 
     @ApiOperation("获取乐器种类")

+ 21 - 0
mec-application/src/main/resources/columnMapper.ini

@@ -14,6 +14,27 @@
 商品描述 = brief
 商品详情 = desc
 
+[组合商品导入模板]
+组合商品名称 = name
+组合商品货号 = sn
+组合商品市场价 = marketPrice
+组合商品零售价 = discountPrice
+组合商品团购价 = groupPurchasePrice
+组合商品品牌 = brand
+组合商品类型 = type
+组合商品分类 = goodsCategoryName
+组合商品型号 = specification
+移动端可用分部 = educationShowOrganName
+课程收费团可用分部 = courseFeeShowOrganName
+会员收费乐团可售分部 = memberFeeShowOrganName
+免费乐团可售分部 = freeFeeShowOrganName
+乐器置换可售分部 = replacementShowOrganName
+组合商品描述 = brief
+组合商品详情 = desc
+组合商品图片 = image
+子商品名称 = subGoodsName
+SKU = sku
+子商品成本 = goodsPrice
 
 [财务支出导入模板]
 财务流程编号 = financialProcessNo

+ 4 - 0
mec-biz/src/main/java/com/ym/mec/biz/dal/dao/GoodsDao.java

@@ -202,4 +202,8 @@ public interface GoodsDao extends BaseDAO<Integer, Goods> {
     BigDecimal getOrganCostPrice(@Param("complementGoodsIdList") String complementGoodsIdList);
 
     List<Goods> exportGoods(Map<String, Object> params);
+
+    void updateStatus(@Param("goodIdList") List<Integer> goodIdList, @Param("status") Boolean status);
+
+    void updateStock(@Param("goodsList") List<Goods> goodsList);
 }

+ 2 - 0
mec-biz/src/main/java/com/ym/mec/biz/dal/dao/MusicGroupCalenderRefundPeriodDao.java

@@ -29,4 +29,6 @@ public interface MusicGroupCalenderRefundPeriodDao extends BaseDAO<Integer, Musi
     void deleteByCalenderId(@Param("calenderId") Long calenderId);
 
     void batchUpdate(@Param("refundPeriods") List<MusicGroupCalenderRefundPeriod> refundPeriods);
+
+    List<MusicGroupCalenderRefundPeriod> queryByIds(@Param("periodsIds") List<Integer> periodsIds);
 }

+ 9 - 0
mec-biz/src/main/java/com/ym/mec/biz/dal/dao/MusicGroupPaymentCalenderAddressDao.java

@@ -0,0 +1,9 @@
+package com.ym.mec.biz.dal.dao;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.ym.mec.biz.dal.entity.MusicGroupPaymentCalenderAddress;
+
+public interface MusicGroupPaymentCalenderAddressDao extends BaseMapper<MusicGroupPaymentCalenderAddress> {
+
+}
+

+ 9 - 0
mec-biz/src/main/java/com/ym/mec/biz/dal/dao/MusicGroupPaymentCalenderGoodsDao.java

@@ -0,0 +1,9 @@
+package com.ym.mec.biz.dal.dao;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.ym.mec.biz.dal.entity.MusicGroupPaymentCalenderGoods;
+
+public interface MusicGroupPaymentCalenderGoodsDao extends BaseMapper<MusicGroupPaymentCalenderGoods> {
+
+}
+

+ 7 - 0
mec-biz/src/main/java/com/ym/mec/biz/dal/dao/MusicGroupPaymentCalenderRepairDao.java

@@ -1,13 +1,20 @@
 package com.ym.mec.biz.dal.dao;
 
+import com.ym.mec.biz.dal.dto.WaitSendMessageDto;
 import com.ym.mec.common.dal.BaseDAO;
 import com.ym.mec.biz.dal.entity.MusicGroupPaymentCalenderRepair;
 import org.apache.ibatis.annotations.Param;
 
+import java.util.List;
+
 public interface MusicGroupPaymentCalenderRepairDao extends BaseDAO<Long, MusicGroupPaymentCalenderRepair> {
 
 
     void deleteByCalenderId(@Param("calenderId") Long calenderId);
 
     MusicGroupPaymentCalenderRepair findByCalenderId(@Param("calenderId") Long calenderId);
+
+    List<WaitSendMessageDto> queryWaitSendMessage();
+
+    void updateSendRemind(@Param("ids") List<Integer> ids);
 }

+ 5 - 0
mec-biz/src/main/java/com/ym/mec/biz/dal/dao/SellOrderDao.java

@@ -4,6 +4,7 @@ import com.ym.mec.biz.dal.dto.StudentPaymentOrderExportDto;
 import com.ym.mec.biz.dal.entity.OperatingReport;
 import com.ym.mec.biz.dal.entity.SellOrder;
 import com.ym.mec.common.dal.BaseDAO;
+import com.ym.mec.common.entity.OrderSkuSync;
 import org.apache.ibatis.annotations.Param;
 
 import java.math.BigDecimal;
@@ -241,4 +242,8 @@ public interface SellOrderDao extends BaseDAO<Integer, SellOrder> {
     List<Map<Long, String>> getMallProductMap(@Param("productIdList") Set<String> productIdList, @Param("database") String database);
 
     List<String> getMallProductCategory(@Param("database") String database);
+
+    List<SellOrder> queryByOrganNos(@Param("orderNos") List<String> orderNos);
+
+    void deleteByOrderNo(@Param("orderNo") String orderNo);
 }

+ 2 - 0
mec-biz/src/main/java/com/ym/mec/biz/dal/dao/StudentPaymentOrderDao.java

@@ -480,4 +480,6 @@ public interface StudentPaymentOrderDao extends BaseDAO<Long, StudentPaymentOrde
     Integer queryPaymentStudentCount(Map<String, Object> params);
 
     List<Double11StaticWrapper.StudentCount> count2023Double11StudentsByOrgan(@Param("param") Double11StaticWrapper.SaleStaticConfigParam configParam);
+
+    void deleteByOrderNo(@Param("orderNo") String orderNo);
 }

+ 2 - 0
mec-biz/src/main/java/com/ym/mec/biz/dal/dao/StudentPaymentRouteOrderDao.java

@@ -98,4 +98,6 @@ public interface StudentPaymentRouteOrderDao extends BaseDAO<Long, StudentPaymen
     FeeFlagNumDto getCountFeeFlagNum(@Param("orderNo") String orderNo);
 
     List<FeeFlagNumDto> queryCountFeeFlagNum(@Param("orderNos") List<String> orderNos);
+
+    List<StudentPaymentRouteOrder> queryByOrderNos(@Param("outOrderNos") List<String> outOrderNos);
 }

+ 2 - 0
mec-biz/src/main/java/com/ym/mec/biz/dal/dao/StudentRepairDao.java

@@ -98,4 +98,6 @@ public interface StudentRepairDao extends com.ym.mec.common.dal.BaseDAO<Integer,
      * @return int
      */
     List<Integer> countStuEducation(@Param("studentId") Integer studentId);
+
+    StudentRepair getByOrderNo(@Param("orderNo") String orderNo);
 }

+ 2 - 0
mec-biz/src/main/java/com/ym/mec/biz/dal/dao/SubjectGoodsMapperDao.java

@@ -36,4 +36,6 @@ public interface SubjectGoodsMapperDao extends BaseDAO<Long, SubjectGoodsMapper>
      * @return
      */
     List<SubjectGoodsDto> querySubjectGoods(Map<String, Object> params);
+
+    List<SubjectGoodsMapper> queryByCategoryIds(@Param("categoryIdList") List<Integer> categoryIdList);
 }

+ 2 - 0
mec-biz/src/main/java/com/ym/mec/biz/dal/dao/SysAreaDao.java

@@ -27,4 +27,6 @@ public interface SysAreaDao extends BaseDAO<Integer, SysArea> {
     SysArea getParentArea(Integer id);
 
     SysArea queryByCode(String code);
+
+    List<SysArea> queryByIds(@Param("areaIds") List<String> areaIds);
 }

+ 14 - 0
mec-biz/src/main/java/com/ym/mec/biz/dal/dto/ComplementGoodsDto.java

@@ -0,0 +1,14 @@
+package com.ym.mec.biz.dal.dto;
+
+import lombok.Data;
+
+import java.math.BigDecimal;
+
+@Data
+public class ComplementGoodsDto {
+        private Integer skuStockId;
+
+        private Integer goodsId;
+
+        private BigDecimal organCostPrice;
+}

+ 3 - 95
mec-biz/src/main/java/com/ym/mec/biz/dal/dto/CooperationCalenderRefundDto.java

@@ -2,9 +2,11 @@ package com.ym.mec.biz.dal.dto;
 
 
 import io.swagger.annotations.ApiModelProperty;
+import lombok.Data;
 
 import java.math.BigDecimal;
 
+@Data
 public class CooperationCalenderRefundDto {
 
     @ApiModelProperty(value = "缴费项目编号",required = false)
@@ -43,99 +45,5 @@ public class CooperationCalenderRefundDto {
     @ApiModelProperty(value = "合同",required = false)
     private String contractUrl;
 
-    public String getContractUrl() {
-        return contractUrl;
-    }
-
-    public void setContractUrl(String contractUrl) {
-        this.contractUrl = contractUrl;
-    }
-
-    public Long getCalenderId() {
-        return calenderId;
-    }
-
-    public void setCalenderId(Long calenderId) {
-        this.calenderId = calenderId;
-    }
-
-    public String getMusicGroupId() {
-        return musicGroupId;
-    }
-
-    public void setMusicGroupId(String musicGroupId) {
-        this.musicGroupId = musicGroupId;
-    }
-
-    public String getMusicGroupName() {
-        return musicGroupName;
-    }
-
-    public void setMusicGroupName(String musicGroupName) {
-        this.musicGroupName = musicGroupName;
-    }
-
-    public String getBatchNo() {
-        return batchNo;
-    }
-
-    public void setBatchNo(String batchNo) {
-        this.batchNo = batchNo;
-    }
-
-    public String getPaymentType() {
-        return paymentType;
-    }
-
-    public void setPaymentType(String paymentType) {
-        this.paymentType = paymentType;
-    }
-
-    public String getCalenderFeeType() {
-        return calenderFeeType;
-    }
-
-    public void setCalenderFeeType(String calenderFeeType) {
-        this.calenderFeeType = calenderFeeType;
-    }
-
-    public BigDecimal getReceivable() {
-        return receivable;
-    }
-
-    public void setReceivable(BigDecimal receivable) {
-        this.receivable = receivable;
-    }
-
-    public BigDecimal getIncome() {
-        return income;
-    }
-
-    public void setIncome(BigDecimal income) {
-        this.income = income;
-    }
-
-    public BigDecimal getPrepaidFee() {
-        return prepaidFee;
-    }
-
-    public void setPrepaidFee(BigDecimal prepaidFee) {
-        this.prepaidFee = prepaidFee;
-    }
-
-    public String getNextRefundDate() {
-        return nextRefundDate;
-    }
-
-    public void setNextRefundDate(String nextRefundDate) {
-        this.nextRefundDate = nextRefundDate;
-    }
-
-    public String getRefundStatus() {
-        return refundStatus;
-    }
-
-    public void setRefundStatus(String refundStatus) {
-        this.refundStatus = refundStatus;
-    }
+    private String memo;
 }

+ 26 - 0
mec-biz/src/main/java/com/ym/mec/biz/dal/dto/CooperationCalenderRefundUpdateDto.java

@@ -0,0 +1,26 @@
+package com.ym.mec.biz.dal.dto;
+
+
+import io.swagger.annotations.ApiModelProperty;
+import lombok.Data;
+
+import java.math.BigDecimal;
+
+@Data
+public class CooperationCalenderRefundUpdateDto {
+
+    @ApiModelProperty(value = "回款周期编号",required = false)
+    private Integer id;
+
+    @ApiModelProperty(value = "回款金额",required = false)
+    private BigDecimal refundAmount;
+
+    @ApiModelProperty(value = "回款时间",required = false)
+    private String refundDate;
+
+    @ApiModelProperty(value = "责任人",required = false)
+    private Integer responsiblePerson;
+
+    @ApiModelProperty(value = "修改原因",required = false)
+    private String memo;
+}

+ 20 - 0
mec-biz/src/main/java/com/ym/mec/biz/dal/dto/GoodsNameDto.java

@@ -0,0 +1,20 @@
+package com.ym.mec.biz.dal.dto;
+
+import io.swagger.annotations.ApiModelProperty;
+import lombok.Data;
+
+import java.math.BigDecimal;
+import java.util.List;
+
+@Data
+public class GoodsNameDto {
+	@ApiModelProperty(value = "商品数量", required = false)
+	private Integer goodsNum = 1;
+
+	@ApiModelProperty(value = "商品编号", required = false)
+	private Integer goodsId;
+
+	@ApiModelProperty(value = "商品名称", required = false)
+	private String goodsName;
+
+}

+ 1 - 0
mec-biz/src/main/java/com/ym/mec/biz/dal/dto/GoodsOrderItemVO.java

@@ -29,4 +29,5 @@ public class GoodsOrderItemVO {
     private String promotionName; // 促销名称
     private BigDecimal realAmount; // 实际支付金额
     private int returnStatus; // 退货状态
+    private String productType; // 商品类型
 }

+ 8 - 192
mec-biz/src/main/java/com/ym/mec/biz/dal/dto/MusicGroupPaymentBaseCalender.java

@@ -4,11 +4,13 @@ import com.ym.mec.biz.dal.entity.*;
 import com.ym.mec.biz.dal.entity.MusicGroupPaymentCalender.PayUserType;
 import com.ym.mec.biz.dal.entity.MusicGroupPaymentCalender.PaymentType;
 import io.swagger.annotations.ApiModelProperty;
+import lombok.Data;
 
 import java.math.BigDecimal;
 import java.util.Date;
 import java.util.List;
 
+@Data
 public class MusicGroupPaymentBaseCalender {
 	@ApiModelProperty(value = "是否继续操作", required = true)
 	private Boolean confirmCreate = false;
@@ -40,6 +42,12 @@ public class MusicGroupPaymentBaseCalender {
 	@ApiModelProperty(value = "批次号", required = false)
 	private String batchNo;
 
+	@ApiModelProperty(value = "商品采购相关信息", required = false)
+	private List<MusicGroupPaymentCalenderGoods> calenderGoodsList;
+
+	@ApiModelProperty(value = "收货地址相关信息", required = false)
+	private MusicGroupPaymentCalenderAddress calenderAddress;
+
 	@ApiModelProperty(value = "会员相关缴费信息", required = false)
 	private MusicGroupPaymentCalenderMember calenderMember;
 
@@ -79,196 +87,4 @@ public class MusicGroupPaymentBaseCalender {
 	@ApiModelProperty(value = "缴费项目名称", required = false)
 	private String name;
 
-	public String getName() {
-		return name;
-	}
-
-	public void setName(String name) {
-		this.name = name;
-	}
-
-	public String getContractUrl() {
-		return contractUrl;
-	}
-
-	public void setContractUrl(String contractUrl) {
-		this.contractUrl = contractUrl;
-	}
-
-	public BigDecimal getCurrentTotalAmount() {
-		return currentTotalAmount;
-	}
-
-	public void setCurrentTotalAmount(BigDecimal currentTotalAmount) {
-		this.currentTotalAmount = currentTotalAmount;
-	}
-
-	public List<MusicGroupCalenderRefundPeriod> getMusicGroupCalenderRefundPeriods() {
-		return musicGroupCalenderRefundPeriods;
-	}
-
-	public void setMusicGroupCalenderRefundPeriods(List<MusicGroupCalenderRefundPeriod> musicGroupCalenderRefundPeriods) {
-		this.musicGroupCalenderRefundPeriods = musicGroupCalenderRefundPeriods;
-	}
-
-	public String getCalenderFeeJson() {
-		return calenderFeeJson;
-	}
-
-	public void setCalenderFeeJson(String calenderFeeJson) {
-		this.calenderFeeJson = calenderFeeJson;
-	}
-
-	public String getCalenderFeeType() {
-		return calenderFeeType;
-	}
-
-	public void setCalenderFeeType(String calenderFeeType) {
-		this.calenderFeeType = calenderFeeType;
-	}
-
-	public Boolean getConfirmCreate() {
-		return confirmCreate;
-	}
-
-	public void setConfirmCreate(Boolean confirmCreate) {
-		this.confirmCreate = confirmCreate;
-	}
-
-	public Long getCalenderId() {
-		return calenderId;
-	}
-
-	public void setCalenderId(Long calenderId) {
-		this.calenderId = calenderId;
-	}
-
-	public CalenderAddStudent getCalenderAddStudent() {
-		return calenderAddStudent;
-	}
-
-	public void setCalenderAddStudent(CalenderAddStudent calenderAddStudent) {
-		this.calenderAddStudent = calenderAddStudent;
-	}
-
-	public List<MusicGroupPaymentCalenderActivity> getCalenderActivityList() {
-		return calenderActivityList;
-	}
-
-	public void setCalenderActivityList(List<MusicGroupPaymentCalenderActivity> calenderActivityList) {
-		this.calenderActivityList = calenderActivityList;
-	}
-
-	public MusicGroupPaymentCalenderRepair getMusicRepair() {
-		return musicRepair;
-	}
-
-	public void setMusicRepair(MusicGroupPaymentCalenderRepair musicRepair) {
-		this.musicRepair = musicRepair;
-	}
-
-	public MusicGroup getMusicGroup() {
-		return musicGroup;
-	}
-
-	public void setMusicGroup(MusicGroup musicGroup) {
-		this.musicGroup = musicGroup;
-	}
-
-	public Date getStartPaymentDate() {
-		return startPaymentDate;
-	}
-
-	public void setStartPaymentDate(Date startPaymentDate) {
-		this.startPaymentDate = startPaymentDate;
-	}
-
-	public Date getDeadlinePaymentDate() {
-		return deadlinePaymentDate;
-	}
-
-	public void setDeadlinePaymentDate(Date deadlinePaymentDate) {
-		this.deadlinePaymentDate = deadlinePaymentDate;
-	}
-
-	public MusicGroupPaymentCalenderMember getCalenderMember() {
-		return calenderMember;
-	}
-
-	public void setCalenderMember(MusicGroupPaymentCalenderMember calenderMember) {
-		this.calenderMember = calenderMember;
-	}
-
-	public String getMusicGroupId() {
-		return musicGroupId;
-	}
-
-	public void setMusicGroupId(String musicGroupId) {
-		this.musicGroupId = musicGroupId;
-	}
-
-	public Integer getMusicGroupOrganizationCourseSettingId() {
-		return musicGroupOrganizationCourseSettingId;
-	}
-
-	public void setMusicGroupOrganizationCourseSettingId(Integer musicGroupOrganizationCourseSettingId) {
-		this.musicGroupOrganizationCourseSettingId = musicGroupOrganizationCourseSettingId;
-	}
-
-	public PayUserType getPayUserType() {
-		return payUserType;
-	}
-
-	public void setPayUserType(PayUserType payUserType) {
-		this.payUserType = payUserType;
-	}
-
-	public PaymentType getPaymentType() {
-		return paymentType;
-	}
-
-	public void setPaymentType(PaymentType paymentType) {
-		this.paymentType = paymentType;
-	}
-
-	public String getMemo() {
-		return memo;
-	}
-
-	public void setMemo(String memo) {
-		this.memo = memo;
-	}
-
-	public List<MusicGroupPaymentCalenderCourseSettings> getMusicGroupPaymentCalenderCourseSettingsList() {
-		return musicGroupPaymentCalenderCourseSettingsList;
-	}
-
-	public void setMusicGroupPaymentCalenderCourseSettingsList(List<MusicGroupPaymentCalenderCourseSettings> musicGroupPaymentCalenderCourseSettingsList) {
-		this.musicGroupPaymentCalenderCourseSettingsList = musicGroupPaymentCalenderCourseSettingsList;
-	}
-
-	public String getBatchNo() {
-		return batchNo;
-	}
-
-	public void setBatchNo(String batchNo) {
-		this.batchNo = batchNo;
-	}
-
-	public String getPaymentItemShowState() {
-		return paymentItemShowState;
-	}
-
-	public void setPaymentItemShowState(String paymentItemShowState) {
-		this.paymentItemShowState = paymentItemShowState;
-	}
-
-	public Boolean getIsShowSalePrice() {
-		return isShowSalePrice;
-	}
-
-	public void setIsShowSalePrice(Boolean isShowSalePrice) {
-		this.isShowSalePrice = isShowSalePrice;
-	}
-
 }

+ 22 - 0
mec-biz/src/main/java/com/ym/mec/biz/dal/dto/OutOrderInfoDto.java

@@ -20,8 +20,30 @@ public class OutOrderInfoDto {
     @ApiModelProperty(value = "缴费单号",required = true)
     private Long calenderId;
 
+    @ApiModelProperty(value = "合作单位",required = true)
+    private String coopName;
+
+    @ApiModelProperty(value = "商品详情",required = true)
+    private List<GoodsNameDto> goodsSellDtos;
+
     private List<SellOrder> sellOrders;
 
+    public List<GoodsNameDto> getGoodsSellDtos() {
+        return goodsSellDtos;
+    }
+
+    public void setGoodsSellDtos(List<GoodsNameDto> goodsSellDtos) {
+        this.goodsSellDtos = goodsSellDtos;
+    }
+
+    public String getCoopName() {
+        return coopName;
+    }
+
+    public void setCoopName(String coopName) {
+        this.coopName = coopName;
+    }
+
     public List<SellOrder> getSellOrders() {
         return sellOrders;
     }

+ 10 - 0
mec-biz/src/main/java/com/ym/mec/biz/dal/dto/ReplacementInstrumentActivityStatDto.java

@@ -19,6 +19,8 @@ public class ReplacementInstrumentActivityStatDto extends ReplacementInstrumentA
     /** 品牌 */
     private String brand;
 
+    private String brandName;
+
     /** 型号 */
     private String specification;
 
@@ -158,4 +160,12 @@ public class ReplacementInstrumentActivityStatDto extends ReplacementInstrumentA
     public void setBalance(BigDecimal balance) {
         this.balance = balance;
     }
+
+    public String getBrandName() {
+        return brandName;
+    }
+
+    public void setBrandName(String brandName) {
+        this.brandName = brandName;
+    }
 }

+ 22 - 0
mec-biz/src/main/java/com/ym/mec/biz/dal/dto/WaitSendMessageDto.java

@@ -0,0 +1,22 @@
+package com.ym.mec.biz.dal.dto;
+
+import io.swagger.annotations.ApiModelProperty;
+import lombok.Data;
+
+@Data
+public class WaitSendMessageDto {
+
+    private Integer id;
+
+    @ApiModelProperty(value = "学校名称", required = false)
+    private String schoolName;
+
+    @ApiModelProperty(value = "缴费批次", required = false)
+    private String batchNo;
+
+    @ApiModelProperty(value = "责任人手机号", required = false)
+    private String phone;
+
+    @ApiModelProperty(value = "用户编号", required = false)
+    private Integer userId;
+}

+ 14 - 2
mec-biz/src/main/java/com/ym/mec/biz/dal/entity/Goods.java

@@ -53,8 +53,8 @@ public class Goods {
 	@ApiModelProperty(value = "库存数量",required = false)
 	private Integer stockCount;
 
-	@ApiModelProperty(value = "税务库存")
-	private Integer taxStockCount;
+//	@ApiModelProperty(value = "税务库存")
+//	private Integer taxStockCount;
 
 	/** 总销量数 */
 	@ApiModelProperty(value = "总销量数",required = false)
@@ -114,6 +114,10 @@ public class Goods {
 	@ApiModelProperty(value = "附件商品列表编号(用逗号分开)",required = false)
 	private String complementGoodsIdList;
 
+	/** 发布时间 */
+//	@ApiModelProperty(value = "附件商品详情",required = false)
+//	private String complementGoodsJson;
+
 	/** 辅件列表 */
 	@ApiModelProperty(value = "辅件列表(子商品)",required = false)
 	private List<Goods> goodsList;
@@ -175,6 +179,12 @@ public class Goods {
 	@ApiModelProperty(value = "库存预警")
 	private YesOrNoEnum stockWarning;
 
+	@ApiModelProperty(value = "是否是组合商品,1:是,0:不是")
+	private Boolean groupGoods;
+
+	@ApiModelProperty(value = "是否删除")
+	private Boolean delFlag;
+
 	private Integer tenantId = TenantContextHolder.getTenantId();
 
 	private String childId;
@@ -185,6 +195,8 @@ public class Goods {
 
 	private String childOrganCostPrice;
 
+	private String brandName;
+
 	@Override
 	public String toString() {
 		return ToStringBuilder.reflectionToString(this);

+ 49 - 0
mec-biz/src/main/java/com/ym/mec/biz/dal/entity/GoodsSub.java

@@ -0,0 +1,49 @@
+package com.ym.mec.biz.dal.entity;
+
+import com.baomidou.mybatisplus.annotation.TableField;
+import com.baomidou.mybatisplus.annotation.TableId;
+import com.baomidou.mybatisplus.annotation.TableName;
+import com.baomidou.mybatisplus.annotation.IdType;
+import lombok.Data;
+
+import io.swagger.annotations.ApiModel;
+import io.swagger.annotations.ApiModelProperty;
+
+import java.io.Serializable;
+
+import java.math.BigDecimal;
+
+/**
+ * 组合商品,子商品信息
+ * 2024-02-21 16:24:38
+ */
+@Data
+@ApiModel(" GoodsSub-组合商品,子商品信息")
+@TableName("goods_sub")
+public class GoodsSub implements Serializable {
+
+    @ApiModelProperty("id")
+    @TableId(value = "id_", type = IdType.AUTO)
+    private Integer id;
+
+    @ApiModelProperty("商品编号")
+    @TableField(value = "goods_id_")
+    private Integer goodsId;
+
+    @ApiModelProperty("商城商品编号")
+    @TableField(value = "mall_goods_id_")
+    private Integer mallGoodsId;
+
+    @ApiModelProperty("sku编号")
+    @TableField(value = "sku_")
+    private Integer sku;
+
+    @ApiModelProperty("商品状态,1:上架、0:下架")
+    @TableField(value = "goods_status_")
+    private Boolean goodsStatus;
+
+    @ApiModelProperty("成本")
+    @TableField(value = "goods_price_")
+    private BigDecimal goodsPrice;
+
+}

+ 11 - 96
mec-biz/src/main/java/com/ym/mec/biz/dal/entity/MusicGroupCalenderRefundPeriod.java

@@ -1,6 +1,7 @@
 package com.ym.mec.biz.dal.entity;
 
 import io.swagger.annotations.ApiModelProperty;
+import lombok.Data;
 import org.apache.commons.lang3.StringUtils;
 import org.apache.commons.lang3.builder.ToStringBuilder;
 
@@ -9,6 +10,7 @@ import java.math.BigDecimal;
 /**
  * 对应数据库表(music_group_calender_refund_period):
  */
+@Data
 public class MusicGroupCalenderRefundPeriod {
 
 	/**  */
@@ -40,6 +42,15 @@ public class MusicGroupCalenderRefundPeriod {
 
 	@ApiModelProperty(value = "订单编号",required = false)
 	private String orderNos;
+
+	@ApiModelProperty(value = "备注",required = false)
+	private String memo;
+
+	@ApiModelProperty(value = "责任人",required = false)
+	private Integer responsiblePerson;
+
+	@ApiModelProperty(value = "是否发送回款提醒",required = false)
+	private Boolean sendRemind = false;
 	
 	/**  */
 	private java.util.Date createTime;
@@ -47,102 +58,6 @@ public class MusicGroupCalenderRefundPeriod {
 	/**  */
 	private java.util.Date updateTime;
 
-	public String getOrderNos() {
-		return orderNos;
-	}
-
-	public void setOrderNos(String orderNos) {
-		this.orderNos = orderNos;
-	}
-
-	public BigDecimal getIncome() {
-		return income;
-	}
-
-	public void setIncome(BigDecimal income) {
-		this.income = income;
-	}
-
-	public Boolean getRefundFlag() {
-		return refundFlag;
-	}
-
-	public void setRefundFlag(Boolean refundFlag) {
-		this.refundFlag = refundFlag;
-	}
-
-	public void setId(Integer id){
-		this.id = id;
-	}
-	
-	public Integer getId(){
-		return this.id;
-	}
-			
-	public void setOrganId(Integer organId){
-		this.organId = organId;
-	}
-	
-	public Integer getOrganId(){
-		return this.organId;
-	}
-			
-	public void setCooperationOrganId(Integer cooperationOrganId){
-		this.cooperationOrganId = cooperationOrganId;
-	}
-	
-	public Integer getCooperationOrganId(){
-		return this.cooperationOrganId;
-	}
-			
-	public void setCalenderId(Long calenderId){
-		this.calenderId = calenderId;
-	}
-	
-	public Long getCalenderId(){
-		return this.calenderId;
-	}
-			
-	public void setRefundDate(String refundDate){
-		this.refundDate = refundDate;
-	}
-	
-	public String getRefundDate(){
-		return this.refundDate;
-	}
-			
-	public void setRefundAmount(java.math.BigDecimal refundAmount){
-		this.refundAmount = refundAmount;
-	}
-	
-	public java.math.BigDecimal getRefundAmount(){
-		return this.refundAmount;
-	}
-			
-	public void setSubRefundAmount(java.math.BigDecimal subRefundAmount){
-		this.subRefundAmount = subRefundAmount;
-	}
-	
-	public java.math.BigDecimal getSubRefundAmount(){
-		return this.subRefundAmount;
-	}
-			
-	public void setCreateTime(java.util.Date createTime){
-		this.createTime = createTime;
-	}
-	
-	public java.util.Date getCreateTime(){
-		return this.createTime;
-	}
-			
-	public void setUpdateTime(java.util.Date updateTime){
-		this.updateTime = updateTime;
-	}
-	
-	public java.util.Date getUpdateTime(){
-		return this.updateTime;
-	}
-			
 	@Override
 	public String toString() {
 		return ToStringBuilder.reflectionToString(this);

+ 1 - 1
mec-biz/src/main/java/com/ym/mec/biz/dal/entity/MusicGroupPaymentCalender.java

@@ -76,7 +76,7 @@ public class MusicGroupPaymentCalender extends BaseEntity {
 
 	public enum PaymentType implements BaseEnum<String, PaymentType> {
 		ADD_STUDENT("新增学员"), ADD_COURSE("临时加课"), MUSIC_APPLY("乐团报名"),
-		MUSIC_RENEW("乐团续费"),SPAN_GROUP_CLASS_ADJUST("跨团班级调整");
+		MUSIC_RENEW("乐团续费"),SPAN_GROUP_CLASS_ADJUST("跨团班级调整"),GOODS_PURCHASE("商品采购");
 
 		private String desc;
 

+ 73 - 0
mec-biz/src/main/java/com/ym/mec/biz/dal/entity/MusicGroupPaymentCalenderAddress.java

@@ -0,0 +1,73 @@
+package com.ym.mec.biz.dal.entity;
+
+
+import com.baomidou.mybatisplus.annotation.IdType;
+import com.baomidou.mybatisplus.annotation.TableField;
+import com.baomidou.mybatisplus.annotation.TableId;
+import io.swagger.annotations.ApiModel;
+import io.swagger.annotations.ApiModelProperty;
+import lombok.Data;
+
+import java.io.Serializable;
+import java.util.Date;
+
+@ApiModel(value = "music_group_payment_calender_address")
+@Data
+public class MusicGroupPaymentCalenderAddress implements Serializable {
+    @TableId(value = "id_", type = IdType.AUTO)
+    @ApiModelProperty(value = "主键")
+    private Long id;
+
+    @TableField("calender_id_")
+    @ApiModelProperty(value = "缴费项目编号")
+    private Long calenderId;
+
+    @TableField("order_no_")
+    @ApiModelProperty("订单编号")
+    private String orderNo;
+
+    @TableField("delivery_flag_")
+    @ApiModelProperty("是否发货")
+    private Boolean deliveryFlag = false;
+
+    @TableField("name_")
+    @ApiModelProperty(value = "收货人")
+    private String name;
+
+    @TableField("phone_")
+    @ApiModelProperty(value = "收货人手机号")
+    private String phone;
+
+    @TableField("province_")
+    @ApiModelProperty(value = "省")
+    private String province;
+
+    @TableField("city_")
+    @ApiModelProperty(value = "市")
+    private String city;
+
+    @TableField("region_")
+    @ApiModelProperty(value = "区")
+    private String region;
+
+    @TableField("post_code_")
+    @ApiModelProperty(value = "邮编")
+    private String postCode;
+
+    @TableField("address_")
+    @ApiModelProperty(value = "详细地址")
+    private String address;
+
+    @TableField("delivery_detail_")
+    @ApiModelProperty(value = "商品发货明细,用于同步订单的发货信息")
+    private String deliveryDetail;
+
+    @TableField("create_time_")
+    @ApiModelProperty(value = "创建时间")
+    private Date createTime;
+
+    @TableField("update_time_")
+    @ApiModelProperty(value = "更新时间")
+    private Date updateTime;
+}
+

+ 0 - 1
mec-biz/src/main/java/com/ym/mec/biz/dal/entity/MusicGroupPaymentCalenderCourseSettings.java

@@ -40,7 +40,6 @@ public class MusicGroupPaymentCalenderCourseSettings extends BaseEntity {
 	@ApiModelProperty(value = "是否学生可选", required = false)
 	private boolean isStudentOptional = true;
 
-
 	/**  */
 	private java.util.Date createTime;
 	

+ 66 - 0
mec-biz/src/main/java/com/ym/mec/biz/dal/entity/MusicGroupPaymentCalenderGoods.java

@@ -0,0 +1,66 @@
+package com.ym.mec.biz.dal.entity;
+
+
+import com.baomidou.mybatisplus.annotation.IdType;
+import com.baomidou.mybatisplus.annotation.TableField;
+import com.baomidou.mybatisplus.annotation.TableId;
+import com.ym.mec.biz.dal.enums.GoodsType;
+import io.swagger.annotations.ApiModel;
+import io.swagger.annotations.ApiModelProperty;
+import lombok.Data;
+
+import java.io.Serializable;
+import java.util.Date;
+
+@ApiModel(value = "music_group_payment_calender_goods")
+@Data
+public class MusicGroupPaymentCalenderGoods implements Serializable {
+    @TableId(value = "id_", type = IdType.AUTO)
+    @ApiModelProperty(value = "主键")
+    private Long id;
+
+    @TableField("calender_id_")
+    @ApiModelProperty(value = "缴费项目编号")
+    private Long calenderId;
+
+    @TableField("goods_id_")
+    @ApiModelProperty(value = "商品编号")
+    private Integer goodsId;
+
+    @TableField("goods_name_")
+    @ApiModelProperty(value = "商品名称")
+    private String goodsName;
+
+    @TableField("goods_type_")
+    @ApiModelProperty(value = "商品类型", required = false)
+    private String goodsType;
+
+    @TableField("goods_sn_")
+    @ApiModelProperty(value = "商品货号")
+    private String goodsSn;
+
+    @TableField("child_goods_json_")
+    @ApiModelProperty(value = "子商品明细")
+    private String childGoodsJson;
+
+    @TableField("num_")
+    @ApiModelProperty(value = "数量")
+    private Integer num;
+
+    @TableField("single_price_")
+    @ApiModelProperty(value = "单价")
+    private java.math.BigDecimal singlePrice;
+
+    @TableField("total_price_")
+    @ApiModelProperty(value = "总价")
+    private java.math.BigDecimal totalPrice;
+
+    @TableField("create_time_")
+    @ApiModelProperty(value = "创建时间")
+    private Date createTime;
+
+    @TableField("update_time_")
+    @ApiModelProperty(value = "更新时间")
+    private Date updateTime;
+}
+

+ 11 - 1
mec-biz/src/main/java/com/ym/mec/biz/dal/entity/ReplacementInstrument.java

@@ -17,6 +17,8 @@ public class ReplacementInstrument extends BaseEntity {
 	
 	/** 品牌 */
 	private String brand;
+
+	private String brandName;
 	
 	/** 型号 */
 	private String specification;
@@ -129,7 +131,15 @@ public class ReplacementInstrument extends BaseEntity {
 	public java.util.Date getUpdateTime(){
 		return this.updateTime;
 	}
-			
+
+	public String getBrandName() {
+		return brandName;
+	}
+
+	public void setBrandName(String brandName) {
+		this.brandName = brandName;
+	}
+
 	@Override
 	public String toString() {
 		return ToStringBuilder.reflectionToString(this);

+ 3 - 0
mec-biz/src/main/java/com/ym/mec/biz/dal/entity/SellOrder.java

@@ -72,6 +72,9 @@ public class SellOrder{
     @ApiModelProperty(value="商品id")
     private Integer goodsId;
 
+    @ApiModelProperty(value="商品sku_id")
+    private Integer goodsSkuId;
+
     @ApiModelProperty(value="商品名称")
     private String goodsName;
 

+ 36 - 1
mec-biz/src/main/java/com/ym/mec/biz/dal/entity/StudentGoodsSell.java

@@ -79,7 +79,42 @@ public class StudentGoodsSell extends BaseEntity {
 	// 商品来源类型 MALL商城
 	private String goodsType;
 
-	public String getGoodsType() {
+    // contactName ,contactMobile,address
+
+    // 收货人
+    private String contactName;
+
+    // 收货人手机号
+    private String contactMobile;
+
+    // 详细地址
+    private String address;
+
+    public String getContactName() {
+        return contactName;
+    }
+
+    public void setContactName(String contactName) {
+        this.contactName = contactName;
+    }
+
+    public String getContactMobile() {
+        return contactMobile;
+    }
+
+    public void setContactMobile(String contactMobile) {
+        this.contactMobile = contactMobile;
+    }
+
+    public String getAddress() {
+        return address;
+    }
+
+    public void setAddress(String address) {
+        this.address = address;
+    }
+
+    public String getGoodsType() {
 		return goodsType;
 	}
 

+ 4 - 0
mec-biz/src/main/java/com/ym/mec/biz/dal/entity/StudentPaymentOrder.java

@@ -4,6 +4,7 @@ import io.swagger.annotations.ApiModelProperty;
 
 import java.math.BigDecimal;
 import java.util.Date;
+import java.util.List;
 
 import lombok.Data;
 import org.apache.commons.lang3.builder.ToStringBuilder;
@@ -139,4 +140,7 @@ public class StudentPaymentOrder extends BaseEntity {
 	private Long calenderId;
 
 	private Integer cooperationId;
+
+	// 需要关闭的订单号
+	private List<String> closeOrderNoList;
 }

+ 56 - 0
mec-biz/src/main/java/com/ym/mec/biz/dal/entity/StudentPaymentOrderAddress.java

@@ -0,0 +1,56 @@
+package com.ym.mec.biz.dal.entity;
+
+import com.baomidou.mybatisplus.annotation.TableField;
+import com.baomidou.mybatisplus.annotation.TableId;
+import com.baomidou.mybatisplus.annotation.TableName;
+import com.baomidou.mybatisplus.annotation.IdType;
+import lombok.Data;
+
+import io.swagger.annotations.ApiModel;
+import io.swagger.annotations.ApiModelProperty;
+
+import java.io.Serializable;
+
+
+/**
+ * 学生订单收货地址
+ * 2024-03-01 12:05:41
+ */
+@Data
+@ApiModel(" StudentPaymentOrderAddress-学生订单收货地址")
+@TableName("student_payment_order_address")
+public class StudentPaymentOrderAddress implements Serializable {
+
+    @ApiModelProperty("id") 
+	    @TableId(value = "id_")
+	    private Long id;
+
+    @ApiModelProperty("订单号") 
+	@TableField(value = "order_no_")
+    private String orderNo;
+
+    @ApiModelProperty("收货人") 
+	@TableField(value = "contact_name_")
+    private String contactName;
+
+    @ApiModelProperty("收货人手机号") 
+	@TableField(value = "contact_mobile_")
+    private String contactMobile;
+
+    @ApiModelProperty("详细地址") 
+	@TableField(value = "address_")
+    private String address;
+
+    @ApiModelProperty("省") 
+	@TableField(value = "province_id_")
+    private Integer provinceId;
+
+    @ApiModelProperty("市") 
+	@TableField(value = "city_id_")
+    private Integer cityId;
+
+    @ApiModelProperty("县/街道") 
+	@TableField(value = "county_id_")
+    private Integer countyId;
+
+}

+ 1 - 0
mec-biz/src/main/java/com/ym/mec/biz/dal/enums/MessageTypeEnum.java

@@ -249,6 +249,7 @@ public enum MessageTypeEnum implements BaseEnum<String, MessageTypeEnum> {
     SMS_TENANT_RECHARGE("SMS_TENANT_RECHARGE",   "云教室充值"),
     SMS_TENANT_INSUFFICIENT_BALANCE("SMS_TENANT_INSUFFICIENT_BALANCE",  "余额不足"),
     SMS_TENANT_EXPIRE("SMS_TENANT_EXPIRE",  "云教室欠费"),
+    SMS_WAIT_REMINDER_PAYMENT("SMS_WAIT_REMINDER_PAYMENT",  "待回款提醒"),
 
 
     STUDENT_SMS_CLOUD_PAYMENT("STUDENT_SMS_CLOUD_PAYMENT",  "待缴费订单"),

+ 1 - 0
mec-biz/src/main/java/com/ym/mec/biz/dal/enums/OrderTypeEnum.java

@@ -38,6 +38,7 @@ public enum OrderTypeEnum implements BaseEnum<String, OrderTypeEnum> {
     ACTIVITY("ACTIVITY", "活动购买"),
     MEMBER("MEMBER", "会员购买"),
     LIVE_BUY("LIVE_BUY", "直播购物"),
+    SCHOOL_GOODS_PURCHASE("SCHOOL_GOODS_PURCHASE","学校商品采购"),
     MALL_BUY("MALL_BUY", "商城购物");
 
 

+ 1 - 0
mec-biz/src/main/java/com/ym/mec/biz/dal/enums/TemplateTypeEnum.java

@@ -4,6 +4,7 @@ import com.ym.mec.common.enums.BaseEnum;
 
 public enum TemplateTypeEnum implements BaseEnum<String, TemplateTypeEnum> {
     GOODS("GOODS","商品导入模板"),
+    GOODS_GROUP("GOODS_GROUP","组合商品导入模板"),
     ROUTE_ORDER("ROUTE_ORDER","财务管理导入模板"),
     FINANCIAL_EXPENDITURE("FINANCIAL_EXPENDITURE","财务支出导入模板"),
     REDEMPTIONCODE("REDEMPTION_CODE", "兑换码分配模板表"),

+ 25 - 0
mec-biz/src/main/java/com/ym/mec/biz/dal/mapper/GoodsSubMapper.java

@@ -0,0 +1,25 @@
+package com.ym.mec.biz.dal.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.ym.mec.biz.dal.dto.ComplementGoodsDto;
+import com.ym.mec.biz.dal.entity.GoodsSub;
+import org.apache.ibatis.annotations.Param;
+import org.springframework.stereotype.Repository;
+
+import java.util.List;
+import java.util.Map;
+
+/**
+ * 组合商品,子商品信息
+ * 2024-02-21 16:24:38
+ */
+@Repository
+public interface GoodsSubMapper extends BaseMapper<GoodsSub> {
+
+
+    void saveBatch(@Param("goodsSubs") List<GoodsSub> goodsSubs);
+
+    void updateStatus(@Param("goodsSubIdList") List<Integer> goodsSubIdList, @Param("status") Boolean status);
+
+    List<ComplementGoodsDto> queryChildGoods(@Param("goodsId") Integer goodsId);
+}

+ 27 - 0
mec-biz/src/main/java/com/ym/mec/biz/dal/mapper/StudentPaymentOrderAddressMapper.java

@@ -0,0 +1,27 @@
+package com.ym.mec.biz.dal.mapper;
+
+import java.util.List;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.baomidou.mybatisplus.core.metadata.IPage;
+import org.apache.ibatis.annotations.Param;
+import org.springframework.stereotype.Repository;
+import com.ym.mec.biz.dal.entity.StudentPaymentOrderAddress;
+import com.ym.mec.biz.dal.wrapper.StudentPaymentOrderAddressWrapper;
+
+/**
+ * 学生订单收货地址
+ * 2024-03-01 12:05:41
+ */
+@Repository
+public interface StudentPaymentOrderAddressMapper extends BaseMapper<StudentPaymentOrderAddress> {
+
+	/**
+	 * 分页查询
+	 * @param page IPage<StudentPaymentOrderAddressWrapper.StudentPaymentOrderAddress>
+	 * @param param StudentPaymentOrderAddressWrapper.StudentPaymentOrderAddressQuery
+	 * @return List<StudentPaymentOrderAddressWrapper.StudentPaymentOrderAddress>
+	 */
+	List<StudentPaymentOrderAddress> selectPage(@Param("page") IPage<StudentPaymentOrderAddress> page, @Param("param") StudentPaymentOrderAddressWrapper.StudentPaymentOrderAddressQuery param);
+	
+}

+ 10 - 0
mec-biz/src/main/java/com/ym/mec/biz/dal/page/GoodsQuery.java

@@ -27,6 +27,8 @@ public class GoodsQuery {
 
     private Integer subjectId;
 
+    private Boolean delFlag;
+
     public String getType() {
         return type;
     }
@@ -90,4 +92,12 @@ public class GoodsQuery {
     public void setReplacementShowOrganId(Integer replacementShowOrganId) {
         this.replacementShowOrganId = replacementShowOrganId;
     }
+
+    public Boolean getDelFlag() {
+        return delFlag;
+    }
+
+    public void setDelFlag(Boolean delFlag) {
+        this.delFlag = delFlag;
+    }
 }

+ 33 - 0
mec-biz/src/main/java/com/ym/mec/biz/dal/page/GoodsQueryInfo.java

@@ -52,6 +52,15 @@ public class GoodsQueryInfo extends QueryInfo {
     @ApiModelProperty(value = "此参数为1则不按分部查询")
     private Integer noOrganSearch;
 
+    @ApiModelProperty(value = "品牌ID")
+    private String brandId;
+
+    @ApiModelProperty(value = "商品名称")
+    private String name;
+
+    @ApiModelProperty(value = "货号")
+    private String sn;
+
     private Integer subjectId;
 
     public Integer getNoOrganSearch() {
@@ -173,4 +182,28 @@ public class GoodsQueryInfo extends QueryInfo {
 	public void setFreeFeeShowOrganId(String freeFeeShowOrganId) {
 		this.freeFeeShowOrganId = freeFeeShowOrganId;
 	}
+
+    public String getBrandId() {
+        return brandId;
+    }
+
+    public void setBrandId(String brandId) {
+        this.brandId = brandId;
+    }
+
+    public String getSn() {
+        return sn;
+    }
+
+    public void setSn(String sn) {
+        this.sn = sn;
+    }
+
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
 }

+ 63 - 0
mec-biz/src/main/java/com/ym/mec/biz/dal/wrapper/GoodsSubWrapper.java

@@ -0,0 +1,63 @@
+package com.ym.mec.biz.dal.wrapper;
+
+import com.alibaba.fastjson.JSON;
+import com.microsvc.toolkit.common.response.paging.QueryInfo;
+import io.swagger.annotations.ApiModel;
+import io.swagger.annotations.ApiModelProperty;
+import java.util.Optional;
+
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+import org.apache.commons.lang3.StringUtils;
+
+/**
+ * 组合商品,子商品信息
+ * 2024-02-26 15:42:42
+ */
+@ApiModel(value = "GoodsSubWrapper对象", description = "组合商品,子商品信息查询对象")
+public class GoodsSubWrapper {
+
+    @Data
+    @Builder
+    @NoArgsConstructor
+    @AllArgsConstructor
+    @ApiModel(" GoodsSubQuery-组合商品,子商品信息")
+    public static class GoodsSubQuery implements QueryInfo {
+
+        @ApiModelProperty("当前页")
+        private Integer page;
+
+        @ApiModelProperty("分页行数")
+        private Integer rows;
+
+        @ApiModelProperty("关键字匹配")
+        private String keyword;
+
+        public String getKeyword() {
+            return Optional.ofNullable(keyword).filter(StringUtils::isNotBlank).orElse(null);
+        }
+
+        public String jsonString() {
+            return JSON.toJSONString(this);
+        }
+
+        public static GoodsSubQuery from(String json) {
+            return JSON.parseObject(json, GoodsSubQuery.class);
+        }
+    }
+
+    @ApiModel(" GoodsSub-组合商品,子商品信息")
+    public static class GoodsSub {
+
+        public String jsonString() {
+            return JSON.toJSONString(this);
+        }
+
+        public static GoodsSub from(String json) {
+            return JSON.parseObject(json, GoodsSub.class);
+        }
+    }
+
+}

+ 256 - 0
mec-biz/src/main/java/com/ym/mec/biz/dal/wrapper/GoodsWrapper.java

@@ -0,0 +1,256 @@
+package com.ym.mec.biz.dal.wrapper;
+
+import com.alibaba.fastjson.JSON;
+import com.ym.mec.biz.dal.enums.GoodsType;
+import com.ym.mec.biz.dal.enums.StockType;
+import com.ym.mec.biz.dal.enums.YesOrNoEnum;
+import com.ym.mec.common.page.QueryInfo;
+import com.ym.mec.common.tenant.TenantContextHolder;
+import io.swagger.annotations.ApiModel;
+import io.swagger.annotations.ApiModelProperty;
+import lombok.Data;
+import org.apache.commons.lang3.builder.ToStringBuilder;
+
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+
+public class GoodsWrapper {
+
+    @ApiModel("商品")
+    @Data
+    public static class Goods {
+
+        @ApiModelProperty(value = "商品编号")
+        private Integer id;
+
+        @ApiModelProperty(value = "产品分类")
+        private Integer goodsCategoryId;
+
+        @ApiModelProperty(value = "产品分类名称")
+        private String goodsCategoryName;
+
+        @ApiModelProperty(value = "商品货号")
+        private String sn;
+
+        @ApiModelProperty(value = "商品名称")
+        private String name;
+
+        @ApiModelProperty(value = "品牌")
+        private String brand;
+
+        @ApiModelProperty(value = "规格")
+        private String specification;
+
+        @ApiModelProperty(value = "展示图片的地址")
+        private String image;
+
+        @ApiModelProperty(value = "库存数量")
+        private Integer stockCount;
+
+        @ApiModelProperty(value = "税务库存")
+        private Integer taxStockCount;
+
+        @ApiModelProperty(value = "总销量数")
+        private Integer sellCount;
+
+        @ApiModelProperty(value = "市场销售价")
+        private BigDecimal marketPrice;
+
+        @ApiModelProperty(value = "商品零售价")
+        private BigDecimal discountPrice;
+
+        @ApiModelProperty(value = "团购价")
+        private BigDecimal groupPurchasePrice;
+
+        @ApiModelProperty(value = "商品价格1")
+        private BigDecimal costPrice;
+
+        @ApiModelProperty(value = "协议成本价")
+        private BigDecimal agreeCostPrice;
+
+        @ApiModelProperty(value = "分部成本价")
+        private BigDecimal organCostPrice;
+
+        @ApiModelProperty(value = "页面简介")
+        private String brief;
+
+        @ApiModelProperty(value = "商品的详细描述")
+        private String desc;
+
+        @ApiModelProperty(value = "是否是新品(1,是  0,否)")
+        private YesOrNoEnum isNew;
+
+        @ApiModelProperty(value = "是否置顶(1,置顶   0,不置顶)")
+        private YesOrNoEnum isTop;
+
+        @ApiModelProperty(value = "状态(1,上架  0,下架)")
+        private YesOrNoEnum status;
+
+        @ApiModelProperty(value = "备注")
+        private String memo;
+
+        @ApiModelProperty(value = "发布时间")
+        private Date publishTime;
+
+        @ApiModelProperty(value = "附件商品列表编号(用逗号分开)")
+        private String complementGoodsIdList;
+
+        @ApiModelProperty(value = "辅件列表(子商品)")
+        private List<com.ym.mec.biz.dal.entity.Goods> goodsList;
+
+        private String subjectIds;
+
+        private java.util.Date createTime;
+
+        private java.util.Date updateTime;
+
+        @ApiModelProperty(value = "商品类型")
+        private GoodsType type;
+
+        @ApiModelProperty(value = "备查货号,进货渠道")
+        private String supplyChannel;
+
+        @ApiModelProperty(value = "客户端展示分部")
+        private String studentShowOrganId;
+
+        @ApiModelProperty(value = "教务端展示分部")
+        private String educationShowOrganId;
+
+        @ApiModelProperty(value = "课程收费团展示分部")
+        private String courseFeeShowOrganId;
+
+        @ApiModelProperty(value = "会员收费团展示分部")
+        private String memberFeeShowOrganId;
+
+        @ApiModelProperty(value = "免费团展示分部")
+        private String freeFeeShowOrganId;
+
+        @ApiModelProperty(value = "乐器置换展示分部")
+        private String replacementShowOrganId;
+
+        @ApiModelProperty(value = "客户端展示分部")
+        private String studentShowOrganName;
+
+        @ApiModelProperty(value = "教务端展示分部")
+        private String educationShowOrganName;
+
+        @ApiModelProperty(value = "课程收费团展示分部")
+        private String courseFeeShowOrganName;
+
+        @ApiModelProperty(value = "会员收费团展示分部")
+        private String memberFeeShowOrganName;
+
+        @ApiModelProperty(value = "免费团展示分部")
+        private String freeFeeShowOrganName;
+
+        @ApiModelProperty(value = "乐器置换展示分部")
+        private String replacementShowOrganName;
+
+        @ApiModelProperty(value = "库存类型")
+        private StockType stockType;
+
+        @ApiModelProperty(value = "库存预警")
+        private YesOrNoEnum stockWarning;
+
+        @ApiModelProperty(value = "是否是组合商品,1:是,0:不是")
+        private Boolean groupGoods;
+
+        private Integer tenantId = TenantContextHolder.getTenantId();
+
+        private String childId;
+
+        private String childName;
+
+        private String childSn;
+
+        private String childOrganCostPrice;
+
+        @ApiModelProperty(value = "品牌名称")
+        private String brandName;
+
+        private List<GoodsSub> goodsSubList = new ArrayList<>();
+
+        @Override
+        public String toString() {
+            return ToStringBuilder.reflectionToString(this);
+        }
+    }
+
+
+    @Data
+    @ApiModel(" GoodsSub_-组合商品,子商品信息")
+    public static class GoodsSub {
+
+        @ApiModelProperty("id")
+        private Integer id;
+
+        @ApiModelProperty("商品编号")
+        private Integer goodsId;
+
+        @ApiModelProperty("商城商品编号")
+        private Integer mallGoodsId;
+
+        @ApiModelProperty("商城商品名称")
+        private String mallGoodsName;
+
+        @ApiModelProperty("skuID")
+        private Integer sku;
+
+        @ApiModelProperty("sku编号")
+        private String skuCode;
+
+        @ApiModelProperty("销售价格")
+        private BigDecimal price;
+
+        @ApiModelProperty("商品状态,1:上架、0:下架")
+        private Boolean goodsStatus;
+
+        @ApiModelProperty("成本")
+        private BigDecimal goodsPrice;
+
+        @ApiModelProperty("货号")
+        private String productSn;
+
+        @ApiModelProperty("品牌ID")
+        private Long brandId;
+
+        @ApiModelProperty("品牌名称")
+        private String brandName;
+
+        public String jsonString() {
+            return JSON.toJSONString(this);
+        }
+
+        public static GoodsSub from(String json) {
+            return JSON.parseObject(json, GoodsSub.class);
+        }
+    }
+
+
+    @Data
+    @ApiModel("商城商品分页查询参数")
+    public static class GoodsSubQuery extends QueryInfo {
+
+        @ApiModelProperty("上架状态,1:上架,0:下架")
+        private Integer publishStatus;
+
+        @ApiModelProperty("商品名称模糊关键字")
+        private String keyword;
+
+        @ApiModelProperty("商品货号")
+        private String productSn;
+
+        @ApiModelProperty("商品编号,多个逗号隔开")
+        private String productIds;
+
+        @ApiModelProperty("商品分类")
+        private Long productCategoryId;
+
+        @ApiModelProperty("商品品牌")
+        private Long brandId;
+
+    }
+
+}

+ 71 - 0
mec-biz/src/main/java/com/ym/mec/biz/dal/wrapper/MusicGroupCalenderRefundPeriodWrapper.java

@@ -0,0 +1,71 @@
+package com.ym.mec.biz.dal.wrapper;
+
+import io.swagger.annotations.ApiModelProperty;
+import lombok.Data;
+import org.apache.commons.lang3.builder.ToStringBuilder;
+
+import java.math.BigDecimal;
+
+public class MusicGroupCalenderRefundPeriodWrapper {
+
+
+    @Data
+    public static class MusicGroupCalenderRefundPeriod {
+
+        /**  */
+        private Integer id;
+
+        @ApiModelProperty(value = "分部",required = false)
+        private Integer organId;
+
+        @ApiModelProperty(value = "合作单位编号",required = false)
+        private Integer cooperationOrganId;
+
+        @ApiModelProperty(value = "缴费项目编号",required = false)
+        private Long calenderId;
+
+        @ApiModelProperty(value = "回款时间",required = false)
+        private String refundDate;
+
+        @ApiModelProperty(value = "回款金额",required = false)
+        private java.math.BigDecimal refundAmount;
+
+        @ApiModelProperty(value = "已回款金额",required = false)
+        private java.math.BigDecimal income = BigDecimal.ZERO;
+
+        @ApiModelProperty(value = "剩余待回款金额",required = false)
+        private java.math.BigDecimal subRefundAmount;
+
+        @ApiModelProperty(value = "是否完成回款",required = false)
+        private Boolean refundFlag = false;
+
+        @ApiModelProperty(value = "订单编号",required = false)
+        private String orderNos;
+
+        @ApiModelProperty(value = "备注",required = false)
+        private String memo;
+
+        @ApiModelProperty(value = "责任人",required = false)
+        private Integer responsiblePerson;
+
+
+        @ApiModelProperty(value = "责任人",required = false)
+        private String responsiblePersonName;
+        private String responsiblePersonPhone;
+
+        @ApiModelProperty(value = "是否发送回款提醒",required = false)
+        private Boolean sendRemind = false;
+
+        /**  */
+        private java.util.Date createTime;
+
+        /**  */
+        private java.util.Date updateTime;
+
+        @Override
+        public String toString() {
+            return ToStringBuilder.reflectionToString(this);
+        }
+
+    }
+}

+ 67 - 0
mec-biz/src/main/java/com/ym/mec/biz/dal/wrapper/MusicGroupPaymentCalenderAddressWrapper.java

@@ -0,0 +1,67 @@
+package com.ym.mec.biz.dal.wrapper;
+
+import com.baomidou.mybatisplus.annotation.IdType;
+import com.baomidou.mybatisplus.annotation.TableField;
+import com.baomidou.mybatisplus.annotation.TableId;
+import io.swagger.annotations.ApiModel;
+import io.swagger.annotations.ApiModelProperty;
+import lombok.Data;
+
+import java.io.Serializable;
+import java.util.Date;
+
+public class MusicGroupPaymentCalenderAddressWrapper {
+
+
+    @Data
+    public static class MusicGroupPaymentCalenderAddress{
+        @ApiModelProperty(value = "主键")
+        private Long id;
+
+        @ApiModelProperty(value = "缴费项目编号")
+        private Long calenderId;
+
+        @ApiModelProperty("订单编号")
+        private String orderNo;
+
+        @ApiModelProperty("是否发货")
+        private Boolean deliveryFlag = false;
+
+        @ApiModelProperty(value = "收货人")
+        private String name;
+
+        @ApiModelProperty(value = "收货人手机号")
+        private String phone;
+
+        @ApiModelProperty(value = "省")
+        private String province;
+
+        @ApiModelProperty(value = "市")
+        private String city;
+
+        @ApiModelProperty(value = "区")
+        private String region;
+
+
+        @ApiModelProperty(value = "省")
+        private String provinceName;
+
+        @ApiModelProperty(value = "市")
+        private String cityName;
+
+        @ApiModelProperty(value = "区")
+        private String regionName;
+
+        @ApiModelProperty(value = "邮编")
+        private String postCode;
+
+        @ApiModelProperty(value = "详细地址")
+        private String address;
+
+        @ApiModelProperty(value = "创建时间")
+        private Date createTime;
+
+        @ApiModelProperty(value = "更新时间")
+        private Date updateTime;
+    }
+}

+ 63 - 0
mec-biz/src/main/java/com/ym/mec/biz/dal/wrapper/StudentPaymentOrderAddressWrapper.java

@@ -0,0 +1,63 @@
+package com.ym.mec.biz.dal.wrapper;
+
+import com.alibaba.fastjson.JSON;
+import com.microsvc.toolkit.common.response.paging.QueryInfo;
+import io.swagger.annotations.ApiModel;
+import io.swagger.annotations.ApiModelProperty;
+import java.util.Optional;
+
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+import org.apache.commons.lang3.StringUtils;
+
+/**
+ * 学生订单收货地址
+ * 2024-03-01 12:05:41
+ */
+@ApiModel(value = "StudentPaymentOrderAddressWrapper对象", description = "学生订单收货地址查询对象")
+public class StudentPaymentOrderAddressWrapper {
+
+    @Data
+	@Builder
+    @NoArgsConstructor
+    @AllArgsConstructor
+    @ApiModel(" StudentPaymentOrderAddressQuery-学生订单收货地址")
+    public static class StudentPaymentOrderAddressQuery implements QueryInfo {
+    
+    	@ApiModelProperty("当前页")
+        private Integer page;
+        
+        @ApiModelProperty("分页行数")
+        private Integer rows;
+        
+        @ApiModelProperty("关键字匹配")
+		private String keyword;
+        
+        public String getKeyword() {
+            return Optional.ofNullable(keyword).filter(StringUtils::isNotBlank).orElse(null);
+        }
+        
+        public String jsonString() {
+            return JSON.toJSONString(this);
+        }
+
+        public static StudentPaymentOrderAddressQuery from(String json) {
+            return JSON.parseObject(json, StudentPaymentOrderAddressQuery.class);
+        }
+    }  
+
+	@ApiModel(" StudentPaymentOrderAddress-学生订单收货地址")
+    public static class StudentPaymentOrderAddress {
+        
+        public String jsonString() {
+            return JSON.toJSONString(this);
+        }
+
+        public static StudentPaymentOrderAddress from(String json) {
+            return JSON.parseObject(json, StudentPaymentOrderAddress.class);
+        }
+	}
+
+}

+ 3 - 0
mec-biz/src/main/java/com/ym/mec/biz/service/CooperationOrganService.java

@@ -4,6 +4,7 @@ import com.ym.mec.biz.dal.dao.CooperationOrganDao;
 import com.ym.mec.biz.dal.entity.CooperationOrgan;
 import com.ym.mec.biz.dal.entity.MusicGroup;
 import com.ym.mec.biz.dal.entity.MusicGroupPaymentCalender;
+import com.ym.mec.common.dto.SchoolDto;
 import com.ym.mec.common.service.BaseService;
 
 import java.util.ArrayList;
@@ -44,5 +45,7 @@ public interface CooperationOrganService extends BaseService<Integer, Cooperatio
 
     List<MusicGroup> musicGroupPage(Integer id);
 
+    List<SchoolDto> coopListByIds(List<Integer> coopIds);
+
     List<MusicGroup> musicGroupPage(String organIds,String coopId);
 }

+ 43 - 9
mec-biz/src/main/java/com/ym/mec/biz/service/GoodsService.java

@@ -1,8 +1,17 @@
 package com.ym.mec.biz.service;
 
 import java.util.List;
+import java.util.Map;
 
+import com.ym.mec.biz.dal.dao.GoodsDao;
 import com.ym.mec.biz.dal.page.GoodsQueryInfo;
+import com.ym.mec.biz.dal.wrapper.GoodsWrapper;
+import com.ym.mec.common.dto.BrandDto;
+import com.ym.mec.common.dto.PmsProductDto;
+import com.ym.mec.common.dto.ProductAttributeCategoryDto;
+import com.ym.mec.common.dto.ProductCategoryDto;
+import com.ym.mec.common.entity.GoodsSubModel;
+import com.ym.mec.common.entity.GoodsSubStockModel;
 import com.ym.mec.common.page.PageInfo;
 import org.springframework.web.multipart.MultipartFile;
 
@@ -16,11 +25,11 @@ import com.ym.mec.common.service.BaseService;
 
 public interface GoodsService extends BaseService<Integer, Goods> {
 
-    List<Goods> exportGoods(GoodsQueryInfo queryInfo);
+    GoodsDao getGoodsDao();
 
-    void addGoods(Goods goods, Integer operatorId);
+    List<Goods> exportGoods(GoodsQueryInfo queryInfo);
 
-    void addGoodsProcurement(GoodsProcurement goodsProcurement);
+    void addGoods(List<GoodsWrapper.Goods> goodsList, Integer operatorId);
 
     /**
      * @describe 更新商品状态
@@ -71,7 +80,16 @@ public interface GoodsService extends BaseService<Integer, Goods> {
      * @param file:
      * @return java.util.List<com.ym.mec.biz.dal.entity.Goods>
      */
-    List<Goods> importGoods(MultipartFile file, Integer operatorId) throws Exception;
+//    List<Goods> importGoods(MultipartFile file, Integer operatorId) throws Exception;
+
+    /**
+     * 导入组合商品
+     * @param file 文件
+     * @param userId 导入人信息
+     * @return 失败时的回执文件路径
+     */
+    String importGoodsV2(MultipartFile file, Integer userId) throws Exception;
+
 
     /**
      * @describe 库存预警
@@ -89,7 +107,7 @@ public interface GoodsService extends BaseService<Integer, Goods> {
      * @date 2020.10.13
      * @return void
      */
-    void sellOrderBatchNoAllot(Integer tenantId);
+//    void sellOrderBatchNoAllot(Integer tenantId);
 
     /**
      * @describe 扣减商品库存
@@ -108,7 +126,7 @@ public interface GoodsService extends BaseService<Integer, Goods> {
      * @param sellOrderIds: 对应批次商品列表
      * @return void
      */
-    void increaseStock(List<SellOrder> sellOrderIds, AccountType accountType);
+//    void increaseStock(List<SellOrder> sellOrderIds, AccountType accountType);
 
     /**
      * @describe 获取辅件商品列表
@@ -126,9 +144,25 @@ public interface GoodsService extends BaseService<Integer, Goods> {
      * @param goodsId
      * @return
      */
-    Goods getDetail(Integer goodsId);
-    
+    GoodsWrapper.Goods getDetail(Integer goodsId);
+
     List<Goods> getGoodsWithLocked(String goodsIds);
-    
+
     int batchUpdate(List<Goods> goodsList);
+
+    void updateGoods(GoodsWrapper.Goods goods);
+
+    PageInfo<PmsProductDto> queryGoodsSubByPage(GoodsWrapper.GoodsSubQuery query);
+
+    Boolean goodsStatusSynchronize(List<GoodsSubModel> goodsSubModelList);
+
+    Boolean goodsStockCountSynchronize(List<GoodsSubStockModel> goodsSubStockModels);
+
+    List<ProductAttributeCategoryDto> queryGoodsTypeList();
+
+    List<BrandDto> queryGoodsBrandList();
+
+    List<ProductCategoryDto> queryGoodsCategoryList();
+
+    Map<String,String> getBrandMap();
 }

+ 15 - 0
mec-biz/src/main/java/com/ym/mec/biz/service/GoodsSubService.java

@@ -0,0 +1,15 @@
+package com.ym.mec.biz.service;
+
+import com.baomidou.mybatisplus.extension.service.IService;
+import com.ym.mec.biz.dal.entity.GoodsSub;
+import com.ym.mec.biz.dal.mapper.GoodsSubMapper;
+
+/**
+ * 组合商品,子商品信息
+ * 2024-02-26 15:42:42
+ */
+public interface GoodsSubService extends IService<GoodsSub> {
+
+    GoodsSubMapper getBaseMapper();
+
+}

+ 3 - 0
mec-biz/src/main/java/com/ym/mec/biz/service/MusicGroupCalenderRefundPeriodService.java

@@ -1,6 +1,7 @@
 package com.ym.mec.biz.service;
 
 import com.ym.mec.biz.dal.dto.CooperationCalenderRefundDto;
+import com.ym.mec.biz.dal.dto.CooperationCalenderRefundUpdateDto;
 import com.ym.mec.biz.dal.dto.CooperationRefundDto;
 import com.ym.mec.biz.dal.dto.MusicGroupPaymentBaseCalender;
 import com.ym.mec.biz.dal.entity.MusicGroupCalenderRefundPeriod;
@@ -35,4 +36,6 @@ public interface MusicGroupCalenderRefundPeriodService extends BaseService<Integ
     * @date 2022/10/19 11:20
     */
     Boolean calcRefundAmount(Long calenderId,String orderNo, BigDecimal amount);
+
+    void batchUpdate(List<CooperationCalenderRefundUpdateDto> refundPeriods);
 }

+ 13 - 0
mec-biz/src/main/java/com/ym/mec/biz/service/MusicGroupPaymentCalenderAddressService.java

@@ -0,0 +1,13 @@
+package com.ym.mec.biz.service;
+
+import com.baomidou.mybatisplus.extension.service.IService;
+import com.ym.mec.biz.dal.dao.MusicGroupPaymentCalenderAddressDao;
+import com.ym.mec.biz.dal.dao.MusicGroupPaymentCalenderGoodsDao;
+import com.ym.mec.biz.dal.entity.MusicGroupPaymentCalenderAddress;
+import com.ym.mec.biz.dal.entity.MusicGroupPaymentCalenderGoods;
+
+public interface MusicGroupPaymentCalenderAddressService extends IService<MusicGroupPaymentCalenderAddress> {
+
+    MusicGroupPaymentCalenderAddressDao getDao();
+}
+

+ 14 - 0
mec-biz/src/main/java/com/ym/mec/biz/service/MusicGroupPaymentCalenderGoodsService.java

@@ -0,0 +1,14 @@
+package com.ym.mec.biz.service;
+
+import com.baomidou.mybatisplus.extension.service.IService;
+import com.ym.mec.biz.dal.dao.MusicGroupPaymentCalenderGoodsDao;
+import com.ym.mec.biz.dal.dto.MusicGroupPaymentBaseCalender;
+import com.ym.mec.biz.dal.entity.MusicGroupPaymentCalenderGoods;
+
+import java.math.BigDecimal;
+
+public interface MusicGroupPaymentCalenderGoodsService extends IService<MusicGroupPaymentCalenderGoods> {
+
+    MusicGroupPaymentCalenderGoodsDao getDao();
+}
+

+ 2 - 0
mec-biz/src/main/java/com/ym/mec/biz/service/MusicGroupPaymentCalenderRepairService.java

@@ -9,4 +9,6 @@ public interface MusicGroupPaymentCalenderRepairService extends BaseService<Long
     void deleteByCalenderId(Long calenderId);
 
     MusicGroupPaymentCalenderRepair findByCalenderId(Long calenderId);
+
+    void pushWaitSendMessageTask();
 }

+ 1 - 0
mec-biz/src/main/java/com/ym/mec/biz/service/SchoolService.java

@@ -2,6 +2,7 @@ package com.ym.mec.biz.service;
 
 import com.ym.mec.biz.dal.entity.School;
 import com.ym.mec.biz.dal.page.SchoolQueryInfo;
+import com.ym.mec.common.dto.SchoolDto;
 import com.ym.mec.common.page.PageInfo;
 import com.ym.mec.common.service.BaseService;
 

+ 25 - 6
mec-biz/src/main/java/com/ym/mec/biz/service/SellOrderService.java

@@ -2,15 +2,16 @@ package com.ym.mec.biz.service;
 
 
 import com.ym.mec.biz.dal.dao.SellOrderDao;
-import com.ym.mec.biz.dal.entity.MusicGroup;
-import com.ym.mec.biz.dal.entity.SellOrder;
-import com.ym.mec.biz.dal.entity.StudentPaymentOrder;
-import com.ym.mec.biz.dal.entity.StudentPaymentOrderDetail;
+import com.ym.mec.biz.dal.entity.*;
+import com.ym.mec.biz.dal.enums.KitGroupPurchaseTypeEnum;
+import com.ym.mec.common.dto.OrderCreate;
 import com.ym.mec.common.service.BaseService;
+import org.springframework.transaction.annotation.Transactional;
 
 import java.math.BigDecimal;
 import java.util.List;
 import java.util.Map;
+import java.util.function.Function;
 
 
 public interface SellOrderService extends BaseService<Integer, SellOrder> {
@@ -26,7 +27,7 @@ public interface SellOrderService extends BaseService<Integer, SellOrder> {
      * @param couponRemitFee 优惠券减免
      * @return
      */
-    List<SellOrder> addSellOrder(Long orderId, String musicGroupId, List<Integer> goodsIds, BigDecimal totalAmount, BigDecimal balance, BigDecimal couponRemitFee);
+//    List<SellOrder> addSellOrder(Long orderId, String musicGroupId, List<Integer> goodsIds, BigDecimal totalAmount, BigDecimal balance, BigDecimal couponRemitFee);
 
     /**
      * 将订单详情加入销售列表
@@ -35,7 +36,7 @@ public interface SellOrderService extends BaseService<Integer, SellOrder> {
      * @param studentPaymentOrder
      * @return
      */
-    List<SellOrder> addOrderDetail2SellOrder(List<StudentPaymentOrderDetail> orderDetails, StudentPaymentOrder studentPaymentOrder, MusicGroup musicGroup,BigDecimal musicRemitFee);
+    void addOrderDetail2SellOrder(List<StudentPaymentOrderDetail> orderDetails, StudentPaymentOrder studentPaymentOrder, String musicGroup);
 
     void batchInsert(List<SellOrder> sellOrders);
 
@@ -82,4 +83,22 @@ public interface SellOrderService extends BaseService<Integer, SellOrder> {
      */
     Map<String,BigDecimal> getSellAmount(String orderNo);
 
+    List<OrderCreate.OrderItem> convertMallOrder(List<SellOrder> sellOrderList);
+
+    void syncSellOrder2Mall(List<SellOrder> sellOrders, StudentPaymentOrder studentPaymentOrder,String musicGroupId);
+
+    void mallRefundByOrderId(List<SellOrder> sellOrders);
+
+    void updateSellOrder(List<SellOrder> sellOrderList, StudentPaymentOrder studentPaymentOrder);
+
+    List<SellOrder> initSellOrder(StudentPaymentOrder order, String musicGroupId, List<Integer> goodsIds,
+                                  KitGroupPurchaseTypeEnum kitGroupPurchaseType, Boolean saveFlag);
+
+    List<SellOrder> initSellOrder(StudentPaymentOrder order, String musicGroupId, List<Integer> goodsIds, KitGroupPurchaseTypeEnum kitGroupPurchaseType,
+                                  BigDecimal totalBalance, BigDecimal expectTotalAmount, BigDecimal couponRemitAmount,
+                                  BigDecimal actualTotalAmount,Boolean saveFlag);
+
+    void deleteByOrderNo(String orderNo);
+
+    void batchUpdate(List<SellOrder> sellOrderList);
 }

+ 43 - 0
mec-biz/src/main/java/com/ym/mec/biz/service/StudentPaymentOrderAddressService.java

@@ -0,0 +1,43 @@
+package com.ym.mec.biz.service;
+
+import com.baomidou.mybatisplus.core.metadata.IPage;
+import com.baomidou.mybatisplus.extension.service.IService;
+import com.ym.mec.biz.dal.wrapper.StudentPaymentOrderAddressWrapper;
+import com.ym.mec.biz.dal.entity.StudentPaymentOrderAddress;
+
+/**
+ * 学生订单收货地址
+ * 2024-03-01 12:05:41
+ */
+public interface StudentPaymentOrderAddressService extends IService<StudentPaymentOrderAddress>  {
+
+	/**
+     * 查询详情
+     * @param id 详情ID
+     * @return StudentPaymentOrderAddress
+     */
+	StudentPaymentOrderAddress detail(Long id);
+
+    /**
+     * 分页查询
+     * @param page IPage<StudentPaymentOrderAddress>
+     * @param query StudentPaymentOrderAddressWrapper.StudentPaymentOrderAddressQuery
+     * @return IPage<StudentPaymentOrderAddress>
+     */
+    IPage<StudentPaymentOrderAddress> selectPage(IPage<StudentPaymentOrderAddress> page, StudentPaymentOrderAddressWrapper.StudentPaymentOrderAddressQuery query);
+	
+    /**
+     * 添加
+     * @param studentPaymentOrderAddress StudentPaymentOrderAddressWrapper.StudentPaymentOrderAddress
+     * @return Boolean
+     */
+     Boolean add(StudentPaymentOrderAddressWrapper.StudentPaymentOrderAddress studentPaymentOrderAddress);   
+
+    /**
+     * 更新
+     * @param studentPaymentOrderAddress StudentPaymentOrderAddressWrapper.StudentPaymentOrderAddress
+     * @return Boolean
+     */
+     Boolean update(StudentPaymentOrderAddressWrapper.StudentPaymentOrderAddress studentPaymentOrderAddress);
+     
+}

+ 5 - 5
mec-biz/src/main/java/com/ym/mec/biz/service/StudentPaymentOrderDetailService.java

@@ -1,11 +1,13 @@
 package com.ym.mec.biz.service;
 
 import com.ym.mec.biz.dal.dao.StudentPaymentOrderDetailDao;
+import com.ym.mec.biz.dal.dto.GoodsSellDto;
 import com.ym.mec.biz.dal.dto.MusicalListDetailDto;
 import com.ym.mec.biz.dal.entity.*;
 import com.ym.mec.biz.dal.enums.DealStatusEnum;
 import com.ym.mec.common.exception.BizException;
 import com.ym.mec.common.service.BaseService;
+import org.springframework.transaction.annotation.Transactional;
 
 import java.math.BigDecimal;
 import java.util.List;
@@ -14,12 +16,8 @@ public interface StudentPaymentOrderDetailService extends BaseService<Long, Stud
 
     StudentPaymentOrderDetailDao getDao();
 
+    int batchAdd(List<StudentPaymentOrderDetail> studentPaymentOrderDetailList,BigDecimal couponRemitFee,BigDecimal expectAmount);
 
-    /**
-     * 批量添加订单
-     *
-     * @param studentPaymentOrderDetailList 订单详情
-     */
     int batchAdd(List<StudentPaymentOrderDetail> studentPaymentOrderDetailList);
     
     int batchUpdate(List<StudentPaymentOrderDetail> studentPaymentOrderDetailList);
@@ -158,4 +156,6 @@ public interface StudentPaymentOrderDetailService extends BaseService<Long, Stud
                            StudentRegistration studentRegistration, List<StudentPaymentOrderDetail> allDetails);
 
     List<StudentPaymentOrderDetail> findByOrderId(Long paymentOrderId);
+
+    List<StudentPaymentOrderDetail> initStudentPaymentOrderDetail(StudentPaymentOrder studentPaymentOrder, List<GoodsSellDto> goodsSellDtos);
 }

+ 4 - 0
mec-biz/src/main/java/com/ym/mec/biz/service/StudentPaymentOrderService.java

@@ -6,6 +6,7 @@ import java.util.List;
 import java.util.Map;
 
 import com.ym.mec.biz.dal.dto.*;
+import com.ym.mec.common.entity.OrderSkuSync;
 import org.apache.ibatis.annotations.Param;
 
 import com.ym.mec.biz.dal.dao.StudentPaymentOrderDao;
@@ -274,4 +275,7 @@ public interface StudentPaymentOrderService extends BaseService<Long, StudentPay
     BigDecimal balance(Long userId);
 
     List<OperatingTotalIncomeDto> queryOperatingSummaryIncome(Map<String, Object> params);
+
+    //商品已发货
+    void updateShippedStatus(List<OrderSkuSync> orderSkuSyncs);
 }

+ 5 - 0
mec-biz/src/main/java/com/ym/mec/biz/service/StudentPaymentRouteOrderService.java

@@ -4,6 +4,8 @@ package com.ym.mec.biz.service;
 import java.math.BigDecimal;
 import java.util.List;
 
+import com.ym.mec.biz.dal.dao.StudentPaymentRouteOrderDao;
+import com.ym.mec.biz.dal.dto.OutOrderInfoDto;
 import com.ym.mec.biz.dal.dto.PageInfoOrder;
 import com.ym.mec.biz.dal.dto.StudentPaymentRouteOrderDto;
 import com.ym.mec.biz.dal.entity.StudentPaymentRouteOrder;
@@ -17,6 +19,7 @@ import org.springframework.web.multipart.MultipartFile;
 
 
 public interface StudentPaymentRouteOrderService extends BaseService<Long, StudentPaymentRouteOrder> {
+	StudentPaymentRouteOrderDao getDao();
 	
 	/**
 	 * 查询审核列表
@@ -74,4 +77,6 @@ public interface StudentPaymentRouteOrderService extends BaseService<Long, Stude
 	 * @return
 	 */
 	HttpResponseResult<List<StudentPaymentRouteOrder>> importRouteOrder(MultipartFile file) throws Exception;
+
+    OutOrderInfoDto getRouteOrder(Long orderId);
 }

+ 2 - 1
mec-biz/src/main/java/com/ym/mec/biz/service/SysAreaService.java

@@ -2,10 +2,10 @@ package com.ym.mec.biz.service;
 
 import com.ym.mec.biz.dal.dto.TreeDto;
 import com.ym.mec.biz.dal.entity.SysArea;
-import com.ym.mec.biz.dal.page.OrganizationQueryInfo;
 import com.ym.mec.common.service.BaseService;
 
 import java.util.List;
+import java.util.Map;
 
 public interface SysAreaService extends BaseService<Integer, SysArea> {
 
@@ -35,4 +35,5 @@ public interface SysAreaService extends BaseService<Integer, SysArea> {
      */
     SysArea queryByCode(String code);
 
+    Map<String,String> getNameMapByIds(List<String> areaIds);
 }

+ 2 - 0
mec-biz/src/main/java/com/ym/mec/biz/service/SysUserCashAccountService.java

@@ -1,5 +1,6 @@
 package com.ym.mec.biz.service;
 
+import com.ym.mec.biz.dal.dao.SysUserCashAccountDao;
 import com.ym.mec.biz.dal.dto.PayParamBasicDto;
 import com.ym.mec.biz.dal.entity.StudentPaymentOrder;
 import com.ym.mec.biz.dal.entity.SysUserCashAccount;
@@ -9,6 +10,7 @@ import com.ym.mec.common.service.BaseService;
 import java.math.BigDecimal;
 
 public interface SysUserCashAccountService extends BaseService<Integer, SysUserCashAccount> {
+	SysUserCashAccountDao getDao();
 
 	/**
 	 * 更新指定用户的账户余额

+ 3 - 3
mec-biz/src/main/java/com/ym/mec/biz/service/impl/ActivityUserMapperServiceImpl.java

@@ -758,7 +758,7 @@ public class ActivityUserMapperServiceImpl extends BaseServiceImpl<Integer, Acti
 								   ActivityUserMapper activityUserMapper){
 		//实际支付金额,去除优惠券
 		BigDecimal totalAmount = activityUserMapper.getSubNoCoursePrice();
-		BigDecimal singleAmount = totalAmount.divide(new BigDecimal(courseNum), ROUND_DOWN);
+		BigDecimal singleAmount = totalAmount.divide(new BigDecimal(courseNum), RoundingMode.DOWN);
 		BigDecimal firstSingleAmount = totalAmount.subtract(singleAmount.multiply(new BigDecimal(courseNum))).add(singleAmount);
 		for (Integer i = 0; i < courseNum; i++) {
 			CourseScheduleStudentPayment courseScheduleStudentPayment = new CourseScheduleStudentPayment();
@@ -1265,9 +1265,9 @@ public class ActivityUserMapperServiceImpl extends BaseServiceImpl<Integer, Acti
 				activityUserMapper.setActualPrice(subActual);
 			} else {
 				//获取比例
-				BigDecimal ratioAmount = activity.getMarketPrice().divide(reduce, 6, BigDecimal.ROUND_HALF_UP);
+				BigDecimal ratioAmount = activity.getMarketPrice().divide(reduce, 16, RoundingMode.DOWN);
 				//获取分配的减免金额
-				BigDecimal multiply = ratioAmount.multiply(totalActual).setScale(2, BigDecimal.ROUND_HALF_UP);
+				BigDecimal multiply = ratioAmount.multiply(totalActual).setScale(2, RoundingMode.DOWN);
 				subActual = subActual.subtract(multiply);
 				activityUserMapper.setActualPrice(multiply);
 			}

+ 3 - 2
mec-biz/src/main/java/com/ym/mec/biz/service/impl/ClassGroupServiceImpl.java

@@ -42,6 +42,7 @@ import org.springframework.transaction.annotation.Propagation;
 import org.springframework.transaction.annotation.Transactional;
 import org.springframework.transaction.interceptor.TransactionAspectSupport;
 import java.math.BigDecimal;
+import java.math.RoundingMode;
 import java.time.*;
 import java.time.format.DateTimeFormatter;
 import java.util.*;
@@ -1404,7 +1405,7 @@ public class ClassGroupServiceImpl extends BaseServiceImpl<Integer, ClassGroup>
                             if (unitPrice != null) {
                                 courseType = courseSchedule.getType();
                                 BigDecimal duration = new BigDecimal(DateUtil.minutesBetween(courseSchedule.getStartClassTime(), courseSchedule.getEndClassTime()));
-                                courseScheduleStudentPayment.setExpectPrice(unitPrice.multiply(duration).setScale(2, BigDecimal.ROUND_DOWN));
+                                courseScheduleStudentPayment.setExpectPrice(unitPrice.multiply(duration).setScale(2, RoundingMode.DOWN));
 
                                 if (totalPriceMap.containsKey(courseType)) {
                                     totalPriceMap.put(courseType, totalPriceMap.get(courseType).add(courseScheduleStudentPayment.getExpectPrice()));
@@ -1417,7 +1418,7 @@ public class ClassGroupServiceImpl extends BaseServiceImpl<Integer, ClassGroup>
                             if (originUnitPrice != null) {
                                 courseType = courseSchedule.getType();
                                 BigDecimal duration = new BigDecimal(DateUtil.minutesBetween(courseSchedule.getStartClassTime(), courseSchedule.getEndClassTime()));
-                                courseScheduleStudentPayment.setOriginalPrice(originUnitPrice.multiply(duration).setScale(2, BigDecimal.ROUND_DOWN));
+                                courseScheduleStudentPayment.setOriginalPrice(originUnitPrice.multiply(duration).setScale(2, RoundingMode.DOWN));
 
                                 if (totalOrignPriceMap.containsKey(courseType)) {
                                     totalOrignPriceMap.put(courseType, totalOrignPriceMap.get(courseType).add(courseScheduleStudentPayment.getOriginalPrice()));

+ 12 - 0
mec-biz/src/main/java/com/ym/mec/biz/service/impl/CooperationOrganServiceImpl.java

@@ -7,6 +7,7 @@ import com.ym.mec.biz.dal.entity.*;
 import com.ym.mec.biz.dal.enums.MusicGroupStatusEnum;
 import com.ym.mec.biz.service.*;
 import com.ym.mec.common.dal.BaseDAO;
+import com.ym.mec.common.dto.SchoolDto;
 import com.ym.mec.common.service.impl.BaseServiceImpl;
 import org.apache.commons.collections.CollectionUtils;
 import org.springframework.stereotype.Service;
@@ -257,4 +258,15 @@ public class CooperationOrganServiceImpl extends BaseServiceImpl<Integer, Cooper
         return musicGroupList.stream().filter(o -> o.getStatus().equals(MusicGroupStatusEnum.PROGRESS)).collect(Collectors.toList());
     }
 
+    @Override
+    public List<SchoolDto> coopListByIds(List<Integer> coopIds) {
+		List<CooperationOrgan> schools = cooperationOrganDao.getCooperationOrganByIds(coopIds);
+		return schools.stream().map(e -> {
+			SchoolDto schoolDto = new SchoolDto();
+			schoolDto.setId(e.getId());
+			schoolDto.setName(e.getName());
+			return schoolDto;
+		}).collect(Collectors.toList());
+    }
+
 }

+ 2 - 2
mec-biz/src/main/java/com/ym/mec/biz/service/impl/CourseScheduleStudentPaymentServiceImpl.java

@@ -510,8 +510,8 @@ public class CourseScheduleStudentPaymentServiceImpl extends BaseServiceImpl<Lon
 					//课程每分钟现价
 					BigDecimal unitMinuteCurrentPrice = detail.getCourseCurrentPrice().divide(new BigDecimal(detail.getTotalCourseMinutes()), CommonConstants.DECIMAL_PLACE, BigDecimal.ROUND_DOWN);
 					BigDecimal unitMinuteOriginalPrice = detail.getCourseOriginalPrice().divide(new BigDecimal(detail.getTotalCourseMinutes()), CommonConstants.DECIMAL_PLACE, BigDecimal.ROUND_DOWN);
-					BigDecimal originalPrice = unitMinuteOriginalPrice.multiply(new BigDecimal(courseMinutes)).setScale(2, BigDecimal.ROUND_DOWN);
-					BigDecimal expectPrice = unitMinuteCurrentPrice.multiply(new BigDecimal(courseMinutes)).setScale(2, BigDecimal.ROUND_DOWN);
+					BigDecimal originalPrice = unitMinuteOriginalPrice.multiply(new BigDecimal(courseMinutes)).setScale(2, RoundingMode.DOWN);
+					BigDecimal expectPrice = unitMinuteCurrentPrice.multiply(new BigDecimal(courseMinutes)).setScale(2, RoundingMode.DOWN);
 					studentPayment.setOriginalPrice(studentPayment.getOriginalPrice().add(originalPrice));
 					studentPayment.setExpectPrice(studentPayment.getExpectPrice().add(expectPrice));
 					detail.setSubCourseCurrentPrice(detail.getSubCourseCurrentPrice().subtract(expectPrice));

+ 3 - 2
mec-biz/src/main/java/com/ym/mec/biz/service/impl/EduPracticeGroupServiceImpl.java

@@ -39,6 +39,7 @@ import org.springframework.transaction.interceptor.TransactionAspectSupport;
 import org.springframework.util.CollectionUtils;
 
 import java.math.BigDecimal;
+import java.math.RoundingMode;
 import java.time.*;
 import java.time.format.DateTimeFormatter;
 import java.time.temporal.WeekFields;
@@ -391,8 +392,8 @@ public class EduPracticeGroupServiceImpl implements EduPracticeGroupService{
         if(teacherDefaultSalary == null){
         	throw new BizException("请设置老师课酬");
         }
-        BigDecimal studentSingleCourseCost=amount.divide(new BigDecimal(practiceCourses.size()), CommonConstants.DECIMAL_PLACE, BigDecimal.ROUND_DOWN);
-        BigDecimal studentSingleCourseOriginalCost=originalAmount.divide(new BigDecimal(practiceCourses.size()), CommonConstants.DECIMAL_PLACE, BigDecimal.ROUND_DOWN);
+        BigDecimal studentSingleCourseCost=amount.divide(new BigDecimal(practiceCourses.size()), CommonConstants.DECIMAL_PLACE, RoundingMode.DOWN);
+        BigDecimal studentSingleCourseOriginalCost=originalAmount.divide(new BigDecimal(practiceCourses.size()), CommonConstants.DECIMAL_PLACE, RoundingMode.DOWN);
         for (CourseSchedule courseSchedule : practiceCourses) {
             //课程与老师薪水表
             CourseScheduleTeacherSalary courseScheduleTeacherSalary = new CourseScheduleTeacherSalary();

+ 58 - 22
mec-biz/src/main/java/com/ym/mec/biz/service/impl/ExportServiceImpl.java

@@ -1792,6 +1792,7 @@ public class ExportServiceImpl implements ExportService {
         Map<String, Object> params = new HashMap<>();
         MapUtil.populateMap(params, queryInfo);
         params.put("notGroupType","MALL_SELL");
+        params.put("notType","SCHOOL_GOODS_PURCHASE");
         int count = studentPaymentOrderService.getDao().queryCount(params);
         if (count <= 0) {
             return BaseController.failed("没有可导出的数据");
@@ -1848,6 +1849,7 @@ public class ExportServiceImpl implements ExportService {
         }
         Map<String, Object> params = new HashMap<>();
         MapUtil.populateMap(params, queryInfo);
+        params.put("notType","SCHOOL_GOODS_PURCHASE");
         int count = studentPaymentOrderService.getDao().queryCount(params);
         if (count <= 0) {
             return BaseController.failed("没有可导出的数据");
@@ -2047,6 +2049,17 @@ public class ExportServiceImpl implements ExportService {
             feeByTypeMap = feeByType.stream().collect(Collectors.groupingBy(StudentPaymentOrderExportDto::getId));
             childRepairMap = MapUtil.convertIntegerMap(sellOrderService.getDao().queryChildRepair(otherOrderIds));
         }
+        //获取外部订单,将学校商品采购划分为大件乐器
+        Map<String, StudentPaymentRouteOrder> routeOrderMap = new HashMap<>();
+        List<String> outOrderNos = studentPaymentOrderExportDtos.stream().filter(e -> e.getGroupType() == GroupType.OUTORDER && e.getType() == OrderTypeEnum.SCHOOL)
+                .map(e -> e.getOrderNo()).collect(Collectors.toList());
+        if(org.apache.commons.collections.CollectionUtils.isNotEmpty(outOrderNos)){
+            List<StudentPaymentRouteOrder> routeOrders = studentPaymentRouteOrderDao.queryByOrderNos(outOrderNos);
+            if (org.apache.commons.collections.CollectionUtils.isNotEmpty(routeOrders)){
+                routeOrderMap = routeOrders.stream().filter(e->e.getSaleAmount().compareTo(BigDecimal.ZERO) > 0)
+                        .collect(Collectors.toMap(StudentPaymentRouteOrder::getOrderNo, Function.identity()));
+            }
+        }
 
         for (StudentPaymentOrderExportDto row : studentPaymentOrderExportDtos) {
             if (row.getActualAmount() == null) {
@@ -2327,20 +2340,25 @@ public class ExportServiceImpl implements ExportService {
                             } else {
                                 //拆分导入订单
                                 if (row.getType() == OrderTypeEnum.OUTORDER || row.getType() == OrderTypeEnum.SCHOOL) {
-                                    if (row.getType() == OrderTypeEnum.SCHOOL) {
-                                        row.setMusicalFee(BigDecimal.ZERO);
-                                        row.setTeachingFee(BigDecimal.ZERO);
-                                        row.setMaintenanceProductFee(BigDecimal.ZERO);
-                                        row.setOtherFee(BigDecimal.ZERO);
-                                        row.setLargeMusicalFee(add);
-                                    }
-                                    //如果有服务收入那么是课程学校采买
-                                    if (subtract.compareTo(BigDecimal.ZERO) == 0) {
+                                    if(routeOrderMap.get(row.getOrderNo()) != null){
+                                        row.setLargeMusicalFee(subtract);
                                         row.setTypeDesc(StudentPaymentOrderExportDto.TypeDesc.LARGE_MUSICAL.getMsg());
-                                    } else {
-                                        row.setTypeDesc(StudentPaymentOrderExportDto.TypeDesc.COURSE_SCHOOL_BUY.getMsg());
+                                    }else {
+                                        if (row.getType() == OrderTypeEnum.SCHOOL) {
+                                            row.setMusicalFee(BigDecimal.ZERO);
+                                            row.setTeachingFee(BigDecimal.ZERO);
+                                            row.setMaintenanceProductFee(BigDecimal.ZERO);
+                                            row.setOtherFee(BigDecimal.ZERO);
+                                            row.setLargeMusicalFee(add);
+                                        }
+                                        //如果有服务收入那么是课程学校采买
+                                        if (subtract.compareTo(BigDecimal.ZERO) == 0) {
+                                            row.setTypeDesc(StudentPaymentOrderExportDto.TypeDesc.LARGE_MUSICAL.getMsg());
+                                        } else {
+                                            row.setTypeDesc(StudentPaymentOrderExportDto.TypeDesc.COURSE_SCHOOL_BUY.getMsg());
+                                        }
+                                        row.setCourseSchoolBuyAmount(subtract);
                                     }
-                                    row.setCourseSchoolBuyAmount(subtract);
                                 } else if (row.getType() == OrderTypeEnum.OTHER) {
                                     row.setOtherFee(row.getOtherFee().add(subtract));
                                 } else {
@@ -2450,6 +2468,17 @@ public class ExportServiceImpl implements ExportService {
             feeByTypeMap = feeByType.stream().collect(Collectors.groupingBy(StudentPaymentOrderExportDto::getId));
             childRepairMap = MapUtil.convertIntegerMap(sellOrderService.getDao().queryChildRepair(otherOrderIds));
         }
+        //获取外部订单,将学校商品采购划分为大件乐器
+        Map<String, StudentPaymentRouteOrder> routeOrderMap = new HashMap<>();
+        List<String> outOrderNos = studentPaymentOrderExportDtos.stream().filter(e -> e.getGroupType() == GroupType.OUTORDER && e.getType() == OrderTypeEnum.SCHOOL)
+                .map(e -> e.getOrderNo()).collect(Collectors.toList());
+        if(org.apache.commons.collections.CollectionUtils.isNotEmpty(outOrderNos)){
+            List<StudentPaymentRouteOrder> routeOrders = studentPaymentRouteOrderDao.queryByOrderNos(outOrderNos);
+            if (org.apache.commons.collections.CollectionUtils.isNotEmpty(routeOrders)){
+                routeOrderMap = routeOrders.stream().filter(e->e.getSaleAmount().compareTo(BigDecimal.ZERO) > 0)
+                        .collect(Collectors.toMap(StudentPaymentRouteOrder::getOrderNo, Function.identity()));
+            }
+        }
         for (StudentPaymentOrderExportDto row : studentPaymentOrderExportDtos) {
             if (row.getActualAmount() == null) {
                 row.setActualAmount(BigDecimal.ZERO);
@@ -2642,14 +2671,18 @@ public class ExportServiceImpl implements ExportService {
                         } else {
                             //拆分导入订单
                             if (row.getType() == OrderTypeEnum.OUTORDER || row.getType() == OrderTypeEnum.SCHOOL) {
-                                if (row.getType() == OrderTypeEnum.SCHOOL) {
-                                    row.setMusicalFee(BigDecimal.ZERO);
-                                    row.setTeachingFee(BigDecimal.ZERO);
-                                    row.setMaintenanceProductFee(BigDecimal.ZERO);
-                                    row.setOtherFee(BigDecimal.ZERO);
-                                    row.setLargeMusicalFee(add);
+                                if(routeOrderMap.get(row.getOrderNo()) != null){
+                                    row.setLargeMusicalFee(subtract);
+                                }else {
+                                    if (row.getType() == OrderTypeEnum.SCHOOL) {
+                                        row.setMusicalFee(BigDecimal.ZERO);
+                                        row.setTeachingFee(BigDecimal.ZERO);
+                                        row.setMaintenanceProductFee(BigDecimal.ZERO);
+                                        row.setOtherFee(BigDecimal.ZERO);
+                                        row.setLargeMusicalFee(add);
+                                    }
+                                    row.setCourseSchoolBuyAmount(subtract);
                                 }
-                                row.setCourseSchoolBuyAmount(subtract);
                             } else if (row.getType() == OrderTypeEnum.OTHER) {
                                 row.setOtherFee(row.getOtherFee().add(subtract));
                             } else {
@@ -2797,7 +2830,10 @@ public class ExportServiceImpl implements ExportService {
         if (!CollectionUtils.isEmpty(sellOrders)) {
             sellOrderMap = sellOrders.stream().collect(Collectors.groupingBy(SellOrder::getOrderId));
             //获取商品列表
-            List<Goods> goodsList = goodsService.findGoodsByIds(sellOrders.stream().map(e -> e.getGoodsId().toString()).distinct().collect(Collectors.joining(",")));
+            List<Goods> goodsList = goodsService.findGoodsByIds(sellOrders.stream().filter(e->e.getGoodsSkuId()==null)
+                    .map(e -> e.getGoodsId().toString()).distinct().collect(Collectors.joining(",")));
+            goodsList.addAll(goodsService.findGoodsByIds(sellOrders.stream().filter(e->e.getGoodsSkuId() != null)
+                    .map(e -> e.getGoodsSkuId().toString()).distinct().collect(Collectors.joining(","))));
             goodsMap = goodsList.stream().collect(Collectors.toMap(Goods::getId, Function.identity()));
         }
 
@@ -3250,7 +3286,7 @@ public class ExportServiceImpl implements ExportService {
         } else if (basicOrder.getSaleAmount().compareTo(BigDecimal.ZERO) > 0) {
             //计算销售收入,排除商品编号是76的商品,其他的商品按分类统计
             for (SellOrder e : sellOrderList) {
-                this.setSaleFee(basicOrder, e, goodsMap.get(e.getGoodsId()));
+                this.setSaleFee(basicOrder, e, goodsMap.get(e.getGoodsSkuId() == null ? e.getGoodsId() : e.getGoodsSkuId()));
             }
         }
     }
@@ -3426,7 +3462,7 @@ public class ExportServiceImpl implements ExportService {
         BigDecimal actualAmount = subTotalAmount;
         for (int i = 0; i < detailList.size(); i++) {
             StudentPaymentOrderDetail detail = detailList.get(i);
-            BigDecimal ratio = detail.getPrice().divide(expectAmount, 8, RoundingMode.DOWN);
+            BigDecimal ratio = detail.getPrice().divide(expectAmount, 16, RoundingMode.DOWN);
             BigDecimal price = actualAmount.multiply(ratio).setScale(2, RoundingMode.DOWN);
             if (i == detailList.size() - 1) {
                 detail.setPrice(subTotalAmount);

+ 820 - 53
mec-biz/src/main/java/com/ym/mec/biz/service/impl/GoodsServiceImpl.java

@@ -2,33 +2,46 @@ package com.ym.mec.biz.service.impl;
 
 import com.alibaba.fastjson.JSON;
 import com.alibaba.fastjson.JSONObject;
-import com.ym.mec.biz.dal.dao.*;
+import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
+import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
+import com.microsvc.toolkit.middleware.oss.OssPluginContext;
+import com.microsvc.toolkit.middleware.oss.impl.TencentOssPlugin;
+import com.ym.mec.biz.dal.dao.GoodsDao;
+import com.ym.mec.biz.dal.dao.OrganizationDao;
+import com.ym.mec.biz.dal.dao.TeacherDao;
 import com.ym.mec.biz.dal.dto.BasicUserDto;
 import com.ym.mec.biz.dal.dto.GoodsSellDto;
-import com.ym.mec.biz.dal.entity.Goods;
-import com.ym.mec.biz.dal.entity.GoodsProcurement;
-import com.ym.mec.biz.dal.entity.Organization;
-import com.ym.mec.biz.dal.entity.SellOrder;
+import com.ym.mec.biz.dal.entity.*;
 import com.ym.mec.biz.dal.enums.*;
+import com.ym.mec.biz.dal.page.GoodsCategoryQueryInfo;
 import com.ym.mec.biz.dal.page.GoodsQuery;
 import com.ym.mec.biz.dal.page.GoodsQueryInfo;
+import com.ym.mec.biz.dal.wrapper.GoodsWrapper;
 import com.ym.mec.biz.service.*;
 import com.ym.mec.common.dal.BaseDAO;
-import com.ym.mec.common.entity.UploadReturnBean;
+import com.ym.mec.common.dto.*;
+import com.ym.mec.common.entity.GoodsSubModel;
+import com.ym.mec.common.entity.GoodsSubStockModel;
 import com.ym.mec.common.exception.BizException;
-import com.ym.mec.common.service.IdGeneratorService;
+import com.ym.mec.common.page.PageInfo;
+import com.ym.mec.common.page.QueryInfo;
 import com.ym.mec.common.service.impl.BaseServiceImpl;
 import com.ym.mec.common.tenant.TenantContextHolder;
+import com.ym.mec.mall.MallFeignService;
 import com.ym.mec.thirdparty.message.MessageSenderPluginContext;
 import com.ym.mec.util.collection.MapUtil;
 import com.ym.mec.util.excel.POIUtil;
 import com.ym.mec.util.ini.IniFileUtil;
-
+import com.ym.mec.util.upload.UploadUtil;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang.math.NumberUtils;
 import org.apache.commons.lang3.StringUtils;
 import org.apache.poi.ss.usermodel.PictureData;
+import org.apache.poi.ss.usermodel.Workbook;
+import org.apache.poi.ss.usermodel.WorkbookFactory;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.system.ApplicationHome;
 import org.springframework.core.io.ClassPathResource;
 import org.springframework.stereotype.Service;
 import org.springframework.transaction.annotation.Isolation;
@@ -36,41 +49,50 @@ import org.springframework.transaction.annotation.Transactional;
 import org.springframework.util.CollectionUtils;
 import org.springframework.web.multipart.MultipartFile;
 
-import java.io.ByteArrayInputStream;
-import java.io.InputStream;
+import javax.annotation.Resource;
+import javax.imageio.ImageIO;
+import java.awt.image.BufferedImage;
+import java.io.*;
 import java.math.BigDecimal;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.text.SimpleDateFormat;
 import java.util.*;
-import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.Function;
 import java.util.stream.Collectors;
 
+@Slf4j
 @Service
 public class GoodsServiceImpl extends BaseServiceImpl<Integer, Goods>  implements GoodsService {
 	private static final Logger LOGGER = LoggerFactory.getLogger(CourseScheduleTeacherSalaryServiceImpl.class);
-	
-	@Autowired
+
+	@Resource
 	private GoodsDao goodsDao;
-	@Autowired
-	private UploadFileService uploadFileService;
-	@Autowired
-	private IdGeneratorService idGeneratorService;
-	@Autowired
-	private GoodsProcurementDao goodsProcurementDao;
-	@Autowired
+	@Resource
 	private SysTenantConfigService sysTenantConfigService;
-	@Autowired
+	@Resource
 	private SysMessageService sysMessageService;
-	@Autowired
+	@Resource
 	private TeacherDao teacherDao;
-	@Autowired
-	private SellOrderDao sellOrderDao;
-	@Autowired
+	@Resource
 	private OrganizationDao organizationDao;
-
+	@Resource
+	private MallFeignService mallFeignService;
+    @Resource
+    private GoodsCategoryService goodsCategoryService;
+	@Resource
+	private GoodsSubService goodsSubService;
+	@Resource
+	private OssPluginContext ossPluginContext;
 	@Override
 	public BaseDAO<Integer, Goods> getDAO() {
 		return goodsDao;
 	}
 
+	public GoodsDao getGoodsDao() {
+		return goodsDao;
+	}
+
 	@Override
 	public List<Goods> exportGoods(GoodsQueryInfo queryInfo) {
 		Map<String, Object> params = new HashMap<String, Object>();
@@ -154,27 +176,53 @@ public class GoodsServiceImpl extends BaseServiceImpl<Integer, Goods>  implement
 	}
 
 	@Override
-	@Transactional(rollbackFor = Exception.class,isolation = Isolation.READ_COMMITTED)
-	public void addGoods(Goods goods, Integer operatorId) {
-		if(StringUtils.isBlank(goods.getSn())){
-			throw new BizException("请指定商品货号");
-		}
-		Goods existsGood = goodsDao.lockBySn(goods.getSn());
-		if(Objects.nonNull(existsGood)){
-			throw new BizException("商品货号重复");
-		}else{
-			if(Objects.isNull(goods.getStockCount())){
-				goods.setStockCount(0);
+	@Transactional(rollbackFor = Exception.class)
+	public void addGoods(List<GoodsWrapper.Goods> goodsList, Integer operatorId) {
+//		List<String> snList = goodsList.stream().map(GoodsWrapper.Goods::getSn).collect(Collectors.toList());
+//		if (snList.size() != new HashSet<>(snList).size()) {
+//			throw new BizException("商品货号重复");
+//		}
+//		List<Goods> bySns = goodsDao.findBySns(snList);
+//		if (!CollectionUtils.isEmpty(bySns)) {
+//			throw new BizException("商品货号重复");
+//		}
+		for (GoodsWrapper.Goods goods : goodsList) {
+			if (StringUtils.isBlank(goods.getSn())) {
+				throw new BizException("请指定商品货号");
 			}
-			if(Objects.isNull(goods.getTaxStockCount())){
-				goods.setTaxStockCount(0);
+//			Goods existsGood = goodsDao.lockBySn(goods.getSn());
+//			if (Objects.nonNull(existsGood)) {
+//				throw new BizException("商品货号重复");
+//			}
+			List<GoodsWrapper.GoodsSub> goodsSubList = goods.getGoodsSubList();
+			//获取最小的库存数
+			String skuIds = goodsSubList.stream().map(e -> e.getSku().toString()).collect(Collectors.joining(","));
+			PmsProductQueryParamDto paramDto = new PmsProductQueryParamDto();
+			paramDto.setSkuStockIds(skuIds);
+//		paramDto.setPublishStatus(1);
+			paramDto.setPageSize(1000);
+			paramDto.setPageNum(1);
+			paramDto.setJson(JSON.toJSONString(paramDto));
+			List<PmsProductDto> productList = mallFeignService.getProductList(paramDto).getRows();
+			if (CollectionUtils.isEmpty(productList)) {
+				throw new BizException("子商品不存在");
 			}
+			//获取最小库存数量
+			Integer stock = productList.stream().map(PmsProductDto::getStock).min(Integer::compareTo).get();
+			goods.setStockCount(stock);
 			goods.setSellCount(0);
-			goodsDao.insert(goods);
+			Goods goodsRecord = JSON.parseObject(JSON.toJSONString(goods), Goods.class);
+			goodsRecord.setStatus(YesOrNoEnum.NO);
+			BigDecimal organCostPrice = goodsSubList.stream().map(GoodsWrapper.GoodsSub::getGoodsPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
+			goodsRecord.setOrganCostPrice(organCostPrice);
+			goodsDao.insert(goodsRecord);
+			List<GoodsSub> goodsSubs = JSON.parseArray(JSON.toJSONString(goodsSubList), GoodsSub.class);
+			goodsSubs.forEach(next -> next.setGoodsId(goodsRecord.getId()));
+			goodsSubService.saveBatch(goodsSubs);
 		}
 	}
 
-	@Override
+	/*@Override
 	@Transactional(rollbackFor = Exception.class)
 	public void addGoodsProcurement(GoodsProcurement goodsProcurement) {
 		Goods existsGood = goodsDao.get(goodsProcurement.getGoodsId());
@@ -204,7 +252,7 @@ public class GoodsServiceImpl extends BaseServiceImpl<Integer, Goods>  implement
 		goodsProcurementDao.insert(goodsProcurement);
 
 		sellOrderBatchNoAllot(existsGood.getTenantId());
-	}
+	}*/
 
 	@Override
 	@Transactional(rollbackFor = Exception.class)
@@ -227,6 +275,13 @@ public class GoodsServiceImpl extends BaseServiceImpl<Integer, Goods>  implement
 					throw new BizException("{}等商品还在销售中", goodsNames);
 				}
 			}
+			List<GoodsWrapper.GoodsSub> goodsSubs = queryGoodsSubByGoodId(goodsId);
+			if (!CollectionUtils.isEmpty(goodsSubs) && status == 1) {
+				long falseSize = goodsSubs.stream().map(GoodsWrapper.GoodsSub::getGoodsStatus).filter(Boolean.FALSE::equals).count();
+				if (falseSize > 0) {
+					throw new BizException("存在已下架的子商品");
+				}
+			}
 		}else{
 			if(status==1){
 				List<Integer> goodsIds = Arrays.stream(goods.getComplementGoodsIdList().split(",")).map(s -> Integer.valueOf(s)).collect(Collectors.toList());
@@ -241,6 +296,56 @@ public class GoodsServiceImpl extends BaseServiceImpl<Integer, Goods>  implement
 		goodsDao.update(goods);
 	}
 
+	private List<GoodsWrapper.GoodsSub> queryGoodsSubByGoodId(Integer goodsId) {
+		// 从管乐迷商城组合的商品
+		QueryWrapper<GoodsSub> queryWrapper = new QueryWrapper<>();
+		queryWrapper.eq("goods_id_", goodsId);
+		List<GoodsSub> goodsSubs = goodsSubService.getBaseMapper().selectList(queryWrapper);
+		if (goodsSubs.isEmpty()) {
+			return new ArrayList<>();
+		}
+//		List<String> skuList = goodsSubs.stream().map(next -> next.getSku().toString()).distinct().collect(Collectors.toList());
+		List<GoodsWrapper.GoodsSub> goodsSubList = goodsSubs.stream().map(next -> {
+			GoodsWrapper.GoodsSub goodsSub = new GoodsWrapper.GoodsSub();
+			goodsSub.setId(next.getId());
+			goodsSub.setGoodsId(goodsId);
+			goodsSub.setMallGoodsId(next.getMallGoodsId());
+			goodsSub.setGoodsStatus(next.getGoodsStatus());
+			goodsSub.setSku(next.getSku());
+			goodsSub.setGoodsPrice(next.getGoodsPrice());
+			return goodsSub;
+		}).collect(Collectors.toList());
+		List<String> goodIdList = goodsSubs.stream().map(next -> next.getMallGoodsId().toString()).distinct().collect(Collectors.toList());
+		PmsProductQueryParamDto build = PmsProductQueryParamDto.builder()
+				.productIds(String.join(",", goodIdList))
+				.pageSize(9999)
+				.pageNum(1).build();
+		build.setJson(JSON.toJSONString(build));
+		List<PmsProductDto> rows = mallFeignService.getProductList(build).getRows();
+		Map<Integer, PmsProductDto> map = rows.stream().collect(Collectors.toMap(PmsProductDto::getSkuStockId, Function.identity()));
+		Map<Long, List<PmsProductDto>> groupByGoodId = rows.stream().collect(Collectors.groupingBy(PmsProductDto::getGoodsId));
+		goodsSubList.forEach(next -> {
+			PmsProductDto dto = map.get(next.getSku());
+			if (dto != null) {
+				next.setPrice(dto.getPrice());
+				next.setSkuCode(dto.getSkuCode());
+				if (1 == dto.getDeleteStatus()) {
+					next.setGoodsStatus(false);
+				} else {
+					next.setGoodsStatus(dto.getPublishStatus() == 1);
+				}
+			}
+			if(groupByGoodId.containsKey(Long.valueOf(next.getMallGoodsId()))){
+				PmsProductDto dto1 =  groupByGoodId.get(Long.valueOf(next.getMallGoodsId())).get(0);
+				next.setMallGoodsName(dto1.getName());
+				next.setProductSn(dto1.getProductSn());
+				next.setBrandId(dto1.getBrandId());
+				next.setBrandName(dto1.getBrandName());
+			}
+		});
+		return goodsSubList;
+	}
+
 	@Override
 	public List<Goods> findGoodsBySubId(GoodsQuery goodsQuery) {
 		return goodsDao.findGoodsBySubId(goodsQuery);
@@ -261,6 +366,20 @@ public class GoodsServiceImpl extends BaseServiceImpl<Integer, Goods>  implement
 	}
 
 	@Override
+	public PageInfo<Goods> queryPage(QueryInfo queryInfo) {
+		PageInfo<Goods> page = super.queryPage(queryInfo);
+
+		List<Goods> rows = page.getRows();
+		if (!rows.isEmpty()) {
+			Map<String, String> brandIdNameMap = this.queryGoodsBrandList().stream().collect(Collectors.toMap(next -> next.getId().toString(), BrandDto::getName));
+			for (Goods row : rows) {
+				row.setBrandName(brandIdNameMap.getOrDefault(row.getBrand(), row.getBrand()));
+			}
+		}
+		return page;
+	}
+
+/*	@Override
 	@Transactional(rollbackFor = Exception.class, isolation = Isolation.READ_COMMITTED)
 	public List<Goods> importGoods(MultipartFile file, Integer operatorId) throws Exception {
 		Map<String, List<Map<String, Object>>> sheetsListMap = POIUtil.importExcel(new ByteArrayInputStream(file.getBytes()), 2, file.getOriginalFilename());
@@ -458,6 +577,373 @@ public class GoodsServiceImpl extends BaseServiceImpl<Integer, Goods>  implement
 		sellOrderBatchNoAllot(TenantContextHolder.getTenantId());
 
 		return goodsList;
+	}*/
+
+
+	@Transactional(rollbackFor = Exception.class)
+	@Override
+	public String importGoodsV2(MultipartFile file, Integer userId) throws Exception {
+		File excel = createImportGoodsTempFile(UUID.randomUUID().toString().replaceAll("-","") + ".xlsx");
+		Workbook workbook = WorkbookFactory.create(file.getInputStream());
+		workbook.write(Files.newOutputStream(excel.toPath()));
+
+		List<String> errList = new ArrayList<>();
+//		Map<String, List<Map<String, Object>>> sheetsListMap = POIUtil.importExcel(new ByteArrayInputStream(file.getBytes()), 2, file.getOriginalFilename());
+		Map<String, List<Map<String, Object>>> sheetsListMap = POIUtil.importExcel(excel, 2);
+		excel.deleteOnExit();
+		if (sheetsListMap.values().isEmpty()) {
+			errList.add("excel未解析到数据");
+			return getExportErrLogFile(errList);
+		}
+
+		// 查询商品分类
+		GoodsCategoryQueryInfo goodsCategoryQueryInfo = new GoodsCategoryQueryInfo();
+		goodsCategoryQueryInfo.setDelFlag(YesOrNoEnum.NO);
+		goodsCategoryQueryInfo.setPage(1);
+		goodsCategoryQueryInfo.setRows(9999);
+
+
+		List<GoodsCategory> categoryList = goodsCategoryService.findAll(new HashMap<>()).stream().filter(next -> YesOrNoEnum.NO.equals(next.getDelFlag())).collect(Collectors.toList());
+		Map<String, Integer> categoryIdNameMap = categoryList
+				.stream().collect(Collectors.toMap(GoodsCategory::getName, GoodsCategory::getId));
+		Set<String> categoryNames = categoryIdNameMap.keySet();
+
+		// 查询员工机构
+		Map<String, Integer> orgNameIdMap = organizationDao.findAllOrgans(TenantContextHolder.getTenantId()).stream()
+				.collect(Collectors.toMap(Organization::getName, Organization::getId));
+
+
+		InputStream inputStream = new ClassPathResource("columnMapper.ini").getInputStream();
+		Map<String, String> columns = IniFileUtil.readIniFile(inputStream, TemplateTypeEnum.GOODS_GROUP.getMsg());
+
+		List<Map<String, Object>> firstSheet = sheetsListMap.entrySet().iterator().next().getValue();
+		List<String> skuList = firstSheet.stream().map(next -> next.get("SKU").toString()).distinct().collect(Collectors.toList());
+
+		List<PmsProductDto> subGoods;
+		try {
+			// 查询SKU对应商品
+			PmsProductQueryParamDto dto = PmsProductQueryParamDto.builder()
+					.skuStockCodes(String.join(",", skuList))
+					.pageNum(1)
+					.pageSize(9999)
+					.build();
+			dto.setJson(JSON.toJSONString(dto));
+			subGoods = new ArrayList<>(mallFeignService.getProductList(dto).getRows());
+		} catch (Exception e) {
+			errList.add("商城服务调用失败");
+			return getExportErrLogFile(errList);
+		}
+		Map<String, PmsProductDto> skuMap = new HashMap<>();
+		subGoods.forEach(next -> {
+			String key = next.getName() + "_" + next.getSkuCode();
+			if (!skuMap.containsKey(key)) { // 处理出现重复key问题
+				skuMap.put(key, next);
+			}
+		});
+
+		// excel中所有的sn
+//		List<String> snSet = firstSheet.stream().map(next -> next.get("组合商品货号").toString()).filter(StringUtils::isNotEmpty).collect(Collectors.toList());
+		// 获取重复的货号
+//		List<String> repeatSnList = snSet.stream().collect(Collectors.groupingBy(e -> e, Collectors.counting()))
+//				.entrySet().stream().filter(e -> e.getValue() > 1)
+//				.map(Map.Entry::getKey).collect(Collectors.toList());
+//		List<String> existSnList = goodsDao.findBySns(snSet.stream().distinct().collect(Collectors.toList())).stream().map(Goods::getSn).distinct().collect(Collectors.toList());
+
+		Map<String, Long> brandNameIdMap = mallFeignService.getList().stream().collect(Collectors.toMap(BrandDto::getName, BrandDto::getId));
+
+		List<JSONObject> jsonObjectList = new ArrayList<>();
+		Map<String, byte[]> snImageMap = new HashMap<>();
+		for (Map.Entry<String, List<Map<String, Object>>> sheetData : sheetsListMap.entrySet()) {
+			List<Map<String, Object>> rows = sheetData.getValue();
+			if (rows.isEmpty()) {
+				continue;
+			}
+			Map<String, Object> firstRow = rows.get(0);
+			// 缺省字段
+			Set<String> templateFields = columns.keySet();
+			List<String> defaultField = templateFields.stream().filter(next->!firstRow.containsKey(next)).collect(Collectors.toList());
+			if (!defaultField.isEmpty()) {
+				errList.add("导入字段缺省:" + String.join(",", defaultField));
+				return getExportErrLogFile(errList);
+			}
+
+			String lineErrMsg = "错误行号:第%s行,%s";
+			Map<String, Object> beforeGoods = new HashMap<>();
+			Map<String, Set<String>> snSubGoodsMap = new HashMap<>();
+			for (int i = 0; i < rows.size(); i++) {
+				JSONObject objectMap = new JSONObject();
+				int rowNum = i + 2;
+				Map<String, Object> row = rows.get(i);
+				if (row.size() == 0) {
+					continue;
+				}
+				// 新商品标志
+				String sn = row.get("组合商品货号").toString();
+				if (StringUtils.isNotEmpty(sn)) {
+					beforeGoods.clear();
+					snSubGoodsMap.clear();
+				}
+				String subGoodsName = null;
+				String subGoodsSku = null;
+				List<String> lineErrList = new ArrayList<>();
+				for (Map.Entry<String, Object> entry : row.entrySet()) {
+					String fieldName = entry.getKey();
+					if (!templateFields.contains(fieldName)) {
+						continue;
+					}
+					String fieldCode = columns.get(fieldName);
+					Object value = entry.getValue();
+
+					// 非子商品字段为空,往上一行获取值
+					if (StringUtils.isEmpty(value.toString())) {
+						if ("subGoodsName".equals(fieldCode) || "sku".equals(fieldCode) || "subGoodsPrice".equals(fieldCode)) {
+							lineErrList.add("字段‘" + fieldName + "’为空");
+						} else {
+							if (beforeGoods.containsKey(fieldCode)) {
+								value = beforeGoods.get(fieldCode);
+							} else {
+								if (!("educationShowOrganName".equals(fieldCode)
+										|| "courseFeeShowOrganName".equals(fieldCode)
+										|| "memberFeeShowOrganName".equals(fieldCode)
+										|| "freeFeeShowOrganName".equals(fieldCode)
+										|| "replacementShowOrganName".equals(fieldCode))) {
+									lineErrList.add("字段‘" + fieldName + "’为空");
+									continue;
+								}
+							}
+						}
+					} else {
+						if ("image".equals(fieldCode)) { // 图片数组 取第一个
+							if (value instanceof List) {
+								Object data = ((List<?>) value).get(0);
+								if (data instanceof PictureData) {
+									value = ((PictureData) data).getData();
+								}
+							} else if (!(value instanceof byte[])) {
+								lineErrList.add("图片格式错误");
+								continue;
+							}
+						}
+						beforeGoods.put(fieldCode, value);
+					}
+//					if ("sn".equals(fieldCode)) {
+//						if (existSnList.contains(value.toString())) {
+//							lineErrList.add("货号[" + value + "]已存在");
+//						} else {
+//							if (repeatSnList.contains(value.toString())) {
+//								lineErrList.add("货号[" + value + "]重复");
+//							}
+//						}
+//						objectMap.put(fieldCode, value);
+//					} else
+						if ("marketPrice".equals(fieldCode)
+							|| "discountPrice".equals(fieldCode)
+							|| "groupPurchasePrice".equals(fieldCode)) {
+						if (NumberUtils.isNumber(value.toString())) {
+							BigDecimal prize = new BigDecimal(value.toString());
+							if (BigDecimal.ZERO.compareTo(prize) > 0) {
+								lineErrList.add("字段‘" + fieldName + "’不能为负数");
+							} else {
+								objectMap.put(fieldCode, value);
+							}
+						} else {
+							lineErrList.add("字段‘" + fieldName + "’类型错误");
+
+						}
+					} else if ("type".equals(fieldCode)) {
+						String tempValue = value.toString();
+						Optional<GoodsType> first = Arrays.stream(GoodsType.values()).filter(next -> next.getDesc().equals(tempValue)).findFirst();
+						if (first.isPresent()) {
+							objectMap.put(fieldCode, first.get().getCode());
+						} else {
+							lineErrList.add("字段‘" + fieldName + "’类型不支持");
+						}
+					} else if ("goodsCategoryName".equals(fieldCode)) {
+						if(categoryNames.contains(value.toString())){
+							objectMap.put("goodsCategoryId", categoryIdNameMap.get(value.toString()));
+						}else {
+							lineErrList.add("字段‘" + fieldName + "’不支持");
+						}
+					} else if ("educationShowOrganName".equals(fieldCode)
+							|| "courseFeeShowOrganName".equals(fieldCode)
+							|| "memberFeeShowOrganName".equals(fieldCode)
+							|| "freeFeeShowOrganName".equals(fieldCode)
+							|| "replacementShowOrganName".equals(fieldCode)
+					) {
+						if (StringUtils.isNotEmpty(value.toString())) {
+							List<String> orgIds = new ArrayList<>();
+							for (String orgName : value.toString().split("[,,]")) {
+								if (!orgNameIdMap.containsKey(orgName)) {
+									lineErrList.add("字段‘" + fieldName + "’:‘" + value + "’分部不支持");
+								} else {
+									orgIds.add(orgNameIdMap.get(orgName).toString());
+								}
+							}
+							String join = String.join(",", orgIds);
+							String fieldKey = fieldCode.replaceAll("Name", "Id");
+							objectMap.put(fieldKey, join);
+						}
+					} else if ("subGoodsName".equals(fieldCode)) {
+						subGoodsName = value.toString();
+						if (StringUtils.isNotEmpty(subGoodsSku)) {
+							String key = subGoodsName + "_" + subGoodsSku;
+							if (skuMap.containsKey(key)) {
+								PmsProductDto dto = skuMap.get(key);
+								objectMap.put("mallGoodsId", dto.getGoodsId().intValue());
+								objectMap.put("sku", dto.getSkuStockId());
+								objectMap.put("stock", dto.getStock());
+								objectMap.put("goodsStatus", dto.getPublishStatus()==1);
+							} else {
+								lineErrList.add("子商品‘" + subGoodsName + "[" + subGoodsSku + "]’不存在");
+							}
+						}
+					} else if ("sku".equals(fieldCode)) {
+						subGoodsSku = value.toString();
+						if (StringUtils.isNotEmpty(subGoodsName)) {
+							String key = subGoodsName + "_" + subGoodsSku;
+							if (skuMap.containsKey(key)) {
+								PmsProductDto dto = skuMap.get(key);
+								objectMap.put("mallGoodsId", dto.getGoodsId().intValue());
+								objectMap.put("sku", dto.getSkuStockId());
+								objectMap.put("stock", dto.getStock());
+								objectMap.put("goodsStatus", dto.getPublishStatus()==1);
+							} else {
+								lineErrList.add("子商品‘" + subGoodsName + "[" + subGoodsSku + "]’不存在");
+							}
+						}
+					} else if ("subGoodsPrice".equals(fieldCode)) {
+						BigDecimal subGoodsPrice = new BigDecimal(value.toString());
+						if (BigDecimal.ZERO.compareTo(subGoodsPrice) > 0) {
+							lineErrList.add("字段‘" + fieldName + "’不能为负数");
+						}
+					} else if ("brand".equals(fieldCode)) {
+						if (brandNameIdMap.containsKey(value.toString())) {
+							objectMap.put("brand", brandNameIdMap.get(value.toString()));
+						} else {
+							lineErrList.add("组合商品品牌‘" + value + "’不支持");
+						}
+					}
+					else {
+						objectMap.put(fieldCode, value);
+					}
+				}
+				// 校验分部可售是否都为空
+				if (!objectMap.containsKey("educationShowOrganId") &&
+						!objectMap.containsKey("courseFeeShowOrganId") &&
+						!objectMap.containsKey("memberFeeShowOrganId") &&
+						!objectMap.containsKey("freeFeeShowOrganId") &&
+						!objectMap.containsKey("replacementShowOrganId")) {
+					lineErrList.add("可售分部至少需要填写一个");
+				}
+				// 校验子商品sku是否重复
+				String tempSn = objectMap.getOrDefault("sn", "").toString();
+				String tempSku = objectMap.getOrDefault("sku", "").toString();
+				if (StringUtils.isNotEmpty(tempSn)) {
+					byte[] images = objectMap.getBytes("image");
+					snImageMap.put(tempSn, images);
+					if (StringUtils.isNotEmpty(tempSku)) {
+						Set<String> set = snSubGoodsMap.getOrDefault(tempSn, new HashSet<>());
+						if (set.contains(tempSku)) {
+							lineErrList.add("子商品SKU重复");
+						} else {
+							set.add(tempSku);
+							snSubGoodsMap.put(tempSn, set);
+						}
+					}
+				}
+
+				if (!lineErrList.isEmpty()) {
+					errList.add(String.format(lineErrMsg, rowNum, String.join(",", lineErrList)));
+				}
+				jsonObjectList.add(objectMap);
+			}
+		}
+
+		if (jsonObjectList.isEmpty()) {
+			errList.add("未解析到数据");
+		}
+
+		if (!errList.isEmpty()) {
+			// 存在错误信息,添加错误日志文件返回
+			return getExportErrLogFile(errList);
+		}
+
+		List<GoodsWrapper.Goods> goodsList = jsonObjectList.stream().map(next -> {
+			next.remove("image");
+			String jsonString = next.toJSONString();
+			GoodsWrapper.Goods goods = JSON.parseObject(jsonString, GoodsWrapper.Goods.class);
+			goods.setSellCount(0);
+			GoodsWrapper.GoodsSub goodsSub = JSON.parseObject(jsonString, GoodsWrapper.GoodsSub.class);
+			ArrayList<GoodsWrapper.GoodsSub> arrayList = new ArrayList<>();
+			arrayList.add(goodsSub);
+			goods.setGoodsSubList(arrayList);
+			return goods;
+		}).collect(Collectors.toList());
+
+		Map<String, List<GoodsWrapper.Goods>> goodsGroup = goodsList.stream().collect(Collectors.groupingBy(next -> next.getName() + "_" + next.getSn()));
+//
+//
+//		// 数据合并
+		Map<Integer, Integer> skuIdMap = subGoods.stream().collect(Collectors.toMap(PmsProductDto::getSkuStockId, PmsProductDto::getStock));
+
+		for (Map.Entry<String, List<GoodsWrapper.Goods>> entry : goodsGroup.entrySet()) {
+			List<GoodsWrapper.Goods> value = entry.getValue();
+			GoodsWrapper.Goods good = value.get(0);
+			String sn = good.getSn();
+
+			// 图片上传
+			byte[] images = snImageMap.get(sn);
+			if (images != null && images.length > 0) {
+				File imgFile = createImportGoodsTempFile(UUID.randomUUID().toString().replaceAll("-","") + ".png");
+				BufferedImage read = ImageIO.read(new ByteArrayInputStream((images)));
+				ImageIO.write(read, "png", imgFile);
+				String url = ossPluginContext.getPluginService(TencentOssPlugin.PLUGIN_NAME).uploadFile("daya/" + UploadUtil.getFileFloder(), imgFile);
+				good.setImage(url);
+				imgFile.deleteOnExit();
+			}
+			List<GoodsWrapper.GoodsSub> goodsSubList = value.stream().map(GoodsWrapper.Goods::getGoodsSubList).flatMap(Collection::stream).collect(Collectors.toList());
+			Integer stock = goodsSubList.stream().map(next -> skuIdMap.get(next.getSku())).min(Integer::compareTo).orElse(0);
+
+			Goods goods = JSON.parseObject(JSON.toJSONString(good), Goods.class);
+			goods.setStatus(YesOrNoEnum.NO);
+			goods.setStockCount(stock);
+			goods.setGroupGoods(true);
+			this.insert(goods);
+
+			List<GoodsSub> subList = goodsSubList.stream().map(next -> {
+				GoodsSub sub = new GoodsSub();
+				sub.setGoodsId(goods.getId());
+				sub.setMallGoodsId(next.getMallGoodsId());
+				sub.setSku(next.getSku());
+				sub.setGoodsStatus(next.getGoodsStatus());
+				sub.setGoodsPrice(next.getGoodsPrice());
+				return sub;
+			}).collect(Collectors.toList());
+            goodsSubService.saveBatch(subList);
+		}
+
+//		goodsGroup.forEach((key, value) -> {
+//			GoodsWrapper.Goods good = value.get(0);
+//			List<GoodsWrapper.GoodsSub> goodsSubList = value.stream().map(GoodsWrapper.Goods::getGoodsSubList).flatMap(Collection::stream).collect(Collectors.toList());
+//			Integer stock = goodsSubList.stream().map(next -> skuIdMap.get(next.getSku())).min(Integer::compareTo).orElse(0);
+//
+//			Goods goods = JSON.parseObject(JSON.toJSONString(good), Goods.class);
+//			goods.setStatus(YesOrNoEnum.NO);
+//			goods.setStockCount(stock);
+//			this.insert(goods);
+//
+//			List<GoodsSub> subList = goodsSubList.stream().map(next -> {
+//				GoodsSub sub = new GoodsSub();
+//				sub.setGoodsId(goods.getId());
+//				sub.setMallGoodsId(next.getMallGoodsId());
+//				sub.setSku(next.getSku());
+//				sub.setGoodsStatus(next.getGoodsStatus());
+//				sub.setGoodsPrice(next.getGoodsPrice());
+//				return sub;
+//			}).collect(Collectors.toList());
+//			goodsSubMapper.saveBatch(subList);
+//		});
+		return null;
 	}
 
 	@Override
@@ -494,7 +980,7 @@ public class GoodsServiceImpl extends BaseServiceImpl<Integer, Goods>  implement
 		}
 	}
 
-	@Override
+/*	@Override
 	@Transactional(rollbackFor = Exception.class, isolation = Isolation.READ_COMMITTED)
 	public void sellOrderBatchNoAllot(Integer tenantId) {
 		List<Integer> noneBatchNoSellOrderIds = sellOrderDao.getNoneBatchNoSellOrderIds(tenantId);
@@ -536,7 +1022,7 @@ public class GoodsServiceImpl extends BaseServiceImpl<Integer, Goods>  implement
 		if(!CollectionUtils.isEmpty(updateSellOrders)){
 			sellOrderDao.batchUpdate(updateSellOrders);
 		}
-	}
+	}*/
 
 	@Override
 	@Transactional(rollbackFor = Exception.class, isolation = Isolation.READ_COMMITTED)
@@ -546,7 +1032,37 @@ public class GoodsServiceImpl extends BaseServiceImpl<Integer, Goods>  implement
 		}
 
 		List<Goods> tempGoodsList = goodsDao.lockGoods(new ArrayList<>(goodsIds));
-		Map<Integer, Goods> idTempGoodsMap = tempGoodsList.stream().collect(Collectors.toMap(Goods::getId, g -> g));
+		PmsProductQueryParamDto paramDto = new PmsProductQueryParamDto();
+		String skuIds = goodsSubService.lambdaQuery().in(GoodsSub::getGoodsId, tempGoodsList.stream().map(Goods::getId).collect(Collectors.toList())).list()
+				.stream().map(e->e.getSku().toString()).collect(Collectors.joining(","));
+		paramDto.setSkuStockIds(skuIds);
+		PageInfo<PmsProductDto> productList = mallFeignService.getProductList(paramDto);
+		if (CollectionUtils.isEmpty(productList.getRows())) {
+			throw new BizException("商品不存在");
+		}
+		Map<Integer,PmsProductDto> skuIdProductMap = productList.getRows().stream().collect(Collectors.toMap(PmsProductDto::getSkuStockId, Function.identity()));
+		List<SellOrder> sellOrders = new ArrayList<>();
+		for (Goods goods : tempGoodsList) {
+			List<GoodsSub> goodsSubs = goodsSubService.lambdaQuery().eq(GoodsSub::getGoodsId, goods.getId()).list();
+			if(CollectionUtils.isEmpty(goodsSubs)){
+				throw new BizException("商品["+goods.getName()+"]未设置子商品");
+			}
+			for (GoodsSub goodsSub : goodsSubs) {
+				PmsProductDto productDto = skuIdProductMap.get(goodsSub.getSku());
+				if(Objects.isNull(productDto)){
+					throw new BizException("商品["+goods.getName()+"]子商品["+goodsSub.getSku()+"]不存在");
+				}
+				SellOrder sellOrder = new SellOrder();
+				sellOrder.setParentGoodsId(goods.getId());
+				sellOrder.setGoodsSkuId(goodsSub.getSku());
+				sellOrder.setNum(1);
+				sellOrder.setGoodsName(productDto.getName());
+				sellOrder.setAccountType(accountType);
+				sellOrder.setOrganSellCost(goodsSub.getGoodsPrice());
+				sellOrders.add(sellOrder);
+			}
+		}
+		/*Map<Integer, Goods> idTempGoodsMap = tempGoodsList.stream().collect(Collectors.toMap(Goods::getId, g -> g));
 		List<GoodsProcurement> goodsProcurements = new ArrayList<>();
 		for (Integer goodsId : goodsIds) {
 			Goods tempGoods = idTempGoodsMap.get(goodsId);
@@ -661,12 +1177,12 @@ public class GoodsServiceImpl extends BaseServiceImpl<Integer, Goods>  implement
 				}
 				sellOrders.add(sellOrder);
 			}
-		}
+		}*/
 
 		return sellOrders;
 	}
 
-	@Override
+/*	@Override
 	@Transactional(rollbackFor = Exception.class, isolation = Isolation.READ_COMMITTED)
 	public void increaseStock(List<SellOrder> sellOrders, AccountType accountType) {
 		if(CollectionUtils.isEmpty(sellOrders)){
@@ -700,10 +1216,10 @@ public class GoodsServiceImpl extends BaseServiceImpl<Integer, Goods>  implement
 			}
 			goods.setSellCount(new AtomicInteger(goods.getSellCount()).addAndGet(-sellOrder.getNum()));
 
-//			goodsDao.update(goods);
-//			goodsProcurementDao.update(goodsProcurement);
+			goodsDao.update(goods);
+			goodsProcurementDao.update(goodsProcurement);
 		}
-	}
+	}*/
 
 	@Override
 	public List<GoodsSellDto> queryGoodsSellDtos(String goodsId) {
@@ -711,7 +1227,7 @@ public class GoodsServiceImpl extends BaseServiceImpl<Integer, Goods>  implement
 	}
 
 	@Override
-	public Goods getDetail(Integer goodsId) {
+	public GoodsWrapper.Goods getDetail(Integer goodsId) {
 		Goods goods = goodsDao.get(goodsId);
 		if(StringUtils.isNotEmpty(goods.getStudentShowOrganId())){
 			goods.setStudentShowOrganName(StringUtils.join(organizationDao.findByOrganIds(goods.getStudentShowOrganId()),","));
@@ -731,7 +1247,14 @@ public class GoodsServiceImpl extends BaseServiceImpl<Integer, Goods>  implement
 		if(StringUtils.isNotEmpty(goods.getFreeFeeShowOrganId())){
 			goods.setFreeFeeShowOrganName(StringUtils.join(organizationDao.findByOrganIds(goods.getFreeFeeShowOrganId()),","));
 		}
-		return goods;
+		GoodsWrapper.Goods detail = JSON.parseObject(JSON.toJSONString(goods), GoodsWrapper.Goods.class);
+		detail.setGoodsSubList(queryGoodsSubByGoodId(goodsId));
+		String brand = detail.getBrand();
+		if (StringUtils.isNotEmpty(brand) && NumberUtils.isNumber(brand)) {
+			Map<Long, String> brandIdNameMap = queryGoodsBrandList().stream().collect(Collectors.toMap(BrandDto::getId, BrandDto::getName));
+			detail.setBrandName(brandIdNameMap.getOrDefault(Long.valueOf(brand), ""));
+		}
+		return detail;
 	}
 
 	@Override
@@ -744,4 +1267,248 @@ public class GoodsServiceImpl extends BaseServiceImpl<Integer, Goods>  implement
 	public int batchUpdate(List<Goods> goodsList) {
 		return goodsDao.batchUpdate(goodsList);
 	}
+
+	@Transactional(rollbackFor = Exception.class)
+	@Override
+	public void updateGoods(GoodsWrapper.Goods goods) {
+		Goods goodsInfo = goodsDao.getGoodsInfo(goods.getId());
+		if (goodsInfo == null) {
+			throw new BizException("参数错误");
+		}
+		List<GoodsWrapper.GoodsSub> goodsSubList = goods.getGoodsSubList();
+		if (StringUtils.isEmpty(goodsInfo.getComplementGoodsIdList()) && goodsSubList.isEmpty()) {
+			throw new BizException("子商品信息不能为空");
+		}
+		goodsInfo = JSON.parseObject(JSON.toJSONString(goods), Goods.class);
+		goodsInfo.setStatus(null);
+		if (!goodsSubList.isEmpty()) {
+			BigDecimal organCostPrice = goodsSubList.stream().map(GoodsWrapper.GoodsSub::getGoodsPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
+			goodsInfo.setOrganCostPrice(organCostPrice);
+
+			//获取最小的库存数
+			String skuIds = goodsSubList.stream().map(e -> e.getSku().toString()).collect(Collectors.joining(","));
+			PmsProductQueryParamDto paramDto = new PmsProductQueryParamDto();
+			paramDto.setSkuStockIds(skuIds);
+			paramDto.setPageSize(1000);
+			paramDto.setPageNum(1);
+			paramDto.setJson(JSON.toJSONString(paramDto));
+			List<PmsProductDto> productList = mallFeignService.getProductList(paramDto).getRows();
+			if(CollectionUtils.isEmpty(productList)){
+				throw new BizException("子商品不存在");
+			}
+			Map<Integer, Long> skuIdGoodIdMap = productList.stream().collect(Collectors.toMap(PmsProductDto::getSkuStockId, PmsProductDto::getGoodsId));
+
+			List<GoodsSub> goodsSubs = JSON.parseArray(JSON.toJSONString(goodsSubList), GoodsSub.class);
+			for (GoodsSub next : goodsSubs) {
+				next.setGoodsId(goods.getId());
+				if (skuIdGoodIdMap.containsKey(next.getSku())) {
+					next.setMallGoodsId(skuIdGoodIdMap.get(next.getSku()).intValue());
+				} else {
+					throw new BizException("存在删除的子商品");
+				}
+			}
+
+			UpdateWrapper<GoodsSub> delWrapper = new UpdateWrapper<>();
+			delWrapper.eq("goods_id_", goods.getId());
+			goodsSubService.getBaseMapper().delete(delWrapper);
+			goodsSubService.saveBatch(goodsSubs);
+
+			goodsInfo.setComplementGoodsIdList(null);
+			//获取最小库存数量
+			Integer stock = productList.stream().map(PmsProductDto::getStock).min(Integer::compareTo).get();
+			goodsInfo.setStockCount(stock);
+		}
+		update(goodsInfo);
+	}
+
+	@Override
+	public PageInfo<PmsProductDto> queryGoodsSubByPage(GoodsWrapper.GoodsSubQuery query) {
+		PmsProductQueryParamDto dto = PmsProductQueryParamDto.builder()
+				.publishStatus(query.getPublishStatus())
+				.keyword(query.getKeyword())
+				.productSn(query.getProductSn())
+				.productIds(query.getProductIds())
+				.productCategoryId(query.getProductCategoryId())
+				.brandId(query.getBrandId())
+				.pageNum(query.getPage())
+				.pageSize(query.getRows())
+				.build();
+		dto.setJson(JSON.toJSONString(dto));
+		return mallFeignService.getProductList(dto);
+	}
+
+	@Transactional
+	@Override
+	public Boolean goodsStatusSynchronize(List<GoodsSubModel> goodsSubModelList) {
+		if (CollectionUtils.isEmpty(goodsSubModelList)) {
+			return false;
+		}
+		log.info(Thread.currentThread().getName() + "开始同步商品状态:" + JSON.toJSONString(goodsSubModelList));
+		List<Integer> skuIds = goodsSubModelList.stream().map(GoodsSubModel::getSkuId).distinct().collect(Collectors.toList());
+		QueryWrapper<GoodsSub> queryWrapper = new QueryWrapper<>();
+		queryWrapper.in("sku_", skuIds);
+		List<GoodsSub> goodsSubs = goodsSubService.getBaseMapper().selectList(queryWrapper);
+		if (CollectionUtils.isEmpty(goodsSubs)) {
+			return true;
+		}
+		Map<Integer, Boolean> keyStatusMap = goodsSubModelList.stream().collect(Collectors.toMap(GoodsSubModel::getSkuId, GoodsSubModel::getGoodsStatus));
+		log.info(Thread.currentThread().getName() + "开始同步商品状态:0/" + goodsSubs.size());
+		List<GoodsSub> goodsSubList = goodsSubs.stream().peek(next -> next.setGoodsStatus(keyStatusMap.get(next.getSku()))).collect(Collectors.toList());
+		// 下架的商品
+		List<GoodsSub> downGoods = goodsSubList.stream().filter(next -> Boolean.FALSE.equals(next.getGoodsStatus())).collect(Collectors.toList());
+		if(!CollectionUtils.isEmpty(downGoods)){
+			List<Integer> goodIdList = downGoods.stream().map(GoodsSub::getGoodsId).distinct().collect(Collectors.toList());
+			goodsDao.updateStatus(goodIdList, false);
+		}
+		Map<Boolean, List<Integer>> listMap = goodsSubList.stream().collect(Collectors.groupingBy(GoodsSub::getGoodsStatus, Collectors.mapping(GoodsSub::getId, Collectors.toList())));
+		listMap.forEach((key, values) -> goodsSubService.getBaseMapper().updateStatus(values, key));
+		log.info(Thread.currentThread().getName() + "同步商品状态完成");
+		return true;
+	}
+
+	/**
+	 * 同步组合商品库存
+	 * @param goodsSubStockModels 商品库存信息
+	 * @return true/false
+	 */
+	@Transactional(rollbackFor = Exception.class)
+	@Override
+	public Boolean goodsStockCountSynchronize(List<GoodsSubStockModel> goodsSubStockModels) {
+		if(goodsSubStockModels.isEmpty()){
+			return false;
+		}
+		List<Integer> skus = goodsSubStockModels.stream().map(GoodsSubStockModel::getSku).distinct().collect(Collectors.toList());
+
+		QueryWrapper<GoodsSub> queryWrapper = new QueryWrapper<>();
+		queryWrapper.in("sku_", skus);
+		List<GoodsSub> goodsSubs = goodsSubService.getBaseMapper().selectList(queryWrapper);
+		if (CollectionUtils.isEmpty(goodsSubs)) {
+			return true;
+		}
+//		Map<Integer, Integer> stockMap = goodsSubStockModels.stream().collect(Collectors.toMap(GoodsSubStockModel::getSku, GoodsSubStockModel::getStock));
+		List<Integer> goodIds = goodsSubs.stream().map(GoodsSub::getGoodsId).distinct().collect(Collectors.toList());
+		goodsDao.lockGoods(goodIds);
+//		List<Goods> goodsList = goodsDao.findGoodsByIds(goodIds.stream().map(String::valueOf).collect(Collectors.joining(",")));
+//		Map<Integer, Integer> goodStockMap = goodsList.stream().collect(Collectors.toMap(Goods::getId, Goods::getStockCount));
+
+		queryWrapper = new QueryWrapper<>();
+		queryWrapper.in("goods_id_", goodIds);
+		List<GoodsSub> allGoodsSubs = goodsSubService.getBaseMapper().selectList(queryWrapper);
+		List<String> allSkuIdList = allGoodsSubs.stream().map(next -> next.getSku().toString()).distinct().collect(Collectors.toList());
+		PmsProductQueryParamDto dto = new PmsProductQueryParamDto();
+		dto.setSkuStockIds(String.join(",", allSkuIdList));
+		dto.setPageNum(1);
+		dto.setPageSize(9999);
+		dto.setJson(JSON.toJSONString(dto));
+		Map<Integer, Integer> skuStockMap = mallFeignService.getProductList(dto).getRows().stream().collect(Collectors.toMap(PmsProductDto::getSkuStockId, PmsProductDto::getStock));
+		goodsSubStockModels.forEach(next-> skuStockMap.put(next.getSku(),next.getStock()));
+
+		Map<Integer, List<GoodsSub>> collect = allGoodsSubs.stream().collect(Collectors.groupingBy(GoodsSub::getGoodsId));
+
+		List<Goods> collect1 = collect.entrySet().stream().map(next -> {
+			Goods goods = new Goods();
+			goods.setId(next.getKey());
+			Integer minStock = next.getValue().stream().map(o -> skuStockMap.getOrDefault(o.getSku(), 0)).min(Integer::compareTo).get();
+			goods.setStockCount(minStock);
+			return goods;
+		}).collect(Collectors.toList());
+
+
+//		List<Goods> updateGoods = new ArrayList<>();
+//		for (GoodsSub goodsSub : goodsSubs) {
+//			Integer goodsId = goodsSub.getGoodsId();
+//			Integer stock = stockMap.get(goodsSub.getSku());
+//			int updateStock = Math.min(goodStockMap.get(goodsId), stock);
+//
+//			Goods goods = new Goods();
+//			goods.setId(goodsId);
+//			goods.setStockCount(updateStock);
+//			updateGoods.add(goods);
+//		}
+		// 处理同一个商品,多个子商品同时更新库存,取最小的库存
+//		Map<Integer, Optional<Goods>> collect = updateGoods.stream().collect(Collectors.groupingBy(Goods::getId, Collectors.minBy(Comparator.comparingInt(Goods::getStockCount))));
+//		List<Goods> collect1 = collect2.entrySet().stream().map(next -> {
+//			if (next.getValue().isPresent()) {
+//				Goods goods = new Goods();
+//				goods.setId(next.getKey());
+//				goods.setStockCount(next.getValue().get().getStockCount());
+//				return goods;
+//			}
+//			return null;
+//		}).filter(Objects::nonNull).collect(Collectors.toList());
+		goodsDao.updateStock(collect1);
+		return true;
+	}
+
+	@Override
+	public List<ProductAttributeCategoryDto> queryGoodsTypeList() {
+		return mallFeignService.getProductAttributeCategoryList();
+	}
+
+	@Override
+	public List<BrandDto> queryGoodsBrandList() {
+		return mallFeignService.getList();
+	}
+
+	@Override
+	public List<ProductCategoryDto> queryGoodsCategoryList() {
+		return mallFeignService.listWithChildren();
+	}
+
+	private File createImportGoodsTempFile(String fileName) {
+		String basePath = new ApplicationHome(this.getClass()).getSource().getParentFile().getPath();
+		File file = new File(basePath + File.separator + "daya" + File.separator + "importGoods" + File.separator + fileName);
+		try {
+			if (!file.getParentFile().exists()) {
+				file.getParentFile().mkdirs();
+			}
+			file.createNewFile();
+			return file;
+		} catch (IOException e) {
+			throw new BizException("导入失败,回执文件上传失败");
+		}
+	}
+
+	private String getExportErrLogFile(List<String> errList) {
+		if (CollectionUtils.isEmpty(errList)) {
+			return null;
+		}
+
+		String format = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
+		File file = createImportGoodsTempFile("商品导入回执" + format + ".csv");
+		try {
+			FileOutputStream out = new FileOutputStream(file);
+			byte[] uft8bom = {(byte) 0xef, (byte) 0xbb, (byte) 0xbf}; // 处理乱码
+			out.write(uft8bom);
+			BufferedWriter csvFileOutputStream = new BufferedWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8));
+
+			for (String errMsg : errList) {
+				csvFileOutputStream.write(errMsg);
+				csvFileOutputStream.newLine();
+			}
+			csvFileOutputStream.flush();
+			csvFileOutputStream.close();
+			String folder = "daya/download/" + UploadUtil.getFileFloder();
+			return ossPluginContext.getPluginService(TencentOssPlugin.PLUGIN_NAME).uploadFile(folder, file);
+		} catch (IOException e) {
+			log.error("上传错误回执文件失败:{}",e.getMessage());
+		} finally {
+			if (file.exists()) {
+				file.deleteOnExit();
+			}
+		}
+		return "";
+	}
+
+    @Override
+    public Map<String,String> getBrandMap(){
+
+        try {
+            return mallFeignService.getList().stream().collect(Collectors.toMap(o ->o.getId().toString(), BrandDto::getName));
+
+        }catch (Exception e){
+            log.error("获取品牌信息失败",e);
+        }
+        return new HashMap<>();
+    }
 }

+ 23 - 0
mec-biz/src/main/java/com/ym/mec/biz/service/impl/GoodsSubServiceImpl.java

@@ -0,0 +1,23 @@
+package com.ym.mec.biz.service.impl;
+
+import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
+import com.ym.mec.biz.dal.entity.GoodsSub;
+import com.ym.mec.biz.dal.mapper.GoodsSubMapper;
+import com.ym.mec.biz.service.GoodsSubService;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+
+/**
+ * 组合商品,子商品信息
+ * 2024-02-26 15:42:42
+ */
+@Slf4j
+@Service
+public class GoodsSubServiceImpl extends ServiceImpl<GoodsSubMapper, GoodsSub> implements GoodsSubService {
+
+    @Override
+    public GoodsSubMapper getBaseMapper() {
+        return baseMapper;
+    }
+
+}

+ 54 - 3
mec-biz/src/main/java/com/ym/mec/biz/service/impl/MusicGroupCalenderRefundPeriodServiceImpl.java

@@ -4,12 +4,12 @@ import com.ym.mec.biz.dal.dao.MusicGroupCalenderRefundPeriodDao;
 import com.ym.mec.biz.dal.dao.MusicGroupDao;
 import com.ym.mec.biz.dal.dao.TeacherDao;
 import com.ym.mec.biz.dal.dto.CooperationCalenderRefundDto;
+import com.ym.mec.biz.dal.dto.CooperationCalenderRefundUpdateDto;
 import com.ym.mec.biz.dal.dto.CooperationRefundDto;
 import com.ym.mec.biz.dal.dto.MusicGroupPaymentBaseCalender;
-import com.ym.mec.biz.dal.entity.MusicGroup;
-import com.ym.mec.biz.dal.entity.MusicGroupCalenderRefundPeriod;
+import com.ym.mec.biz.dal.entity.*;
 import com.ym.mec.biz.dal.page.CooperationRefundQueryInfo;
-import com.ym.mec.biz.service.MusicGroupCalenderRefundPeriodService;
+import com.ym.mec.biz.service.*;
 import com.ym.mec.common.dal.BaseDAO;
 import com.ym.mec.common.exception.BizException;
 import com.ym.mec.common.page.PageInfo;
@@ -36,6 +36,12 @@ public class MusicGroupCalenderRefundPeriodServiceImpl extends BaseServiceImpl<I
     private MusicGroupDao musicGroupDao;
     @Autowired
     private TeacherDao teacherDao;
+    @Autowired
+    private SellOrderService sellOrderService;
+    @Autowired
+    private MusicGroupPaymentCalenderAddressService musicGroupPaymentCalenderAddressService;
+    @Autowired
+    private StudentPaymentOrderService studentPaymentOrderService;
 
     @Override
     public BaseDAO<Integer, MusicGroupCalenderRefundPeriod> getDAO() {
@@ -188,4 +194,49 @@ public class MusicGroupCalenderRefundPeriodServiceImpl extends BaseServiceImpl<I
         }
         return false;
     }
+
+    @Override
+    public void batchUpdate(List<CooperationCalenderRefundUpdateDto> refundPeriods) {
+        List<Integer> periodsIds = refundPeriods.stream().map(e -> e.getId()).collect(Collectors.toList());
+        List<MusicGroupCalenderRefundPeriod> periods = musicGroupCalenderRefundPeriodDao.queryByIds(periodsIds);
+        BigDecimal originalAmount = periods.stream().map(e -> e.getRefundAmount()).reduce(BigDecimal.ZERO, BigDecimal::add);
+        Map<Integer, CooperationCalenderRefundUpdateDto> periodMap = refundPeriods.stream().collect(Collectors.toMap(e -> e.getId(), e -> e));
+        periods.forEach(e->{
+            CooperationCalenderRefundUpdateDto dto = periodMap.get(e.getId());
+            e.setRefundAmount(dto.getRefundAmount());
+            e.setMemo(dto.getMemo());
+            e.setRefundDate(dto.getRefundDate());
+            e.setResponsiblePerson(dto.getResponsiblePerson());
+            if (e.getRefundAmount().compareTo(e.getIncome()) <= 0) {
+                e.setSubRefundAmount(BigDecimal.ZERO);
+                e.setRefundFlag(true);
+            } else {
+                e.setSubRefundAmount(e.getRefundAmount().subtract(e.getIncome()));
+                e.setRefundFlag(false);
+            }
+        });
+        musicGroupCalenderRefundPeriodDao.batchUpdate(periods);
+        BigDecimal currentAmount = periods.stream().map(e -> e.getRefundAmount()).reduce(BigDecimal.ZERO, BigDecimal::add);
+        if(originalAmount.compareTo(currentAmount) != 0){
+            //变更订单信息
+            Long calenderId = periods.get(0).getCalenderId();
+            MusicGroupPaymentCalenderAddress address =
+                    musicGroupPaymentCalenderAddressService.lambdaQuery().eq(MusicGroupPaymentCalenderAddress::getCalenderId, calenderId).one();
+            if(Objects.isNull(address)){
+                return;
+            }
+            StudentPaymentOrder order = studentPaymentOrderService.findOrderByOrderNo(address.getOrderNo());
+            if (Objects.isNull(order)) {
+                return;
+            }
+            order.setExpectAmount(currentAmount);
+            order.setActualAmount(currentAmount);
+            studentPaymentOrderService.update(order);
+            List<SellOrder> orderSellOrder = sellOrderService.getDao().getOrderSellOrder(order.getId());
+            if (CollectionUtils.isEmpty(orderSellOrder)) {
+                return;
+            }
+            sellOrderService.updateSellOrder(orderSellOrder,order);
+        }
+    }
 }

+ 22 - 0
mec-biz/src/main/java/com/ym/mec/biz/service/impl/MusicGroupPaymentCalenderAddressServiceImpl.java

@@ -0,0 +1,22 @@
+package com.ym.mec.biz.service.impl;
+
+import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
+import com.ym.mec.biz.dal.dao.MusicGroupPaymentCalenderAddressDao;
+import com.ym.mec.biz.dal.entity.MusicGroupPaymentCalenderAddress;
+import com.ym.mec.biz.service.MusicGroupPaymentCalenderAddressService;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Service;
+
+@Service("musicGroupPaymentCalenderAddressService")
+public class MusicGroupPaymentCalenderAddressServiceImpl extends ServiceImpl<MusicGroupPaymentCalenderAddressDao, MusicGroupPaymentCalenderAddress> implements MusicGroupPaymentCalenderAddressService {
+
+    private final static Logger log = LoggerFactory.getLogger(MusicGroupPaymentCalenderAddressServiceImpl.class);
+
+    @Override
+    public MusicGroupPaymentCalenderAddressDao getDao() {
+        return this.baseMapper;
+    }
+
+}
+

+ 80 - 0
mec-biz/src/main/java/com/ym/mec/biz/service/impl/MusicGroupPaymentCalenderGoodsServiceImpl.java

@@ -0,0 +1,80 @@
+package com.ym.mec.biz.service.impl;
+
+import com.alibaba.fastjson.JSONObject;
+import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
+import com.ym.mec.biz.dal.dao.GoodsDao;
+import com.ym.mec.biz.dal.dao.MusicGroupPaymentCalenderGoodsDao;
+import com.ym.mec.biz.dal.dto.MusicGroupPaymentBaseCalender;
+import com.ym.mec.biz.dal.entity.*;
+import com.ym.mec.biz.service.GoodsService;
+import com.ym.mec.biz.service.MusicGroupPaymentCalenderBaseService;
+import com.ym.mec.biz.service.MusicGroupPaymentCalenderGoodsService;
+import org.apache.commons.collections.CollectionUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+import java.math.BigDecimal;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+@Service("musicGroupPaymentCalenderGoodsService")
+public class MusicGroupPaymentCalenderGoodsServiceImpl extends ServiceImpl<MusicGroupPaymentCalenderGoodsDao, MusicGroupPaymentCalenderGoods>
+        implements MusicGroupPaymentCalenderGoodsService, MusicGroupPaymentCalenderBaseService<MusicGroupPaymentCalenderGoods> {
+
+    private final static Logger log = LoggerFactory.getLogger(MusicGroupPaymentCalenderGoodsServiceImpl.class);
+
+    @Override
+    public MusicGroupPaymentCalenderGoodsDao getDao() {
+        return this.baseMapper;
+    }
+
+    @Autowired
+    private GoodsDao goodsDao;
+
+    @Override
+    public MusicGroupPaymentCalender.PaymentCalenderStatusEnum checkComponentAmount(MusicGroupPaymentBaseCalender baseCalender) {
+        return null;
+    }
+
+    @Override
+    public BigDecimal getActualAmount(MusicGroupPaymentBaseCalender baseCalender) {
+        List<MusicGroupPaymentCalenderGoods> goodsList = baseCalender.getCalenderGoodsList();
+        if(CollectionUtils.isNotEmpty(goodsList)){
+            //计算现价
+            return JSONObject.parseObject(baseCalender.getCalenderFeeJson()).getBigDecimal("allTotal");
+        }
+        return BigDecimal.ZERO;
+    }
+
+    @Override
+    public BigDecimal getOriginalAmount(MusicGroupPaymentBaseCalender musicGroupPaymentBaseCalender) {
+        List<MusicGroupPaymentCalenderGoods> goodsList = musicGroupPaymentBaseCalender.getCalenderGoodsList();
+        if(CollectionUtils.isNotEmpty(goodsList)){
+            List<Integer> goodsIds = goodsList.stream().map(e -> e.getGoodsId()).collect(Collectors.toList());
+            List<Goods> goodies = goodsDao.getGoodies(goodsIds);
+            Map<Integer,Goods> goodsMap = goodies.stream().collect(Collectors.toMap(Goods::getId, e -> e));
+            //计算原价
+            return goodsList.stream().map(e -> {
+                Goods goods = goodsMap.get(e.getGoodsId());
+                return goods.getDiscountPrice().multiply(new BigDecimal(e.getNum()));
+            }).reduce(BigDecimal.ZERO,BigDecimal::add);
+        }
+        return BigDecimal.ZERO;
+    }
+
+    @Override
+    public BigDecimal getCurrentAmount(MusicGroupPaymentBaseCalender baseCalender) {
+        return getOriginalAmount(baseCalender);
+    }
+
+    @Override
+    public <E> E initBean(E bean) {
+        return null;
+    }
+
+}
+

+ 28 - 4
mec-biz/src/main/java/com/ym/mec/biz/service/impl/MusicGroupPaymentCalenderRepairServiceImpl.java

@@ -2,22 +2,27 @@ package com.ym.mec.biz.service.impl;
 
 import com.ym.mec.biz.dal.dao.MusicGroupPaymentCalenderRepairDao;
 import com.ym.mec.biz.dal.dto.MusicGroupPaymentBaseCalender;
+import com.ym.mec.biz.dal.dto.WaitSendMessageDto;
 import com.ym.mec.biz.dal.entity.MusicGroupPaymentCalender;
 import com.ym.mec.biz.dal.entity.MusicGroupPaymentCalenderRepair;
 import com.ym.mec.biz.dal.enums.CalenderBaseServiceEnum;
-import com.ym.mec.biz.service.MusicGroupPaymentCalenderBaseService;
-import com.ym.mec.biz.service.MusicGroupPaymentCalenderRepairService;
-import com.ym.mec.biz.service.SysConfigService;
-import com.ym.mec.biz.service.SysTenantConfigService;
+import com.ym.mec.biz.dal.enums.MessageTypeEnum;
+import com.ym.mec.biz.service.*;
 import com.ym.mec.common.dal.BaseDAO;
 import com.ym.mec.common.exception.BizException;
 import com.ym.mec.common.service.impl.BaseServiceImpl;
 import com.ym.mec.common.tenant.TenantContextHolder;
+import com.ym.mec.thirdparty.message.MessageSenderPluginContext;
+import org.apache.commons.collections.CollectionUtils;
 import org.apache.commons.lang3.StringUtils;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
 
 import java.math.BigDecimal;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
 
 import static com.ym.mec.biz.dal.entity.MusicGroupPaymentCalender.PaymentCalenderStatusEnum.AUDITING;
 import static com.ym.mec.biz.dal.entity.MusicGroupPaymentCalender.PaymentCalenderStatusEnum.NO;
@@ -36,6 +41,8 @@ public class MusicGroupPaymentCalenderRepairServiceImpl extends BaseServiceImpl<
 
     @Autowired
     private SysTenantConfigService sysTenantConfigService;
+    @Autowired
+    private SysMessageService sysMessageService;
 
     public MusicGroupPaymentCalenderRepairServiceImpl() {
         MusicGroupPaymentCalenderBaseService.calenderBaseServiceMap.put(CalenderBaseServiceEnum.MUSIC_REPAIR,this);
@@ -93,6 +100,23 @@ public class MusicGroupPaymentCalenderRepairServiceImpl extends BaseServiceImpl<
         return musicGroupPaymentCalenderRepairDao.findByCalenderId(calenderId);
     }
 
+    @Override
+    public void pushWaitSendMessageTask() {
+        //获取截止回款日期还未回款的数据
+        List<WaitSendMessageDto> messageDtos = musicGroupPaymentCalenderRepairDao.queryWaitSendMessage();
+        if (CollectionUtils.isNotEmpty(messageDtos)) {
+            for (WaitSendMessageDto messageDto : messageDtos) {
+                //发送消息
+                Map<Integer, String> receivers = new HashMap<>(1);
+                receivers.put(messageDto.getUserId(), messageDto.getPhone());
+                sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.AWSMS,
+                        MessageTypeEnum.SMS_WAIT_REMINDER_PAYMENT, receivers, null, 0, null, null,messageDto.getSchoolName(),messageDto.getBatchNo());
+            }
+            List<Integer> ids = messageDtos.stream().map(e -> e.getId()).collect(Collectors.toList());
+            musicGroupPaymentCalenderRepairDao.updateSendRemind(ids);
+        }
+    }
+
     private BigDecimal getAmount(MusicGroupPaymentBaseCalender baseCalender,String configName){
         MusicGroupPaymentCalenderRepair musicRepair = baseCalender.getMusicRepair();
         if(musicRepair != null){

+ 373 - 39
mec-biz/src/main/java/com/ym/mec/biz/service/impl/MusicGroupPaymentCalenderServiceImpl.java

@@ -2,7 +2,6 @@ package com.ym.mec.biz.service.impl;
 
 import com.alibaba.fastjson.JSON;
 import com.alibaba.fastjson.JSONObject;
-import com.ym.mec.auth.api.client.SysUserFeignService;
 import com.ym.mec.auth.api.entity.SysUser;
 import com.ym.mec.biz.dal.dao.*;
 import com.ym.mec.biz.dal.dto.*;
@@ -15,35 +14,36 @@ import com.ym.mec.biz.dal.entity.MusicGroupStudentFee.PaymentStatus;
 import com.ym.mec.biz.dal.enums.*;
 import com.ym.mec.biz.dal.page.BaseOrganQueryInfo;
 import com.ym.mec.biz.dal.page.MusicGroupPaymentCalenderQueryInfo;
+import com.ym.mec.biz.dal.wrapper.MusicGroupCalenderRefundPeriodWrapper;
+import com.ym.mec.biz.dal.wrapper.MusicGroupPaymentCalenderAddressWrapper;
 import com.ym.mec.biz.event.source.GroupEventSource;
 import com.ym.mec.biz.event.source.SendSeoMessageSource;
 import com.ym.mec.biz.service.*;
+import com.ym.mec.common.api.CommonResult;
 import com.ym.mec.common.controller.BaseController;
 import com.ym.mec.common.dal.BaseDAO;
+import com.ym.mec.common.dto.OrderCreate;
 import com.ym.mec.common.entity.HttpResponseResult;
 import com.ym.mec.common.exception.BizException;
 import com.ym.mec.common.page.PageInfo;
+import com.ym.mec.common.page.WrapperUtil;
 import com.ym.mec.common.service.IdGeneratorService;
 import com.ym.mec.common.service.impl.BaseServiceImpl;
 import com.ym.mec.common.tenant.TenantContextHolder;
+import com.ym.mec.mall.MallFeignService;
 import com.ym.mec.thirdparty.message.MessageSenderPluginContext;
 import com.ym.mec.util.collection.MapUtil;
-import com.ym.mec.util.excel.POIUtil;
-import com.ym.mec.util.ini.IniFileUtil;
 import org.apache.commons.collections.CollectionUtils;
 import org.apache.commons.lang3.StringUtils;
 import org.springframework.beans.BeanUtils;
 import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.core.io.ClassPathResource;
 import org.springframework.stereotype.Service;
 import org.springframework.transaction.annotation.Isolation;
 import org.springframework.transaction.annotation.Transactional;
 import org.springframework.ui.ModelMap;
-import org.springframework.web.multipart.MultipartFile;
 
-import java.io.ByteArrayInputStream;
-import java.io.InputStream;
 import java.math.BigDecimal;
+import java.math.RoundingMode;
 import java.util.*;
 import java.util.concurrent.CompletableFuture;
 import java.util.concurrent.ExecutorService;
@@ -112,6 +112,10 @@ public class MusicGroupPaymentCalenderServiceImpl extends BaseServiceImpl<Long,
     @Autowired
     private CloudTeacherOrderService cloudTeacherOrderService;
     @Autowired
+    private MusicGroupPaymentCalenderAddressService musicGroupPaymentCalenderAddressService;
+    @Autowired
+    private MusicGroupPaymentCalenderGoodsServiceImpl musicGroupPaymentCalenderGoodsService;
+    @Autowired
     private MusicGroupPaymentCalenderActivityServiceImpl musicGroupPaymentCalenderActivityService;
     @Autowired
     private MusicGroupPaymentCalenderMemberServiceImpl musicGroupPaymentCalenderMemberService;
@@ -135,9 +139,20 @@ public class MusicGroupPaymentCalenderServiceImpl extends BaseServiceImpl<Long,
     private ImGroupMemberService imGroupMemberService;
     @Autowired
     private MemberFeeSettingService memberFeeSettingService;
-
     @Autowired
     private CloudCoachPaymentProgramDao cloudCoachPaymentProgramDao;
+    @Autowired
+    private MallFeignService mallFeignService;
+    @Autowired
+    private StudentPaymentRouteOrderService studentPaymentRouteOrderService;
+    @Autowired
+    private GoodsSubService goodsSubService;
+    @Autowired
+    private GoodsDao goodsDao;
+    @Autowired
+    private SellOrderService sellOrderService;
+    @Autowired
+    private SysAreaService sysAreaService;
 
     @Override
     public BaseDAO<Long, MusicGroupPaymentCalender> getDAO() {
@@ -253,34 +268,41 @@ public class MusicGroupPaymentCalenderServiceImpl extends BaseServiceImpl<Long,
 
         SysUser sysUser = sysUserService.getUser();
 
-        // 不是进行中,只能创建一次缴费
-        if (musicGroup.getStatus() != MusicGroupStatusEnum.PROGRESS) {
-            List<MusicGroupPaymentCalender> list = musicGroupPaymentCalenderDao.findByMusicGroupId(musicGroupId);
-            if (list.size() > 0) {
-                throw new BizException("创建失败,已经存在缴费信息");
-            }
-        }
         //进行中加学员拓展信息
         CalenderAddStudent calenderAddStudent = musicGroupPaymentBaseCalender.getCalenderAddStudent();
         MusicGroupPaymentCalender musicGroupPaymentCalender = new MusicGroupPaymentCalender();
         BeanUtils.copyProperties(musicGroupPaymentBaseCalender,musicGroupPaymentCalender);
-        //判断缴费项目类型
-        if (musicGroup.getStatus() == MusicGroupStatusEnum.DRAFT || musicGroup.getStatus() == MusicGroupStatusEnum.AUDIT_FAILED || musicGroup.getStatus() == MusicGroupStatusEnum.FEE_AUDIT_FAILED) {
-            musicGroupPaymentCalender.setPaymentType(MUSIC_APPLY);
-        } else {
-            if (calenderAddStudent != null && calenderAddStudent.getStudentIds() != null) {
-                musicGroupPaymentCalender.setPaymentType(ADD_STUDENT);
-                //预计缴费人数
-                musicGroupPaymentCalender.setAttribute1(calenderAddStudent.getClassGroupIds());
-                musicGroupPaymentCalender.setStudentIds(calenderAddStudent.getStudentIds().toString());
-                musicGroupPaymentCalender.setExpectNum(1);
-                //校验是否可以加学员
-                checkAddStudent(calenderAddStudent, musicGroup);
+        if(musicGroupPaymentBaseCalender.getCalenderGoodsList() != null){
+            musicGroupPaymentCalender.setPaymentType(GOODS_PURCHASE);
+            musicGroupPaymentCalender.setPayUserType(SCHOOL);
+        }else {
+            //判断缴费项目类型
+            if (musicGroup.getStatus() == MusicGroupStatusEnum.DRAFT || musicGroup.getStatus() == MusicGroupStatusEnum.AUDIT_FAILED || musicGroup.getStatus() == MusicGroupStatusEnum.FEE_AUDIT_FAILED) {
+                musicGroupPaymentCalender.setPaymentType(MUSIC_APPLY);
             } else {
-                if (musicGroupPaymentBaseCalender.getMusicGroupOrganizationCourseSettingId() != null) {
-                    musicGroupPaymentCalender.setPaymentType(MUSIC_RENEW);
+                if (calenderAddStudent != null && calenderAddStudent.getStudentIds() != null) {
+                    musicGroupPaymentCalender.setPaymentType(ADD_STUDENT);
+                    //预计缴费人数
+                    musicGroupPaymentCalender.setAttribute1(calenderAddStudent.getClassGroupIds());
+                    musicGroupPaymentCalender.setStudentIds(calenderAddStudent.getStudentIds().toString());
+                    musicGroupPaymentCalender.setExpectNum(1);
+                    //校验是否可以加学员
+                    checkAddStudent(calenderAddStudent, musicGroup);
                 } else {
-                    musicGroupPaymentCalender.setPaymentType(ADD_COURSE);
+                    if (musicGroupPaymentBaseCalender.getMusicGroupOrganizationCourseSettingId() != null) {
+                        musicGroupPaymentCalender.setPaymentType(MUSIC_RENEW);
+                    } else {
+                        musicGroupPaymentCalender.setPaymentType(ADD_COURSE);
+                    }
+                }
+            }
+            // 不是进行中,只能创建一次缴费
+            if (musicGroup.getStatus() != MusicGroupStatusEnum.PROGRESS && musicGroupPaymentCalender.getPaymentType() != GOODS_PURCHASE) {
+                List<MusicGroupPaymentCalender> list = musicGroupPaymentCalenderDao.findByMusicGroupId(musicGroupId);
+                //排除商品采购
+                List<MusicGroupPaymentCalender> collect = list.stream().filter(e -> e.getPaymentType() != GOODS_PURCHASE).collect(Collectors.toList());
+                if (collect.size() > 0) {
+                    throw new BizException("创建失败,已经存在缴费信息");
                 }
             }
         }
@@ -291,9 +313,11 @@ public class MusicGroupPaymentCalenderServiceImpl extends BaseServiceImpl<Long,
         BigDecimal memberOriginalAmount = musicGroupPaymentCalenderMemberService.getOriginalAmount(musicGroupPaymentBaseCalender);
         BigDecimal repairOriginalAmount = musicGroupPaymentCalenderRepairService.getOriginalAmount(musicGroupPaymentBaseCalender);
         BigDecimal activityOriginalAmount = musicGroupPaymentCalenderActivityService.getOriginalAmount(musicGroupPaymentBaseCalender);
+        BigDecimal goodsOriginalAmount = musicGroupPaymentCalenderGoodsService.getOriginalAmount(musicGroupPaymentBaseCalender);
 
         BigDecimal originalTotalAmount = courseOriginalAmount.add(memberOriginalAmount)
                 .add(activityOriginalAmount)
+                .add(goodsOriginalAmount)
                 .add(repairOriginalAmount).setScale(0, BigDecimal.ROUND_HALF_UP);
 
         //计算缴费项目总金额(前端录入)
@@ -301,9 +325,11 @@ public class MusicGroupPaymentCalenderServiceImpl extends BaseServiceImpl<Long,
         BigDecimal memberActualAmount = musicGroupPaymentCalenderMemberService.getActualAmount(musicGroupPaymentBaseCalender);
         BigDecimal repairActualAmount = musicGroupPaymentCalenderRepairService.getActualAmount(musicGroupPaymentBaseCalender);
         BigDecimal activityActualAmount = musicGroupPaymentCalenderActivityService.getActualAmount(musicGroupPaymentBaseCalender);
+        BigDecimal goodsActualAmount = musicGroupPaymentCalenderGoodsService.getActualAmount(musicGroupPaymentBaseCalender);
 
         BigDecimal actualTotalAmount = courseActualAmount.add(memberActualAmount)
                 .add(repairActualAmount)
+                .add(goodsActualAmount)
                 .add(activityActualAmount).setScale(0, BigDecimal.ROUND_HALF_UP);
         //标记是否云教练缴费
         if(musicGroupPaymentCalender.getPayUserType() == STUDENT && musicGroup.getCourseViewType() == CourseViewTypeEnum.MEMBER_FEE){
@@ -345,7 +371,9 @@ public class MusicGroupPaymentCalenderServiceImpl extends BaseServiceImpl<Long,
                 BigDecimal memberCurrentAmount = musicGroupPaymentCalenderMemberService.getCurrentAmount(musicGroupPaymentBaseCalender);
                 BigDecimal repairCurrentAmount = musicGroupPaymentCalenderRepairService.getCurrentAmount(musicGroupPaymentBaseCalender);
                 BigDecimal activityCurrentAmount = musicGroupPaymentCalenderActivityService.getCurrentAmount(musicGroupPaymentBaseCalender);
+                BigDecimal goodsCurrentAmount = musicGroupPaymentCalenderGoodsService.getCurrentAmount(musicGroupPaymentBaseCalender);
                 BigDecimal currentTotalAmount = courseCurrentAmount.add(memberCurrentAmount)
+                        .add(goodsCurrentAmount)
                         .add(repairCurrentAmount)
                         .add(activityCurrentAmount).setScale(0, BigDecimal.ROUND_HALF_UP);
                 status = actualTotalAmount.compareTo(currentTotalAmount) == 0 ? NO : AUDITING;
@@ -403,7 +431,7 @@ public class MusicGroupPaymentCalenderServiceImpl extends BaseServiceImpl<Long,
         }
         //保存活动缴费信息
         List<MusicGroupPaymentCalenderActivity> calenderActivityList = musicGroupPaymentBaseCalender.getCalenderActivityList();
-        if (calenderActivityList != null && calenderActivityList.size() > 0) {
+        if (CollectionUtils.isNotEmpty(calenderActivityList)) {
             musicGroupPaymentCalenderActivityService.initBean(calenderActivityList);
             musicGroupPaymentCalenderActivityService.batchInsert(musicGroupPaymentBaseCalender, calenderId);
         }
@@ -429,6 +457,32 @@ public class MusicGroupPaymentCalenderServiceImpl extends BaseServiceImpl<Long,
             musicGroupPaymentCalender.setMusicGroupPaymentCalenderCourseSettingsList(courseSettingsList);
             musicGroupPaymentCalenderCourseSettingsService.batchInsert(musicGroupPaymentCalender);
         }
+        //保存商品缴费信息
+        if (musicGroupPaymentCalender.getPaymentType() == GOODS_PURCHASE) {
+            if(CollectionUtils.isNotEmpty(musicGroupPaymentBaseCalender.getCalenderGoodsList())){
+                List<Integer> goodsIds = musicGroupPaymentBaseCalender.getCalenderGoodsList().stream().map(e -> e.getGoodsId()).collect(Collectors.toList());
+                Map<Integer, Goods> goodsMap = goodsDao.getGoodies(goodsIds).stream().collect(Collectors.toMap(Goods::getId, e -> e));
+                for (MusicGroupPaymentCalenderGoods e : musicGroupPaymentBaseCalender.getCalenderGoodsList()) {
+                    Goods goods = goodsMap.get(e.getGoodsId());
+                    e.setGoodsSn(goods.getSn());
+                    e.setTotalPrice(goods.getDiscountPrice().multiply(new BigDecimal(e.getNum())));
+                    e.setSinglePrice(goods.getDiscountPrice());
+                    e.setCalenderId(calenderId);
+                    e.setGoodsType(goods.getType().getCode());
+                    e.setGoodsName(goods.getName());
+                    List<ComplementGoodsDto> childGoods = goodsSubService.getBaseMapper().queryChildGoods(e.getGoodsId());
+                    if(CollectionUtils.isEmpty(childGoods)){
+                        throw new BizException("商品{}没有子商品",goods.getName());
+                    }
+                    e.setChildGoodsJson(JSON.toJSONString(childGoods));
+                }
+                musicGroupPaymentCalenderGoodsService.saveBatch(musicGroupPaymentBaseCalender.getCalenderGoodsList());
+            }
+            if(musicGroupPaymentBaseCalender.getCalenderAddress() != null){
+                musicGroupPaymentBaseCalender.getCalenderAddress().setCalenderId(calenderId);
+                musicGroupPaymentCalenderAddressService.save(musicGroupPaymentBaseCalender.getCalenderAddress());
+            }
+        }
 
         // 如果是报名,需要修改乐团状态
         if (musicGroupPaymentCalender.getPaymentType() == MUSIC_APPLY) {
@@ -445,7 +499,7 @@ public class MusicGroupPaymentCalenderServiceImpl extends BaseServiceImpl<Long,
         Organization organization = organizationDao.get(musicGroup.getOrganId());
         sendSeoMessageSource.sendSeoMessage(musicGroup.getOrganId(), new SysUserRoleEnum[]{ORGAN_MANAGER},
                 null, null, MessageTypeEnum.BACKSTAGE_PAYMENT_CALENDER_AUDIT, organization.getName(), musicGroup.getName());
-        
+        TenantContextHolder.setTenantId(organization.getTenantId());
         if (musicGroupPaymentCalender.getPaymentType() == PaymentType.ADD_STUDENT && musicGroupPaymentCalender.getStatus() != AUDITING ){
             addStudent(musicGroupPaymentCalender, musicGroup);
             //将0元未缴费学员缴费状态更新为已缴费
@@ -467,6 +521,7 @@ public class MusicGroupPaymentCalenderServiceImpl extends BaseServiceImpl<Long,
         }
         ModelMap map = new ModelMap(1);
         map.put("musicGroupPaymentCalenderBatchNo", batchNo);
+        TenantContextHolder.clearTenantId();
         return BaseController.succeed(map);
     }
 
@@ -481,8 +536,8 @@ public class MusicGroupPaymentCalenderServiceImpl extends BaseServiceImpl<Long,
         // 分摊总金额
         for (int i = 0; i < lastIndex; i++) {
             MusicGroupPaymentCalenderCourseSettings setting = settings.get(i);
-            BigDecimal ratio = setting.getUnitPrice().divide(totalUnitPrice, 10, BigDecimal.ROUND_HALF_UP);
-            BigDecimal itemAmount = totalAmount.multiply(ratio).setScale(2, BigDecimal.ROUND_HALF_UP);
+            BigDecimal ratio = setting.getUnitPrice().divide(totalUnitPrice, 10, RoundingMode.DOWN);
+            BigDecimal itemAmount = totalAmount.multiply(ratio).setScale(2, RoundingMode.DOWN);
             setting.setOverflowCoursePrice(itemAmount.add(setting.getOverflowCoursePrice()));
             remainingAmount = remainingAmount.subtract(itemAmount);
         }
@@ -533,6 +588,24 @@ public class MusicGroupPaymentCalenderServiceImpl extends BaseServiceImpl<Long,
         if (calenderMember != null) {
             result.put("memberPrivilegesItemList", memberRankPrivilegesService.queryByMemberRankId(calenderMember.getMemberRankSettingId()));
         }
+        //获取商品采购信息
+        result.put("goods",musicGroupPaymentCalenderGoodsService.lambdaQuery().eq(MusicGroupPaymentCalenderGoods::getCalenderId,calenderId).list());
+        MusicGroupPaymentCalenderAddress one = musicGroupPaymentCalenderAddressService.lambdaQuery().eq(MusicGroupPaymentCalenderAddress::getCalenderId, calenderId).one();
+        if(Objects.nonNull(one)){
+            MusicGroupPaymentCalenderAddressWrapper.MusicGroupPaymentCalenderAddress musicGroupPaymentCalenderAddress = JSON
+                    .parseObject(JSON.toJSONString(one), MusicGroupPaymentCalenderAddressWrapper.MusicGroupPaymentCalenderAddress.class);
+            // 查询地区信息
+            List<String> areaIds = new ArrayList<>();
+            areaIds.add(one.getProvince());
+            areaIds.add(one.getCity());
+            areaIds.add(one.getRegion());
+            areaIds = areaIds.stream().filter(StringUtils::isNotBlank).distinct().collect(Collectors.toList());
+            Map<String, String> nameMapByIds = sysAreaService.getNameMapByIds(areaIds);
+            musicGroupPaymentCalenderAddress.setProvinceName(nameMapByIds.getOrDefault(one.getProvince(),""));
+            musicGroupPaymentCalenderAddress.setCityName(nameMapByIds.getOrDefault(one.getCity(),""));
+            musicGroupPaymentCalenderAddress.setRegionName(nameMapByIds.getOrDefault(one.getRegion(),""));
+            result.put("address", musicGroupPaymentCalenderAddress);
+        }
         return result;
     }
 
@@ -553,7 +626,25 @@ public class MusicGroupPaymentCalenderServiceImpl extends BaseServiceImpl<Long,
         }
         //如果是学校缴费并且金额不为0,返回费用信息
         if (calender.getPayUserType() == SCHOOL && calender.getCurrentTotalAmount().compareTo(BigDecimal.ZERO) > 0){
-            result.put("calenderRefundPeriods",musicGroupCalenderRefundPeriodService.findByCalenderId(id));
+            List<MusicGroupCalenderRefundPeriod> list = musicGroupCalenderRefundPeriodService.findByCalenderId(id);
+            if (CollectionUtils.isEmpty(list)) {
+
+                result.put("calenderRefundPeriods", list);
+            } else {
+                List<MusicGroupCalenderRefundPeriodWrapper.MusicGroupCalenderRefundPeriod> parseArray = JSON.parseArray(JSON.toJSONString(list), MusicGroupCalenderRefundPeriodWrapper.MusicGroupCalenderRefundPeriod.class);
+
+                List<Integer> userIds = list.stream().map(o -> o.getResponsiblePerson()).filter(Objects::nonNull).distinct().collect(Collectors.toList());
+                if (CollectionUtils.isNotEmpty(userIds)) {
+                    Map<Long, SysUser> mapByIds = sysUserService.getMapByIds(userIds);
+                    parseArray.forEach(o -> {
+                        if (o.getResponsiblePerson() != null) {
+                            o.setResponsiblePersonName(mapByIds.getOrDefault(o.getResponsiblePerson().longValue(),new SysUser()).getRealName());
+                            o.setResponsiblePersonPhone(mapByIds.getOrDefault(o.getResponsiblePerson().longValue(),new SysUser()).getPhone());
+                        }
+                    });
+                }
+                result.put("calenderRefundPeriods", parseArray);
+            }
         }
 
         if (calender.getOrganId() != null) {
@@ -921,13 +1012,13 @@ public class MusicGroupPaymentCalenderServiceImpl extends BaseServiceImpl<Long,
         Date date = new Date();
         for (String batchNo : split) {
             List<MusicGroupPaymentCalender> musicGroupPaymentCalenders = musicGroupPaymentCalenderDao.findByBatchNo(batchNo);
-            if (musicGroupPaymentCalenders == null || musicGroupPaymentCalenders.size() == 0) {
+            if (CollectionUtils.isEmpty(musicGroupPaymentCalenders)) {
                 throw new BizException("缴费项目不存在");
             }
             MusicGroupPaymentCalender calender = musicGroupPaymentCalenders.get(0);
             MusicGroup musicGroup = musicGroupDao.get(calender.getMusicGroupId());
 
-            if (musicGroup.getStatus() != MusicGroupStatusEnum.PROGRESS && musicGroup.getStatus() != MusicGroupStatusEnum.FEE_AUDIT) {
+            if (musicGroup.getStatus() != MusicGroupStatusEnum.PROGRESS && musicGroup.getStatus() != MusicGroupStatusEnum.FEE_AUDIT && calender.getPaymentType() != GOODS_PURCHASE) {
                 throw new BizException("当前乐团状态不支持此操作");
             }
             
@@ -1015,6 +1106,45 @@ public class MusicGroupPaymentCalenderServiceImpl extends BaseServiceImpl<Long,
                 musicGroupPaymentCalenderDetailService.batchAdd(calender, calenderStudentDetails);
                 classGroupService.spanGroupClassAdjustPass(adjust.getMasterClassGroupId()
                         , studentIds, courseIds, classGroupStudents, allLockCourseIds, batchNo, adjust.getMasterTotalPrice());
+            } else if (calender.getPaymentType() == GOODS_PURCHASE) {
+                MusicGroupPaymentCalenderAddress address = musicGroupPaymentCalenderAddressService.lambdaQuery()
+                        .eq(MusicGroupPaymentCalenderAddress::getCalenderId, calender.getId()).one();
+                if (address == null) {
+                    throw new BizException("收货地址不存在");
+                }
+                //获取商品信息
+                List<MusicGroupPaymentCalenderGoods> goods = musicGroupPaymentCalenderGoodsService.lambdaQuery()
+                        .eq(MusicGroupPaymentCalenderGoods::getCalenderId, calender.getId()).list();
+                if (CollectionUtils.isEmpty(goods)) {
+                    throw new BizException("商品信息不存在");
+                }
+                String orderNo = "Y" + idGeneratorService.generatorId("payment");
+                //获取账期金额
+                List<MusicGroupCalenderRefundPeriod> refundPeriods = musicGroupCalenderRefundPeriodService.findByCalenderId(calender.getId());
+                BigDecimal totalAmount = refundPeriods.stream().map(e -> e.getRefundAmount()).reduce(BigDecimal.ZERO, BigDecimal::add);
+                //管乐迷应收订单创建
+                StudentPaymentOrder studentPaymentOrder = new StudentPaymentOrder();
+                studentPaymentOrder.setActualAmount(totalAmount);
+                studentPaymentOrder.setCooperationId(musicGroup.getCooperationOrganId());
+                studentPaymentOrder.setMusicGroupId(calender.getMusicGroupId());
+                studentPaymentOrder.setCalenderId(calender.getId());
+                studentPaymentOrder.setType(OrderTypeEnum.SCHOOL_GOODS_PURCHASE);
+                studentPaymentOrder.setGroupType(GroupType.OUTORDER);
+                studentPaymentOrder.setOrganId(musicGroup.getOrganId());
+                studentPaymentOrder.setRoutingOrganId(musicGroup.getOrganId());
+                studentPaymentOrder.setExpectAmount(totalAmount);
+                studentPaymentOrder.setStatus(DealStatusEnum.SUCCESS);
+                studentPaymentOrder.setCreateTime(date);
+                studentPaymentOrder.setUpdateTime(date);
+                studentPaymentOrder.setPayTime(date);
+                studentPaymentOrder.setOrderNo(orderNo);
+                studentPaymentOrderDao.insert(studentPaymentOrder);
+                //保存商品订单详情
+                this.saveSellOrder(goods, studentPaymentOrder);
+                address.setOrderNo(orderNo);
+                musicGroupPaymentCalenderAddressService.updateById(address);
+                // 同步订单到商城
+                this.syncMallOrder(address, calender, musicGroup, goods);
             }
             for (MusicGroupPaymentCalender musicGroupPaymentCalender : musicGroupPaymentCalenders) {
                 //将0元未缴费学员缴费状态更新为已缴费
@@ -1027,6 +1157,176 @@ public class MusicGroupPaymentCalenderServiceImpl extends BaseServiceImpl<Long,
         }
     }
 
+    public void saveSellOrder(List<MusicGroupPaymentCalenderGoods> goods, StudentPaymentOrder studentPaymentOrder) {
+        List<SellOrder> sellOrderList = new ArrayList<>();
+        BigDecimal originalTotalAmount = goods.stream().map(e -> e.getTotalPrice()).reduce(BigDecimal.ZERO, BigDecimal::add);
+        //获取优惠金额
+        BigDecimal totalDiscountAmount = originalTotalAmount.subtract(studentPaymentOrder.getExpectAmount());
+        //待分配优惠
+        BigDecimal waitDiscountAmount = totalDiscountAmount;
+        for (int k = 0; k < goods.size(); k++) {
+            MusicGroupPaymentCalenderGoods calenderGood = goods.get(k);
+            //获取比例
+            BigDecimal totalProportion = BigDecimal.ZERO;
+            if(studentPaymentOrder.getExpectAmount().compareTo(BigDecimal.ZERO) > 0){
+                totalProportion = calenderGood.getTotalPrice().divide(originalTotalAmount, 16, RoundingMode.DOWN);
+            }
+            //获取现价
+            BigDecimal currentTotalAmount;
+            if (k == goods.size() - 1) {
+                currentTotalAmount = calenderGood.getTotalPrice().subtract(waitDiscountAmount);
+            } else {
+                BigDecimal amount = totalDiscountAmount.multiply(totalProportion).setScale(2, RoundingMode.DOWN);
+                waitDiscountAmount = waitDiscountAmount.subtract(amount);
+                currentTotalAmount = calenderGood.getTotalPrice().subtract(amount);
+            }
+            BigDecimal subCurrentTotalAmount = currentTotalAmount;
+            //待分配金额
+            for (Integer i = 0; i < calenderGood.getNum(); i++) {
+                List<ComplementGoodsDto> goodsDtoList = JSON.parseArray(calenderGood.getChildGoodsJson(), ComplementGoodsDto.class);
+                //获取总成本
+                BigDecimal totalCostPrice = goodsDtoList.stream().map(e->e.getOrganCostPrice()).reduce(BigDecimal.ZERO, BigDecimal::add);
+                //待分配金额
+                BigDecimal totalAmount;
+                if(i == calenderGood.getNum() - 1){
+                    totalAmount = subCurrentTotalAmount;
+                }else {
+                    BigDecimal divide = currentTotalAmount.divide(new BigDecimal(calenderGood.getNum()), 2, RoundingMode.DOWN);
+                    totalAmount = divide;
+                    subCurrentTotalAmount = subCurrentTotalAmount.subtract(divide);
+                }
+                BigDecimal waitAmount = totalAmount;
+                for (int j = 0; j < goodsDtoList.size(); j++) {
+                    ComplementGoodsDto goodsDto = goodsDtoList.get(j);
+                    //获取比例
+                    BigDecimal proportion = BigDecimal.ZERO;
+                    if (totalCostPrice.compareTo(BigDecimal.ZERO) > 0) {
+                        proportion = goodsDto.getOrganCostPrice().divide(totalCostPrice, 16, RoundingMode.DOWN);
+                    }
+                    SellOrder sellOrder = new SellOrder();
+                    sellOrder.setGoodsSkuId(goodsDto.getSkuStockId());
+                    sellOrder.setOrganSellCost(goodsDto.getOrganCostPrice());
+                    sellOrder.setOrderId(studentPaymentOrder.getId());
+                    sellOrder.setType(StringUtils.endsWithIgnoreCase("INSTRUMENT", calenderGood.getGoodsType()) ? SellTypeEnum.INSTRUMENT
+                            : StringUtils.endsWithIgnoreCase("ACCESSORIES", calenderGood.getGoodsType()) ? SellTypeEnum.ACCESSORIES
+                            : StringUtils.endsWithIgnoreCase("TEACHING", calenderGood.getGoodsType()) ? SellTypeEnum.TEACHING
+                            : StringUtils.endsWithIgnoreCase("STAFF", calenderGood.getGoodsType()) ? SellTypeEnum.STAFF
+                            : SellTypeEnum.OTHER);
+                    sellOrder.setOrderNo(studentPaymentOrder.getOrderNo());
+                    if (j == goodsDtoList.size() - 1) {
+                        sellOrder.setOrderAmount(waitAmount);
+                    } else {
+                        BigDecimal amount = totalAmount.multiply(proportion).setScale(2, RoundingMode.DOWN);
+                        waitAmount = waitAmount.subtract(amount);
+                        sellOrder.setOrderAmount(amount);
+                    }
+                    sellOrder.setActualAmount(sellOrder.getOrderAmount());
+                    sellOrder.setExpectAmount(sellOrder.getOrderAmount());
+                    sellOrder.setCouponRemitAmount(BigDecimal.ZERO);
+                    sellOrder.setBalanceAmount(BigDecimal.ZERO);
+                    sellOrder.setParentGoodsId(calenderGood.getGoodsId());
+                    sellOrder.setNum(1);
+                    sellOrder.setGoodsName(calenderGood.getGoodsName());
+                    sellOrder.setAccountType(AccountType.INTERNAL);
+                    sellOrder.setCooperationOrganId(studentPaymentOrder.getCooperationId());
+                    sellOrder.setOrganId(studentPaymentOrder.getOrganId());
+                    sellOrder.setTransNo(studentPaymentOrder.getTransNo());
+                    sellOrder.setPaymentChannel(studentPaymentOrder.getPaymentChannel());
+                    sellOrder.setMerNo(studentPaymentOrder.getMerNos());
+                    sellOrder.setSellTime(studentPaymentOrder.getCreateTime());
+                    sellOrder.setTenantId(studentPaymentOrder.getTenantId());
+                    sellOrderList.add(sellOrder);
+                }
+            }
+        }
+        sellOrderService.batchInsert(sellOrderList);
+    }
+
+    public void updateSellOrder(List<SellOrder> sellOrderList, StudentPaymentOrder studentPaymentOrder) {
+        //获取总价
+        BigDecimal totalCostPrice = sellOrderList.stream().map(e->e.getExpectAmount()).reduce(BigDecimal.ZERO, BigDecimal::add);
+        //待分配金额
+        BigDecimal waitAmount = studentPaymentOrder.getExpectAmount();
+        for (int i = 0; i < sellOrderList.size(); i++) {
+            SellOrder sellOrder = sellOrderList.get(i);
+            //获取比例
+            BigDecimal proportion = BigDecimal.ZERO;
+            if (totalCostPrice.compareTo(BigDecimal.ZERO) > 0) {
+                proportion = sellOrder.getExpectAmount().divide(totalCostPrice, 16, RoundingMode.DOWN);
+            }
+            if (i == sellOrderList.size() - 1) {
+                sellOrder.setOrderAmount(waitAmount);
+            } else {
+                BigDecimal amount = studentPaymentOrder.getExpectAmount().multiply(proportion).setScale(2, RoundingMode.DOWN);
+                waitAmount = waitAmount.subtract(amount);
+                sellOrder.setOrderAmount(amount);
+            }
+            sellOrder.setActualAmount(sellOrder.getOrderAmount());
+            sellOrder.setExpectAmount(sellOrder.getOrderAmount());
+        }
+        sellOrderService.batchUpdate(sellOrderList);
+    }
+
+    public void syncMallOrder(MusicGroupPaymentCalenderAddress address, MusicGroupPaymentCalender calender,
+                              MusicGroup musicGroup, List<MusicGroupPaymentCalenderGoods> goods){
+        // 查询地区信息
+        List<String> areaIds = new ArrayList<>();
+        areaIds.add(address.getProvince());
+        areaIds.add(address.getCity());
+        areaIds.add(address.getRegion());
+        areaIds = areaIds.stream().filter(StringUtils::isNotBlank).distinct().collect(Collectors.toList());
+        Map<String, String> nameMapByIds = sysAreaService.getNameMapByIds(areaIds);
+        OrderCreate orderCreate = new OrderCreate();
+        orderCreate.setOrderNo(address.getOrderNo());
+        orderCreate.setOrchestraId(musicGroup.getId());
+        orderCreate.setMemberId(musicGroup.getCooperationOrganId().longValue());
+        orderCreate.setTotalAmount(calender.getCurrentTotalAmount());
+        orderCreate.setOrderFormType("MEC");
+        orderCreate.setPlatformType("SCHOOL");
+        orderCreate.setSourceType(2);
+        orderCreate.setReceiverName(address.getName());
+        orderCreate.setReceiverPostCode(address.getPostCode());
+        orderCreate.setReceiverPhone(address.getPhone());
+        orderCreate.setReceiverProvince(nameMapByIds.getOrDefault(address.getProvince(),""));
+        orderCreate.setReceiverCity(nameMapByIds.getOrDefault(address.getCity(),""));
+        orderCreate.setReceiverRegion(nameMapByIds.getOrDefault(address.getRegion(),""));
+        orderCreate.setReceiverDetailAddress(address.getAddress());
+        orderCreate.setStatus(1);
+        orderCreate.setPayType(4);
+        List<OrderCreate.OrderItem> orderItems = new ArrayList<>();
+        for (MusicGroupPaymentCalenderGoods e : goods) {
+            BigDecimal totalPrice = e.getTotalPrice();
+            List<ComplementGoodsDto> goodsDtoList = JSON.parseArray(e.getChildGoodsJson(), ComplementGoodsDto.class);
+            //总金额按比例分配
+            //待分配
+            BigDecimal waitRemitFee = totalPrice;
+            BigDecimal totalAmount = WrapperUtil.sumList(goodsDtoList, ComplementGoodsDto::getOrganCostPrice);
+            for (int i = 0; i < goodsDtoList.size(); i++) {
+                ComplementGoodsDto goodsDto = goodsDtoList.get(i);
+                OrderCreate.OrderItem orderItemCreate = new OrderCreate.OrderItem();
+                orderItemCreate.setProductQuantity(e.getNum());
+                orderItemCreate.setProductSkuId(goodsDto.getSkuStockId().longValue());
+                //如果是最后一件商品
+                if (i == goodsDtoList.size() - 1) {
+                    orderItemCreate.setRealAmount(waitRemitFee);
+                } else {
+                    //获取比例
+                    BigDecimal ratioAmount = goodsDto.getOrganCostPrice().divide(totalAmount, 16, RoundingMode.DOWN);
+                    //获取分配的金额
+                    BigDecimal multiply = ratioAmount.multiply(totalPrice).setScale(2, RoundingMode.DOWN);
+                    orderItemCreate.setRealAmount(multiply);
+                    waitRemitFee = waitRemitFee.subtract(multiply);
+                }
+                orderItems.add(orderItemCreate);
+            }
+        }
+        orderCreate.setOrderItemList(orderItems);
+        CommonResult<Boolean> result = mallFeignService.productOrderCreate(orderCreate);
+        if (result.getCode() != 200) {
+            throw new BizException(result.getMessage());
+        }
+    }
+
     private void createPreImGroup(MusicGroup musicGroup){
         // 创建群
         imGroupService.create(musicGroup.getId(), null, "乐团预报名", null,
@@ -1083,7 +1383,7 @@ public class MusicGroupPaymentCalenderServiceImpl extends BaseServiceImpl<Long,
             MusicGroupPaymentCalender calender = musicGroupPaymentCalenders.get(0);
 
 			MusicGroup musicGroup = musicGroupDao.get(calender.getMusicGroupId());
-            if (musicGroup.getStatus() != MusicGroupStatusEnum.PROGRESS && musicGroup.getStatus() != MusicGroupStatusEnum.FEE_AUDIT) {
+            if (musicGroup.getStatus() != MusicGroupStatusEnum.PROGRESS && musicGroup.getStatus() != MusicGroupStatusEnum.FEE_AUDIT && calender.getPaymentType() != GOODS_PURCHASE){
                 throw new BizException("当前乐团状态不支持此操作");
             }
             //如果是报名,并且所有的报名都审核通过,需要修改乐团状态
@@ -1201,7 +1501,9 @@ public class MusicGroupPaymentCalenderServiceImpl extends BaseServiceImpl<Long,
     		throw new BizException("缴费项目[{}]查询失败", calenderId);
     	}
     	
-    	if(musicGroupPaymentCalender.getStatus() != PaymentCalenderStatusEnum.DRAFT && musicGroupPaymentCalender.getStatus() != PaymentCalenderStatusEnum.REJECT){
+    	if(musicGroupPaymentCalender.getStatus() != PaymentCalenderStatusEnum.DRAFT
+                && musicGroupPaymentCalender.getStatus() != PaymentCalenderStatusEnum.REJECT
+        && musicGroupPaymentCalender.getPaymentType() != GOODS_PURCHASE){
     		throw new BizException("当前缴费项目状态不支持修改");
     	}
     	
@@ -1357,6 +1659,30 @@ public class MusicGroupPaymentCalenderServiceImpl extends BaseServiceImpl<Long,
         if (musicGroupPaymentCalenderDetailList != null && musicGroupPaymentCalenderDetailList.size() > 0) {
             throw new BizException("操作失败:缴费项目中已存在学员");
         }
+        //商品采购订单
+        MusicGroupPaymentCalenderAddress address = null;
+        if(calender.getStatus() == OPEN && calender.getPaymentType() == GOODS_PURCHASE){
+            //TODO 商品采购订单是否已经发货
+            address = musicGroupPaymentCalenderAddressService.lambdaQuery().eq(MusicGroupPaymentCalenderAddress::getCalenderId, id).one();
+            if(address != null){
+                if (address.getDeliveryFlag()) {
+                    throw new BizException("操作失败:商品采购订单已发货");
+                }
+                musicGroupPaymentCalenderAddressService.removeById(address.getId());
+                //商品采购订单是否已经录入
+                StudentPaymentRouteOrder byOrderNo = studentPaymentRouteOrderService.getDao().getByOrderNo(address.getOrderNo());
+                if (byOrderNo != null) {
+                    throw new BizException("操作失败:商品采购订单已录入");
+                }
+                //删除关联的商品采购订单
+                if(StringUtils.isNotEmpty(address.getOrderNo())){
+                    studentPaymentOrderDao.deleteByOrderNo(address.getOrderNo());
+                    sellOrderService.deleteByOrderNo(address.getOrderNo());
+                }
+            }
+            musicGroupPaymentCalenderGoodsService.lambdaUpdate().eq(MusicGroupPaymentCalenderGoods::getCalenderId,id).remove();
+        }
+
         //如果是学校缴费,删除缴费周期
         musicGroupCalenderRefundPeriodService.deleteByCalenderId(id);
         MusicGroupStudentClassAdjust adjust = musicGroupStudentClassAdjustDao.findByBatchNo(calender.getBatchNo());
@@ -1407,6 +1733,14 @@ public class MusicGroupPaymentCalenderServiceImpl extends BaseServiceImpl<Long,
                 musicGroupDao.update(musicGroup);
             }
         }
+        //商品采购订单
+        if(calender.getPaymentType() == GOODS_PURCHASE && address != null){
+            //关闭商城订单
+            CommonResult<Boolean> result = mallFeignService.productUpdateOrderStatus(address.getOrderNo(), 4);
+            if (result.getCode() != 200) {
+                throw new BizException("操作失败:关闭商城订单失败",result.getMessage());
+            }
+        }
     }
 
     @Override

+ 3 - 2
mec-biz/src/main/java/com/ym/mec/biz/service/impl/MusicGroupPaymentStudentCourseDetailServiceImpl.java

@@ -15,6 +15,7 @@ import org.springframework.stereotype.Service;
 import org.springframework.transaction.annotation.Transactional;
 
 import java.math.BigDecimal;
+import java.math.RoundingMode;
 import java.util.*;
 import java.util.stream.Collectors;
 
@@ -205,8 +206,8 @@ public class MusicGroupPaymentStudentCourseDetailServiceImpl extends BaseService
 		// 分摊总金额
 		for (int i = 0; i < lastIndex; i++) {
 			MusicGroupPaymentStudentCourseDetail courseDetail = courseDetails.get(i);
-			BigDecimal ratio = courseDetail.getCourseOriginalPrice().divide(totalUnitPrice, 10, BigDecimal.ROUND_HALF_UP);
-			BigDecimal itemAmount = totalAmount.multiply(ratio).setScale(2, BigDecimal.ROUND_HALF_UP);
+			BigDecimal ratio = courseDetail.getCourseOriginalPrice().divide(totalUnitPrice, 10, RoundingMode.DOWN);
+			BigDecimal itemAmount = totalAmount.multiply(ratio).setScale(2, RoundingMode.DOWN);
 			courseDetail.setCourseCurrentPrice(itemAmount.add(courseDetail.getCourseCurrentPrice()));
 			courseDetail.setSubCourseCurrentPrice(courseDetail.getCourseCurrentPrice());
 			remainingAmount = remainingAmount.subtract(itemAmount);

+ 1 - 1
mec-biz/src/main/java/com/ym/mec/biz/service/impl/MusicGroupServiceImpl.java

@@ -4287,7 +4287,7 @@ public class MusicGroupServiceImpl extends BaseServiceImpl<String, MusicGroup> i
                     continue;
                 }
                 JSONObject objectMap = new JSONObject();
-                valueIsNull: for (String s : row.keySet()) {
+                for (String s : row.keySet()) {
                     String columnValue = columns.get(s);
                     if (StringUtils.isEmpty(columnValue)) {
                         continue;

+ 18 - 20
mec-biz/src/main/java/com/ym/mec/biz/service/impl/PayServiceImpl.java

@@ -1,15 +1,7 @@
 package com.ym.mec.biz.service.impl;
 
 import java.math.BigDecimal;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
+import java.util.*;
 import java.util.concurrent.atomic.AtomicInteger;
 import java.util.stream.Collectors;
 
@@ -79,10 +71,6 @@ public class PayServiceImpl implements PayService {
     private SellOrderService sellOrderService;
     @Autowired
     private HfMemberDao hfMemberDao;
-    @Autowired
-    private RedisCache<String, Object> redisCache;
-    @Autowired
-    private GoodsProcurementDao goodsProcurementDao;
     
     @Autowired
     private StudentPaymentOrderDao studentPaymentOrderDao;
@@ -227,7 +215,7 @@ public class PayServiceImpl implements PayService {
         		List<StudentPaymentOrderDetail> studentPaymentOrderDetailList = studentPaymentOrderDetailService.queryOrderDetail(studentPaymentOrder.getId());
         		if (studentPaymentOrderDetailList != null && studentPaymentOrderDetailList.size() > 0) {
         			
-        			Map<Long, GoodsProcurement> goodsProcurementMap = new HashMap<Long, GoodsProcurement>();
+//        			Map<Long, GoodsProcurement> goodsProcurementMap = new HashMap<Long, GoodsProcurement>();
         			
         			String goodIds = studentPaymentOrderDetailList.stream().filter(t -> StringUtils.isNotBlank(t.getGoodsIdList())).map(StudentPaymentOrderDetail :: getGoodsIdList).collect(Collectors.joining(","));
         			if(StringUtils.isNotBlank(goodIds)){
@@ -235,7 +223,6 @@ public class PayServiceImpl implements PayService {
         				
         				Map<Integer,Goods> goodsMap = goodsList.stream().collect(Collectors.toMap(Goods :: getId, t -> t));
         				Goods goods = null;
-        				GoodsProcurement goodsProcurement = null;
         				BigDecimal totalAmout = studentPaymentOrder.getExpectAmount();
         				List<Integer> minuendStockGoodsIdList = null;
         				
@@ -259,8 +246,19 @@ public class PayServiceImpl implements PayService {
         							continue;
         						}
         						goods = goodsMap.get(Integer.parseInt(goodsIdStr));
-        						
-        						if(goods != null){
+        						if(Objects.nonNull(goods)){
+									totalGroupPurchaseAmount = totalGroupPurchaseAmount.add(goods.getGroupPurchasePrice());
+									if(batchUpdateGoodsMap.get(goods.getId()) != null){
+										goods = batchUpdateGoodsMap.get(goods.getId());
+									}
+									groupPurchaseAmount = groupPurchaseAmount.add(goods.getGroupPurchasePrice());
+//										goods.setStockCount(new AtomicInteger(goods.getStockCount()).decrementAndGet());
+									goods.setSellCount(new AtomicInteger(goods.getSellCount()).incrementAndGet());
+									goods.setUpdateTime(date);
+									batchUpdateGoodsMap.put(goods.getId(), goods);
+									minuendStockGoodsIdList.add(goods.getId());
+								}
+        						/*if(goods != null){
         							// 是否是组合商品
         							if(StringUtils.isNotBlank(goods.getComplementGoodsIdList())){
         								goodsList = goodsService.getGoodsWithLocked(goods.getComplementGoodsIdList());
@@ -323,7 +321,7 @@ public class PayServiceImpl implements PayService {
     										}
         								}
         							}
-        						}
+        						}*/
         					}
         					
 							if (groupPurchaseAmount.compareTo(BigDecimal.ZERO) > 0) {
@@ -357,9 +355,9 @@ public class PayServiceImpl implements PayService {
         				}
         			}
         			
-        			if(goodsProcurementMap.size() > 0){
+        			/*if(goodsProcurementMap.size() > 0){
         				goodsProcurementDao.batchUpdate(new ArrayList<GoodsProcurement>(goodsProcurementMap.values()));
-        			}
+        			}*/
         		}
         		
         		if(batchUpdateList.size() > 0){

+ 30 - 32
mec-biz/src/main/java/com/ym/mec/biz/service/impl/ReplacementInstrumentActivityServiceImpl.java

@@ -8,6 +8,11 @@ import java.util.List;
 import java.util.Map;
 import java.util.stream.Collectors;
 
+import com.ym.mec.biz.dal.entity.*;
+import com.ym.mec.biz.service.*;
+import com.ym.mec.common.dto.BrandDto;
+import com.ym.mec.mall.MallFeignService;
+import org.apache.commons.lang.math.NumberUtils;
 import org.apache.commons.lang3.StringUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -32,19 +37,6 @@ import com.ym.mec.biz.dal.dto.ReplacementInstrumentActivityDto;
 import com.ym.mec.biz.dal.dto.ReplacementInstrumentActivityStatDto;
 import com.ym.mec.biz.dal.dto.ReplacementInstrumentActivityStatHead;
 import com.ym.mec.biz.dal.dto.ReplacementPayDto;
-import com.ym.mec.biz.dal.entity.CooperationOrgan;
-import com.ym.mec.biz.dal.entity.Goods;
-import com.ym.mec.biz.dal.entity.QuestionnaireQuestion;
-import com.ym.mec.biz.dal.entity.QuestionnaireQuestionItem;
-import com.ym.mec.biz.dal.entity.QuestionnaireTopic;
-import com.ym.mec.biz.dal.entity.QuestionnaireUserResult;
-import com.ym.mec.biz.dal.entity.ReplacementInstrumentActivity;
-import com.ym.mec.biz.dal.entity.ReplacementInstrumentCooperation;
-import com.ym.mec.biz.dal.entity.SellOrder;
-import com.ym.mec.biz.dal.entity.Student;
-import com.ym.mec.biz.dal.entity.StudentPaymentOrder;
-import com.ym.mec.biz.dal.entity.SysUserCashAccount;
-import com.ym.mec.biz.dal.entity.SysUserCashAccountDetail;
 import com.ym.mec.biz.dal.enums.AccountType;
 import com.ym.mec.biz.dal.enums.DealStatusEnum;
 import com.ym.mec.biz.dal.enums.GoodsType;
@@ -58,19 +50,6 @@ import com.ym.mec.biz.dal.enums.QuestionnaireActiveTypeEnum;
 import com.ym.mec.biz.dal.enums.SellTypeEnum;
 import com.ym.mec.biz.dal.enums.YesOrNoEnum;
 import com.ym.mec.biz.dal.page.ReplacementInstrumentActivityQueryInfo;
-import com.ym.mec.biz.service.ContractService;
-import com.ym.mec.biz.service.CooperationOrganService;
-import com.ym.mec.biz.service.GoodsService;
-import com.ym.mec.biz.service.PayService;
-import com.ym.mec.biz.service.ReplacementInstrumentActivityService;
-import com.ym.mec.biz.service.StudentPaymentOrderService;
-import com.ym.mec.biz.service.StudentPaymentRouteOrderService;
-import com.ym.mec.biz.service.StudentService;
-import com.ym.mec.biz.service.SysCouponCodeService;
-import com.ym.mec.biz.service.SysMessageService;
-import com.ym.mec.biz.service.SysPaymentConfigService;
-import com.ym.mec.biz.service.SysUserCashAccountDetailService;
-import com.ym.mec.biz.service.SysUserCashAccountService;
 import com.ym.mec.common.dal.BaseDAO;
 import com.ym.mec.common.exception.BizException;
 import com.ym.mec.common.page.PageInfo;
@@ -80,6 +59,8 @@ import com.ym.mec.thirdparty.message.MessageSenderPluginContext;
 import com.ym.mec.util.collection.MapUtil;
 import com.ym.mec.util.http.HttpUtil;
 
+import javax.annotation.Resource;
+
 @Service
 public class ReplacementInstrumentActivityServiceImpl extends BaseServiceImpl<Integer, ReplacementInstrumentActivity> implements ReplacementInstrumentActivityService {
 
@@ -122,7 +103,7 @@ public class ReplacementInstrumentActivityServiceImpl extends BaseServiceImpl<In
     @Autowired
     private SysPaymentConfigService sysPaymentConfigService;
     @Autowired
-    private SellOrderDao sellOrderDao;
+    private SellOrderService sellOrderService;
     @Autowired
     private QuestionnaireTopicDao questionnaireTopicDao;
     @Autowired
@@ -133,6 +114,8 @@ public class ReplacementInstrumentActivityServiceImpl extends BaseServiceImpl<In
     private QuestionnaireQuestionItemDao questionnaireQuestionItemDao;
     @Autowired
     private SysCouponCodeService sysCouponCodeService;
+    @Resource
+    private MallFeignService mallFeignService;
 
     private final Logger logger = LoggerFactory.getLogger(this.getClass());
 
@@ -184,6 +167,7 @@ public class ReplacementInstrumentActivityServiceImpl extends BaseServiceImpl<In
         if (sendPush && replacementInstrumentActivity.getOpenFlag().equals(1) && replacementInstrumentActivity.getInstrumentsId() != null) {
             //换成商品列表中商品4.25
             Goods goods = goodsDao.get(replacementInstrumentActivity.getGoodsId());
+            goods.setBrand(goodsService.getBrandMap().getOrDefault(goods.getBrand(),goods.getBrand()));
             Map<Integer, String> userMap = new HashMap<>();
             Map<Integer, String> userPhoneMap = new HashMap<>();
             Integer userId = replacementInstrumentActivity.getUserId();
@@ -267,6 +251,7 @@ public class ReplacementInstrumentActivityServiceImpl extends BaseServiceImpl<In
         if (sendPush && replacementInstrumentActivity.getOpenFlag().equals(1) && replacementInstrumentActivity.getInstrumentsId() != null) {
             //换成商品列表中商品4.25
             Goods goods = goodsDao.get(replacementInstrumentActivity.getGoodsId());
+            goods.setBrand(goodsService.getBrandMap().getOrDefault(goods.getBrand(),goods.getBrand()));
             Map<Integer, String> userMap = new HashMap<>();
             Map<Integer, String> userPhoneMap = new HashMap<>();
             Integer userId = replacementInstrumentActivity.getUserId();
@@ -496,7 +481,10 @@ public class ReplacementInstrumentActivityServiceImpl extends BaseServiceImpl<In
                 sysUserCashAccountDetailService.insert(paymentDetail);
             }
             //添加sell_order
-            this.addSellOrder(studentPaymentOrder, replacementInstrumentActivity);
+//            this.addSellOrder(studentPaymentOrder, replacementInstrumentActivity);
+            List<Integer> goodsIds = new ArrayList<>();
+            goodsIds.add(replacementInstrumentActivity.getInstrumentsId());
+            sellOrderService.initSellOrder(studentPaymentOrder,null,goodsIds,null,true);
             try {
                 contractService.transferProduceContract(userId, null, studentPaymentOrder.getType());
             } catch (Exception e) {
@@ -561,11 +549,21 @@ public class ReplacementInstrumentActivityServiceImpl extends BaseServiceImpl<In
                     replacementInstrumentActivityStatDto.setBalance(activityOrders.get(0).getBalancePaymentAmount());
                 }
             }
+            List<String> brandIdList = dataList.stream().map(ReplacementInstrumentActivityStatDto::getBrand).filter(StringUtils::isNotEmpty).distinct().collect(Collectors.toList());
+            if (!brandIdList.isEmpty()) {
+                Map<Long, String> idNameMap = mallFeignService.getList().stream().collect(Collectors.toMap(BrandDto::getId, BrandDto::getName));
+                for (ReplacementInstrumentActivityStatDto statDto : dataList) {
+                    String brand = statDto.getBrand();
+                    if (StringUtils.isNotEmpty(brand) && NumberUtils.isNumber(brand)) {
+                        statDto.setBrandName(idNameMap.getOrDefault(Long.valueOf(brand), ""));
+                    }
+                }
+            }
         }
         pageInfo.setRows(dataList);
         return pageInfo;
     }
-
+/*
     private List<SellOrder> addSellOrder(StudentPaymentOrder order, ReplacementInstrumentActivity replacementInstrumentActivity) {
         if (replacementInstrumentActivity.getGoodsId() == null) {
             return null;
@@ -585,7 +583,6 @@ public class ReplacementInstrumentActivityServiceImpl extends BaseServiceImpl<In
         List<Integer> goodsIds = new ArrayList<>();
         goodsIds.add(goods.getId());
         List<SellOrder> sellOrders = goodsService.subtractStock(goodsIds, accountType);
-
         BigDecimal hasRouteSellOrderExpectAmount = BigDecimal.ZERO; //已分配预计金额
         BigDecimal hasRouteSellOrderBalance = BigDecimal.ZERO; //已分配余额
 
@@ -623,10 +620,11 @@ public class ReplacementInstrumentActivityServiceImpl extends BaseServiceImpl<In
             i++;
         }
         if (sellOrders.size() > 0) {
-            sellOrderDao.batchInsert(sellOrders);
+            sellOrderService.batchInsert(sellOrders);
+            sellOrderService.syncSellOrder2Mall(sellOrders,order);
         }
         return sellOrders;
-    }
+    }*/
 
     @Transactional(rollbackFor = Exception.class)
     public void resultSync() {

+ 18 - 0
mec-biz/src/main/java/com/ym/mec/biz/service/impl/ReplacementInstrumentServiceImpl.java

@@ -4,19 +4,25 @@ import com.ym.mec.biz.dal.dao.GoodsDao;
 import com.ym.mec.biz.dal.entity.Goods;
 import com.ym.mec.biz.dal.page.ReplacementInstrumentQueryInfo;
 import com.ym.mec.common.dal.BaseDAO;
+import com.ym.mec.common.dto.BrandDto;
 import com.ym.mec.common.page.PageInfo;
 import com.ym.mec.common.service.impl.BaseServiceImpl;
+import com.ym.mec.mall.MallFeignService;
 import com.ym.mec.util.collection.MapUtil;
+import org.apache.commons.lang.math.NumberUtils;
+import org.apache.commons.lang3.StringUtils;
 import org.springframework.beans.factory.annotation.Autowired;
 import com.ym.mec.biz.dal.entity.ReplacementInstrument;
 import com.ym.mec.biz.service.ReplacementInstrumentService;
 import com.ym.mec.biz.dal.dao.ReplacementInstrumentDao;
 import org.springframework.stereotype.Service;
 
+import javax.annotation.Resource;
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
+import java.util.stream.Collectors;
 
 @Service
 public class ReplacementInstrumentServiceImpl extends BaseServiceImpl<Integer, ReplacementInstrument> implements ReplacementInstrumentService {
@@ -25,6 +31,8 @@ public class ReplacementInstrumentServiceImpl extends BaseServiceImpl<Integer, R
     private ReplacementInstrumentDao replacementInstrumentDao;
     @Autowired
     private GoodsDao goodsDao;
+    @Resource
+    private MallFeignService mallFeignService;
 
     @Override
     public BaseDAO<Integer, ReplacementInstrument> getDAO() {
@@ -44,6 +52,16 @@ public class ReplacementInstrumentServiceImpl extends BaseServiceImpl<Integer, R
             pageInfo.setTotal(count);
             params.put("offset", pageInfo.getOffset());
             dataList = goodsDao.getReplacementGoodsPage(params);
+            List<String> brandIdList = dataList.stream().map(ReplacementInstrument::getBrand).filter(StringUtils::isNotEmpty).distinct().collect(Collectors.toList());
+            if (!brandIdList.isEmpty()) {
+                Map<Long, String> idNameMap = mallFeignService.getList().stream().collect(Collectors.toMap(BrandDto::getId, BrandDto::getName));
+                for (ReplacementInstrument instrument : dataList) {
+                    String brand = instrument.getBrand();
+                    if (StringUtils.isNotEmpty(brand) && NumberUtils.isNumber(brand)) {
+                        instrument.setBrandName(idNameMap.getOrDefault(Long.valueOf(brand), ""));
+                    }
+                }
+            }
         }
         pageInfo.setRows(dataList);
         return pageInfo;

+ 1 - 0
mec-biz/src/main/java/com/ym/mec/biz/service/impl/SchoolServiceImpl.java

@@ -6,6 +6,7 @@ import com.ym.mec.biz.dal.entity.School;
 import com.ym.mec.biz.dal.page.SchoolQueryInfo;
 import com.ym.mec.biz.service.SchoolService;
 import com.ym.mec.common.dal.BaseDAO;
+import com.ym.mec.common.dto.SchoolDto;
 import com.ym.mec.common.exception.BizException;
 import com.ym.mec.common.page.PageInfo;
 import com.ym.mec.common.service.impl.BaseServiceImpl;

+ 470 - 375
mec-biz/src/main/java/com/ym/mec/biz/service/impl/SellOrderServiceImpl.java

@@ -1,54 +1,36 @@
 package com.ym.mec.biz.service.impl;
 
 
-import static com.ym.mec.biz.dal.enums.GroupType.GOODS_SELL;
-
-import java.math.BigDecimal;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.stream.Collectors;
-
+import com.alibaba.fastjson.JSON;
+import com.ym.mec.biz.dal.dao.*;
+import com.ym.mec.biz.dal.entity.*;
+import com.ym.mec.biz.dal.enums.*;
+import com.ym.mec.biz.dal.page.MusicGroupShippingAddressQueryInfo;
+import com.ym.mec.biz.service.*;
+import com.ym.mec.common.api.CommonResult;
+import com.ym.mec.common.dal.BaseDAO;
+import com.ym.mec.common.dto.OrderCreate;
+import com.ym.mec.common.dto.PmsProductDto;
+import com.ym.mec.common.dto.PmsProductQueryParamDto;
+import com.ym.mec.common.dto.ReturnApplyDto;
+import com.ym.mec.common.exception.BizException;
+import com.ym.mec.common.page.PageInfo;
+import com.ym.mec.common.service.impl.BaseServiceImpl;
+import com.ym.mec.mall.MallFeignService;
 import org.apache.commons.collections.CollectionUtils;
 import org.apache.commons.lang3.StringUtils;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
-import org.springframework.transaction.annotation.Isolation;
 import org.springframework.transaction.annotation.Transactional;
 
-import com.ym.mec.biz.dal.dao.GoodsDao;
-import com.ym.mec.biz.dal.dao.MusicGroupDao;
-import com.ym.mec.biz.dal.dao.SellOrderDao;
-import com.ym.mec.biz.dal.dao.SporadicChargeInfoDao;
-import com.ym.mec.biz.dal.dao.StudentPaymentOrderDao;
-import com.ym.mec.biz.dal.dao.StudentPaymentOrderDetailDao;
-import com.ym.mec.biz.dal.dao.StudentRepairDao;
-import com.ym.mec.biz.dal.entity.Goods;
-import com.ym.mec.biz.dal.entity.MusicGroup;
-import com.ym.mec.biz.dal.entity.SellOrder;
-import com.ym.mec.biz.dal.entity.SporadicChargeInfo;
-import com.ym.mec.biz.dal.entity.StudentPaymentOrder;
-import com.ym.mec.biz.dal.entity.StudentPaymentOrderDetail;
-import com.ym.mec.biz.dal.entity.SysUserCashAccountLog;
-import com.ym.mec.biz.dal.enums.AccountType;
-import com.ym.mec.biz.dal.enums.GoodsType;
-import com.ym.mec.biz.dal.enums.KitGroupPurchaseTypeEnum;
-import com.ym.mec.biz.dal.enums.OrderDetailTypeEnum;
-import com.ym.mec.biz.dal.enums.OrderTypeEnum;
-import com.ym.mec.biz.dal.enums.PaymentChannelEnum;
-import com.ym.mec.biz.dal.enums.ReturnFeeEnum;
-import com.ym.mec.biz.dal.enums.SellStatus;
-import com.ym.mec.biz.dal.enums.SellTypeEnum;
-import com.ym.mec.biz.dal.enums.SporadicChargeTypeEnum;
-import com.ym.mec.biz.service.GoodsService;
-import com.ym.mec.biz.service.SellOrderService;
-import com.ym.mec.biz.service.StudentPaymentOrderDetailService;
-import com.ym.mec.biz.service.SysPaymentConfigService;
-import com.ym.mec.biz.service.SysUserCashAccountLogService;
-import com.ym.mec.common.dal.BaseDAO;
-import com.ym.mec.common.service.impl.BaseServiceImpl;
+import java.math.BigDecimal;
+import java.math.RoundingMode;
+import java.util.*;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+import static com.ym.mec.biz.dal.enums.GroupType.GOODS_SELL;
+import static com.ym.mec.biz.dal.enums.GroupType.MUSIC;
 
 @Service
 public class SellOrderServiceImpl extends BaseServiceImpl<Integer, SellOrder> implements SellOrderService {
@@ -65,14 +47,27 @@ public class SellOrderServiceImpl extends BaseServiceImpl<Integer, SellOrder> im
     @Autowired
     private SysUserCashAccountLogService sysUserCashAccountLogService;
     @Autowired
-    private GoodsService goodsService;
-    @Autowired
     private StudentPaymentOrderDetailDao studentPaymentOrderDetailDao;
     @Autowired
     private SporadicChargeInfoDao sporadicChargeInfoDao;
     @Autowired
     private StudentPaymentOrderDetailService studentPaymentOrderDetailService;
+    @Autowired
+    private GoodsSubService goodsSubService;
+    @Autowired
+    private MallFeignService mallFeignService;
+    @Autowired
+    private MusicGroupShippingAddressService musicGroupShippingAddressService;
+
+    @Autowired
+    private SysAreaService sysAreaService;
+
+    @Autowired
+    private StudentRepairDao studentRepairDao;
 
+
+    @Autowired
+    private StudentPaymentOrderAddressService studentPaymentOrderAddressService;
     @Override
     public BaseDAO<Integer, SellOrder> getDAO() {
         return sellOrderDao;
@@ -82,343 +77,94 @@ public class SellOrderServiceImpl extends BaseServiceImpl<Integer, SellOrder> im
         return sellOrderDao;
     }
 
-
     @Override
-    @Transactional(rollbackFor = Exception.class, isolation = Isolation.READ_COMMITTED)
-    public List<SellOrder> addSellOrder(Long orderId, String musicGroupId, List<Integer> goodsIds, BigDecimal totalAmount, BigDecimal balance, BigDecimal couponRemitFee) {
-        if (goodsIds == null || goodsIds.size() <= 0) {
-            return null;
-        }
-        if (balance == null) {
-            balance = BigDecimal.ZERO;
+    @Transactional(rollbackFor = Exception.class)
+    public void addOrderDetail2SellOrder(List<StudentPaymentOrderDetail> orderDetails,
+                                                    StudentPaymentOrder studentPaymentOrder, String musicGroupId) {
+        //过滤非商品详情
+        List<StudentPaymentOrderDetail> goodsOrderDetails = orderDetails.stream().filter(e -> StringUtils.isNotEmpty(e.getGoodsIdList())).collect(Collectors.toList());
+        if(CollectionUtils.isEmpty(goodsOrderDetails)){
+            return;
         }
-        StudentPaymentOrder order = studentPaymentOrderDao.get(orderId);
-        BigDecimal totalActualAmount = order.getActualAmount() == null ? BigDecimal.ZERO : order.getActualAmount();
-        MusicGroup musicGroup = new MusicGroup();
-        if (StringUtils.isNotBlank(musicGroupId)) {
-            musicGroup = musicGroupDao.get(musicGroupId);
-        }
-        int goodsNum = goodsIds.size();
-        BigDecimal goodsTotalPrice = BigDecimal.ZERO;
-        List<Goods> goodies = goodsDao.getGoodies(goodsIds);
-        int i = 1;
-        for (Integer goodsId : goodsIds) {
-            for (Goods goods : goodies) {
-                if (goods.getId().equals(goodsId)) {
-                    goodsTotalPrice = goodsTotalPrice.add(goods.getDiscountPrice());
-                    break;
-                }
-            }
+        //获取总金额
+        BigDecimal detailTotalPrice = goodsOrderDetails.stream().map(StudentPaymentOrderDetail::getPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
+        //获取比例
+        BigDecimal totalRatioAmount = BigDecimal.ZERO;
+        if(studentPaymentOrder.getExpectAmount().compareTo(BigDecimal.ZERO) > 0){
+            totalRatioAmount = detailTotalPrice.divide(studentPaymentOrder.getExpectAmount(), 32, RoundingMode.DOWN);
         }
-        //商品总价值去掉优惠券减免
-//        if(goodsTotalPrice.compareTo(couponRemitFee) <= 0){
-//            goodsTotalPrice = BigDecimal.ZERO;
-//        }else {
-//            goodsTotalPrice = goodsTotalPrice.subtract(couponRemitFee);
-//        }
-
-        //已分配的商品余额
-        BigDecimal hasRouteBalance = BigDecimal.ZERO;
-        //已分配的商品现金
-        BigDecimal hasRouteActualAmount = BigDecimal.ZERO;
-        //商品占用的的余额
-        BigDecimal goodsTotalBalance = totalAmount.compareTo(BigDecimal.ZERO) <= 0 ? BigDecimal.ZERO : goodsTotalPrice.multiply(balance).divide(totalAmount, 2, BigDecimal.ROUND_DOWN);
-        //商品占用的总现金
-        BigDecimal goodsTotalActualAmount = totalAmount.compareTo(BigDecimal.ZERO) <= 0 ? BigDecimal.ZERO : goodsTotalPrice.multiply(totalActualAmount).divide(totalAmount, 2, BigDecimal.ROUND_DOWN);
-        AccountType accountType = sysPaymentConfigService.checkAccountType(PaymentChannelEnum.valueOf(order.getPaymentChannel()), order.getMerNos(), order.getTenantId());
-
-        List<SellOrder> sellOrderList = goodsService.subtractStock(goodsIds, accountType);
-        BigDecimal freeCouponRemitFee = couponRemitFee;
-        for (int j = 0; j < goodsIds.size(); j++) {
-            Integer goodsId = goodsIds.get(j);
-            BigDecimal goodsPrice = BigDecimal.ZERO;
-            Goods nowGoods = new Goods();
-            for (Goods goods : goodies) {
-                if (goods.getId().equals(goodsId)) {
-                    nowGoods = goods;
-                    break;
-                }
-            }
-            goodsPrice = nowGoods.getDiscountPrice();
-            //扣除减免金额
-//            if(couponRemitFee.compareTo(BigDecimal.ZERO) > 0){
-//                if(j == goodsIds.size() - 1){
-//                    goodsPrice = goodsPrice.subtract(freeCouponRemitFee);
-//                }else {
-//                    //获取比例
-//                    BigDecimal divide = goodsPrice.divide(goodsPrice.add(couponRemitFee), 6, BigDecimal.ROUND_HALF_UP);
-//                    //分摊金额
-//                    BigDecimal scale = couponRemitFee.multiply(divide).setScale(2, BigDecimal.ROUND_HALF_UP);
-//                    freeCouponRemitFee = freeCouponRemitFee.subtract(scale);
-//                    goodsPrice = goodsPrice.subtract(scale);
-//                }
-//            }
-
-            //当前商品占用的总优惠券减免
-            BigDecimal couponBalance = goodsTotalPrice.compareTo(BigDecimal.ZERO) <= 0 ? BigDecimal.ZERO :
-                    couponRemitFee.multiply(goodsPrice).divide(goodsTotalPrice, 2, BigDecimal.ROUND_DOWN);
-            //当前商品占用的总余额
-            BigDecimal goodsBalance = goodsTotalPrice.compareTo(BigDecimal.ZERO) <= 0 ? BigDecimal.ZERO :
-                    goodsTotalBalance.multiply(goodsPrice).divide(goodsTotalPrice, 2, BigDecimal.ROUND_DOWN);
-            //当前商品占用的总现金
-            BigDecimal goodsActualAmount = goodsTotalPrice.compareTo(BigDecimal.ZERO) <= 0 ? BigDecimal.ZERO :
-                    goodsTotalActualAmount.multiply(goodsPrice).divide(goodsTotalPrice, 2, BigDecimal.ROUND_DOWN);
-
-            if (i == goodsNum) {
-                couponBalance = couponRemitFee.subtract(freeCouponRemitFee);
-                goodsBalance = goodsTotalBalance.subtract(hasRouteBalance);
-                goodsActualAmount = goodsTotalActualAmount.subtract(hasRouteActualAmount);
-            }
-            freeCouponRemitFee = freeCouponRemitFee.subtract(couponBalance);
-            hasRouteBalance = hasRouteBalance.add(goodsBalance);
-            hasRouteActualAmount = hasRouteActualAmount.add(goodsActualAmount);
-            i++;
-
-            int complementGoodsNum = nowGoods.getComplementGoodsIdList() == null ? 1 : nowGoods.getComplementGoodsIdList().split(",").length;
-            BigDecimal complementPrice = nowGoods.getDiscountPrice();
-            Map<Integer, BigDecimal> complementGoodsPrice = new HashMap<>();
-            complementGoodsPrice.put(nowGoods.getId(), nowGoods.getDiscountPrice());
-            if (nowGoods.getComplementGoodsIdList() != null) {
-                List<Goods> complementGoodies = goodsDao.findGoodsByIds(nowGoods.getComplementGoodsIdList());
-                complementGoodsPrice = complementGoodies.stream().collect(Collectors.toMap(Goods::getId, Goods::getDiscountPrice));
-                complementPrice = complementGoodies.stream().map(Goods::getDiscountPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
-            }
-
-            BigDecimal hasRouteSellOrderActualAmount = BigDecimal.ZERO;
-            BigDecimal hasRouteSellOrderBalance = BigDecimal.ZERO;
-            BigDecimal hasRouteCouponBalance = BigDecimal.ZERO;
-            for (SellOrder sellOrder : sellOrderList) {
-                if (!goodsId.equals(sellOrder.getParentGoodsId()) && !goodsId.equals(sellOrder.getGoodsId())) {
-                    continue;
-                }
-                if (sellOrder.getHasRoute()) {
-                    continue;
-                }
-                BigDecimal sellOrderActualAmount = BigDecimal.ZERO;
-                BigDecimal sellOrderBalance = BigDecimal.ZERO;
-                if (complementPrice.compareTo(BigDecimal.ZERO) > 0) {
-                    sellOrderActualAmount = complementGoodsPrice.get(sellOrder.getGoodsId()).multiply(new BigDecimal(sellOrder.getNum())).multiply(goodsActualAmount).divide(complementPrice, 2, BigDecimal.ROUND_DOWN);
-                    sellOrderBalance = complementGoodsPrice.get(sellOrder.getGoodsId()).multiply(new BigDecimal(sellOrder.getNum())).multiply(goodsBalance).divide(complementPrice, 2, BigDecimal.ROUND_DOWN);
-                }
+        //获取分配的余额
+        BigDecimal balancePaymentAmount = studentPaymentOrder.getBalancePaymentAmount().multiply(totalRatioAmount).setScale(2, RoundingMode.DOWN);
+        //获取分配的现金
+        BigDecimal totalDetailActualAmount = studentPaymentOrder.getActualAmount().multiply(totalRatioAmount).setScale(2, RoundingMode.DOWN);
+        //获取总优惠券金额
+        BigDecimal detailTotalRemitPrice = goodsOrderDetails.stream().map(StudentPaymentOrderDetail::getRemitFee).reduce(BigDecimal.ZERO, BigDecimal::add);
 
-                complementGoodsNum = complementGoodsNum - sellOrder.getNum();
-                if (complementGoodsNum <= 0) {
-                    sellOrderActualAmount = goodsActualAmount.subtract(hasRouteSellOrderActualAmount);
-                    sellOrderBalance = goodsBalance.subtract(hasRouteSellOrderBalance);
-                }
-                hasRouteSellOrderActualAmount = hasRouteSellOrderActualAmount.add(sellOrderActualAmount);
-                hasRouteSellOrderBalance = hasRouteSellOrderBalance.add(sellOrderBalance);
-
-                sellOrder.setExpectAmount(sellOrderActualAmount.add(sellOrderBalance));
-                sellOrder.setBalanceAmount(sellOrderBalance);
-//                sellOrder.setCouponRemitAmount(sellOrderCouponBalance);
-                sellOrder.setActualAmount(sellOrderActualAmount);
-                sellOrder.setOrganId(order.getOrganId());
-                sellOrder.setCooperationOrganId(musicGroup.getCooperationOrganId());
-                sellOrder.setTransNo(order.getTransNo());
-                sellOrder.setOrderId(order.getId());
-                sellOrder.setOrderNo(order.getOrderNo());
-                sellOrder.setUserId(order.getUserId());
-                sellOrder.setPaymentChannel(order.getPaymentChannel());
-                sellOrder.setMerNo(order.getMerNos());
-                sellOrder.setSellTime(order.getCreateTime());
-                sellOrder.setCreateIme(new Date());
-                sellOrder.setUpdateTime(new Date());
-                if (nowGoods.getType().equals(GoodsType.INSTRUMENT)) {
-                    sellOrder.setType(SellTypeEnum.INSTRUMENT);
-                } else if (nowGoods.getType().equals(GoodsType.ACCESSORIES)) {
-                    sellOrder.setType(SellTypeEnum.ACCESSORIES);
-                } else {
-                    sellOrder.setType(SellTypeEnum.OTHER);
-                }
-                sellOrder.setHasRoute(true);
-                if (complementGoodsNum <= 0) {
-                    break;
+        List<SellOrder> sellOrders = new ArrayList<>();
+        if(balancePaymentAmount.add(totalDetailActualAmount).compareTo(detailTotalPrice) < 0){
+            //多出来的金额
+            BigDecimal subtract = detailTotalPrice.subtract(balancePaymentAmount).subtract(totalDetailActualAmount);
+            if(balancePaymentAmount.compareTo(BigDecimal.ZERO) == 0){
+                totalDetailActualAmount = totalDetailActualAmount.add(subtract);
+            }else if(totalDetailActualAmount.compareTo(BigDecimal.ZERO) == 0){
+                balancePaymentAmount = balancePaymentAmount.add(subtract);
+            }else {
+                balancePaymentAmount = balancePaymentAmount.add(subtract);
+                if(balancePaymentAmount.compareTo(studentPaymentOrder.getBalancePaymentAmount()) > 0){
+                    totalDetailActualAmount = totalDetailActualAmount.add(balancePaymentAmount.subtract(studentPaymentOrder.getBalancePaymentAmount()));
+                    balancePaymentAmount = studentPaymentOrder.getBalancePaymentAmount();
                 }
             }
         }
-        if (sellOrderList.size() > 0) {
-            //如果有优惠券金额
-            if (couponRemitFee.compareTo(BigDecimal.ZERO) > 0) {
-                BigDecimal reduce = sellOrderList.stream().map(e -> e.getExpectAmount()).reduce(BigDecimal.ZERO, BigDecimal::add);
-                List<SellOrder> sellOrders = sellOrderList.stream().filter(e -> e.getExpectAmount().compareTo(BigDecimal.ZERO) > 0).collect(Collectors.toList());
-                //可用优惠券金额
-                BigDecimal subCouponMarketAmount = couponRemitFee;
-                for (int j = 0; j < sellOrders.size(); j++) {
-                    SellOrder sellOrder = sellOrders.get(j);
-                    //如果是最后一件商品
-                    if (j == sellOrders.size() - 1) {
-                        sellOrder.setCouponRemitAmount(subCouponMarketAmount);
-                    } else {
-                        //获取比例
-                        BigDecimal ratioAmount = sellOrder.getExpectAmount().divide(reduce, 6, BigDecimal.ROUND_HALF_UP);
-                        //获取分配的减免金额
-                        BigDecimal multiply = couponRemitFee.multiply(ratioAmount).setScale(2, BigDecimal.ROUND_HALF_UP);
-                        subCouponMarketAmount = subCouponMarketAmount.subtract(multiply);
-                        sellOrder.setCouponRemitAmount(multiply);
-                    }
-                }
+        //剩余待分配的余额
+        BigDecimal subDetailBalance = balancePaymentAmount;
+        //剩余待分配的优惠券金额
+        BigDecimal subDetailCouponRemitFee = detailTotalRemitPrice;
+        //剩余待分配现金
+        BigDecimal subDetailActualAmount = totalDetailActualAmount;
+        for (int i = 0; i < goodsOrderDetails.size(); i++) {
+            StudentPaymentOrderDetail orderDetail = goodsOrderDetails.get(i);
+            //获取支付金额比例
+            BigDecimal ratioAmount = BigDecimal.ZERO;
+            if(detailTotalPrice.compareTo(BigDecimal.ZERO) > 0){
+                ratioAmount = orderDetail.getPrice().divide(detailTotalPrice, 32, RoundingMode.DOWN);
             }
-            sellOrderDao.batchInsert(sellOrderList);
-        }
-        return sellOrderList;
-    }
-
-    @Override
-    @Transactional(rollbackFor = Exception.class, isolation = Isolation.READ_COMMITTED)
-    public List<SellOrder> addOrderDetail2SellOrder(List<StudentPaymentOrderDetail> orderDetails,
-                                                    StudentPaymentOrder studentPaymentOrder, MusicGroup musicGroup,BigDecimal musicRemitFee) {
-        Integer tenantId = studentPaymentOrder.getTenantId();
-        List<SellOrder> sellOrders = new ArrayList<>();
-        //总余额支付
-        BigDecimal totalBalance = studentPaymentOrder.getBalancePaymentAmount() != null ? studentPaymentOrder.getBalancePaymentAmount() : BigDecimal.ZERO;
-        //总价格
-        BigDecimal totalPrice = studentPaymentOrder.getExpectAmount();
-        //商品总付款
-        BigDecimal detailTotalPrice = orderDetails.stream().map(StudentPaymentOrderDetail::getPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
-        //商品销售占的余额
-        BigDecimal detailTotalBalance = detailTotalPrice.compareTo(BigDecimal.ZERO) <= 0 ? BigDecimal.ZERO :
-                detailTotalPrice.multiply(totalBalance).divide(totalPrice, 2, BigDecimal.ROUND_DOWN);
-
-        int i = 1;
-        BigDecimal detailRouteBalance = BigDecimal.ZERO;
-
-        AccountType accountType = sysPaymentConfigService.checkAccountType(PaymentChannelEnum.valueOf(studentPaymentOrder.getPaymentChannel()), studentPaymentOrder.getMerNos(), tenantId);
-
-        for (StudentPaymentOrderDetail orderDetail : orderDetails) {
-            BigDecimal detailBalance = orderDetail.getPrice().compareTo(BigDecimal.ZERO) <= 0 ? BigDecimal.ZERO :
-                    orderDetail.getPrice().multiply(detailTotalBalance).divide(detailTotalPrice, 2, BigDecimal.ROUND_DOWN);
-            if (i == orderDetails.size()) {
-                detailBalance = detailTotalBalance.subtract(detailRouteBalance);
-            }
-            detailRouteBalance = detailRouteBalance.add(detailBalance);
-            i++;
-
-            BigDecimal goodsTotalPrice = orderDetail.getGoodsList().stream().map(Goods::getGroupPurchasePrice).reduce(BigDecimal.ZERO, BigDecimal::add);
-            BigDecimal routePrice = BigDecimal.ZERO;
-            BigDecimal routeBalance = BigDecimal.ZERO;
-            int j = 1;
-
-            List<Integer> goodsIds = orderDetail.getGoodsList().stream().map(Goods::getId).collect(Collectors.toList());
-            List<SellOrder> sellOrderList = goodsService.subtractStock(goodsIds, accountType);
-            for (Goods goods : orderDetail.getGoodsList()) {
-                BigDecimal expectAmount = BigDecimal.ZERO;
-                BigDecimal balance = BigDecimal.ZERO;
-                if (goodsTotalPrice.compareTo(BigDecimal.ZERO) > 0) {
-                    expectAmount = goods.getGroupPurchasePrice().multiply(orderDetail.getPrice()).divide(goodsTotalPrice, 2, BigDecimal.ROUND_DOWN);
-                    balance = goods.getGroupPurchasePrice().multiply(detailBalance).divide(goodsTotalPrice, 2, BigDecimal.ROUND_DOWN);
-                }
-                if (j == orderDetail.getGoodsList().size()) {
-                    expectAmount = orderDetail.getPrice().subtract(routePrice);
-                    balance = detailBalance.subtract(routeBalance);
-                }
-                routePrice = routePrice.add(expectAmount);
-                routeBalance = routeBalance.add(balance);
-                j++;
-
-                int complementGoodsNum = goods.getComplementGoodsIdList() == null ? 1 : goods.getComplementGoodsIdList().split(",").length;
-                BigDecimal complementPrice = goods.getGroupPurchasePrice();
-                Map<Integer, BigDecimal> complementGoodsPrice = new HashMap<>();
-                complementGoodsPrice.put(goods.getId(), goods.getGroupPurchasePrice());
-                if (goods.getComplementGoodsIdList() != null) {
-                    List<Goods> complementGoodies = goodsDao.findGoodsByIds(goods.getComplementGoodsIdList());
-                    complementGoodsPrice = complementGoodies.stream().collect(Collectors.toMap(Goods::getId, Goods::getGroupPurchasePrice));
-                    complementPrice = complementGoodies.stream().map(Goods::getGroupPurchasePrice).reduce(BigDecimal.ZERO, BigDecimal::add);
-                }
-
-                BigDecimal hasRouteSellOrderExpectAmount = BigDecimal.ZERO;
-                BigDecimal hasRouteSellOrderBalance = BigDecimal.ZERO;
-                for (SellOrder sellOrder : sellOrderList) {
-                    if (!goods.getId().equals(sellOrder.getParentGoodsId()) && !goods.getId().equals(sellOrder.getGoodsId())) {
-                        continue;
-                    }
-                    if (sellOrder.getHasRoute()) {
-                        continue;
-                    }
-                    sellOrder.setTenantId(tenantId);
-                    BigDecimal sellOrderExpectAmount = BigDecimal.ZERO;
-                    BigDecimal sellOrderBalance = BigDecimal.ZERO;
-                    if (complementPrice.compareTo(BigDecimal.ZERO) > 0) {
-                        sellOrderExpectAmount = complementGoodsPrice.get(sellOrder.getGoodsId()).multiply(new BigDecimal(sellOrder.getNum())).multiply(expectAmount).divide(complementPrice, 2, BigDecimal.ROUND_DOWN);
-                        sellOrderBalance = complementGoodsPrice.get(sellOrder.getGoodsId()).multiply(new BigDecimal(sellOrder.getNum())).multiply(balance).divide(complementPrice, 2, BigDecimal.ROUND_DOWN);
-                    }
-                    complementGoodsNum = complementGoodsNum - sellOrder.getNum();
-                    if (complementGoodsNum <= 0) {
-                        sellOrderExpectAmount = expectAmount.subtract(hasRouteSellOrderExpectAmount);
-                        sellOrderBalance = balance.subtract(hasRouteSellOrderBalance);
-                    }
-                    hasRouteSellOrderExpectAmount = hasRouteSellOrderExpectAmount.add(sellOrderExpectAmount);
-                    hasRouteSellOrderBalance = hasRouteSellOrderBalance.add(sellOrderBalance);
-
-                    sellOrder.setOrganId(studentPaymentOrder.getOrganId());
-                    sellOrder.setTransNo(studentPaymentOrder.getTransNo());
-                    sellOrder.setOrderId(studentPaymentOrder.getId());
-                    if (musicGroup != null) {
-                        sellOrder.setCooperationOrganId(musicGroup.getCooperationOrganId());
-                        sellOrder.setEduTeacherId(musicGroup.getEducationalTeacherId());
-                    }
-                    sellOrder.setOrderNo(studentPaymentOrder.getOrderNo());
-                    sellOrder.setActualAmount(sellOrderExpectAmount.subtract(sellOrderBalance));
-                    sellOrder.setBalanceAmount(sellOrderBalance);
-                    sellOrder.setExpectAmount(sellOrderExpectAmount);
-//                    sellOrder.setCouponRemitAmount(goods.getGroupPurchasePrice().subtract(sellOrderExpectAmount));
-                    sellOrder.setNum(1);
-                    sellOrder.setUserId(studentPaymentOrder.getUserId());
-                    sellOrder.setPaymentChannel(studentPaymentOrder.getPaymentChannel());
-                    sellOrder.setMerNo(studentPaymentOrder.getMerNos());
-                    sellOrder.setSellTime(studentPaymentOrder.getCreateTime());
-                    sellOrder.setCreateIme(new Date());
-                    sellOrder.setUpdateTime(new Date());
-                    if (goods.getType().equals(GoodsType.INSTRUMENT)) {
-                        sellOrder.setType(SellTypeEnum.INSTRUMENT);
-                    } else if (goods.getType().equals(GoodsType.ACCESSORIES)) {
-                        sellOrder.setType(SellTypeEnum.ACCESSORIES);
-                    } else {
-                        sellOrder.setType(SellTypeEnum.OTHER);
-                    }
-                    //租赁、免费的没有销售收入,有销售成本
-                    if (orderDetail.getType().equals(OrderDetailTypeEnum.MUSICAL) &&
-                            (orderDetail.getKitGroupPurchaseType().equals(KitGroupPurchaseTypeEnum.LEASE) ||
-                                    orderDetail.getKitGroupPurchaseType().equals(KitGroupPurchaseTypeEnum.FREE)
-                            )) {
-                        sellOrder.setActualAmount(BigDecimal.ZERO);
-                        sellOrder.setBalanceAmount(BigDecimal.ZERO);
-                        sellOrder.setExpectAmount(BigDecimal.ZERO);
-                    }
-                    sellOrder.setHasRoute(true);
-                    if (complementGoodsNum <= 0) {
-                        break;
-                    }
-                }
-
+            BigDecimal ratioCouponAmount = BigDecimal.ZERO;
+            if (detailTotalRemitPrice.compareTo(BigDecimal.ZERO) > 0) {
+                //获取优惠券金额比例
+                ratioCouponAmount = orderDetail.getRemitFee().divide(detailTotalRemitPrice, 32, RoundingMode.DOWN);
             }
-            sellOrders.addAll(sellOrderList);
-        }
-        if (sellOrders.size() > 0) {
-            //如果有优惠券金额
-            if (musicRemitFee.compareTo(BigDecimal.ZERO) > 0) {
-                BigDecimal reduce = sellOrders.stream().map(e -> e.getExpectAmount()).reduce(BigDecimal.ZERO, BigDecimal::add);
-                List<SellOrder> sellOrderList = sellOrders.stream().filter(e -> e.getExpectAmount().compareTo(BigDecimal.ZERO) > 0).collect(Collectors.toList());
-                //可用优惠券金
-                BigDecimal subCouponMarketAmount = musicRemitFee;
-                for (int j = 0; j < sellOrderList.size(); j++) {
-                    SellOrder sellOrder = sellOrderList.get(j);
-                    //如果是最后一件商品
-                    if (j == sellOrderList.size() - 1) {
-                        sellOrder.setCouponRemitAmount(subCouponMarketAmount);
-                    } else {
-                        //获取比例
-                        BigDecimal ratioAmount = sellOrder.getExpectAmount().divide(reduce, 6, BigDecimal.ROUND_HALF_UP);
-                        //获取分配的减免金额
-                        BigDecimal multiply = musicRemitFee.multiply(ratioAmount).setScale(2, BigDecimal.ROUND_HALF_UP);
-                        subCouponMarketAmount = subCouponMarketAmount.subtract(multiply);
-                        sellOrder.setCouponRemitAmount(multiply);
-                    }
-                }
+            //获取分配的余额
+            BigDecimal detailBalance;
+            //获取分配的优惠券金额
+            BigDecimal couponRemitFee;
+            //获取剩余待分配的现金
+            BigDecimal detailActualAmount;
+            if (i == goodsOrderDetails.size() - 1) {
+                //获取分配的余额
+                detailBalance = subDetailBalance;
+                //获取分配的优惠券金额
+                couponRemitFee = subDetailCouponRemitFee;
+                //获取剩余待分配的现金
+                detailActualAmount = subDetailActualAmount;
+            } else {
+                //获取分配的余额
+                detailBalance = balancePaymentAmount.multiply(ratioAmount).setScale(2, RoundingMode.DOWN);
+                subDetailBalance = subDetailBalance.subtract(detailBalance);
+                //获取分配的优惠券金额
+                couponRemitFee = detailTotalRemitPrice.multiply(ratioCouponAmount).setScale(2, RoundingMode.DOWN);
+                subDetailCouponRemitFee = subDetailCouponRemitFee.subtract(couponRemitFee);
+                //获取剩余待分配的现金
+                detailActualAmount = totalDetailActualAmount.multiply(ratioAmount).setScale(2, RoundingMode.DOWN);
+                subDetailActualAmount = subDetailActualAmount.subtract(detailActualAmount);
             }
-            sellOrderDao.batchInsert(sellOrders);
+            List<Integer> goodsIds = Arrays.asList(orderDetail.getGoodsIdList().split(",")).stream().map(Integer::parseInt).collect(Collectors.toList());
+            sellOrders.addAll(this.initSellOrder(studentPaymentOrder, musicGroupId, goodsIds, orderDetail.getKitGroupPurchaseType(),
+                    detailBalance, orderDetail.getPrice(), couponRemitFee, detailActualAmount, false));
         }
-        return sellOrders;
+        this.batchInsert(sellOrders);
+        //同步销售订单到商城
+        this.syncSellOrder2Mall(sellOrders, studentPaymentOrder,musicGroupId);
     }
 
     @Override
@@ -432,9 +178,10 @@ public class SellOrderServiceImpl extends BaseServiceImpl<Integer, SellOrder> im
     }
 
     @Override
-    @Transactional(rollbackFor = Exception.class, isolation = Isolation.READ_COMMITTED)
+    @Transactional(rollbackFor = Exception.class)
     public List<SellOrder> refund(List<SellOrder> sellOrders, Boolean reBackFee) {
         Date nowDate = new Date();
+        String orderNo = sellOrders.get(0).getOrderNo();
         for (SellOrder sellOrder : sellOrders) {
             //1、更改销售列表状态
             sellOrder.setStatus(SellStatus.REFUND);
@@ -457,13 +204,18 @@ public class SellOrderServiceImpl extends BaseServiceImpl<Integer, SellOrder> im
             }
         }
         //3、退货
-        if (sellOrders.get(0).getAccountType() != null) {
+        /*if (sellOrders.get(0).getAccountType() != null) {
             goodsService.increaseStock(sellOrders, sellOrders.get(0).getAccountType());
-        }
+        }*/
+        //4退货同步到商城
+        this.mallRefundByOrderId(sellOrders);
+        //5、更改订单状态
+        mallFeignService.productUpdateOrderStatus(orderNo,4);
         return sellOrders;
     }
 
     @Override
+    @Transactional(rollbackFor = Exception.class)
     public List<SellOrder> refundByOrderId(Long orderId, Boolean reBackFee) {
         List<SellOrder> sellOrders = sellOrderDao.getSellOrderByParentGoodsId(orderId, null);
         if (sellOrders.size() <= 0) {
@@ -515,6 +267,349 @@ public class SellOrderServiceImpl extends BaseServiceImpl<Integer, SellOrder> im
         return sellAmount;
     }
 
+    @Override
+    public List<OrderCreate.OrderItem> convertMallOrder(List<SellOrder> sellOrderList) {
+        //按组合商品分组
+        List<OrderCreate.OrderItem> orderItems = new ArrayList<>();
+        Map<Integer, List<SellOrder>> goodsIdSellOrderMap = sellOrderList.stream().collect(Collectors.groupingBy(SellOrder::getParentGoodsId));
+        goodsIdSellOrderMap.keySet().forEach(e -> {
+            List<SellOrder> sellOrders = goodsIdSellOrderMap.get(e);
+            //按sku分组
+            Map<Integer, List<SellOrder>> skuIdSellOrderMap = sellOrders.stream().collect(Collectors.groupingBy(SellOrder::getGoodsSkuId));
+            skuIdSellOrderMap.keySet().forEach(skuId -> {
+                List<SellOrder> orders = skuIdSellOrderMap.get(skuId);
+                OrderCreate.OrderItem orderItemCreate = new OrderCreate.OrderItem();
+                orderItemCreate.setProductQuantity(orders.size());
+                orderItemCreate.setProductSkuId(skuId.longValue());
+                orderItemCreate.setRealAmount(orders.stream().map(SellOrder::getExpectAmount).reduce(BigDecimal.ZERO, BigDecimal::add).divide(new BigDecimal(orders.size()), 2, RoundingMode.DOWN));
+                orderItems.add(orderItemCreate);
+            });
+        });
+        return orderItems;
+    }
+
+    @Override
+    @Transactional(rollbackFor = Exception.class)
+    public void syncSellOrder2Mall(List<SellOrder> sellOrders, StudentPaymentOrder studentPaymentOrder,String musicGroupId) {
+        List<OrderCreate.OrderItem> orderItems = this.convertMallOrder(sellOrders);
+        OrderCreate mallOrder = new OrderCreate();
+        mallOrder.setOrderItemList(orderItems);
+        mallOrder.setOrchestraId(studentPaymentOrder.getMusicGroupId());
+        mallOrder.setStatus(1);
+        mallOrder.setOrderNo(studentPaymentOrder.getOrderNo());
+        mallOrder.setTotalAmount(sellOrders.stream().map(SellOrder::getExpectAmount).reduce(BigDecimal.ZERO, BigDecimal::add));
+        String paymentBusinessChannel = studentPaymentOrder.getPaymentBusinessChannel();
+        if(StringUtils.isEmpty(paymentBusinessChannel)) {
+            if (StringUtils.isEmpty(studentPaymentOrder.getPaymentChannel())){
+                mallOrder.setPayType(4);
+            }else {
+                mallOrder.setPayType(3);
+            }
+        }else {
+            if (StringUtils.endsWithIgnoreCase(paymentBusinessChannel, "wx_pub") ||
+                    StringUtils.endsWithIgnoreCase(paymentBusinessChannel, "WECHAT") ||
+                    StringUtils.endsWithIgnoreCase(paymentBusinessChannel, "WXPay")) {
+                mallOrder.setPayType(2);
+            } else if (StringUtils.endsWithIgnoreCase(paymentBusinessChannel, "BALANCE")) {
+                mallOrder.setPayType(3);
+            }else {
+                mallOrder.setPayType(1);
+            }
+        }
+        Integer memberId = studentPaymentOrder.getUserId()==null?studentPaymentOrder.getCooperationId():studentPaymentOrder.getUserId();
+        mallOrder.setMemberId(memberId==null?0L:memberId);
+        mallOrder.setPlatformType(studentPaymentOrder.getUserId()==null?"SCHOOL":"STUDENT");
+        mallOrder.setSourceType(mallOrder.getPlatformType().equals("SCHOOL")?2:1);
+
+        // 乐团学生报名默认收货地址
+        if ((studentPaymentOrder.getType() == OrderTypeEnum.APPLY || studentPaymentOrder.getType() == OrderTypeEnum.SUBJECT_CHANGE)
+            && StringUtils.isNotBlank(mallOrder.getOrchestraId())) {
+
+            // 查询乐团默认收货地址
+            MusicGroupShippingAddressQueryInfo queryInfo = new MusicGroupShippingAddressQueryInfo();
+            queryInfo.setMusicGroupId(musicGroupId);
+            queryInfo.setPage(1);
+            queryInfo.setRows(10);
+            List<MusicGroupShippingAddress> rows = musicGroupShippingAddressService.queryPage(queryInfo).getRows();
+            if (CollectionUtils.isNotEmpty(rows)) {
+                MusicGroupShippingAddress address = rows.get(0);
+                mallOrder.setReceiverName(address.getConsigneeName());
+                mallOrder.setReceiverPhone(address.getMobile());
+                mallOrder.setReceiverProvince(address.getRegionProvince());
+                mallOrder.setReceiverCity(address.getRegionCity());
+                mallOrder.setReceiverRegion(address.getRegionCounty());
+                mallOrder.setReceiverDetailAddress(address.getDetailAddress());
+            }
+        } else if(studentPaymentOrder.getType() == OrderTypeEnum.GOODS_SELL) {
+            StudentPaymentOrderAddress one = studentPaymentOrderAddressService.lambdaQuery()
+                .eq(StudentPaymentOrderAddress::getOrderNo, studentPaymentOrder.getOrderNo())
+                .last("limit 1")
+                .one();
+            if(one != null) {
+                // 查询地区信息
+                List<String> areaIds = new ArrayList<>();
+                areaIds.add(one.getProvinceId()==null?null:one.getProvinceId().toString());
+                areaIds.add(one.getCityId()==null?null:one.getCityId().toString());
+                areaIds.add(one.getCountyId()==null?null:one.getCountyId().toString());
+                areaIds = areaIds.stream().filter(StringUtils::isNotBlank).distinct().collect(Collectors.toList());
+                Map<String, String> nameMapByIds = sysAreaService.getNameMapByIds(areaIds);
+                mallOrder.setReceiverName(one.getContactName());
+                mallOrder.setReceiverPhone(one.getContactMobile());
+                if (one.getProvinceId() != null) {
+                    mallOrder.setReceiverProvince(nameMapByIds.getOrDefault(one.getProvinceId().toString(), ""));
+                }
+                if (one.getCityId() != null) {
+                    mallOrder.setReceiverCity(nameMapByIds.getOrDefault(one.getCityId().toString(), ""));
+                }
+                if (one.getCountyId() != null) {
+                    mallOrder.setReceiverRegion(nameMapByIds.getOrDefault(one.getCountyId().toString(), ""));
+                }
+                mallOrder.setReceiverDetailAddress(one.getAddress());
+
+            }
+        } else if (studentPaymentOrder.getType() == OrderTypeEnum.REPAIR) {
+            StudentRepair studentRepair = studentRepairDao.getByOrderNo(studentPaymentOrder.getOrderNo());
+            if (studentRepair != null) {
+                mallOrder.setReceiverName(studentRepair.getContactName());
+                mallOrder.setReceiverPhone(studentRepair.getContactMobile());
+                mallOrder.setReceiverDetailAddress(studentRepair.getAddress());
+            }
+        }
+
+        CommonResult<Boolean> result = mallFeignService.productOrderCreate(mallOrder);
+        if (result.getCode() != 200) {
+            throw new BizException("同步商城订单失败:{}",result.getMessage());
+        }
+    }
+
+    @Override
+    @Transactional(rollbackFor = Exception.class)
+    public void mallRefundByOrderId(List<SellOrder> sellOrders) {
+        ReturnApplyDto returnApply = new ReturnApplyDto();
+        returnApply.setOrderSn(sellOrders.get(0).getOrderNo());
+        returnApply.setReason("管乐迷商品更换退货");
+        if(sellOrders.get(0).getGoodsSkuId() != null){
+            String skuIds = sellOrders.stream().map(e -> e.getGoodsSkuId() == null ?"":e.getGoodsSkuId().toString()).collect(Collectors.joining(","));
+            returnApply.setSkuIds(skuIds);
+            CommonResult<Boolean> result = mallFeignService.returnApply(returnApply);
+            if (result.getCode() != 200){
+                throw new BizException("商城订单退货失败",result.getMessage());
+            }
+        }
+    }
+
+    @Override
+    @Transactional(rollbackFor = Exception.class)
+    public List<SellOrder> initSellOrder(StudentPaymentOrder order, String musicGroupId, List<Integer> goodsIds, KitGroupPurchaseTypeEnum kitGroupPurchaseType,
+                                         BigDecimal totalBalance, BigDecimal expectTotalAmount, BigDecimal couponRemitAmount,
+                                         BigDecimal actualTotalAmount, Boolean saveFlag) {
+        //可用优惠券金额
+        BigDecimal subCouponRemitAmount = couponRemitAmount;
+        //可用总金额
+        BigDecimal subExpectTotalAmount = expectTotalAmount;
+        //可用总余额
+        BigDecimal subTotalBalance = totalBalance;
+        //实际金额
+        BigDecimal subTotalActualAmount = actualTotalAmount;
+        Integer tenantId = order.getTenantId();
+        MusicGroup musicGroup = new MusicGroup();
+        if (StringUtils.isNotBlank(musicGroupId)) {
+            musicGroup = musicGroupDao.get(musicGroupId);
+        }
+        List<Goods> goodies = goodsDao.getGoodies(goodsIds);
+        BigDecimal goodsTotalPrice = goodies.stream().map(e->order.getGroupType() == MUSIC ?e.getGroupPurchasePrice():e.getDiscountPrice()).
+                reduce(BigDecimal.ZERO, BigDecimal::add);
+
+        AccountType accountType = AccountType.INTERNAL;
+        if(StringUtils.isNotEmpty(order.getPaymentChannel())){
+            accountType  = sysPaymentConfigService.checkAccountType(PaymentChannelEnum.valueOf(order.getPaymentChannel()), order.getMerNos(), order.getTenantId());
+        }
+        PmsProductQueryParamDto paramDto = new PmsProductQueryParamDto();
+        String skuIds = goodsSubService.lambdaQuery().in(GoodsSub::getGoodsId, goodies.stream().map(Goods::getId).collect(Collectors.toList())).list()
+                .stream().map(e->e.getSku().toString()).collect(Collectors.joining(","));
+        paramDto.setSkuStockIds(skuIds);
+        paramDto.setPageSize(1000);
+        paramDto.setPageNum(1);
+        paramDto.setJson(JSON.toJSONString(paramDto));
+        PageInfo<PmsProductDto> productList = mallFeignService.getProductList(paramDto);
+        if (org.springframework.util.CollectionUtils.isEmpty(productList.getRows())) {
+            throw new BizException("商城商品不存在");
+        }
+        Map<Integer,PmsProductDto> skuIdProductMap = productList.getRows().stream().collect(Collectors.toMap(PmsProductDto::getSkuStockId, Function.identity()));
+        List<SellOrder> sellOrderList = new ArrayList<>();
+        for (int i = 0; i < goodies.size(); i++) {
+            Goods nowGoods = goodies.get(i);
+            //获取比例
+            BigDecimal goodsRatioAmount = BigDecimal.ZERO;
+            //预计金额
+            BigDecimal expectAmount;
+            //余额
+            BigDecimal goodsBalance;
+            //减免金额
+            BigDecimal remitAmount;
+            //实际金额
+            BigDecimal actualAmount;
+
+            if (goodsTotalPrice.compareTo(BigDecimal.ZERO) > 0) {
+                goodsRatioAmount = order.getGroupType() == MUSIC ?nowGoods.getGroupPurchasePrice():nowGoods.getDiscountPrice()
+                        .divide(goodsTotalPrice, 32, RoundingMode.DOWN);
+            }
+            if(i == goodies.size() - 1){
+                expectAmount = subExpectTotalAmount;
+                goodsBalance = subTotalBalance;
+                remitAmount = subCouponRemitAmount;
+                actualAmount = subTotalActualAmount;
+            }else {
+                expectAmount = goodsRatioAmount.multiply(expectTotalAmount).setScale(2, RoundingMode.DOWN);
+                subExpectTotalAmount = subExpectTotalAmount.subtract(expectAmount);
+                goodsBalance = goodsRatioAmount.multiply(totalBalance).setScale(2, RoundingMode.DOWN);
+                subTotalBalance = subTotalBalance.subtract(goodsBalance);
+                remitAmount = goodsRatioAmount.multiply(couponRemitAmount).setScale(2, RoundingMode.DOWN);
+                subCouponRemitAmount = subCouponRemitAmount.subtract(remitAmount);
+                actualAmount = expectAmount.subtract(goodsBalance).subtract(remitAmount);
+                subTotalActualAmount = subTotalActualAmount.subtract(actualAmount);
+            }
+            //剩余预计金额
+            BigDecimal subExpectAmount = expectAmount;
+            //剩余余额
+            BigDecimal subGoodsBalance = goodsBalance;
+            //剩余减免金额
+            BigDecimal subRemitAmount = remitAmount;
+            //剩余实际金额
+            BigDecimal subActualAmount = actualAmount;
+            //租赁、免费的没有销售收入,有销售成本
+            if (nowGoods.getType().equals(GoodsType.INSTRUMENT) && kitGroupPurchaseType != null &&
+                    (kitGroupPurchaseType.equals(KitGroupPurchaseTypeEnum.LEASE) || kitGroupPurchaseType.equals(KitGroupPurchaseTypeEnum.FREE))) {
+                goodsBalance = BigDecimal.ZERO;
+                expectAmount = BigDecimal.ZERO;
+            }
+
+            List<GoodsSub> goodsSubs = goodsSubService.lambdaQuery().eq(GoodsSub::getGoodsId, nowGoods.getId()).list();
+            //商品原始总价
+            BigDecimal complementPrice = goodsSubs.stream().map(GoodsSub::getGoodsPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
+            //生成sellOrder
+            for (int j = 0; j < goodsSubs.size(); j++) {
+                GoodsSub goodsSub = goodsSubs.get(j);
+                PmsProductDto productDto = skuIdProductMap.get(goodsSub.getSku());
+                if(Objects.isNull(productDto)){
+                    throw new BizException("商品["+nowGoods.getName()+"]子商品["+goodsSub.getSku()+"]不存在");
+                }
+                SellOrder sellOrder = new SellOrder();
+                //获取比例
+                BigDecimal ratioAmount = BigDecimal.ZERO;
+                if(complementPrice.compareTo(BigDecimal.ZERO) > 0){
+                    ratioAmount = goodsSub.getGoodsPrice().divide(complementPrice, 16, RoundingMode.DOWN);
+                }
+                if (j == goodsSubs.size() - 1){
+                    sellOrder.setExpectAmount(subExpectAmount);
+                    sellOrder.setBalanceAmount(subGoodsBalance);
+                    sellOrder.setActualAmount(subActualAmount);
+                    sellOrder.setCouponRemitAmount(subRemitAmount);
+                }else {
+                    BigDecimal decimal = expectAmount.multiply(ratioAmount).setScale(2, RoundingMode.DOWN);
+                    sellOrder.setExpectAmount(decimal);
+                    subExpectAmount = subExpectAmount.subtract(decimal);
+                    BigDecimal balance = goodsBalance.multiply(ratioAmount).setScale(2, RoundingMode.DOWN);
+                    sellOrder.setBalanceAmount(balance);
+                    subGoodsBalance = subGoodsBalance.subtract(balance);
+                    BigDecimal actual = actualAmount.multiply(ratioAmount).setScale(2, RoundingMode.DOWN);
+                    sellOrder.setActualAmount(actual);
+                    subActualAmount = subActualAmount.subtract(actual);
+                    BigDecimal remit = remitAmount.multiply(ratioAmount).setScale(2, RoundingMode.DOWN);
+                    sellOrder.setCouponRemitAmount(remit);
+                    subRemitAmount = subRemitAmount.subtract(remit);
+                }
+                sellOrder.setParentGoodsId(nowGoods.getId());
+                sellOrder.setGoodsSkuId(goodsSub.getSku());
+                sellOrder.setNum(1);
+                sellOrder.setGoodsName(productDto.getName());
+                sellOrder.setAccountType(accountType);
+                sellOrder.setOrganSellCost(goodsSub.getGoodsPrice());
+                sellOrder.setOrganId(order.getOrganId());
+                sellOrder.setCooperationOrganId(order.getCooperationId());
+                sellOrder.setEduTeacherId(musicGroup.getEducationalTeacherId());
+                sellOrder.setTransNo(order.getTransNo());
+                sellOrder.setOrderId(order.getId());
+                sellOrder.setOrderNo(order.getOrderNo());
+                sellOrder.setUserId(order.getUserId());
+                sellOrder.setPaymentChannel(order.getPaymentChannel());
+                sellOrder.setMerNo(order.getMerNos());
+                sellOrder.setSellTime(order.getCreateTime());
+                sellOrder.setTenantId(tenantId);
+                if (nowGoods.getType().equals(GoodsType.INSTRUMENT)) {
+                    sellOrder.setType(SellTypeEnum.INSTRUMENT);
+                } else if (nowGoods.getType().equals(GoodsType.ACCESSORIES)) {
+                    sellOrder.setType(SellTypeEnum.ACCESSORIES);
+                } else {
+                    sellOrder.setType(SellTypeEnum.OTHER);
+                }
+                sellOrderList.add(sellOrder);
+            }
+        }
+        if (saveFlag && !org.springframework.util.CollectionUtils.isEmpty(sellOrderList)) {
+            this.batchInsert(sellOrderList);
+            this.syncSellOrder2Mall(sellOrderList,order,musicGroupId);
+        }
+        return sellOrderList;
+    }
+
+    @Override
+    @Transactional(rollbackFor = Exception.class)
+    public void deleteByOrderNo(String orderNo) {
+        sellOrderDao.deleteByOrderNo(orderNo);
+    }
+
+    @Override
+    @Transactional(rollbackFor = Exception.class)
+    public void batchUpdate(List<SellOrder> sellOrderList) {
+        sellOrderDao.batchUpdate(sellOrderList);
+    }
+
+    @Override
+    @Transactional(rollbackFor = Exception.class)
+    public void updateSellOrder(List<SellOrder> sellOrderList, StudentPaymentOrder studentPaymentOrder) {
+        //获取总价
+        BigDecimal totalCostPrice = sellOrderList.stream().map(e->e.getExpectAmount()).reduce(BigDecimal.ZERO, BigDecimal::add);
+        //待分配金额
+        BigDecimal waitAmount = studentPaymentOrder.getExpectAmount();
+        for (int i = 0; i < sellOrderList.size(); i++) {
+            SellOrder sellOrder = sellOrderList.get(i);
+            //获取比例
+            BigDecimal proportion = BigDecimal.ZERO;
+            if (totalCostPrice.compareTo(BigDecimal.ZERO) > 0) {
+                proportion = sellOrder.getExpectAmount().divide(totalCostPrice, 16, RoundingMode.DOWN);
+            }
+            if (i == sellOrderList.size() - 1) {
+                sellOrder.setOrderAmount(waitAmount);
+            } else {
+                BigDecimal amount = studentPaymentOrder.getExpectAmount().multiply(proportion).setScale(2, RoundingMode.DOWN);
+                waitAmount = waitAmount.subtract(amount);
+                sellOrder.setOrderAmount(amount);
+            }
+            sellOrder.setActualAmount(sellOrder.getOrderAmount());
+            sellOrder.setExpectAmount(sellOrder.getOrderAmount());
+        }
+        this.batchUpdate(sellOrderList);
+    }
+
+    @Override
+    @Transactional(rollbackFor = Exception.class)
+    public List<SellOrder> initSellOrder(StudentPaymentOrder order, String musicGroupId, List<Integer> goodsIds,
+                                         KitGroupPurchaseTypeEnum kitGroupPurchaseType,Boolean saveFlag) {
+        if (CollectionUtils.isEmpty(goodsIds)) {
+            return null;
+        }
+        BigDecimal totalBalance = order.getBalancePaymentAmount();
+        if (totalBalance == null) {
+            totalBalance = BigDecimal.ZERO;
+        }
+        BigDecimal expectTotalAmount = order.getExpectAmount();
+        BigDecimal couponRemitAmount = order.getCouponRemitFee();
+        BigDecimal actualTotalAmount = order.getActualAmount();
+        return this.initSellOrder(order, musicGroupId, goodsIds, kitGroupPurchaseType, totalBalance, expectTotalAmount,
+                couponRemitAmount, actualTotalAmount,saveFlag==null?true:saveFlag);
+    }
+
     public Map<String, BigDecimal> calcSellAmount(StudentPaymentOrder order,BigDecimal cloudBalanceIncome,BigDecimal cloudIncome) {
         List<StudentPaymentOrderDetail> orderDetails = studentPaymentOrderDetailDao.getOrderDetail(order.getId());
         //总余额支付
@@ -524,13 +619,13 @@ public class SellOrderServiceImpl extends BaseServiceImpl<Integer, SellOrder> im
         //商品总付款
         BigDecimal detailTotalPrice = orderDetails.stream().map(StudentPaymentOrderDetail::getPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
         //商品销售占的余额
-        BigDecimal detailTotalBalance = detailTotalPrice.multiply(totalBalance).divide(totalPrice, 2, BigDecimal.ROUND_DOWN);
+        BigDecimal detailTotalBalance = detailTotalPrice.multiply(totalBalance).divide(totalPrice, 2, RoundingMode.DOWN);
 
         if(detailTotalBalance.subtract(cloudBalanceIncome).compareTo(BigDecimal.ZERO) < 0) {
             detailTotalBalance = cloudBalanceIncome;
         }
 
-        BigDecimal actualAmount = detailTotalPrice.multiply(order.getActualAmount()).divide(totalPrice, 2, BigDecimal.ROUND_DOWN);
+        BigDecimal actualAmount = detailTotalPrice.multiply(order.getActualAmount()).divide(totalPrice, 2, RoundingMode.DOWN);
 
         if(actualAmount.subtract(cloudIncome).compareTo(BigDecimal.ZERO) < 0){
             actualAmount = cloudIncome;

+ 12 - 7
mec-biz/src/main/java/com/ym/mec/biz/service/impl/StudentGoodsSellServiceImpl.java

@@ -3,16 +3,16 @@ package com.ym.mec.biz.service.impl;
 
 import com.alibaba.fastjson.JSONObject;
 import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
-import com.ym.mec.biz.dal.dao.*;
+import com.ym.mec.biz.dal.dao.GoodsDao;
+import com.ym.mec.biz.dal.dao.StudentGoodsSellDao;
+import com.ym.mec.biz.dal.dao.StudentInstrumentDao;
+import com.ym.mec.biz.dal.dao.SysCouponCodeDao;
 import com.ym.mec.biz.dal.dto.GoodsSellDto;
 import com.ym.mec.biz.dal.dto.StudentGoodsSellDto;
 import com.ym.mec.biz.dal.dto.StudentPaymentOrderDto;
 import com.ym.mec.biz.dal.entity.*;
 import com.ym.mec.biz.dal.page.GoodsSellQueryInfo;
-import com.ym.mec.biz.service.StudentGoodsSellService;
-import com.ym.mec.biz.service.SysConfigService;
-import com.ym.mec.biz.service.SysTenantConfigService;
-import com.ym.mec.biz.service.TenantInfoService;
+import com.ym.mec.biz.service.*;
 import com.ym.mec.common.dal.BaseDAO;
 import com.ym.mec.common.page.PageInfo;
 import com.ym.mec.common.service.impl.BaseServiceImpl;
@@ -33,8 +33,6 @@ public class StudentGoodsSellServiceImpl extends BaseServiceImpl<Integer, Studen
     @Autowired
     private StudentGoodsSellDao studentGoodsSellDao;
     @Autowired
-    private SysConfigDao sysConfigDao;
-    @Autowired
     private SysTenantConfigService sysTenantConfigService;
     @Autowired
     private TenantInfoService tenantInfoService;
@@ -45,6 +43,9 @@ public class StudentGoodsSellServiceImpl extends BaseServiceImpl<Integer, Studen
     @Autowired
     private SysCouponCodeDao sysCouponCodeDao;
 
+    @Autowired
+    private GoodsService goodsService;
+
     @Override
     public BaseDAO<Integer, StudentGoodsSell> getDAO() {
         return studentGoodsSellDao;
@@ -146,6 +147,10 @@ public class StudentGoodsSellServiceImpl extends BaseServiceImpl<Integer, Studen
             return null;
         }
         List<Goods> goodies = goodsDao.getGoodiesAndCate(goodsIds);
+        Map<String, String> brandMap = goodsService.getBrandMap();
+        for (Goods goody : goodies) {
+            goody.setBrand(brandMap.getOrDefault(goody.getBrand(),goody.getBrand()));
+        }
         List<StudentInstrument> studentInstruments = new ArrayList<>();
         for (Goods goods : goodies) {
             StudentInstrument studentInstrument = new StudentInstrument();

+ 6 - 0
mec-biz/src/main/java/com/ym/mec/biz/service/impl/StudentInstrumentServiceImpl.java

@@ -305,6 +305,8 @@ public class StudentInstrumentServiceImpl extends BaseServiceImpl<Long, StudentI
     @Override
     public StudentInstrument addStudentInstrument(StudentInstrument studentInstrument) {
         Goods goods = goodsService.get(studentInstrument.getGoodsId());
+
+        goods.setBrand(goodsService.getBrandMap().getOrDefault(goods.getBrand(),goods.getBrand()));
         GoodsCategory goodsCategory = goodsCategoryService.get(goods.getGoodsCategoryId());
         studentInstrument.setGoodsCategoryId(goods.getGoodsCategoryId());
         studentInstrument.setGoodsCategoryName(goodsCategory.getName());
@@ -351,6 +353,8 @@ public class StudentInstrumentServiceImpl extends BaseServiceImpl<Long, StudentI
     @Override
     public StudentInstrument updateStudentInstrument(StudentInstrument studentInstrument) {
         Goods goods = goodsService.get(studentInstrument.getGoodsId());
+
+        goods.setBrand(goodsService.getBrandMap().getOrDefault(goods.getBrand(),goods.getBrand()));
         GoodsCategory goodsCategory = goodsCategoryService.get(goods.getGoodsCategoryId());
         studentInstrument.setGoodsCategoryId(goods.getGoodsCategoryId());
         studentInstrument.setGoodsCategoryName(goodsCategory.getName());
@@ -394,6 +398,8 @@ public class StudentInstrumentServiceImpl extends BaseServiceImpl<Long, StudentI
         }
         
         Goods goods = goodsService.get(studentInstrument.getGoodsId());
+
+        goods.setBrand(goodsService.getBrandMap().getOrDefault(goods.getBrand(),goods.getBrand()));
         GoodsCategory goodsCategory = goodsCategoryService.get(goods.getGoodsCategoryId());
         studentInstrument.setGoodsCategoryId(goods.getGoodsCategoryId());
         studentInstrument.setGoodsCategoryName(goodsCategory.getName());

+ 65 - 0
mec-biz/src/main/java/com/ym/mec/biz/service/impl/StudentPaymentOrderAddressServiceImpl.java

@@ -0,0 +1,65 @@
+package com.ym.mec.biz.service.impl;
+
+import com.alibaba.fastjson.JSON;
+import com.baomidou.mybatisplus.core.metadata.IPage;
+import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
+import org.springframework.stereotype.Service;
+import lombok.extern.slf4j.Slf4j;
+import com.ym.mec.biz.dal.entity.StudentPaymentOrderAddress;
+import com.ym.mec.biz.dal.wrapper.StudentPaymentOrderAddressWrapper;
+import com.ym.mec.biz.dal.mapper.StudentPaymentOrderAddressMapper;
+import com.ym.mec.biz.service.StudentPaymentOrderAddressService;
+
+/**
+ * 学生订单收货地址
+ * 2024-03-01 12:05:41
+ */
+@Slf4j
+@Service
+public class StudentPaymentOrderAddressServiceImpl extends ServiceImpl<StudentPaymentOrderAddressMapper, StudentPaymentOrderAddress> implements StudentPaymentOrderAddressService {
+
+	/**
+     * 查询详情
+     * @param id 详情ID
+     * @return StudentPaymentOrderAddress
+     */
+	@Override
+    public StudentPaymentOrderAddress detail(Long id) {
+        
+        return baseMapper.selectById(id);
+    }
+    
+    /**
+     * 分页查询
+     * @param page IPage<StudentPaymentOrderAddress>
+     * @param query StudentPaymentOrderAddressWrapper.StudentPaymentOrderAddressQuery
+     * @return IPage<StudentPaymentOrderAddress>
+     */
+    @Override
+    public IPage<StudentPaymentOrderAddress> selectPage(IPage<StudentPaymentOrderAddress> page, StudentPaymentOrderAddressWrapper.StudentPaymentOrderAddressQuery query) {
+        
+        return page.setRecords(baseMapper.selectPage(page, query));
+    }
+	
+    /**
+     * 添加
+     * @param studentPaymentOrderAddress StudentPaymentOrderAddressWrapper.StudentPaymentOrderAddress
+     * @return Boolean
+     */
+    @Override
+    public Boolean add(StudentPaymentOrderAddressWrapper.StudentPaymentOrderAddress studentPaymentOrderAddress) {    	
+        
+        return this.save(JSON.parseObject(studentPaymentOrderAddress.jsonString(), StudentPaymentOrderAddress.class));
+    }
+
+    /**
+     * 更新
+     * @param studentPaymentOrderAddress StudentPaymentOrderAddressWrapper.StudentPaymentOrderAddress
+     * @return Boolean
+     */
+    @Override
+    public Boolean update(StudentPaymentOrderAddressWrapper.StudentPaymentOrderAddress studentPaymentOrderAddress){
+
+        return this.updateById(JSON.parseObject(studentPaymentOrderAddress.jsonString(), StudentPaymentOrderAddress.class));       
+    }
+}

+ 118 - 51
mec-biz/src/main/java/com/ym/mec/biz/service/impl/StudentPaymentOrderDetailServiceImpl.java

@@ -1,6 +1,7 @@
 package com.ym.mec.biz.service.impl;
 
 import com.ym.mec.biz.dal.dao.*;
+import com.ym.mec.biz.dal.dto.GoodsSellDto;
 import com.ym.mec.biz.dal.dto.MusicalListDetailDto;
 import com.ym.mec.biz.dal.entity.*;
 import com.ym.mec.biz.dal.enums.*;
@@ -10,13 +11,12 @@ import com.ym.mec.common.exception.BizException;
 import com.ym.mec.common.page.WrapperUtil;
 import com.ym.mec.common.service.impl.BaseServiceImpl;
 import com.ym.mec.util.collection.MapUtil;
-
 import org.apache.commons.collections.CollectionUtils;
 import org.apache.commons.lang3.StringUtils;
-import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
 import org.springframework.transaction.annotation.Transactional;
 
+import javax.annotation.Resource;
 import java.math.BigDecimal;
 import java.math.RoundingMode;
 import java.util.*;
@@ -29,48 +29,43 @@ import static com.ym.mec.biz.dal.enums.PaymentStatusEnum.YES;
 @Service
 public class StudentPaymentOrderDetailServiceImpl extends BaseServiceImpl<Long, StudentPaymentOrderDetail> implements StudentPaymentOrderDetailService {
 
-    @Autowired
+    @Resource
     private StudentPaymentOrderDetailDao studentPaymentOrderDetailDao;
-    @Autowired
+    @Resource
     private GoodsService goodsService;
-    @Autowired
+    @Resource
     private TeacherDao teacherDao;
-    @Autowired
+    @Resource
     private MusicGroupDao musicGroupDao;
-    @Autowired
+    @Resource
     private OrganizationDao organizationDao;
-    @Autowired
+    @Resource
     private MusicGroupPurchaseListDao musicGroupPurchaseListDao;
-    @Autowired
+    @Resource
     private StudentRegistrationDao studentRegistrationDao;
-    @Autowired
+    @Resource
     private SubjectDao subjectDao;
-    @Autowired
+    @Resource
     private SubjectChangeDao subjectChangeDao;
-    @Autowired
+    @Resource
     private StudentCourseFeeDetailDao studentCourseFeeDetailDao;
-    @Autowired
+    @Resource
     private SellOrderService sellOrderService;
-    @Autowired
+    @Resource
     private ActivityUserMapperService activityUserMapperService;
-    @Autowired
+    @Resource
     private StudentInstrumentService studentInstrumentService;
-    @Autowired
+    @Resource
     private CloudTeacherOrderService cloudTeacherOrderService;
-    @Autowired
+    @Resource
     private StudentPaymentOrderService studentPaymentOrderService;
-    @Autowired
+    @Resource
     private MusicGroupPaymentCalenderDetailService musicGroupPaymentCalenderDetailService;
-    @Autowired
-    private ChargeTypeSubjectMapperDao chargeTypeSubjectMapperDao;
-    @Autowired
-    private StudentMusicCourseFeeService studentMusicCourseFeeService;
-    @Autowired
+    @Resource
     private MemberFeeSettingService memberFeeSettingService;
-    @Autowired
+    @Resource
     private MusicGroupPaymentCalenderMemberDao musicGroupPaymentCalenderMemberDao;
-
-    @Autowired
+    @Resource
     private ImUserFriendService imUserFriendService;
     @Override
     public BaseDAO<Long, StudentPaymentOrderDetail> getDAO() {
@@ -84,6 +79,28 @@ public class StudentPaymentOrderDetailServiceImpl extends BaseServiceImpl<Long,
 
     @Transactional(rollbackFor = Exception.class)
     @Override
+    public int batchAdd(List<StudentPaymentOrderDetail> studentPaymentOrderDetailList,BigDecimal couponRemitFee,BigDecimal expectAmount) {
+        if(couponRemitFee.compareTo(BigDecimal.ZERO) > 0 && expectAmount.compareTo(BigDecimal.ZERO) > 0){
+            BigDecimal subCouponRemitFee = couponRemitFee;
+            for (int i = 0; i < studentPaymentOrderDetailList.size(); i++) {
+                StudentPaymentOrderDetail orderDetail = studentPaymentOrderDetailList.get(i);
+                if (i == studentPaymentOrderDetailList.size() - 1) {
+                    orderDetail.setRemitFee(subCouponRemitFee);
+                } else {
+                    //获取比例
+                    BigDecimal ratioAmount = orderDetail.getPrice().divide(expectAmount, 16, RoundingMode.DOWN);
+                    //获取分配的减免金额
+                    BigDecimal multiply = ratioAmount.multiply(couponRemitFee).setScale(2, RoundingMode.DOWN);
+                    subCouponRemitFee = subCouponRemitFee.subtract(multiply);
+                    orderDetail.setRemitFee(multiply);
+                }
+            }
+        }
+        return studentPaymentOrderDetailDao.batchAdd(studentPaymentOrderDetailList);
+    }
+
+    @Transactional(rollbackFor = Exception.class)
+    @Override
     public int batchAdd(List<StudentPaymentOrderDetail> studentPaymentOrderDetailList) {
         return Optional.ofNullable(studentPaymentOrderDetailList)
                 .filter(CollectionUtils::isNotEmpty)
@@ -133,9 +150,9 @@ public class StudentPaymentOrderDetailServiceImpl extends BaseServiceImpl<Long,
                     orderDetail.setRemitFee(orderDetail.getRemitFee().add(waitRemitFee));
                 } else {
                     //获取比例
-                    BigDecimal ratioAmount = orderDetail.getPrice().divide(totalAmount, 6, RoundingMode.HALF_UP);
+                    BigDecimal ratioAmount = orderDetail.getPrice().divide(totalAmount, 16, RoundingMode.DOWN);
                     //获取分配的减免金额
-                    BigDecimal multiply = ratioAmount.multiply(couponRemitFee).setScale(2, RoundingMode.HALF_UP);
+                    BigDecimal multiply = ratioAmount.multiply(couponRemitFee).setScale(2, RoundingMode.DOWN);
                     waitRemitFee = waitRemitFee.subtract(multiply);
                     useRemitFee = useRemitFee.add(multiply);
                     orderDetail.setPrice(orderDetail.getPrice().subtract(multiply));
@@ -294,7 +311,7 @@ public class StudentPaymentOrderDetailServiceImpl extends BaseServiceImpl<Long,
     public List<Goods> findApplyOrderGoods(Long orderId) {
         List<StudentPaymentOrderDetail> applyOrderGoods = studentPaymentOrderDetailDao.findApplyOrderGoods(orderId);
 
-        if (applyOrderGoods == null || applyOrderGoods.size() == 0) {
+        if (CollectionUtils.isEmpty(applyOrderGoods)) {
             return null;
         }
         String goodsIdsStr = "";
@@ -633,7 +650,6 @@ public class StudentPaymentOrderDetailServiceImpl extends BaseServiceImpl<Long,
         //SurplusCourseFee
         Integer userId = studentPaymentOrder.getUserId();
         Long orderId = studentPaymentOrder.getId();
-        String musicGroupId = musicGroup.getId();
         Integer tenantId = studentPaymentOrder.getTenantId();
         List<StudentPaymentOrderDetail> allDetails = this.findByOrderId(orderId);
         BigDecimal courseFee = allDetails.stream().filter(o -> !(o.getType() == MUSICAL)
@@ -685,27 +701,7 @@ public class StudentPaymentOrderDetailServiceImpl extends BaseServiceImpl<Long,
 
         //销售订单详情
         if (allDetails.size() > 0 && (detailTypeEnums.contains(MUSICAL) || detailTypeEnums.contains(ACCESSORIES) || detailTypeEnums.contains(TEACHING))) {
-            BigDecimal couponRemitFee = studentPaymentOrder.getCouponRemitFee();
-            if (couponRemitFee.compareTo(BigDecimal.ZERO) > 0) {
-                BigDecimal musicFee = allDetails.stream()
-                        .filter(o -> o.getType() == MUSICAL || o.getType() == ACCESSORIES || o.getType() == TEACHING)
-                        .map(StudentPaymentOrderDetail::getPrice)
-                        .reduce(BigDecimal.ZERO, BigDecimal::add);
-                BigDecimal expectAmount = studentPaymentOrder.getExpectAmount();
-                
-				BigDecimal organShareProfit = allDetails.stream().filter(o -> o.getType() == ORGAN_SHARE_PROFIT).map(StudentPaymentOrderDetail::getPrice)
-						.reduce(BigDecimal.ZERO, BigDecimal::add);
-				
-				if(organShareProfit != null){
-					expectAmount = expectAmount.subtract(organShareProfit);
-				}
-                
-                //获取比例
-                BigDecimal ratioAmount = musicFee.divide(expectAmount, 6, BigDecimal.ROUND_HALF_UP);
-                //获取分配的减免金额
-                couponRemitFee = couponRemitFee.multiply(ratioAmount).setScale(2, BigDecimal.ROUND_HALF_UP);
-            }
-            sellOrderService.addOrderDetail2SellOrder(allDetails, studentPaymentOrder, musicGroup, couponRemitFee);
+            sellOrderService.addOrderDetail2SellOrder(allDetails, studentPaymentOrder, musicGroup.getId());
         }
 
         //活动小课包处理
@@ -865,4 +861,75 @@ public class StudentPaymentOrderDetailServiceImpl extends BaseServiceImpl<Long,
         }
         return paymentOrderDetails;
     }
+
+
+    @Override
+    @Transactional(rollbackFor = Exception.class)
+    public List<StudentPaymentOrderDetail> initStudentPaymentOrderDetail(StudentPaymentOrder studentPaymentOrder, List<GoodsSellDto> goodsSellDtos){
+        Date date = new Date();
+        //添加订单详情
+        List<StudentPaymentOrderDetail> studentPaymentOrderDetailList = new ArrayList<StudentPaymentOrderDetail>();
+        // 添加studentPaymentOrderDetail
+        StudentPaymentOrderDetail studentPaymentOrderDetail = null;
+
+        if (goodsSellDtos != null) {
+            StringBuffer sb = new StringBuffer();
+            for (GoodsSellDto goodsSellDto : goodsSellDtos) {
+                for (int i = 0; i < goodsSellDto.getGoodsNum(); i++) {
+                    sb.append(goodsSellDto.getGoodsId()).append(",");
+                }
+            }
+            String goodsIdsStr = StringUtils.removeEnd(sb.toString(), ",");
+
+            List<Goods> goodsList = goodsService.findGoodsByIds(goodsIdsStr);
+            Map<Integer, Goods> goodsMap = goodsList.stream().collect(Collectors.toMap(Goods::getId, t -> t));
+            BigDecimal totalGroupPurchasePrice =
+                    goodsSellDtos.stream().map(t -> goodsMap.get(t.getGoodsId()).getDiscountPrice().
+                            multiply(new BigDecimal(t.getGoodsNum()))).reduce(BigDecimal.ZERO, BigDecimal::add);
+
+            String[] goodsIds = goodsIdsStr.split(",");
+            BigDecimal subTotalPrice = studentPaymentOrder.getExpectAmount();
+            for (int i = 0; i < goodsIds.length; i++) {
+                String goodsIdStr = goodsIds[i];
+                if (StringUtils.isBlank(goodsIdStr)) {
+                    continue;
+                }
+                Goods goods = goodsMap.get(Integer.parseInt(goodsIdStr));
+                studentPaymentOrderDetail = new StudentPaymentOrderDetail();
+                studentPaymentOrderDetail.setCreateTime(date);
+                studentPaymentOrderDetail.setTenantId(studentPaymentOrder.getTenantId());
+                if (goods.getType() == GoodsType.INSTRUMENT) {
+                    studentPaymentOrderDetail.setType(OrderDetailTypeEnum.MUSICAL);
+                } else if (goods.getType() == GoodsType.ACCESSORIES) {
+                    studentPaymentOrderDetail.setType(OrderDetailTypeEnum.ACCESSORIES);
+                } else if (goods.getType() == GoodsType.TEACHING || goods.getType() == GoodsType.STAFF) {
+                    studentPaymentOrderDetail.setType(OrderDetailTypeEnum.TEACHING);
+                } else {
+                    studentPaymentOrderDetail.setType(OrderDetailTypeEnum.OTHER);
+                }
+                studentPaymentOrderDetail.setGoodsIdList(goodsIdStr);
+
+                //获取比例
+                BigDecimal tempPrice = BigDecimal.ZERO;
+                if (totalGroupPurchasePrice.compareTo(BigDecimal.ZERO) > 0) {
+                    tempPrice = goods.getDiscountPrice().divide(totalGroupPurchasePrice,16, RoundingMode.DOWN);
+                }
+                if(i == goodsIds.length - 1){
+                    studentPaymentOrderDetail.setPrice(subTotalPrice);
+                }else {
+                    BigDecimal decimal = studentPaymentOrder.getExpectAmount().multiply(tempPrice).setScale(2, RoundingMode.DOWN);
+                    studentPaymentOrderDetail.setPrice(decimal);
+                    subTotalPrice = subTotalPrice.subtract(decimal);
+                }
+                studentPaymentOrderDetail.setUpdateTime(date);
+                studentPaymentOrderDetail.setPaymentOrderId(studentPaymentOrder.getId());
+                studentPaymentOrderDetailList.add(studentPaymentOrderDetail);
+            }
+        }
+
+        if (CollectionUtils.isNotEmpty(studentPaymentOrderDetailList)) {
+            this.batchAdd(studentPaymentOrderDetailList,studentPaymentOrder.getCouponRemitFee(),studentPaymentOrder.getExpectAmount());
+        }
+        return studentPaymentOrderDetailList;
+    }
 }

+ 175 - 153
mec-biz/src/main/java/com/ym/mec/biz/service/impl/StudentPaymentOrderServiceImpl.java

@@ -18,6 +18,7 @@ import com.ym.mec.common.dal.BaseDAO;
 import com.ym.mec.common.entity.HttpResponseResult;
 import com.ym.mec.common.entity.MallCreateOrderModel;
 import com.ym.mec.common.entity.OrderCancelModel;
+import com.ym.mec.common.entity.OrderSkuSync;
 import com.ym.mec.common.exception.BizException;
 import com.ym.mec.common.page.PageInfo;
 import com.ym.mec.common.page.PageUtil;
@@ -44,10 +45,13 @@ import org.springframework.stereotype.Service;
 import org.springframework.transaction.annotation.Propagation;
 import org.springframework.transaction.annotation.Transactional;
 
+import javax.annotation.Resource;
 import java.io.IOException;
 import java.math.BigDecimal;
+import java.math.RoundingMode;
 import java.util.*;
 import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.Function;
 import java.util.stream.Collectors;
 
 import static com.ym.mec.biz.dal.enums.DealStatusEnum.CLOSE;
@@ -56,89 +60,92 @@ import static com.ym.mec.biz.dal.enums.DealStatusEnum.SUCCESS;
 @Service
 public class StudentPaymentOrderServiceImpl extends BaseServiceImpl<Long, StudentPaymentOrder> implements StudentPaymentOrderService {
 
-    @Autowired
+    @Resource
     private StudentPaymentOrderDao studentPaymentOrderDao;
-    @Autowired
+    @Resource
     private YqPayFeignService yqPayFeignService;
-    @Autowired
+    @Resource
     private StudentRegistrationService studentRegistrationService;
-    @Autowired
+    @Resource
     @Lazy
     private VipGroupService vipGroupService;
-    @Autowired
+    @Resource
     private MusicGroupService musicGroupService;
-    @Autowired
+    @Resource
     private SporadicChargeInfoService sporadicChargeInfoService;
-    @Autowired
+    @Resource
     private PracticeGroupService practiceGroupService;
-    @Autowired
-    private SysUserCashAccountDao sysUserCashAccountDao;
-    @Autowired
+    @Resource
     private StudentRepairService studentRepairService;
-    @Autowired
+    @Resource
     private SysUserCashAccountService sysUserCashAccountService;
-    @Autowired
+    @Resource
     private SubjectChangeService subjectChangeService;
-    @Autowired
+    @Resource
     private DegreeRegistrationService degreeRegistrationService;
-    @Autowired
-    private StudentPaymentRouteOrderDao studentPaymentRouteOrderDao;
-    @Autowired
+    @Resource
     private StudentPaymentOrderDetailService studentPaymentOrderDetailService;
-    @Autowired
+    @Resource
     private IdGeneratorService idGeneratorService;
-    @Autowired
+    @Resource
     private SysConfigDao sysConfigDao;
-    @Autowired
-    private GoodsDao goodsDao;
-    @Autowired
+    @Resource
     private GoodsService goodsService;
-    @Autowired
+    @Resource
     private StudentInstrumentService studentInstrumentService;
-    @Autowired
+    @Resource
     private ReplacementInstrumentActivityService replacementInstrumentActivityService;
-    @Autowired
+    @Resource
     private ChildrenDayReserveService childrenDayReserveService;
-    @Autowired
+    @Resource
     private MemberRankSettingService memberRankSettingService;
-    @Autowired
+    @Resource
     private PayService payService;
-    @Autowired
+    @Resource
     private StudentPaymentRouteOrderService studentPaymentRouteOrderService;
-    @Autowired
+    @Resource
     private CloudTeacherOrderService cloudTeacherOrderService;
-    @Autowired
+    @Resource
     private SysCouponCodeService sysCouponCodeService;
-    @Autowired
+    @Resource
     private VipGroupActivityService vipGroupActivityService;
-    @Autowired
+    @Resource
     private ActivityUserMapperService activityUserMapperService;
-    @Autowired
+    @Resource
     private MusicGroupSubjectPlanService musicGroupSubjectPlanService;
-    @Autowired
+    @Resource
     private SysUserFeignService sysUserFeignService;
-    @Autowired
+    @Resource
     private TenantConfigService tenantConfigService;
-    @Autowired
+    @Resource
     private GoodsProcurementDao goodsProcurementDao;
-    @Autowired
+    @Resource
     private SysPaymentConfigService sysPaymentConfigService;
-    @Autowired
+    @Resource
     private SellOrderDao sellOrderDao;
     @Lazy
-    @Autowired
+    @Resource
     private ContractService contractService;
-    @Autowired
+    @Resource
     private HfMerchantConfigService hfMerchantConfigService;
-    @Autowired
+    @Resource
     private StudentDao studentDao;
-    @Autowired
+    @Resource
     private SysUserCashAccountDetailService sysUserCashAccountDetailService;
-    
-    @Autowired
+    @Resource
     private YeepayPaymentService yeepayPaymentService;
-    @Autowired
+    @Resource
     private CourseScheduleStudentPaymentDao courseScheduleStudentPaymentDao;
+    @Resource
+    private StudentRepairDao studentRepairDao;
+    @Resource
+    private MusicGroupDao musicGroupDao;
+    @Resource
+    private StudentGoodsSellDao studentGoodsSellDao;
+    @Resource
+    private StudentPaymentOrderService studentPaymentOrderService;
+    @Resource
+    private MusicGroupPaymentCalenderAddressService musicGroupPaymentCalenderAddressService;
 
     private final Logger logger = LoggerFactory.getLogger(this.getClass());
     @Override
@@ -424,11 +431,11 @@ public class StudentPaymentOrderServiceImpl extends BaseServiceImpl<Long, Studen
     @Override
     @Transactional(rollbackFor = Exception.class)
     public void updateOrder(Map<String, String> rpMap) throws Exception {
-        DealStatusEnum status = "1".equals(rpMap.get("tradeState")) ? DealStatusEnum.SUCCESS : DealStatusEnum.FAILED;
+        DealStatusEnum status = "1".equals(rpMap.get("tradeState")) ? SUCCESS : DealStatusEnum.FAILED;
         StudentPaymentOrder order = findOrderByOrderNo(rpMap.get("merOrderNo"));
         //关闭或失败的订单查询订单成功,订单改成成功,钱退到余额
-        if (order != null && (order.getStatus().equals(DealStatusEnum.CLOSE) || order.getStatus().equals(DealStatusEnum.FAILED)) && status.equals(DealStatusEnum.SUCCESS)) {
-            String memo = order.getStatus().equals(DealStatusEnum.CLOSE) ? "关闭订单" : "失败订单";
+        if (order != null && (order.getStatus().equals(CLOSE) || order.getStatus().equals(DealStatusEnum.FAILED)) && status.equals(SUCCESS)) {
+            String memo = order.getStatus().equals(CLOSE) ? "关闭订单" : "失败订单";
             memo = memo + ",实际支付成功,退到用户余额";
             //更新订单状态
             order.setStatus(status);
@@ -455,7 +462,7 @@ public class StudentPaymentOrderServiceImpl extends BaseServiceImpl<Long, Studen
             return;
         }
 
-        if (status.equals(DealStatusEnum.SUCCESS)) {
+        if (status.equals(SUCCESS)) {
             order.setPayTime(new Date());
         } else {
             order.setMemo(rpMap.get("remarks"));
@@ -473,7 +480,7 @@ public class StudentPaymentOrderServiceImpl extends BaseServiceImpl<Long, Studen
 
         callOrderCallBack(order);
 
-        if (status.equals(DealStatusEnum.SUCCESS)
+        if (status.equals(SUCCESS)
                 && StringUtils.isNotBlank(order.getPaymentChannel())
                 && (order.getPaymentChannel().equals(PaymentChannelEnum.ADAPAY.getCode()) || order.getPaymentChannel().equals(PaymentChannelEnum.YEEPAY.getCode()))
                 && !rpMap.containsKey("simulation")) {
@@ -492,7 +499,7 @@ public class StudentPaymentOrderServiceImpl extends BaseServiceImpl<Long, Studen
         
         HfMerchantConfig hfMerchantConfig = null;
         
-        List<StudentPaymentRouteOrder> routeOrders = studentPaymentRouteOrderDao.getRouteOrders(order.getOrderNo());
+        List<StudentPaymentRouteOrder> routeOrders = studentPaymentRouteOrderService.getDao().getRouteOrders(order.getOrderNo());
         
         PaymentChannelEnum paymentChannel = PaymentChannelEnum.codeOf(order.getPaymentChannel());
         
@@ -530,7 +537,7 @@ public class StudentPaymentOrderServiceImpl extends BaseServiceImpl<Long, Studen
                     LOGGER.info("分账信息返回:{}", map);
                     routeOrder.setServiceFee(new BigDecimal(map.get("fee_amt").toString()));
                     routeOrder.setUpdateTime(date);
-                    studentPaymentRouteOrderDao.update(routeOrder);
+                    studentPaymentRouteOrderService.getDao().update(routeOrder);
                 } catch (Exception e) {
                 	LOGGER.error("分账失败 orderId:{}", order.getId(), e);
                     continue;
@@ -588,51 +595,13 @@ public class StudentPaymentOrderServiceImpl extends BaseServiceImpl<Long, Studen
 
 			for (StudentPaymentRouteOrder spro : routeOrders) {
 
-				studentPaymentRouteOrderDao.update(spro);
+                studentPaymentRouteOrderService.getDao().update(spro);
 			}
 		}
         
         return true;
     }
 
-    //Date date = new Date();
-    //        BigDecimal balance = BigDecimal.ZERO;
-    //        MusicGroup musicGroup = musicGroupDao.get(studentRegistration.getMusicGroupId());
-    //        if (registerPayDto.getIsUseBalancePayment() && amount.compareTo(BigDecimal.ZERO) > 0) {
-    //            SysUserCashAccount userCashAccount = sysUserCashAccountService.getLocked(userId);
-    //            if (userCashAccount == null) {
-    //                throw new BizException("用户账户找不到");
-    //            }
-    //            if (userCashAccount.getBalance() != null && userCashAccount.getBalance().compareTo(BigDecimal.ZERO) > 0) {
-    //                balance = amount.compareTo(userCashAccount.getBalance()) >= 0 ? userCashAccount.getBalance() : amount;
-    //                amount = amount.subtract(balance);
-    //                studentPaymentOrder.setPaymentChannel("BALANCE");
-    //                studentPaymentOrder.setActualAmount(amount);
-    //                studentPaymentOrder.setBalancePaymentAmount(balance);
-    //                sysUserCashAccountService.updateBalance(userId, balance.negate(), PlatformCashAccountDetailTypeEnum.PAY_FEE, "乐团报名");
-    //            }
-    //        }
-    //        studentPaymentOrder.setPaymentChannel("BALANCE");
-    //        studentPaymentOrder.setRemitFee(remitFee);
-    //        studentPaymentOrder.setCourseRemitFee(courseRemitFee);
-    //        studentPaymentOrder.setOrganId(musicGroup.getOrganId());
-    //        studentPaymentOrder.setRoutingOrganId(musicGroup.getOrganId());
-    //        studentPaymentOrder.setUpdateTime(date);
-    //        studentPaymentOrderService.update(studentPaymentOrder);
-    //        studentPaymentOrder.setVersion(studentPaymentOrder.getVersion() + 1);
-    //
-    //        if (amount.compareTo(BigDecimal.ZERO) == 0) {
-    //            //如果赠送网管课
-    //            studentPaymentRouteOrderService.addRouteOrder(orderNo, musicGroup.getOrganId(), balance);
-    //            Map<String, String> notifyMap = new HashMap<>();
-    //            notifyMap.put("tradeState", "1");
-    //            notifyMap.put("merOrderNo", studentPaymentOrder.getOrderNo());
-    //            notifyMap.put("channelType", channelType);
-    //            notifyMap.put("orderNo", "");
-    //            studentPaymentOrderService.updateOrder(notifyMap);
-    //            return notifyMap;
-    //        }
-
     //调用相应业务回调接口
     @Override
     public void callOrderCallBack(StudentPaymentOrder order) throws Exception {
@@ -674,7 +643,7 @@ public class StudentPaymentOrderServiceImpl extends BaseServiceImpl<Long, Studen
                 memberRankSettingService.liveBuyOrderCallback(order);
             } else if (order.getType().equals(OrderTypeEnum.MALL_BUY)) {
                 // 商城购买订单回调
-                this.mallBuyOrderCallback(order);
+                studentPaymentOrderService.mallBuyOrderCallback(order);
             }
         }
     }
@@ -755,7 +724,7 @@ public class StudentPaymentOrderServiceImpl extends BaseServiceImpl<Long, Studen
         int count = this.findCount(params);
         count = count + jmCount;
 
-        BigDecimal totalUserBalance = sysUserCashAccountDao.getTotalUserBalance(params);
+        BigDecimal totalUserBalance = sysUserCashAccountService.getDao().getTotalUserBalance(params);
         pageInfo.setTotalUserBalance(totalUserBalance);
         if (count > 0) {
             pageInfo.setTotal(count);
@@ -837,7 +806,7 @@ public class StudentPaymentOrderServiceImpl extends BaseServiceImpl<Long, Studen
         List<StudentPaymentOrderExportDto> orders = studentPaymentOrderDao.getUserApplyOrders(studentId, musicGroupId);
         StudentRegistration studentRegister = studentRegistrationService.getStudentRegister(musicGroupId, studentId);
         for (StudentPaymentOrderExportDto order : orders) {
-            if ((DealStatusEnum.ING.equals(order.getStatus()) || DealStatusEnum.SUCCESS.equals(order.getStatus())) &&
+            if ((DealStatusEnum.ING.equals(order.getStatus()) || SUCCESS.equals(order.getStatus())) &&
                     studentRegister.getPayingStatus().equals(2)) {
                 order.setPayingStatus(2);
             }
@@ -858,7 +827,7 @@ public class StudentPaymentOrderServiceImpl extends BaseServiceImpl<Long, Studen
                     }
                 }
                 if (StringUtils.isNotBlank(childGoodIds)) {
-                    studentPaymentOrderDetail.setChildGoodsList(goodsDao.findGoodsByIds(childGoodIds));
+                    studentPaymentOrderDetail.setChildGoodsList(goodsService.getGoodsDao().findGoodsByIds(childGoodIds));
                 }
                 if (studentPaymentOrderDetail.getType() == OrderDetailTypeEnum.CLOUD_TEACHER || studentPaymentOrderDetail.getType() == OrderDetailTypeEnum.CLOUD_TEACHER_PLUS) {
                     studentPaymentOrderDetail.setCloudTeacherOrderDto(cloudTeacherOrderService.queryOrderInfoByOrderId(studentPaymentOrderDetail.getPaymentOrderId()));
@@ -1082,7 +1051,7 @@ public class StudentPaymentOrderServiceImpl extends BaseServiceImpl<Long, Studen
             return BaseController.failed(HttpStatus.CONTINUE, "您有支付中的订单,是否继续支付");
         }
         //处理关闭订单
-        order.setStatus(DealStatusEnum.CLOSE);
+        order.setStatus(CLOSE);
         order.setMemo("关闭订单");
 
         
@@ -1091,13 +1060,11 @@ public class StudentPaymentOrderServiceImpl extends BaseServiceImpl<Long, Studen
         List<StudentPaymentOrderDetail> studentPaymentOrderDetailList = studentPaymentOrderDetailService.queryOrderDetail(order.getId());
         String goodsIds = studentPaymentOrderDetailList.stream().filter(t -> StringUtils.isNotBlank(t.getMinuendStockGoodsIdList())).map(t -> t.getMinuendStockGoodsIdList()).collect(Collectors.joining(","));
         if(StringUtils.isNotBlank(goodsIds)){
-        	GoodsProcurement goodsProcurement = null;
         	List<Goods> goodsList = goodsService.getGoodsWithLocked(goodsIds);
         	Map<Integer,Goods> goodsMap = goodsList.stream().collect(Collectors.toMap(Goods :: getId, t -> t));
         	Goods goods = null;
 			Map<Integer, Goods> batchUpdateGoodsMap = new HashMap<Integer, Goods>();
-			Map<Long, GoodsProcurement> goodsProcurementMap = new HashMap<Long, GoodsProcurement>();
-        	
+
         	for(String goodsIdStr : goodsIds.split(",")){
         		if(StringUtils.isBlank(goodsIdStr)){
 					continue;
@@ -1106,29 +1073,11 @@ public class StudentPaymentOrderServiceImpl extends BaseServiceImpl<Long, Studen
 				if(batchUpdateGoodsMap.get(goods.getId()) != null){
 					goods = batchUpdateGoodsMap.get(goods.getId());
 				}
-				goods.setStockCount(new AtomicInteger(goods.getStockCount()).incrementAndGet());
 				goods.setSellCount(new AtomicInteger(goods.getSellCount()).decrementAndGet());
 				goods.setUpdateTime(nowDate);
 				
 				batchUpdateGoodsMap.put(goods.getId(), goods);
-				
-				// 进货清单
-				goodsProcurement = goodsProcurementDao.getWithStockSurplusProcurement(goods.getId());
-				if(goodsProcurement != null){
-					if(goodsProcurementMap.get(goodsProcurement.getId()) != null){
-						goodsProcurement = goodsProcurementMap.get(goodsProcurement.getId());
-					}
-					goodsProcurement.setStockSoldNum(new AtomicInteger(goodsProcurement.getStockSoldNum()).decrementAndGet());
-					goodsProcurement.setUpdateTime(nowDate);
-					goodsProcurementMap.put(goodsProcurement.getId(), goodsProcurement);
-				}
-				
         	}
-        	
-        	if(goodsProcurementMap.size() > 0){
-        		goodsProcurementDao.batchUpdate(new ArrayList<GoodsProcurement>(goodsProcurementMap.values()));
-        	}
-            
             if(batchUpdateGoodsMap.size() > 0){
             	goodsService.batchUpdate(new ArrayList<Goods>(batchUpdateGoodsMap.values()));
             }
@@ -1155,7 +1104,7 @@ public class StudentPaymentOrderServiceImpl extends BaseServiceImpl<Long, Studen
             StudentRegistration studentRegistration = studentRegistrationService.getStudentRegister(musicGroupId, userId);
             //获取学员在乐团的状态,如果是在读,那么不处理人数
             if (studentRegistration.getMusicGroupStatus() == StudentMusicGroupStatusEnum.APPLY) {
-                List<StudentPaymentOrder> oldStudentPaymentOrderList = this.queryByCondition(GroupType.MUSIC, musicGroupId, userId, DealStatusEnum.SUCCESS, OrderTypeEnum.APPLY);
+                List<StudentPaymentOrder> oldStudentPaymentOrderList = this.queryByCondition(GroupType.MUSIC, musicGroupId, userId, SUCCESS, OrderTypeEnum.APPLY);
                 //判断是否有成功的订单,如果有,表示已经处理过人数
                 if (oldStudentPaymentOrderList == null || oldStudentPaymentOrderList.size() == 0) {
                     List<StudentPaymentOrderDetail> orderDetail = studentPaymentOrderDetailService.getOrderDetail(order.getId());
@@ -1245,14 +1194,6 @@ public class StudentPaymentOrderServiceImpl extends BaseServiceImpl<Long, Studen
         return studentPaymentOrderDao.getMemberIngOrder(member, status);
     }
 
-    @Autowired
-    private StudentRepairDao studentRepairDao;
-    @Autowired
-    private MusicGroupDao musicGroupDao;
-
-    @Autowired
-    private StudentGoodsSellDao studentGoodsSellDao;
-
     @Override
     @Transactional
     public Map createOrder(MallCreateOrderModel model) throws Exception {
@@ -1322,7 +1263,7 @@ public class StudentPaymentOrderServiceImpl extends BaseServiceImpl<Long, Studen
 
         studentPaymentOrder.setStatus(DealStatusEnum.ING);
         if (studentPaymentOrder.getActualAmount().compareTo(BigDecimal.ZERO) == 0) {
-            studentPaymentOrder.setStatus(DealStatusEnum.SUCCESS);
+            studentPaymentOrder.setStatus(SUCCESS);
         }
         studentPaymentOrder.setGroupType(GroupType.MALL_SELL);
         studentPaymentOrder.setUserId(model.getUserId());
@@ -1427,7 +1368,7 @@ public class StudentPaymentOrderServiceImpl extends BaseServiceImpl<Long, Studen
     }
 
     @Override
-    @Transactional
+    @Transactional(rollbackFor = Exception.class)
     public void mallBuyOrderCallback(StudentPaymentOrder studentPaymentOrder) {
         Date nowDate = new Date();
         //更新订单信息
@@ -1442,7 +1383,7 @@ public class StudentPaymentOrderServiceImpl extends BaseServiceImpl<Long, Studen
         Map<Integer, String> map = new HashMap<>();
         map.put(userId, userId.toString());
 
-        if (studentPaymentOrder.getStatus() == DealStatusEnum.SUCCESS) {
+        if (studentPaymentOrder.getStatus() == SUCCESS) {
             try {
                 contractService.transferProduceContract(userId, null, studentPaymentOrder.getType());
             } catch (Exception e) {
@@ -1465,7 +1406,7 @@ public class StudentPaymentOrderServiceImpl extends BaseServiceImpl<Long, Studen
                         //如果有空的商品货号,不处理
                         if(count == 0l){
                             List<String> productSns = goodsOrderItemVOS.stream().map(e -> e.getProductSn()).distinct().collect(Collectors.toList());
-                            List<Goods> goodsList = goodsDao.findBySns(productSns);
+                            List<Goods> goodsList = goodsService.getGoodsDao().findBySns(productSns);
                             //如果有不匹配的商品货号,不处理
                             if(CollectionUtils.isEmpty(goodsList) || goodsList.size() < productSns.size()){
                                 return;
@@ -1499,8 +1440,8 @@ public class StudentPaymentOrderServiceImpl extends BaseServiceImpl<Long, Studen
                                     sellOrder.setBalanceAmount(subjectBalance);
                                 }else {
                                     //获取比例
-                                    BigDecimal ratioAmount = totalAmount.divide(studentGoodsSellDto.getExpectAmount(), 6, BigDecimal.ROUND_HALF_UP);
-                                    BigDecimal multiply = balancePaymentAmount.multiply(ratioAmount).setScale(2, BigDecimal.ROUND_HALF_UP);
+                                    BigDecimal ratioAmount = totalAmount.divide(studentGoodsSellDto.getExpectAmount(), 16, RoundingMode.DOWN);
+                                    BigDecimal multiply = balancePaymentAmount.multiply(ratioAmount).setScale(2, RoundingMode.DOWN);
                                     subjectBalance = subjectBalance.subtract(multiply);
                                     sellOrder.setBalanceAmount(multiply);
                                 }
@@ -1566,7 +1507,7 @@ public class StudentPaymentOrderServiceImpl extends BaseServiceImpl<Long, Studen
             rechargeDetail.setAmount(amount);
             rechargeDetail.setBalance(cashAccount.getBalance().add(amount));
             rechargeDetail.setComment("缴费前充值");
-            rechargeDetail.setStatus(DealStatusEnum.SUCCESS);
+            rechargeDetail.setStatus(SUCCESS);
             rechargeDetail.setTransNo(studentPaymentOrder.getTransNo());
             rechargeDetail.setType(PlatformCashAccountDetailTypeEnum.RECHARGE);
             rechargeDetail.setUserId(userId);
@@ -1581,12 +1522,12 @@ public class StudentPaymentOrderServiceImpl extends BaseServiceImpl<Long, Studen
             paymentDetail.setAmount(amount.negate());
             paymentDetail.setBalance(cashAccount.getBalance());
             paymentDetail.setComment("商品销售");
-            paymentDetail.setStatus(DealStatusEnum.SUCCESS);
+            paymentDetail.setStatus(SUCCESS);
             paymentDetail.setTransNo(studentPaymentOrder.getTransNo());
             paymentDetail.setType(PlatformCashAccountDetailTypeEnum.GOODS_SELL);
             paymentDetail.setUserId(userId);
             sysUserCashAccountDetailService.insert(paymentDetail);
-        } else if (studentPaymentOrder.getStatus() == DealStatusEnum.CLOSE || studentPaymentOrder.getStatus() == DealStatusEnum.FAILED) {
+        } else if (studentPaymentOrder.getStatus() == CLOSE || studentPaymentOrder.getStatus() == DealStatusEnum.FAILED) {
 
             if (studentPaymentOrder.getBalancePaymentAmount() != null && studentPaymentOrder.getBalancePaymentAmount().compareTo(BigDecimal.ZERO) > 0) {
                 sysUserCashAccountService.updateBalance(studentPaymentOrder.getUserId(), studentPaymentOrder.getBalancePaymentAmount(), PlatformCashAccountDetailTypeEnum.REFUNDS, "商城购买支付失败");
@@ -1627,7 +1568,7 @@ public class StudentPaymentOrderServiceImpl extends BaseServiceImpl<Long, Studen
                         //如果有空的商品货号,不处理
                         if(count == 0l){
                             List<String> productSns = goodsOrderItemVOS.stream().map(e -> e.getProductSn()).distinct().collect(Collectors.toList());
-                            List<Goods> goodsList = goodsDao.findBySns(productSns);
+                            List<Goods> goodsList = goodsService.getGoodsDao().findBySns(productSns);
                             //如果有不匹配的商品货号,不处理
                             if(CollectionUtils.isEmpty(goodsList) || goodsList.size() < productSns.size()){
                                 return;
@@ -1661,8 +1602,8 @@ public class StudentPaymentOrderServiceImpl extends BaseServiceImpl<Long, Studen
                                     sellOrder.setBalanceAmount(subjectBalance);
                                 }else {
                                     //获取比例
-                                    BigDecimal ratioAmount = totalAmount.divide(studentGoodsSellDto.getExpectAmount(), 6, BigDecimal.ROUND_HALF_UP);
-                                    BigDecimal multiply = balancePaymentAmount.multiply(ratioAmount).setScale(2, BigDecimal.ROUND_HALF_UP);
+                                    BigDecimal ratioAmount = totalAmount.divide(studentGoodsSellDto.getExpectAmount(), 16, RoundingMode.DOWN);
+                                    BigDecimal multiply = balancePaymentAmount.multiply(ratioAmount).setScale(2, RoundingMode.DOWN);
                                     subjectBalance = subjectBalance.subtract(multiply);
                                     sellOrder.setBalanceAmount(multiply);
                                 }
@@ -1734,6 +1675,7 @@ public class StudentPaymentOrderServiceImpl extends BaseServiceImpl<Long, Studen
     @Transactional
     public OrderCancelModel cancelOrder(StudentPaymentOrder order, String reason) {
         OrderCancelModel model = new OrderCancelModel();
+        model.setSuccess(true);
         try {
             HfMerchantConfig hfMerchantConfig = hfMerchantConfigService.queryByTenantId(order.getTenantId(), order.getPaymentChannel());
             if(hfMerchantConfig == null){
@@ -1770,14 +1712,29 @@ public class StudentPaymentOrderServiceImpl extends BaseServiceImpl<Long, Studen
                 model.setStatus(false);
                 order.setStatus(CLOSE);
                 order.setMemo(reason);
+            } else if (status.equals("pending")){
+                // 执行关单操作
+                Map<String, String> closeInfo = new HashMap<>();
+                if(StringUtils.equals(order.getPaymentChannel(), PaymentChannelEnum.ADAPAY.getCode())) {
+                    closeInfo = Payment.closeWithKey(order.getTransNo(), "", hfMerchantConfig.getMerKey());
+                }else if(StringUtils.equals(order.getPaymentChannel(), PaymentChannelEnum.YEEPAY.getCode())) {
+                    closeInfo = yeepayPaymentService.close(hfMerchantConfig, order.getTransNo(), "", order.getOrderNo());
+                }
+                boolean success = "success".equals(closeInfo.get("status"));
+                model.setStatus(false);
+                order.setStatus(CLOSE);
+                model.setSuccess(success);
+                model.setMessage(closeInfo.get("msg"));
             }
-            TenantContextHolder.setTenantId(order.getTenantId());
-            callOrderCallBack(order);
-            TenantContextHolder.clearTenantId();
-            model.setSuccess(true);
-        } catch (Exception e) {
+            if (model.getSuccess()) {
+                TenantContextHolder.setTenantId(order.getTenantId());
+                callOrderCallBack(order);
+                TenantContextHolder.clearTenantId();
+            }
+        }catch (Exception e) {
             model.setSuccess(false);
-            e.printStackTrace();
+            model.setMessage(e.getMessage());
+            logger.error("订单[{}]取消失败", order.getTransNo(), e);
         }
         return model;
     }
@@ -1858,6 +1815,17 @@ public class StudentPaymentOrderServiceImpl extends BaseServiceImpl<Long, Studen
             feeByTypeMap = feeByType.stream().collect(Collectors.groupingBy(StudentPaymentOrderExportDto::getId));
             childRepairMap = MapUtil.convertIntegerMap(sellOrderDao.queryChildRepair(otherOrderIds));
         }
+        //获取外部订单,将学校商品采购划分为大件乐器
+        Map<String, StudentPaymentRouteOrder> routeOrderMap = new HashMap<>();
+        List<String> outOrderNos = studentPaymentOrderExportDtos.stream().filter(e -> e.getGroupType() == GroupType.OUTORDER && e.getType() == OrderTypeEnum.SCHOOL)
+        .map(e -> e.getOrderNo()).collect(Collectors.toList());
+        if(CollectionUtils.isNotEmpty(outOrderNos)){
+            List<StudentPaymentRouteOrder> routeOrders = studentPaymentRouteOrderService.getDao().queryByOrderNos(outOrderNos);
+            if (CollectionUtils.isNotEmpty(routeOrders)){
+                routeOrderMap = routeOrders.stream().filter(e->e.getSaleAmount().compareTo(BigDecimal.ZERO) > 0)
+                        .collect(Collectors.toMap(StudentPaymentRouteOrder::getOrderNo, Function.identity()));
+            }
+        }
         //阳光、善学、坚韧、做更好的自己
 //        List<Integer> organIds = studentPaymentOrderExportDtos.stream().map(e -> e.getOrganId()).distinct().collect(Collectors.toList());
         Map<Integer, String> userOrganNameMap = this.getMap("organization","id_","name_",true,1,Integer.class,String.class);
@@ -2008,7 +1976,7 @@ public class StudentPaymentOrderServiceImpl extends BaseServiceImpl<Long, Studen
                         row.setMusicalFee(row.getActualAmount());
                     } else if (row.getGroupType().equals(GroupType.GOODS_SELL)) {
                         row.setRetailGoodsFee(row.getActualAmount());
-                    } else {
+                    }else {
                         List<StudentPaymentOrderExportDto> exportDtoList = feeByTypeMap.get(row.getId());
                         if (!org.springframework.util.CollectionUtils.isEmpty(exportDtoList)) {
                             StudentPaymentOrderExportDto feeByType = exportDtoList.get(0);
@@ -2022,7 +1990,7 @@ public class StudentPaymentOrderServiceImpl extends BaseServiceImpl<Long, Studen
                                         subtract(row.getTeachingFee()).subtract(row.getMaintenanceFee()).subtract(row.getMaintenanceProductFee()).
                                         subtract(feeByType.getOtherFee()).subtract(row.getLeaseFee()).subtract(row.getCloudTeacherFee()).
                                         subtract(row.getVipCourseFee()).subtract(row.getPracticeCourseFee()));
-                            } else if (row.getGroupType().equals(OrderTypeEnum.REPAIR)) {
+                            } else if (StringUtils.equals(row.getGroupType().getCode(),"REPAIR")) {
                                 row.setRepairFee(feeByType.getActualAmount().subtract(feeByType.getMusicalFee()).subtract(feeByType.getTeachingFee()).subtract(feeByType.getOtherFee()));
                             } else if (row.getGroupType() == GroupType.OUTORDER) {
                                 //销售收入
@@ -2040,14 +2008,18 @@ public class StudentPaymentOrderServiceImpl extends BaseServiceImpl<Long, Studen
                                 } else {
                                     //拆分导入订单
                                     if (row.getType() == OrderTypeEnum.OUTORDER || row.getType() == OrderTypeEnum.SCHOOL) {
-                                        if (row.getType() == OrderTypeEnum.SCHOOL) {
-                                            row.setMusicalFee(BigDecimal.ZERO);
-                                            row.setTeachingFee(BigDecimal.ZERO);
-                                            row.setMaintenanceProductFee(BigDecimal.ZERO);
-                                            row.setOtherFee(BigDecimal.ZERO);
-                                            row.setLargeMusicalFee(add);
+                                        if(routeOrderMap.get(row.getOrderNo()) != null){
+                                            row.setLargeMusicalFee(subtract);
+                                        }else {
+                                            if (row.getType() == OrderTypeEnum.SCHOOL) {
+                                                row.setMusicalFee(BigDecimal.ZERO);
+                                                row.setTeachingFee(BigDecimal.ZERO);
+                                                row.setMaintenanceProductFee(BigDecimal.ZERO);
+                                                row.setOtherFee(BigDecimal.ZERO);
+                                                row.setLargeMusicalFee(add);
+                                            }
+                                            row.setCourseSchoolBuyAmount(subtract);
                                         }
-                                        row.setCourseSchoolBuyAmount(subtract);
                                     } else if (row.getType() == OrderTypeEnum.OTHER) {
                                         row.setOtherFee(row.getOtherFee().add(subtract));
                                     } else {
@@ -2140,9 +2112,59 @@ public class StudentPaymentOrderServiceImpl extends BaseServiceImpl<Long, Studen
         return incomeDtos;
     }
 
+    @Override
+    @Transactional(rollbackFor = Exception.class)
+    public void updateShippedStatus(List<OrderSkuSync> orderSkuSyncs) {
+        if (CollectionUtils.isEmpty(orderSkuSyncs)) {
+            return;
+        }
+        List<String> orderNos = orderSkuSyncs.stream().map(e -> e.getOrderNo()).collect(Collectors.toList());
+        List<SellOrder> sellOrders = sellOrderDao.queryByOrganNos(orderNos);
+        if (CollectionUtils.isEmpty(sellOrders)) {
+            return;
+        }
+        sellOrders = sellOrders.stream().filter(e -> e.getDeliveryTime() == null).collect(Collectors.toList());
+        if(CollectionUtils.isEmpty(sellOrders)){
+            return;
+        }
+        String format = DateUtil.format(new Date(), DateUtil.ISO_EXPANDED_DATE_FORMAT);
+        Map<String,List<SellOrder>> sellOrderMap = sellOrders.stream().collect(Collectors.groupingBy(SellOrder::getOrderNo));
+        for (OrderSkuSync orderSkuSync : orderSkuSyncs) {
+            List<SellOrder> dtos = sellOrderMap.get(orderSkuSync.getOrderNo());
+            if(CollectionUtils.isEmpty(dtos)){
+                continue;
+            }
+            Map<Long,List<SellOrder>> goodsSkuMap = dtos.stream().collect(Collectors.groupingBy(e->e.getGoodsSkuId().longValue()));
+            for (OrderSkuSync.SkuSync skuSync : orderSkuSync.getSkuSyncList()) {
+                List<SellOrder> sellOrderList = goodsSkuMap.get(skuSync.getSku());
+                for (int i = 0; i < skuSync.getCount(); i++) {
+                    SellOrder sellOrder = this.getSellorder(sellOrderList,i);
+                    sellOrder.setDeliveryTime(format);
+                    sellOrder.setSellCost(skuSync.getPrice());
+                    sellOrder.setStockType(StringUtils.equalsIgnoreCase(skuSync.getType(),"INTERNAL")?StockType.INTERNAL:StockType.EXTERNAL);
+                }
+            }
+        }
+        sellOrderDao.batchUpdate(sellOrders);
+        musicGroupPaymentCalenderAddressService.lambdaUpdate().eq(MusicGroupPaymentCalenderAddress::getOrderNo,sellOrders.get(0).getOrderNo())
+                .set(MusicGroupPaymentCalenderAddress::getDeliveryFlag,true).update();
+    }
+
+    private SellOrder getSellorder(List<SellOrder> sellOrderList,Integer index){
+        if(index >= sellOrderList.size()){
+            return new SellOrder();
+        }
+        SellOrder sellOrder = sellOrderList.get(index);
+        if(StringUtils.isNotEmpty(sellOrder.getDeliveryTime())){
+            return getSellorder(sellOrderList,index+1);
+        }else {
+            return sellOrder;
+        }
+    }
+
     public BigDecimal getActualAmount(BigDecimal price, StudentPaymentOrderExportDto row) {
         if (row.getExpectAmount().compareTo(BigDecimal.ZERO) > 0) {
-            return price.multiply(row.getActualAmount()).divide(row.getExpectAmount(), 2, BigDecimal.ROUND_DOWN);
+            return price.multiply(row.getActualAmount()).divide(row.getExpectAmount(), 2, RoundingMode.DOWN);
         }
         return BigDecimal.ZERO;
     }

+ 143 - 164
mec-biz/src/main/java/com/ym/mec/biz/service/impl/StudentPaymentRouteOrderServiceImpl.java

@@ -1,79 +1,72 @@
 package com.ym.mec.biz.service.impl;
 
-import java.io.ByteArrayInputStream;
-import java.io.InputStream;
-import java.math.BigDecimal;
-import java.util.*;
-import java.util.Map.Entry;
-import java.util.stream.Collectors;
-
-import com.alibaba.fastjson.JSONArray;
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONObject;
 import com.ym.mec.auth.api.client.SysUserFeignService;
 import com.ym.mec.auth.api.entity.SysUser;
 import com.ym.mec.biz.dal.dao.*;
+import com.ym.mec.biz.dal.dto.*;
 import com.ym.mec.biz.dal.entity.*;
 import com.ym.mec.biz.dal.enums.*;
-import com.ym.mec.biz.service.MusicGroupCalenderRefundPeriodService;
+import com.ym.mec.biz.dal.page.StudentPaymentOrderQueryInfo;
+import com.ym.mec.biz.service.*;
+import com.ym.mec.common.dal.BaseDAO;
 import com.ym.mec.common.entity.HttpResponseResult;
+import com.ym.mec.common.exception.BizException;
+import com.ym.mec.common.page.PageInfo;
+import com.ym.mec.common.page.QueryInfo;
+import com.ym.mec.common.service.IdGeneratorService;
+import com.ym.mec.common.service.impl.BaseServiceImpl;
 import com.ym.mec.common.tenant.TenantContextHolder;
+import com.ym.mec.util.collection.MapUtil;
 import com.ym.mec.util.date.DateUtil;
 import com.ym.mec.util.excel.POIUtil;
 import com.ym.mec.util.ini.IniFileUtil;
-
+import org.apache.commons.collections.CollectionUtils;
 import org.apache.commons.lang3.StringUtils;
-import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.core.io.ClassPathResource;
 import org.springframework.stereotype.Service;
 import org.springframework.transaction.annotation.Isolation;
 import org.springframework.transaction.annotation.Transactional;
-
-import com.alibaba.fastjson.JSON;
-import com.alibaba.fastjson.JSONObject;
-import com.ym.mec.biz.dal.dto.PageInfoOrder;
-import com.ym.mec.biz.dal.dto.StudentPaymentRouteOrderDto;
-import com.ym.mec.biz.dal.page.StudentPaymentOrderQueryInfo;
-import com.ym.mec.biz.service.GoodsService;
-import com.ym.mec.biz.service.SellOrderService;
-import com.ym.mec.biz.service.StudentPaymentRouteOrderService;
-import com.ym.mec.common.dal.BaseDAO;
-import com.ym.mec.common.exception.BizException;
-import com.ym.mec.common.page.PageInfo;
-import com.ym.mec.common.page.QueryInfo;
-import com.ym.mec.common.service.IdGeneratorService;
-import com.ym.mec.common.service.impl.BaseServiceImpl;
-import com.ym.mec.util.collection.MapUtil;
-
 import org.springframework.web.multipart.MultipartFile;
 
+import javax.annotation.Resource;
+import java.io.ByteArrayInputStream;
+import java.io.InputStream;
+import java.math.BigDecimal;
+import java.util.*;
+import java.util.Map.Entry;
+import java.util.stream.Collectors;
+
 @Service
 public class StudentPaymentRouteOrderServiceImpl extends BaseServiceImpl<Long, StudentPaymentRouteOrder> implements StudentPaymentRouteOrderService {
 
-    @Autowired
+    @Resource
     private StudentPaymentRouteOrderDao studentPaymentRouteOrderDao;
-    @Autowired
+    @Resource
     private SysUserCashAccountDao sysUserCashAccountDao;
-    @Autowired
-    private StudentPaymentOrderDao studentPaymentOrderDao;
-    @Autowired
+    @Resource
+    private StudentPaymentOrderService studentPaymentOrderService;
+    @Resource
+    private StudentPaymentOrderDetailService studentPaymentOrderDetailService;
+    @Resource
     private IdGeneratorService idGeneratorService;
-    @Autowired
-    private SellOrderDao sellOrderDao;
-    @Autowired
+    @Resource
     private GoodsDao goodsDao;
-    @Autowired
-    private GoodsService goodsService;
-    @Autowired
+    @Resource
     private SellOrderService sellOrderService;
-    @Autowired
+    @Resource
     private SysUserFeignService sysUserFeignService;
-    @Autowired
+    @Resource
     private TeacherDao teacherDao;
-    @Autowired
+    @Resource
     private MusicGroupPaymentCalenderDao musicGroupPaymentCalenderDao;
-    @Autowired
+    @Resource
     private MusicGroupPaymentCalenderDetailDao musicGroupPaymentCalenderDetailDao;
-    @Autowired
+    @Resource
     private MusicGroupCalenderRefundPeriodService musicGroupCalenderRefundPeriodService;
+    @Resource
+    private CooperationOrganDao cooperationOrganDao;
 
     @Override
     public BaseDAO<Long, StudentPaymentRouteOrder> getDAO() {
@@ -81,6 +74,11 @@ public class StudentPaymentRouteOrderServiceImpl extends BaseServiceImpl<Long, S
     }
 
     @Override
+    public StudentPaymentRouteOrderDao getDao() {
+        return studentPaymentRouteOrderDao;
+    }
+
+    @Override
     public PageInfo<StudentPaymentRouteOrder> queryAuditList(QueryInfo queryInfo) {
         PageInfo<StudentPaymentRouteOrder> pageInfo = new PageInfo<StudentPaymentRouteOrder>(queryInfo.getPage(), queryInfo.getRows());
         Map<String, Object> params = new HashMap<String, Object>();
@@ -141,6 +139,11 @@ public class StudentPaymentRouteOrderServiceImpl extends BaseServiceImpl<Long, S
             if (musicGroupPaymentCalender == null) {
                 throw new BizException("学校缴费单号(审核通过)不存在,请核查");
             }
+            if(musicGroupPaymentCalender.getPaymentType() == MusicGroupPaymentCalender.PaymentType.GOODS_PURCHASE){
+                studentPaymentRouteOrder.setSaleAmount(studentPaymentRouteOrder.getRouteAmount());
+            }else {
+                studentPaymentRouteOrder.setServiceAmount(studentPaymentRouteOrder.getRouteAmount());
+            }
         }
         Date nowDate = new Date();
         String orderNo = idGeneratorService.generatorId("payment") + "";
@@ -190,20 +193,18 @@ public class StudentPaymentRouteOrderServiceImpl extends BaseServiceImpl<Long, S
         studentPaymentRouteOrder.setUpdateTime(nowDate);
         studentPaymentRouteOrder.setAuditComment(memo);
         studentPaymentRouteOrder.setAuditStatus(auditStatus);
-        if (auditStatus == AuditStatusEnum.PASS) {
-            studentPaymentRouteOrder.setOrderNo(orderNo);
-        }
-
+        studentPaymentRouteOrder.setOrderNo(orderNo);
         studentPaymentRouteOrderDao.update(studentPaymentRouteOrder);
-
         if (auditStatus == AuditStatusEnum.PASS) {
+            MusicGroupPaymentCalender musicGroupPaymentCalender = musicGroupPaymentCalenderDao.get(studentPaymentRouteOrder.getCalenderId());
             StudentPaymentOrder studentPaymentOrder = new StudentPaymentOrder();
             studentPaymentOrder.setActualAmount(studentPaymentRouteOrder.getRouteAmount());
             if(studentPaymentRouteOrder.getSchoolId() != null) {
                 studentPaymentOrder.setCooperationId(studentPaymentRouteOrder.getSchoolId());
             }
+            MusicGroupPaymentCalender calender = null;
             if(studentPaymentRouteOrder.getCalenderId() != null){
-                MusicGroupPaymentCalender calender = musicGroupPaymentCalenderDao.get(studentPaymentRouteOrder.getCalenderId());
+                calender = musicGroupPaymentCalenderDao.get(studentPaymentRouteOrder.getCalenderId());
                 studentPaymentOrder.setMusicGroupId(calender.getMusicGroupId());
                 studentPaymentOrder.setCalenderId(studentPaymentRouteOrder.getCalenderId());
             }
@@ -212,6 +213,7 @@ public class StudentPaymentRouteOrderServiceImpl extends BaseServiceImpl<Long, S
             studentPaymentOrder.setOrderNo(studentPaymentRouteOrder.getOrderNo());
             studentPaymentOrder.setGroupType(GroupType.OUTORDER);
             studentPaymentOrder.setOrganId(studentPaymentRouteOrder.getRouteOrganId());
+            studentPaymentOrder.setRoutingOrganId(studentPaymentRouteOrder.getRouteOrganId());
             studentPaymentOrder.setExpectAmount(studentPaymentRouteOrder.getRouteAmount());
             studentPaymentOrder.setStatus(DealStatusEnum.SUCCESS);
             studentPaymentOrder.setCreateTime(studentPaymentRouteOrder.getPayTime());
@@ -224,86 +226,19 @@ public class StudentPaymentRouteOrderServiceImpl extends BaseServiceImpl<Long, S
 
             studentPaymentRouteOrderDao.insertOrder(studentPaymentOrder);
 
-            if (StringUtils.isNoneBlank(studentPaymentRouteOrder.getGoodsJson())) {
-                BigDecimal hasRouteAmount = BigDecimal.ZERO;
-                BigDecimal goodsTotalPrice = BigDecimal.ZERO;
 
-                List<Integer> goodsIdList = new ArrayList<>();
+            if (StringUtils.isNoneBlank(studentPaymentRouteOrder.getGoodsJson())) {
                 JSONObject jsonObj = JSON.parseObject(studentPaymentRouteOrder.getGoodsJson());
+                List<GoodsSellDto> goodsSellDtos = new ArrayList<>();
                 for (Entry<String, Object> goodsMap : jsonObj.entrySet()) {
-                    Integer goodsId = Integer.parseInt(goodsMap.getKey());
-                    Integer nums = Integer.parseInt(goodsMap.getValue().toString());
-                    Goods goods = goodsDao.get(goodsId);
-                    goodsTotalPrice = goodsTotalPrice.add(goods.getGroupPurchasePrice().multiply(new BigDecimal(nums)));
-                    for (int i = 0; i < nums; i++) {
-                        goodsIdList.add(goodsId);
-                    }
-                }
-                List<SellOrder> sellOrderList = goodsService.subtractStock(goodsIdList, AccountType.INTERNAL);
-
-                int i = 1;
-                for (Entry<String, Object> goodsMap : jsonObj.entrySet()) {
-                    Integer goodsId = Integer.parseInt(goodsMap.getKey());
-                    Integer nums = Integer.parseInt(goodsMap.getValue().toString());
-                    Goods goods = goodsDao.get(goodsId);
-
-                    BigDecimal actualAmount = BigDecimal.ZERO;
-                    if (goodsTotalPrice.compareTo(BigDecimal.ZERO) != 0) {
-                        actualAmount = studentPaymentRouteOrder.getSaleAmount().multiply(goods.getGroupPurchasePrice().multiply(new BigDecimal(nums))).divide(goodsTotalPrice, 2, BigDecimal.ROUND_DOWN);
-                    }
-                    if (i == jsonObj.entrySet().size()) {
-                        actualAmount = studentPaymentRouteOrder.getSaleAmount().subtract(hasRouteAmount);
-                    }
-                    hasRouteAmount = hasRouteAmount.add(actualAmount);
-                    i++;
-
-                    int complementNum = goods.getComplementGoodsIdList() == null ? 1 : goods.getComplementGoodsIdList().split(",").length;
-                    int goodsNum = nums * complementNum;
-                    BigDecimal complementPrice = goods.getGroupPurchasePrice().multiply(new BigDecimal(nums));
-                    Map<Integer, BigDecimal> complementGoodsPrice = new HashMap<>();
-                    complementGoodsPrice.put(goods.getId(), goods.getGroupPurchasePrice());
-                    if (goods.getComplementGoodsIdList() != null) {
-                        List<Goods> complementGoodies = goodsDao.findGoodsByIds(goods.getComplementGoodsIdList());
-                        complementGoodsPrice = complementGoodies.stream().collect(Collectors.toMap(Goods::getId, Goods::getGroupPurchasePrice));
-                        complementPrice = complementGoodies.stream().map(Goods::getGroupPurchasePrice).reduce(BigDecimal.ZERO, BigDecimal::add).multiply(new BigDecimal(nums));
-                    }
-
-                    BigDecimal hasRouteSellOrderActualAmount = BigDecimal.ZERO;
-                    for (SellOrder sellOrder : sellOrderList) {
-                        if (!Integer.valueOf(goodsMap.getKey()).equals(sellOrder.getParentGoodsId()) && !Integer.valueOf(goodsMap.getKey()).equals(sellOrder.getGoodsId())) {
-                            continue;
-                        }
-                        BigDecimal sellOrderActualAmount = BigDecimal.ZERO;
-                        if (complementPrice.compareTo(BigDecimal.ZERO) > 0) {
-                            sellOrderActualAmount = complementGoodsPrice.get(sellOrder.getGoodsId()).multiply(new BigDecimal(sellOrder.getNum())).multiply(actualAmount).divide(complementPrice, 2, BigDecimal.ROUND_DOWN);
-                        }
-                        goodsNum = goodsNum - sellOrder.getNum();
-                        if (goodsNum <= 0) {
-                            sellOrderActualAmount = actualAmount.subtract(hasRouteSellOrderActualAmount);
-                        }
-                        hasRouteSellOrderActualAmount = hasRouteSellOrderActualAmount.add(sellOrderActualAmount);
-
-                        sellOrder.setSellTime(studentPaymentRouteOrder.getPayTime());
-                        sellOrder.setOrganId(studentPaymentRouteOrder.getRouteOrganId());
-                        sellOrder.setCooperationOrganId(studentPaymentRouteOrder.getSchoolId());
-                        sellOrder.setTransNo(studentPaymentRouteOrder.getTransNo());
-                        sellOrder.setOrderId(studentPaymentOrder.getId());
-                        sellOrder.setOrderNo(studentPaymentRouteOrder.getOrderNo());
-                        sellOrder.setActualAmount(sellOrderActualAmount);
-                        sellOrder.setBalanceAmount(BigDecimal.ZERO);
-                        sellOrder.setExpectAmount(sellOrderActualAmount);
-                        sellOrder.setUserId(studentPaymentRouteOrder.getUserId());
-                        sellOrder.setPaymentChannel(studentPaymentOrder.getPaymentChannel());
-                        sellOrder.setMerNo(studentPaymentRouteOrder.getMerNo());
-                        sellOrder.setSellTime(studentPaymentRouteOrder.getCreateTime());
-                        sellOrder.setCreateIme(nowDate);
-                        sellOrder.setUpdateTime(nowDate);
-                        sellOrder.setType(SellTypeEnum.SCHOOL_BUY);
-                    }
+                    GoodsSellDto goodsSellDto = new GoodsSellDto();
+                    goodsSellDto.setGoodsId(Integer.parseInt(goodsMap.getKey()));
+                    goodsSellDto.setGoodsNum(Integer.parseInt(goodsMap.getValue().toString()));
+                    goodsSellDtos.add(goodsSellDto);
                 }
-                sellOrderDao.batchInsert(sellOrderList);
+                List<StudentPaymentOrderDetail> orderDetails = studentPaymentOrderDetailService.initStudentPaymentOrderDetail(studentPaymentOrder, goodsSellDtos);
+                sellOrderService.addOrderDetail2SellOrder(orderDetails, studentPaymentOrder, studentPaymentOrder.getMusicGroupId());
             }
-
             if (studentPaymentRouteOrder.getCalenderId() == null) {
                 return true;
             }
@@ -316,8 +251,6 @@ public class StudentPaymentRouteOrderServiceImpl extends BaseServiceImpl<Long, S
             //是否已完成回款
             if(aBoolean){
                 List<MusicGroupPaymentCalenderDetail> calenderDetails = musicGroupPaymentCalenderDetailDao.getCalenderDetailWithCalender(studentPaymentRouteOrder.getCalenderId());
-                MusicGroupPaymentCalender musicGroupPaymentCalender = musicGroupPaymentCalenderDao.get(studentPaymentRouteOrder.getCalenderId());
-
                 if (studentPaymentRouteOrder.getRouteAmount().compareTo(musicGroupPaymentCalender.getCurrentTotalAmount()) >= 0) {
                     musicGroupPaymentCalender.setActualNum(musicGroupPaymentCalender.getExpectNum());
                     musicGroupPaymentCalender.setStatus(MusicGroupPaymentCalender.PaymentCalenderStatusEnum.PAID);
@@ -327,7 +260,7 @@ public class StudentPaymentRouteOrderServiceImpl extends BaseServiceImpl<Long, S
                         calenderDetail.setPaymentStatus(MusicGroupStudentFee.PaymentStatus.PAID_COMPLETED);
                         calenderDetail.setPayTime(nowDate);
                     }
-                    if (calenderDetails.size() > 0) {
+                    if (CollectionUtils.isNotEmpty(calenderDetails)) {
                         musicGroupPaymentCalenderDetailDao.batchUpdate(calenderDetails);
                     }
                 }
@@ -353,16 +286,16 @@ public class StudentPaymentRouteOrderServiceImpl extends BaseServiceImpl<Long, S
     @Override
     @Transactional(rollbackFor = Exception.class)
     public Boolean deleteRouteOrder(Long orderId) {
-        StudentPaymentOrder studentPaymentOrder = studentPaymentOrderDao.get(orderId);
+        StudentPaymentOrder studentPaymentOrder = studentPaymentOrderService.get(orderId);
         if (studentPaymentOrder == null) {
             throw new BizException("订单不存在,请核查");
         }
-        studentPaymentOrderDao.delete(orderId);
+        studentPaymentOrderService.delete(orderId);
         studentPaymentRouteOrderDao.deleteByOrderNo(studentPaymentOrder.getOrderNo());
         //归还库存
         List<SellOrder> sellOrders = sellOrderService.getSellOrderByParentGoodsId(orderId, null);
-        if (sellOrders.size() > 0) {
-            sellOrderDao.deleteByOrderId(orderId);
+        if (CollectionUtils.isNotEmpty(sellOrders)) {
+            sellOrderService.getDao().deleteByOrderId(orderId);
         }
         return true;
     }
@@ -386,7 +319,7 @@ public class StudentPaymentRouteOrderServiceImpl extends BaseServiceImpl<Long, S
         for (String e : sheetsListMap.keySet()) {
             List<Map<String, Object>> sheet = sheetsListMap.get(e);
             List<Object> collect = sheet.stream().map(m -> m.get("交易流水号")).collect(Collectors.toList());
-            if (collect == null || collect.size() == 0) {
+            if (CollectionUtils.isEmpty(collect)) {
                 continue;
             }
             Date nowDate = new Date();
@@ -399,7 +332,7 @@ public class StudentPaymentRouteOrderServiceImpl extends BaseServiceImpl<Long, S
             for (int j = 0; j < sheet.size(); j++) {
                 int rowNum = j + 2;
                 Map<String, Object> row = sheet.get(j);
-                if (row.size() == 0) {
+                if (row == null || row.isEmpty()) {
                     continue;
                 }
                 JSONObject objectMap = new JSONObject();
@@ -412,7 +345,7 @@ public class StudentPaymentRouteOrderServiceImpl extends BaseServiceImpl<Long, S
                     String columnValue = columns.get(s);
                     if (columnValue.equals("incomeType")) {
                         if (StringUtils.isEmpty(row.get(s).toString())) {
-                            sb.append("第" + rowNum).append("行数据导入失败:收入类型不可为空;");
+                            sb.append("第").append(rowNum).append("行数据导入失败:收入类型不可为空;");
                             continue valueIsNull;
                         } else {
                             objectMap.put("incomeType", row.get(s));
@@ -420,7 +353,7 @@ public class StudentPaymentRouteOrderServiceImpl extends BaseServiceImpl<Long, S
                     }
                     if (columnValue.equals("type")) {
                         if (StringUtils.isEmpty(row.get(s).toString())) {
-                            sb.append("第" + rowNum).append("行数据导入失败:订单类型不可为空;");
+                            sb.append("第").append(rowNum).append("行数据导入失败:订单类型不可为空;");
                             continue valueIsNull;
                         } else {
                             for (OrderTypeEnum orderTypeEnum : OrderTypeEnum.values()) {
@@ -434,19 +367,19 @@ public class StudentPaymentRouteOrderServiceImpl extends BaseServiceImpl<Long, S
                     }
                     if (columnValue.equals("transNo")) {
                         if (StringUtils.isEmpty(row.get(s).toString())) {
-                            sb.append("第" + rowNum).append("行数据导入失败:交易流水号不可为空;");
+                            sb.append("第").append(rowNum).append("行数据导入失败:交易流水号不可为空;");
                             continue valueIsNull;
                         }
                     }
                     if (columnValue.equals("payTime") && StringUtils.isEmpty(row.get(s).toString())) {
                         if (StringUtils.isEmpty(row.get(s).toString())) {
-                            sb.append("第" + rowNum).append("行数据导入失败:交易日期不可为空;");
+                            sb.append("第").append(rowNum).append("行数据导入失败:交易日期不可为空;");
                             continue valueIsNull;
                         }
                     }
                     if (columnValue.equals("merNo")) {
                         if (StringUtils.isEmpty(row.get(s).toString())) {
-                            sb.append("第" + rowNum).append("行数据导入失败:收款账户不可为空;");
+                            sb.append("第").append(rowNum).append("行数据导入失败:收款账户不可为空;");
                             continue valueIsNull;
                         } else {
                             objectMap.put("merNo", row.get(s));
@@ -456,7 +389,7 @@ public class StudentPaymentRouteOrderServiceImpl extends BaseServiceImpl<Long, S
                     if (columnValue.equals("organName") && StringUtils.isNotEmpty(row.get(s).toString())) {
                         Integer integer = organMap.get(row.get(s));
                         if (integer == null) {
-                            sb.append("第" + rowNum).append("行数据导入失败:分部名称不存在;");
+                            sb.append("第").append(rowNum).append("行数据导入失败:分部名称不存在;");
                             continue valueIsNull;
                         } else {
                             objectMap.put("routeOrganId", integer);
@@ -468,7 +401,7 @@ public class StudentPaymentRouteOrderServiceImpl extends BaseServiceImpl<Long, S
                         if (integer != null) {
                             objectMap.put("schoolId", integer);
                         } else {
-                            sb.append("第" + rowNum).append("行数据导入失败:所属学校名称不存在;");
+                            sb.append("第").append(rowNum).append("行数据导入失败:所属学校名称不存在;");
                             continue valueIsNull;
                         }
                         continue;
@@ -478,7 +411,7 @@ public class StudentPaymentRouteOrderServiceImpl extends BaseServiceImpl<Long, S
                         if (flag) {
                             objectMap.put("userId", row.get(s));
                         } else {
-                            sb.append("第" + rowNum).append("行数据导入失败:学员编号不存在;");
+                            sb.append("第").append(rowNum).append("行数据导入失败:学员编号不存在;");
                             continue valueIsNull;
                         }
                         continue;
@@ -487,10 +420,10 @@ public class StudentPaymentRouteOrderServiceImpl extends BaseServiceImpl<Long, S
                         String toString = row.get(s).toString();
                         Date date = DateUtil.stringToDate(toString, DateUtil.DEFAULT_PATTERN);
                         if (date == null) {
-                            sb.append("第" + rowNum).append("行数据导入失败:交易日期格式错误;");
+                            sb.append("第").append(rowNum).append("行数据导入失败:交易日期格式错误;");
                             continue valueIsNull;
                         } else if (date.after(nowDate)) {
-                            sb.append("第" + rowNum).append("行数据导入失败:交易日期不能大于当前日期");
+                            sb.append("第").append(rowNum).append("行数据导入失败:交易日期不能大于当前日期");
                             continue valueIsNull;
                         } else {
                             objectMap.put(columnValue, DateUtil.format(date, DateUtil.DEFAULT_PATTERN));
@@ -499,7 +432,7 @@ public class StudentPaymentRouteOrderServiceImpl extends BaseServiceImpl<Long, S
                     }
                     if (columnValue.equals("calenderId")) {
                         if (StringUtils.isNotBlank(row.get(s).toString()) && !schoolCalender.containsKey(row.get(s).toString())) {
-                            sb.append("第" + rowNum).append("行数据导入失败:学校缴费单号(审核通过)不存在;");
+                            sb.append("第").append(rowNum).append("行数据导入失败:学校缴费单号(审核通过)不存在;");
                             continue valueIsNull;
                         } else {
                             objectMap.put("calenderId", row.get(s));
@@ -511,6 +444,7 @@ public class StudentPaymentRouteOrderServiceImpl extends BaseServiceImpl<Long, S
                 StudentPaymentRouteOrder studentPaymentRouteOrder = JSONObject.parseObject(objectMap.toJSONString(), StudentPaymentRouteOrder.class);
                 //销售收入
                 if ("销售收入".equals(studentPaymentRouteOrder.getIncomeType())) {
+                    boolean calenderFlag = studentPaymentRouteOrder.getCalenderId()==null;
                     if (studentPaymentRouteOrder.getSaleAmount() == null) {
                         throw new BizException("导入失败:交易流水号{},收入类型为销售收入时,销售金额不可为空", studentPaymentRouteOrder.getTransNo());
                     }
@@ -518,30 +452,32 @@ public class StudentPaymentRouteOrderServiceImpl extends BaseServiceImpl<Long, S
                     String goodsIds = studentPaymentRouteOrder.getGoodsIds();
                     String goodsNums = studentPaymentRouteOrder.getGoodsNums();
 
-                    if (StringUtils.isEmpty(goodsNums)) {
+                    if (calenderFlag && StringUtils.isEmpty(goodsNums)) {
                         throw new BizException("导入失败:有销售金额时商品数量必填");
                     }
-                    if (StringUtils.isEmpty(goodsIds)) {
+                    if (calenderFlag && StringUtils.isEmpty(goodsIds)) {
                         throw new BizException("导入失败:有销售金额时商品编号必填");
                     }
-                    List<String> goodsIdList = new ArrayList(Arrays.asList(goodsIds.split(",")));
-                    List<String> goodsNumList = new ArrayList(Arrays.asList(goodsNums.split(",")));
-                    if (goodsIdList.size() != goodsNumList.size()) {
-                        throw new BizException("导入失败:商品编号和商品数量不一致");
-                    }
-                    JSONObject goodsJSON = new JSONObject();
-                    for (int i = 0; i < goodsIdList.size(); i++) {
-                        if (!goodsDao.findByIdAndStatus(goodsIdList.get(i), 1)) {
-                            throw new BizException("导入失败:商品编号{}不存在", goodsIdList.get(i));
+                    if(StringUtils.isNotEmpty(goodsNums) && StringUtils.isNotEmpty(goodsIds)){
+                        List<String> goodsIdList = Arrays.asList(goodsIds.split(","));
+                        List<String> goodsNumList = Arrays.asList(goodsNums.split(","));
+                        if (goodsIdList.size() != goodsNumList.size()) {
+                            throw new BizException("导入失败:商品编号和商品数量不一致");
                         }
-                        try {
-                            int goodsNum = Integer.parseInt(goodsNumList.get(i));
-                            goodsJSON.put(goodsIdList.get(i), goodsNum);
-                        } catch (Exception e1) {
-                            throw new BizException("导入失败:商品数量{}填写错误", goodsNumList.get(i));
+                        JSONObject goodsJSON = new JSONObject();
+                        for (int i = 0; i < goodsIdList.size(); i++) {
+                            if (!goodsDao.findByIdAndStatus(goodsIdList.get(i), 1)) {
+                                throw new BizException("导入失败:商品编号{}不存在", goodsIdList.get(i));
+                            }
+                            try {
+                                int goodsNum = Integer.parseInt(goodsNumList.get(i));
+                                goodsJSON.put(goodsIdList.get(i), goodsNum);
+                            } catch (Exception e1) {
+                                throw new BizException("导入失败:商品数量{}填写错误", goodsNumList.get(i));
+                            }
                         }
+                        studentPaymentRouteOrder.setGoodsJson(goodsJSON.toJSONString());
                     }
-                    studentPaymentRouteOrder.setGoodsJson(goodsJSON.toJSONString());
                     //服务收入
                 } else {
                     studentPaymentRouteOrder.setSaleAmount(BigDecimal.ZERO);
@@ -561,12 +497,12 @@ public class StudentPaymentRouteOrderServiceImpl extends BaseServiceImpl<Long, S
         if(sb.length() > 0){
             throw new BizException(sb.toString());
         }
-        if (studentPaymentRouteOrders.size() > 0) {
+        if (CollectionUtils.isNotEmpty(studentPaymentRouteOrders)) {
             studentPaymentRouteOrderDao.batchAdd(studentPaymentRouteOrders);
         } else {
             throw new BizException(sb.length() > 0 ? sb.toString() : "导入失败:没有可以录入的数据");
         }
-        HttpResponseResult httpResponseResult = new HttpResponseResult();
+        HttpResponseResult<List<StudentPaymentRouteOrder>> httpResponseResult = new HttpResponseResult<List<StudentPaymentRouteOrder>>();
         httpResponseResult.setData(studentPaymentRouteOrders);
         httpResponseResult.setMsg(sb.toString());
         if (StringUtils.isNotEmpty(sb.toString())) {
@@ -577,4 +513,47 @@ public class StudentPaymentRouteOrderServiceImpl extends BaseServiceImpl<Long, S
         return httpResponseResult;
     }
 
+    @Override
+    public OutOrderInfoDto getRouteOrder(Long orderId) {
+        OutOrderInfoDto outOrderInfoDto = new OutOrderInfoDto();
+        StudentPaymentOrder order = studentPaymentOrderService.get(orderId);
+        outOrderInfoDto.setStudentPaymentOrder(order);
+        StudentPaymentRouteOrder routeOrder = studentPaymentRouteOrderDao.getByOrderNo(order.getOrderNo());
+        String goodsJson = routeOrder.getGoodsJson();
+        if(StringUtils.isNotEmpty(goodsJson)){
+            JSONObject jsonObj = JSON.parseObject(goodsJson);
+            List<GoodsNameDto> goodsSellDtos = new ArrayList<>();
+            for (Map.Entry<String, Object> goodsMap : jsonObj.entrySet()) {
+                GoodsNameDto goodsSellDto = new GoodsNameDto();
+                goodsSellDto.setGoodsId(Integer.parseInt(goodsMap.getKey()));
+                goodsSellDto.setGoodsNum(Integer.parseInt(goodsMap.getValue().toString()));
+                goodsSellDtos.add(goodsSellDto);
+            }
+            List<Integer> goosIds = goodsSellDtos.stream().map(e -> e.getGoodsId()).collect(Collectors.toList());
+            List<Goods> goodies = goodsDao.getGoodies(goosIds);
+            if(CollectionUtils.isNotEmpty(goodies)){
+                Map<Integer, String> goodsMap = goodies.stream().collect(Collectors.toMap(Goods::getId, Goods::getName));
+                goodsSellDtos.forEach(e -> e.setGoodsName(goodsMap.get(e.getGoodsId())));
+            }
+            outOrderInfoDto.setGoodsSellDtos(goodsSellDtos);
+        }
+        outOrderInfoDto.setCalenderId(routeOrder.getCalenderId());
+        if(order.getCooperationId() != null){
+            CooperationOrgan cooperationOrgan = cooperationOrganDao.get(order.getCooperationId());
+            if (cooperationOrgan != null) {
+                outOrderInfoDto.setCoopName(cooperationOrgan.getName());
+            }
+        }
+        BigDecimal goodsAmount = BigDecimal.ZERO;
+        List<SellOrder> sellOrders = sellOrderService.getDao().getOrderSellOrder(orderId);
+        if(CollectionUtils.isNotEmpty(sellOrders)){
+            goodsAmount = sellOrders.stream().map(SellOrder::getActualAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
+            outOrderInfoDto.setSellOrders(sellOrders);
+            outOrderInfoDto.setGoodsAmount(goodsAmount);
+        }
+        BigDecimal serviceAmount = outOrderInfoDto.getStudentPaymentOrder().getActualAmount().subtract(goodsAmount);
+        outOrderInfoDto.setServiceAmount(serviceAmount);
+        return outOrderInfoDto;
+    }
+
 }

+ 37 - 137
mec-biz/src/main/java/com/ym/mec/biz/service/impl/StudentRegistrationServiceImpl.java

@@ -1,136 +1,16 @@
 package com.ym.mec.biz.service.impl;
 
-import static com.ym.mec.biz.dal.entity.MusicGroupStudentFee.PaymentStatus.NON_PAYMENT;
-import static com.ym.mec.biz.dal.entity.MusicGroupStudentFee.PaymentStatus.PAID_COMPLETED;
-import static com.ym.mec.biz.dal.enums.OrderDetailTypeEnum.MAINTENANCE;
-import static com.ym.mec.biz.dal.enums.OrderDetailTypeEnum.PRACTICE;
-import static com.ym.mec.biz.dal.enums.OrderDetailTypeEnum.VIP;
-import static com.ym.mec.biz.dal.enums.PaymentStatusEnum.YES;
-import static com.ym.mec.biz.dal.enums.SysUserRoleEnum.ORGAN_MANAGER;
-
-import java.io.IOException;
-import java.math.BigDecimal;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Objects;
-import java.util.Set;
-import java.util.concurrent.CompletableFuture;
-import java.util.concurrent.atomic.AtomicInteger;
-import java.util.stream.Collectors;
-
-import javax.annotation.Resource;
-
-import com.ym.mec.biz.service.*;
-import org.apache.commons.collections.CollectionUtils;
-import org.apache.commons.lang3.StringUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Lazy;
-import org.springframework.http.HttpStatus;
-import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
-import org.springframework.stereotype.Service;
-import org.springframework.transaction.annotation.Propagation;
-import org.springframework.transaction.annotation.Transactional;
-
 import com.alibaba.fastjson.JSONObject;
 import com.ym.mec.auth.api.client.SysUserFeignService;
 import com.ym.mec.auth.api.entity.SysUser;
 import com.ym.mec.auth.api.enums.CertificateTypeEnum;
-import com.ym.mec.biz.dal.dao.CourseScheduleDao;
-import com.ym.mec.biz.dal.dao.GoodsDao;
-import com.ym.mec.biz.dal.dao.GoodsProcurementDao;
-import com.ym.mec.biz.dal.dao.ImGroupDao;
-import com.ym.mec.biz.dal.dao.MusicGroupDao;
-import com.ym.mec.biz.dal.dao.MusicGroupPaymentCalenderDao;
-import com.ym.mec.biz.dal.dao.MusicGroupPaymentCalenderDetailDao;
-import com.ym.mec.biz.dal.dao.MusicGroupPaymentCalenderStudentDetailDao;
-import com.ym.mec.biz.dal.dao.MusicGroupPaymentStudentCourseDetailDao;
-import com.ym.mec.biz.dal.dao.MusicGroupStudentFeeDao;
-import com.ym.mec.biz.dal.dao.MusicGroupSubjectPlanDao;
-import com.ym.mec.biz.dal.dao.OrganizationDao;
-import com.ym.mec.biz.dal.dao.StudentCourseFeeDetailDao;
-import com.ym.mec.biz.dal.dao.StudentDao;
-import com.ym.mec.biz.dal.dao.StudentInstrumentDao;
-import com.ym.mec.biz.dal.dao.StudentPaymentOrderDetailDao;
-import com.ym.mec.biz.dal.dao.StudentRegistrationDao;
-import com.ym.mec.biz.dal.dao.SubjectChangeDao;
-import com.ym.mec.biz.dal.dao.SubjectDao;
-import com.ym.mec.biz.dal.dao.SysConfigDao;
-import com.ym.mec.biz.dal.dao.SysUserCashAccountDao;
-import com.ym.mec.biz.dal.dao.TeacherDao;
-import com.ym.mec.biz.dal.dto.MusicGroupApplyGoodsDto;
-import com.ym.mec.biz.dal.dto.NoClassMusicStudentDto;
-import com.ym.mec.biz.dal.dto.PageInfoReg;
-import com.ym.mec.biz.dal.dto.RegisterDto;
-import com.ym.mec.biz.dal.dto.RegisterPayDto;
-import com.ym.mec.biz.dal.dto.StudentAddDto;
-import com.ym.mec.biz.dal.dto.StudentApplyDetailDto;
-import com.ym.mec.biz.dal.dto.StudentCourseInfoDto;
-import com.ym.mec.biz.dal.dto.StudentInfo;
-import com.ym.mec.biz.dal.dto.StudentMusicDetailDto;
-import com.ym.mec.biz.dal.dto.StudentMusicGroupDto;
-import com.ym.mec.biz.dal.dto.StudentRegisterInstrumentsDetailDto;
-import com.ym.mec.biz.dal.entity.ClassGroup;
-import com.ym.mec.biz.dal.entity.ClassGroupStudentMapper;
-import com.ym.mec.biz.dal.entity.CloudTeacherOrder;
-import com.ym.mec.biz.dal.entity.CooperationOrgan;
-import com.ym.mec.biz.dal.entity.CouponPayParam;
-import com.ym.mec.biz.dal.entity.CouponPayTypeInfo;
-import com.ym.mec.biz.dal.entity.CourseSchedule;
-import com.ym.mec.biz.dal.entity.CourseScheduleStudentPayment;
-import com.ym.mec.biz.dal.entity.Goods;
-import com.ym.mec.biz.dal.entity.GoodsProcurement;
-import com.ym.mec.biz.dal.entity.MusicGroup;
-import com.ym.mec.biz.dal.entity.MusicGroupPaymentCalender;
-import com.ym.mec.biz.dal.entity.MusicGroupPaymentCalenderActivity;
-import com.ym.mec.biz.dal.entity.MusicGroupPaymentCalenderCourseSettings;
-import com.ym.mec.biz.dal.entity.MusicGroupPaymentCalenderMember;
-import com.ym.mec.biz.dal.entity.MusicGroupPaymentCalenderRepair;
-import com.ym.mec.biz.dal.entity.MusicGroupPaymentCalenderStudentDetail;
-import com.ym.mec.biz.dal.entity.MusicGroupPaymentStudentCourseDetail;
-import com.ym.mec.biz.dal.entity.MusicGroupStudentFee;
-import com.ym.mec.biz.dal.entity.MusicGroupSubjectGoodsGroup;
-import com.ym.mec.biz.dal.entity.MusicGroupSubjectPlan;
-import com.ym.mec.biz.dal.entity.Organization;
-import com.ym.mec.biz.dal.entity.Student;
-import com.ym.mec.biz.dal.entity.StudentCourseFeeDetail;
-import com.ym.mec.biz.dal.entity.StudentInstrument;
-import com.ym.mec.biz.dal.entity.StudentPaymentOrder;
-import com.ym.mec.biz.dal.entity.StudentPaymentOrderDetail;
-import com.ym.mec.biz.dal.entity.StudentRegistration;
-import com.ym.mec.biz.dal.entity.Subject;
-import com.ym.mec.biz.dal.entity.SubjectChange;
-import com.ym.mec.biz.dal.entity.SysUserCashAccount;
-import com.ym.mec.biz.dal.entity.SysUserCashAccountDetail;
-import com.ym.mec.biz.dal.enums.ClassGroupStudentStatusEnum;
-import com.ym.mec.biz.dal.enums.ClassGroupTypeEnum;
-import com.ym.mec.biz.dal.enums.CouponDetailTypeEnum;
-import com.ym.mec.biz.dal.enums.CourseStatusEnum;
-import com.ym.mec.biz.dal.enums.CourseViewTypeEnum;
-import com.ym.mec.biz.dal.enums.DealStatusEnum;
-import com.ym.mec.biz.dal.enums.GoodsType;
-import com.ym.mec.biz.dal.enums.GroupType;
-import com.ym.mec.biz.dal.enums.KitGroupPurchaseTypeEnum;
-import com.ym.mec.biz.dal.enums.MessageTypeEnum;
-import com.ym.mec.biz.dal.enums.MusicGroupStatusEnum;
-import com.ym.mec.biz.dal.enums.OrderDetailTypeEnum;
-import com.ym.mec.biz.dal.enums.OrderTypeEnum;
-import com.ym.mec.biz.dal.enums.PaymentStatusEnum;
-import com.ym.mec.biz.dal.enums.PlatformCashAccountDetailTypeEnum;
-import com.ym.mec.biz.dal.enums.StudentMusicGroupStatusEnum;
-import com.ym.mec.biz.dal.enums.SysUserRoleEnum;
-import com.ym.mec.biz.dal.page.MusicGroupRecordStudentQueryInfo;
-import com.ym.mec.biz.dal.page.NoClassMusicStudentQueryInfo;
-import com.ym.mec.biz.dal.page.RegistrationOrPreQueryInfo;
-import com.ym.mec.biz.dal.page.StudentPreRegistrationQueryInfo;
-import com.ym.mec.biz.dal.page.StudentRegistrationQueryInfo;
+import com.ym.mec.biz.dal.dao.*;
+import com.ym.mec.biz.dal.dto.*;
+import com.ym.mec.biz.dal.entity.*;
+import com.ym.mec.biz.dal.enums.*;
+import com.ym.mec.biz.dal.page.*;
 import com.ym.mec.biz.event.source.SendSeoMessageSource;
+import com.ym.mec.biz.service.*;
 import com.ym.mec.common.dal.BaseDAO;
 import com.ym.mec.common.entity.HttpResponseResult;
 import com.ym.mec.common.entity.ImResult;
@@ -144,6 +24,30 @@ import com.ym.mec.thirdparty.message.MessageSenderPluginContext;
 import com.ym.mec.util.collection.MapUtil;
 import com.ym.mec.util.date.DateUtil;
 import com.ym.mec.util.http.HttpUtil;
+import org.apache.commons.collections.CollectionUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Lazy;
+import org.springframework.http.HttpStatus;
+import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Propagation;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.annotation.Resource;
+import java.io.IOException;
+import java.math.BigDecimal;
+import java.util.*;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
+
+import static com.ym.mec.biz.dal.entity.MusicGroupStudentFee.PaymentStatus.NON_PAYMENT;
+import static com.ym.mec.biz.dal.entity.MusicGroupStudentFee.PaymentStatus.PAID_COMPLETED;
+import static com.ym.mec.biz.dal.enums.OrderDetailTypeEnum.*;
+import static com.ym.mec.biz.dal.enums.PaymentStatusEnum.YES;
+import static com.ym.mec.biz.dal.enums.SysUserRoleEnum.ORGAN_MANAGER;
 
 @Service
 public class StudentRegistrationServiceImpl extends BaseServiceImpl<Long, StudentRegistration> implements StudentRegistrationService {
@@ -232,10 +136,6 @@ public class StudentRegistrationServiceImpl extends BaseServiceImpl<Long, Studen
     private ImGroupDao imGroupDao;
     @Autowired
     private StudentInstrumentDao studentInstrumentDao;
-    
-    @Autowired
-    private GoodsProcurementDao goodsProcurementDao;
-    
     @Autowired
     private MusicGroupPaymentCalenderStudentDetailDao musicGroupPaymentCalenderStudentDetailDao;
     @Autowired
@@ -1484,12 +1384,12 @@ public class StudentRegistrationServiceImpl extends BaseServiceImpl<Long, Studen
             List<StudentPaymentOrderDetail> studentPaymentOrderDetailList = studentPaymentOrderDetailService.queryOrderDetail(studentPaymentOrder.getId());
             String goodsIds = studentPaymentOrderDetailList.stream().filter(t -> StringUtils.isNotBlank(t.getMinuendStockGoodsIdList())).map(t -> t.getMinuendStockGoodsIdList()).collect(Collectors.joining(","));
             if(StringUtils.isNotBlank(goodsIds)){
-            	GoodsProcurement goodsProcurement = null;
+//            	GoodsProcurement goodsProcurement = null;
             	List<Goods> goodsList = goodsService.getGoodsWithLocked(goodsIds);
             	Map<Integer,Goods> goodsMap = goodsList.stream().collect(Collectors.toMap(Goods :: getId, t -> t));
             	Goods goods = null;
     			Map<Integer, Goods> batchUpdateGoodsMap = new HashMap<Integer, Goods>();
-    			Map<Long, GoodsProcurement> goodsProcurementMap = new HashMap<Long, GoodsProcurement>();
+//    			Map<Long, GoodsProcurement> goodsProcurementMap = new HashMap<Long, GoodsProcurement>();
             	
             	for(String goodsIdStr : goodsIds.split(",")){
             		if(StringUtils.isBlank(goodsIdStr)){
@@ -1499,14 +1399,14 @@ public class StudentRegistrationServiceImpl extends BaseServiceImpl<Long, Studen
 					if(batchUpdateGoodsMap.get(goods.getId()) != null){
 						goods = batchUpdateGoodsMap.get(goods.getId());
 					}
-					goods.setStockCount(new AtomicInteger(goods.getStockCount()).incrementAndGet());
+//					goods.setStockCount(new AtomicInteger(goods.getStockCount()).incrementAndGet());
 					goods.setSellCount(new AtomicInteger(goods.getSellCount()).decrementAndGet());
 					goods.setUpdateTime(nowDate);
 					
 					batchUpdateGoodsMap.put(goods.getId(), goods);
 					
 					// 进货清单
-					goodsProcurement = goodsProcurementDao.getWithStockSurplusProcurement(goods.getId());
+					/*goodsProcurement = goodsProcurementDao.getWithStockSurplusProcurement(goods.getId());
 					if(goodsProcurement != null){
 						if(goodsProcurementMap.get(goodsProcurement.getId()) != null){
 							goodsProcurement = goodsProcurementMap.get(goodsProcurement.getId());
@@ -1514,13 +1414,13 @@ public class StudentRegistrationServiceImpl extends BaseServiceImpl<Long, Studen
 						goodsProcurement.setStockSoldNum(new AtomicInteger(goodsProcurement.getStockSoldNum()).decrementAndGet());
 						goodsProcurement.setUpdateTime(nowDate);
 						goodsProcurementMap.put(goodsProcurement.getId(), goodsProcurement);
-					}
+					}*/
 					
             	}
             	
-            	if(goodsProcurementMap.size() > 0){
+            	/*if(goodsProcurementMap.size() > 0){
             		goodsProcurementDao.batchUpdate(new ArrayList<GoodsProcurement>(goodsProcurementMap.values()));
-            	}
+            	}*/
                 
                 if(batchUpdateGoodsMap.size() > 0){
                 	goodsService.batchUpdate(new ArrayList<Goods>(batchUpdateGoodsMap.values()));

+ 85 - 430
mec-biz/src/main/java/com/ym/mec/biz/service/impl/StudentRepairServiceImpl.java

@@ -1,65 +1,52 @@
 package com.ym.mec.biz.service.impl;
 
-import static com.ym.mec.biz.dal.enums.CouponDetailTypeEnum.ACCESSORIES;
-import static com.ym.mec.biz.dal.enums.CouponDetailTypeEnum.MUSICAL;
-import static com.ym.mec.biz.dal.enums.DealStatusEnum.CLOSE;
-import static com.ym.mec.biz.dal.enums.DealStatusEnum.ING;
-import static com.ym.mec.biz.dal.enums.DealStatusEnum.SUCCESS;
-
-import java.math.BigDecimal;
-import java.math.RoundingMode;
-import java.util.*;
-import java.util.concurrent.atomic.AtomicInteger;
-import java.util.stream.Collectors;
-
-import com.ym.mec.biz.dal.entity.*;
-import com.ym.mec.biz.service.*;
-import org.apache.commons.collections.CollectionUtils;
-import org.apache.commons.lang3.StringUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Lazy;
-import org.springframework.stereotype.Service;
-import org.springframework.transaction.annotation.Isolation;
-import org.springframework.transaction.annotation.Propagation;
-import org.springframework.transaction.annotation.Transactional;
-
 import com.alibaba.fastjson.JSON;
 import com.alibaba.fastjson.JSONArray;
 import com.alibaba.fastjson.JSONObject;
 import com.ym.mec.auth.api.client.SysUserFeignService;
 import com.ym.mec.auth.api.entity.SysUser;
-import com.ym.mec.biz.dal.dao.GoodsProcurementDao;
 import com.ym.mec.biz.dal.dao.MusicGroupDao;
-import com.ym.mec.biz.dal.dao.StudentDao;
 import com.ym.mec.biz.dal.dao.StudentGoodsSellDao;
 import com.ym.mec.biz.dal.dao.StudentRepairDao;
 import com.ym.mec.biz.dal.dao.SysConfigDao;
 import com.ym.mec.biz.dal.dto.BasicUserDto;
 import com.ym.mec.biz.dal.dto.GoodsSellDto;
 import com.ym.mec.biz.dal.dto.RepairGoodsDto;
-import com.ym.mec.biz.dal.enums.AccountType;
-import com.ym.mec.biz.dal.enums.CouponDetailTypeEnum;
-import com.ym.mec.biz.dal.enums.DealStatusEnum;
-import com.ym.mec.biz.dal.enums.GoodsType;
-import com.ym.mec.biz.dal.enums.GroupType;
-import com.ym.mec.biz.dal.enums.MessageTypeEnum;
-import com.ym.mec.biz.dal.enums.OrderDetailTypeEnum;
-import com.ym.mec.biz.dal.enums.OrderTypeEnum;
-import com.ym.mec.biz.dal.enums.PayStatus;
-import com.ym.mec.biz.dal.enums.PaymentChannelEnum;
-import com.ym.mec.biz.dal.enums.PlatformCashAccountDetailTypeEnum;
-import com.ym.mec.biz.dal.enums.SellTypeEnum;
+import com.ym.mec.biz.dal.entity.*;
+import com.ym.mec.biz.dal.enums.*;
 import com.ym.mec.biz.dal.page.RepairStudentQueryInfo;
+import com.ym.mec.biz.service.*;
 import com.ym.mec.common.dal.BaseDAO;
+import com.ym.mec.common.dto.BrandDto;
 import com.ym.mec.common.exception.BizException;
 import com.ym.mec.common.page.PageInfo;
 import com.ym.mec.common.page.QueryInfo;
 import com.ym.mec.common.service.IdGeneratorService;
 import com.ym.mec.common.service.impl.BaseServiceImpl;
+import com.ym.mec.mall.MallFeignService;
 import com.ym.mec.thirdparty.message.MessageSenderPluginContext;
 import com.ym.mec.util.collection.MapUtil;
+import org.apache.commons.collections.CollectionUtils;
+import org.apache.commons.lang.math.NumberUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Lazy;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Isolation;
+import org.springframework.transaction.annotation.Propagation;
+import org.springframework.transaction.annotation.Transactional;
+
+import java.math.BigDecimal;
+import java.math.RoundingMode;
+import java.util.*;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
+
+import static com.ym.mec.biz.dal.enums.CouponDetailTypeEnum.ACCESSORIES;
+import static com.ym.mec.biz.dal.enums.CouponDetailTypeEnum.MUSICAL;
+import static com.ym.mec.biz.dal.enums.DealStatusEnum.*;
 
 @Service
 public class StudentRepairServiceImpl extends BaseServiceImpl<Integer, StudentRepair> implements StudentRepairService {
@@ -79,8 +66,6 @@ public class StudentRepairServiceImpl extends BaseServiceImpl<Integer, StudentRe
     @Autowired
     private StudentPaymentOrderDetailService studentPaymentOrderDetailService;
     @Autowired
-    private SysPaymentConfigService sysPaymentConfigService;
-    @Autowired
     private MusicGroupDao musicGroupDao;
     @Autowired
     private SysUserCashAccountService sysUserCashAccountService;
@@ -97,7 +82,7 @@ public class StudentRepairServiceImpl extends BaseServiceImpl<Integer, StudentRe
     @Autowired
     private StudentGoodsSellDao studentGoodsSellDao;
     @Autowired
-    private GoodsProcurementDao goodsProcurementDao;
+    private StudentPaymentOrderAddressService studentPaymentOrderAddressService;
 
     @Lazy
     @Autowired
@@ -112,6 +97,8 @@ public class StudentRepairServiceImpl extends BaseServiceImpl<Integer, StudentRe
     private SysCouponCodeService sysCouponCodeService;
     @Autowired
     private TeacherService teacherService;
+    @Autowired
+    private MallFeignService mallFeignService;
 
     private final Logger logger = LoggerFactory.getLogger(this.getClass());
 
@@ -172,6 +159,14 @@ public class StudentRepairServiceImpl extends BaseServiceImpl<Integer, StudentRe
     @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class, isolation = Isolation.READ_COMMITTED)
     public Map addGoodsSellOrder(StudentGoodsSell studentGoodsSell) throws Exception {
         //关闭老订单
+        StudentPaymentOrderAddress studentPaymentOrderAddress = null;
+        if (StringUtils.isNotBlank(studentGoodsSell.getAddress())) {
+            studentPaymentOrderAddress = new StudentPaymentOrderAddress();
+            studentPaymentOrderAddress.setAddress(studentGoodsSell.getAddress());
+            studentPaymentOrderAddress.setContactMobile(studentGoodsSell.getContactMobile());
+            studentPaymentOrderAddress.setContactName(studentGoodsSell.getContactName());
+        }
+
         if (StringUtils.isNotEmpty(studentGoodsSell.getOrderNo())) {
             StudentPaymentOrder orderByOrderNo = studentPaymentOrderService.findOrderByOrderNo(studentGoodsSell.getOrderNo());
             if (orderByOrderNo.getBalancePaymentAmount() != null && orderByOrderNo.getBalancePaymentAmount().longValue() != 0l) {
@@ -207,12 +202,12 @@ public class StudentRepairServiceImpl extends BaseServiceImpl<Integer, StudentRe
                 List<StudentPaymentOrderDetail> studentPaymentOrderDetailList = studentPaymentOrderDetailService.queryOrderDetail(orderByOrderNo.getId());
                 String goodsIds = studentPaymentOrderDetailList.stream().filter(t -> StringUtils.isNotBlank(t.getMinuendStockGoodsIdList())).map(t -> t.getMinuendStockGoodsIdList()).collect(Collectors.joining(","));
                 if (StringUtils.isNotBlank(goodsIds)) {
-                    GoodsProcurement goodsProcurement = null;
+//                    GoodsProcurement goodsProcurement = null;
                     List<Goods> goodsList = goodsService.getGoodsWithLocked(goodsIds);
                     Map<Integer, Goods> goodsMap = goodsList.stream().collect(Collectors.toMap(Goods::getId, t -> t));
                     Goods goods = null;
                     Map<Integer, Goods> batchUpdateGoodsMap = new HashMap<Integer, Goods>();
-                    Map<Long, GoodsProcurement> goodsProcurementMap = new HashMap<Long, GoodsProcurement>();
+//                    Map<Long, GoodsProcurement> goodsProcurementMap = new HashMap<Long, GoodsProcurement>();
 
                     for (String goodsIdStr : goodsIds.split(",")) {
                         if (StringUtils.isBlank(goodsIdStr)) {
@@ -222,14 +217,14 @@ public class StudentRepairServiceImpl extends BaseServiceImpl<Integer, StudentRe
                         if (batchUpdateGoodsMap.get(goods.getId()) != null) {
                             goods = batchUpdateGoodsMap.get(goods.getId());
                         }
-                        goods.setStockCount(new AtomicInteger(goods.getStockCount()).incrementAndGet());
+//                        goods.setStockCount(new AtomicInteger(goods.getStockCount()).incrementAndGet());
                         goods.setSellCount(new AtomicInteger(goods.getSellCount()).decrementAndGet());
                         goods.setUpdateTime(nowDate);
 
                         batchUpdateGoodsMap.put(goods.getId(), goods);
 
                         // 进货清单
-                        goodsProcurement = goodsProcurementDao.getWithStockSurplusProcurement(goods.getId());
+                        /*goodsProcurement = goodsProcurementDao.getWithStockSurplusProcurement(goods.getId());
                         if (goodsProcurement != null) {
                             if (goodsProcurementMap.get(goodsProcurement.getId()) != null) {
                                 goodsProcurement = goodsProcurementMap.get(goodsProcurement.getId());
@@ -237,13 +232,13 @@ public class StudentRepairServiceImpl extends BaseServiceImpl<Integer, StudentRe
                             goodsProcurement.setStockSoldNum(new AtomicInteger(goodsProcurement.getStockSoldNum()).decrementAndGet());
                             goodsProcurement.setUpdateTime(nowDate);
                             goodsProcurementMap.put(goodsProcurement.getId(), goodsProcurement);
-                        }
+                        }*/
 
                     }
 
-                    if (goodsProcurementMap.size() > 0) {
+                    /*if (goodsProcurementMap.size() > 0) {
                         goodsProcurementDao.batchUpdate(new ArrayList<GoodsProcurement>(goodsProcurementMap.values()));
-                    }
+                    }*/
 
                     if (batchUpdateGoodsMap.size() > 0) {
                         goodsService.batchUpdate(new ArrayList<Goods>(batchUpdateGoodsMap.values()));
@@ -336,6 +331,10 @@ public class StudentRepairServiceImpl extends BaseServiceImpl<Integer, StudentRe
         }
         studentGoodsSell.setTenantId(student.getTenantId());
         studentGoodsSellDao.insert(studentGoodsSell);
+        if (studentPaymentOrderAddress !=null) {
+            studentPaymentOrderAddress.setOrderNo(orderNo);
+            studentPaymentOrderAddressService.save(studentPaymentOrderAddress);
+        }
 
         if (studentGoodsSell.getType() == 1) {
             Map<String, Object> repairInfoMap = new HashMap<>();
@@ -353,77 +352,7 @@ public class StudentRepairServiceImpl extends BaseServiceImpl<Integer, StudentRe
         studentPaymentOrder.setTenantId(student.getTenantId());
         studentPaymentOrderService.insert(studentPaymentOrder);
 
-        Date date = new Date();
-        //添加订单详情
-        List<StudentPaymentOrderDetail> studentPaymentOrderDetailList = new ArrayList<StudentPaymentOrderDetail>();
-        // 添加studentPaymentOrderDetail
-        StudentPaymentOrderDetail studentPaymentOrderDetail = null;
-
-        BigDecimal totalPrice = BigDecimal.ZERO;
-
-        if (goodsSellDtos != null) {
-            //String goodsIdsStr = goodsSellDtos.stream().map(t -> t.getGoodsId().toString()).collect(Collectors.joining(","));
-
-            StringBuffer sb = new StringBuffer();
-            for (GoodsSellDto goodsSellDto : goodsSellDtos) {
-                for (int i = 0; i < goodsSellDto.getGoodsNum(); i++) {
-                    sb.append(goodsSellDto.getGoodsId()).append(",");
-                }
-            }
-
-            String goodsIdsStr = StringUtils.removeEnd(sb.toString(), ",");
-
-            List<Goods> goodsList = goodsService.findGoodsByIds(goodsIdsStr);
-            Map<Integer, Goods> goodsMap = goodsList.stream().collect(Collectors.toMap(Goods::getId, t -> t));
-            BigDecimal totalGroupPurchasePrice = BigDecimal.ZERO;
-
-            for (String goodsIdStr : goodsIdsStr.split(",")) {
-                totalGroupPurchasePrice = totalGroupPurchasePrice.add(goodsMap.get(Integer.parseInt(goodsIdStr)).getGroupPurchasePrice());
-            }
-
-            Goods goods = null;
-            for (String goodsIdStr : goodsIdsStr.split(",")) {
-                if (StringUtils.isBlank(goodsIdStr)) {
-                    continue;
-                }
-                goods = goodsMap.get(Integer.parseInt(goodsIdStr));
-
-                if (goods != null) {
-                    studentPaymentOrderDetail = new StudentPaymentOrderDetail();
-                    studentPaymentOrderDetail.setCreateTime(date);
-                    if (goods.getType() == GoodsType.INSTRUMENT) {
-                        studentPaymentOrderDetail.setType(OrderDetailTypeEnum.MUSICAL);
-                    } else if (goods.getType() == GoodsType.ACCESSORIES) {
-                        studentPaymentOrderDetail.setType(OrderDetailTypeEnum.ACCESSORIES);
-                    } else if (goods.getType() == GoodsType.TEACHING || goods.getType() == GoodsType.STAFF) {
-                        studentPaymentOrderDetail.setType(OrderDetailTypeEnum.TEACHING);
-                    } else {
-                        studentPaymentOrderDetail.setType(OrderDetailTypeEnum.OTHER);
-                    }
-                    studentPaymentOrderDetail.setGoodsIdList(goodsIdStr);
-
-                    BigDecimal tempPrice = BigDecimal.ZERO;
-                    if (totalGroupPurchasePrice.compareTo(BigDecimal.ZERO) > 0) {
-                        tempPrice = studentPaymentOrder.getExpectAmount().multiply(goods.getGroupPurchasePrice()).divide(totalGroupPurchasePrice, BigDecimal.ROUND_DOWN).setScale(2, BigDecimal.ROUND_DOWN);
-                    }
-
-                    if (totalPrice.add(tempPrice).compareTo(studentPaymentOrder.getExpectAmount()) > 0 || goodsIdsStr.split(",").length == studentPaymentOrderDetailList.size() + 1) {
-                        studentPaymentOrderDetail.setPrice(studentPaymentOrder.getExpectAmount().subtract(totalPrice));
-                    } else {
-                        studentPaymentOrderDetail.setPrice(tempPrice);
-                    }
-                    studentPaymentOrderDetail.setUpdateTime(date);
-                    studentPaymentOrderDetail.setPaymentOrderId(studentPaymentOrder.getId());
-
-                    totalPrice = totalPrice.add(studentPaymentOrderDetail.getPrice());
-                    studentPaymentOrderDetailList.add(studentPaymentOrderDetail);
-                }
-            }
-        }
-
-        if (studentPaymentOrderDetailList.size() > 0) {
-            studentPaymentOrderDetailService.batchAdd(studentPaymentOrderDetailList);
-        }
+        studentPaymentOrderDetailService.initStudentPaymentOrderDetail(studentPaymentOrder, goodsSellDtos);
 
         studentPaymentOrder.setVersion(0);
         BigDecimal balance = BigDecimal.ZERO;
@@ -437,6 +366,7 @@ public class StudentRepairServiceImpl extends BaseServiceImpl<Integer, StudentRe
                 amount = amount.subtract(balance);
                 studentPaymentOrder.setActualAmount(amount);
                 studentPaymentOrder.setBalancePaymentAmount(balance);
+                studentPaymentOrder.setPaymentChannel("BALANCE");
                 sysUserCashAccountService.updateBalance(studentId, balance.negate(), PlatformCashAccountDetailTypeEnum.PAY_FEE, "商品销售");
             }
         }
@@ -472,6 +402,7 @@ public class StudentRepairServiceImpl extends BaseServiceImpl<Integer, StudentRe
         return payMap;
     }
 
+
     @Override
     @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
     public Map studentPaymentGoodsOrder(Integer goodsSellId) throws Exception {
@@ -543,6 +474,8 @@ public class StudentRepairServiceImpl extends BaseServiceImpl<Integer, StudentRe
         studentPaymentOrder.setTenantId(studentGoodsSell.getTenantId());
         studentPaymentOrderService.insert(studentPaymentOrder);
 
+        studentPaymentOrderDetailService.initStudentPaymentOrderDetail(studentPaymentOrder, goodsSellDtos);
+
         studentPaymentOrder.setVersion(0);
         BigDecimal balance = BigDecimal.ZERO;
         if (studentGoodsSell.getIsUseBalancePayment() && amount.compareTo(BigDecimal.ZERO) > 0) {
@@ -594,13 +527,13 @@ public class StudentRepairServiceImpl extends BaseServiceImpl<Integer, StudentRe
     @Transactional(rollbackFor = Exception.class)
     public Map addRepair(StudentRepair repairInfo) throws Exception {
         studentService.getDao().lockUser(repairInfo.getEmployeeId());
-        if (repairInfo.getSendType() != null && repairInfo.getSendType().equals(1) &&
+        /*if (repairInfo.getSendType() != null && repairInfo.getSendType().equals(1) &&
                 (repairInfo.getContactName() == null || repairInfo.getContactName().isEmpty()) &&
                 (repairInfo.getContactMobile() == null || repairInfo.getContactMobile().isEmpty()) &&
                 (repairInfo.getAddress() == null || repairInfo.getAddress().isEmpty())
         ) {
             throw new BizException("邮寄信息必填");
-        }
+        }*/
         Date date = new Date();
         StudentInstrument studentInstrument = null;
         if (repairInfo.getStudentInstrumentId() != null) {
@@ -741,7 +674,7 @@ public class StudentRepairServiceImpl extends BaseServiceImpl<Integer, StudentRe
 
                     BigDecimal tempPrice = BigDecimal.ZERO;
                     if (totalGroupPurchasePrice.compareTo(BigDecimal.ZERO) > 0) {
-                        tempPrice = studentPaymentOrder.getExpectAmount().subtract(repairPrice).multiply(goods.getGroupPurchasePrice()).divide(totalGroupPurchasePrice, BigDecimal.ROUND_DOWN).setScale(2, BigDecimal.ROUND_DOWN);
+                        tempPrice = studentPaymentOrder.getExpectAmount().subtract(repairPrice).multiply(goods.getGroupPurchasePrice()).divide(totalGroupPurchasePrice, RoundingMode.DOWN).setScale(2, RoundingMode.DOWN);
                     }
 
                     if (totalPrice.add(tempPrice).compareTo(studentPaymentOrder.getExpectAmount()) > 0 || goodsIds.split(",").length == studentPaymentOrderDetailList.size()) {
@@ -758,8 +691,8 @@ public class StudentRepairServiceImpl extends BaseServiceImpl<Integer, StudentRe
             }
         }
 
-        if (studentPaymentOrderDetailList.size() > 0) {
-            studentPaymentOrderDetailService.batchAdd(studentPaymentOrderDetailList);
+        if (CollectionUtils.isNotEmpty(studentPaymentOrderDetailList)) {
+            studentPaymentOrderDetailService.batchAdd(studentPaymentOrderDetailList,studentPaymentOrder.getCouponRemitFee(),studentPaymentOrder.getExpectAmount());
         }
 
         BigDecimal balance = BigDecimal.ZERO;
@@ -867,6 +800,19 @@ public class StudentRepairServiceImpl extends BaseServiceImpl<Integer, StudentRe
             List<Integer> collect = Arrays.stream(couponIds.split(",")).map(e -> Integer.valueOf(e)).collect(Collectors.toList());
             repairInfo.setCouponCodeDtos(sysCouponCodeService.findByIdList(collect));
         }
+        String goodsJson = repairInfo.getGoodsJson();
+        if (StringUtils.isNotEmpty(goodsJson)) {
+            JSONArray goods = JSON.parseArray(repairInfo.getGoodsJson());
+            Map<Long, String> brandIdNameMap = mallFeignService.getList().stream().collect(Collectors.toMap(BrandDto::getId, BrandDto::getName));
+            for (Object good : goods) {
+                JSONObject goodObject = (JSONObject) good;
+                String brand = goodObject.getString("brand");
+                if (Objects.nonNull(brand) && NumberUtils.isNumber(brand)) {
+                    goodObject.put("brandName", brandIdNameMap.getOrDefault(Long.valueOf(brand), ""));
+                }
+            }
+            repairInfo.setGoodsJson(JSON.toJSONString(goods));
+        }
         return repairInfo;
     }
 
@@ -990,7 +936,7 @@ public class StudentRepairServiceImpl extends BaseServiceImpl<Integer, StudentRe
                     }
                     studentPaymentOrderDetail.setGoodsIdList(goodsIdStr);
 
-                    BigDecimal tempPrice = studentPaymentOrder.getExpectAmount().subtract(repairPrice).multiply(goods.getGroupPurchasePrice()).divide(totalGroupPurchasePrice, BigDecimal.ROUND_DOWN).setScale(2, BigDecimal.ROUND_DOWN);
+                    BigDecimal tempPrice = studentPaymentOrder.getExpectAmount().subtract(repairPrice).multiply(goods.getGroupPurchasePrice()).divide(totalGroupPurchasePrice, RoundingMode.DOWN).setScale(2, RoundingMode.DOWN);
 
                     if (totalPrice.add(tempPrice).compareTo(studentPaymentOrder.getExpectAmount()) > 0 || goodsIds.split(",").length == studentPaymentOrderDetailList.size()) {
                         studentPaymentOrderDetail.setPrice(studentPaymentOrder.getExpectAmount().subtract(totalPrice));
@@ -1127,19 +1073,21 @@ public class StudentRepairServiceImpl extends BaseServiceImpl<Integer, StudentRe
             //将购买的乐器加入学生乐器列表
             studentGoodsSellService.saveStudentInstrument(studentPaymentOrder);
             //购买的商品加入销售列表
-            saveSellOrder(studentPaymentOrder.getOrderNo());
+//            saveSellOrder(studentPaymentOrder.getOrderNo());
+            List<StudentPaymentOrderDetail> orderDetail = studentPaymentOrderDetailService.getOrderDetail(studentPaymentOrder.getId());
+            sellOrderService.addOrderDetail2SellOrder(orderDetail,studentPaymentOrder,null);
         } else if (studentPaymentOrder.getStatus() == DealStatusEnum.CLOSE || studentPaymentOrder.getStatus() == DealStatusEnum.FAILED) {
 
             //增加商品库存
             List<StudentPaymentOrderDetail> studentPaymentOrderDetailList = studentPaymentOrderDetailService.queryOrderDetail(studentPaymentOrder.getId());
             String goodsIds = studentPaymentOrderDetailList.stream().filter(t -> StringUtils.isNotBlank(t.getMinuendStockGoodsIdList())).map(t -> t.getMinuendStockGoodsIdList()).collect(Collectors.joining(","));
             if (StringUtils.isNotBlank(goodsIds)) {
-                GoodsProcurement goodsProcurement = null;
+//                GoodsProcurement goodsProcurement = null;
                 List<Goods> goodsList = goodsService.getGoodsWithLocked(goodsIds);
                 Map<Integer, Goods> goodsMap = goodsList.stream().collect(Collectors.toMap(Goods::getId, t -> t));
                 Goods goods = null;
                 Map<Integer, Goods> batchUpdateGoodsMap = new HashMap<Integer, Goods>();
-                Map<Long, GoodsProcurement> goodsProcurementMap = new HashMap<Long, GoodsProcurement>();
+//                Map<Long, GoodsProcurement> goodsProcurementMap = new HashMap<Long, GoodsProcurement>();
 
                 for (String goodsIdStr : goodsIds.split(",")) {
                     if (StringUtils.isBlank(goodsIdStr)) {
@@ -1149,14 +1097,14 @@ public class StudentRepairServiceImpl extends BaseServiceImpl<Integer, StudentRe
                     if (batchUpdateGoodsMap.get(goods.getId()) != null) {
                         goods = batchUpdateGoodsMap.get(goods.getId());
                     }
-                    goods.setStockCount(new AtomicInteger(goods.getStockCount()).incrementAndGet());
+//                    goods.setStockCount(new AtomicInteger(goods.getStockCount()).incrementAndGet());
                     goods.setSellCount(new AtomicInteger(goods.getSellCount()).decrementAndGet());
                     goods.setUpdateTime(nowDate);
 
                     batchUpdateGoodsMap.put(goods.getId(), goods);
 
                     // 进货清单
-                    goodsProcurement = goodsProcurementDao.getWithStockSurplusProcurement(goods.getId());
+/*                    goodsProcurement = goodsProcurementDao.getWithStockSurplusProcurement(goods.getId());
                     if (goodsProcurement != null) {
                         if (goodsProcurementMap.get(goodsProcurement.getId()) != null) {
                             goodsProcurement = goodsProcurementMap.get(goodsProcurement.getId());
@@ -1164,13 +1112,13 @@ public class StudentRepairServiceImpl extends BaseServiceImpl<Integer, StudentRe
                         goodsProcurement.setStockSoldNum(new AtomicInteger(goodsProcurement.getStockSoldNum()).decrementAndGet());
                         goodsProcurement.setUpdateTime(nowDate);
                         goodsProcurementMap.put(goodsProcurement.getId(), goodsProcurement);
-                    }
+                    }*/
 
                 }
 
-                if (goodsProcurementMap.size() > 0) {
+                /*if (goodsProcurementMap.size() > 0) {
                     goodsProcurementDao.batchUpdate(new ArrayList<GoodsProcurement>(goodsProcurementMap.values()));
-                }
+                }*/
 
                 if (batchUpdateGoodsMap.size() > 0) {
                     goodsService.batchUpdate(new ArrayList<Goods>(batchUpdateGoodsMap.values()));
@@ -1209,232 +1157,6 @@ public class StudentRepairServiceImpl extends BaseServiceImpl<Integer, StudentRe
         return pageInfo;
     }
 
-    @Transactional(rollbackFor = Exception.class, isolation = Isolation.READ_COMMITTED)
-    public void saveSellOrder(String orderNo) {
-        StudentPaymentOrder orderByOrderNo = studentPaymentOrderService.findOrderByOrderNo(orderNo);
-        StudentGoodsSell studentGoodsSell = studentGoodsSellDao.findByOrderNo(orderNo);
-        String goodsJson = studentGoodsSell.getGoodsJson();
-        List<GoodsSellDto> goodsSellDtos = JSONObject.parseArray(goodsJson, GoodsSellDto.class);
-        //用户选择的商品
-        Map<Integer, List<GoodsSellDto>> collect = goodsSellDtos.stream().collect(Collectors.groupingBy(GoodsSellDto::getGoodsId));
-        List<Integer> goodsIds = new ArrayList<>();
-        goodsSellDtos.forEach(e -> {
-            for (int i = 0; i < e.getGoodsNum(); i++) {
-                goodsIds.add(e.getGoodsId());
-            }
-        });
-        AccountType accountType = AccountType.INTERNAL;
-        if (StringUtils.isNotEmpty(orderByOrderNo.getPaymentChannel())) {
-            accountType = sysPaymentConfigService.checkAccountType(PaymentChannelEnum.valueOf(orderByOrderNo.getPaymentChannel()), orderByOrderNo.getMerNos(), orderByOrderNo.getTenantId());
-        }
-        //实际扣减的库存商品
-        List<SellOrder> sellOrderList = goodsService.subtractStock(goodsIds, accountType);
-        Map<String, BigDecimal> costMap = new HashMap<>(2);
-        BigDecimal balancePaymentAmount = orderByOrderNo.getBalancePaymentAmount();
-        //可用余额
-        BigDecimal usableBalance = balancePaymentAmount;
-        BigDecimal marketAmount = studentGoodsSell.getMarketAmount().add(studentGoodsSell.getCouponMarketAmount());
-        //可用减免金额
-        BigDecimal usableMarketAmount = marketAmount;
-        //包含减免余额的总金额
-        BigDecimal totalAmount = goodsSellDtos.stream().map(e -> e.getTotalGoodsPrice()).reduce(BigDecimal.ZERO, BigDecimal::add);
-        //组合商品减免金额
-        Map<Integer, BigDecimal> parentGoodsCutTotalPriceMap = new HashMap<>();
-        //组合商品附加金额
-        Map<Integer, BigDecimal> parentGoodsAddTotalPriceMap = new HashMap<>();
-        //组合商品实际总价
-        Map<Integer, BigDecimal> parentGoodsTotalPriceMap = new HashMap<>();
-        //应付总额
-        BigDecimal totalActual = totalAmount.subtract(marketAmount);
-        //可用应付
-        BigDecimal usableActual = totalActual;
-        //获取实付总额
-        BigDecimal realityAmount = totalActual.subtract(usableBalance);
-        //可用实付总额
-        BigDecimal usableAmount = realityAmount;
-        //可用组合商品总减免金额
-        BigDecimal usableParentGoodsCutTotalPrice;
-        //可用组合商品总附加金额
-        BigDecimal usableParentGoodsAddTotalPrice;
-
-        //获取组合商品列表
-        List<SellOrder> orderList = sellOrderList.stream().filter(sellOrder -> sellOrder.getParentGoodsId() != null).collect(Collectors.toList());
-        Map<Integer, List<SellOrder>> orderListMap = orderList.stream().collect(Collectors.groupingBy(SellOrder::getParentGoodsId));
-
-        //获取组合商品实际销售价,和单个商品总和价
-        for (Integer integer : orderListMap.keySet()) {
-            SellOrder sellOrder = orderListMap.get(integer).get(0);
-            //获取组合商品销售总价
-            GoodsSellDto goodsSellDto = collect.get(sellOrder.getParentGoodsId()).get(0);
-            BigDecimal parentTotalGoodsPrice = goodsSellDto.getTotalGoodsPrice().divide(new BigDecimal(goodsSellDto.getGoodsNum()));
-            BigDecimal totalGoodsPrice = BigDecimal.ZERO;
-            //获取单个商品销售总价
-            for (GoodsSellDto sellDto : goodsSellDto.getGoodsSellDtos()) {
-                totalGoodsPrice = totalGoodsPrice.add(sellDto.getTotalGoodsPrice());
-            }
-            parentGoodsTotalPriceMap.put(sellOrder.getParentGoodsId(), totalGoodsPrice);
-            //如果组合价大于预计总价
-            if (parentTotalGoodsPrice.compareTo(totalGoodsPrice) == 1) {
-                parentGoodsAddTotalPriceMap.put(sellOrder.getParentGoodsId(), parentTotalGoodsPrice.subtract(totalGoodsPrice));
-            } else if (parentTotalGoodsPrice.compareTo(totalGoodsPrice) == -1) {//小于
-                parentGoodsCutTotalPriceMap.put(sellOrder.getParentGoodsId(), totalGoodsPrice.subtract(parentTotalGoodsPrice));
-            }
-        }
-        //分配组合商品的中单个商品的价格
-        noFreeAmount:
-        for (Integer parentGoodsId : orderListMap.keySet()) {
-
-            BigDecimal addTotalPrice = parentGoodsAddTotalPriceMap.get(parentGoodsId);
-            usableParentGoodsAddTotalPrice = addTotalPrice;
-            BigDecimal cutTotalPrice = parentGoodsCutTotalPriceMap.get(parentGoodsId);
-            usableParentGoodsCutTotalPrice = cutTotalPrice;
-
-            //获取组合商品销售总价
-            GoodsSellDto goodsSellDto = collect.get(parentGoodsId).get(0);
-//            BigDecimal divide = goodsSellDto.getGoodsPrice();
-
-            //获取子商品明细map
-            List<GoodsSellDto> sellDtos = goodsSellDto.getGoodsSellDtos();
-            Map<Integer, List<GoodsSellDto>> subGoodsMap = sellDtos.stream().collect(Collectors.groupingBy(GoodsSellDto::getGoodsId));
-            List<Integer> integers = new ArrayList<>(subGoodsMap.keySet());
-            BigDecimal divide = parentGoodsTotalPriceMap.get(parentGoodsId);
-            for (int i = 0; i < integers.size(); i++) {
-                GoodsSellDto sellDto = subGoodsMap.get(integers.get(i)).get(0);
-                //获取比例
-                BigDecimal ratioAmount = sellDto.getTotalGoodsPrice().divide(divide, 6, BigDecimal.ROUND_HALF_UP);
-
-                if (addTotalPrice != null && addTotalPrice.doubleValue() > 0l) {
-                    //如果是最后一件商品
-                    if (i == integers.size() - 1) {
-                        sellDto.setTotalGoodsPrice(sellDto.getTotalGoodsPrice().add(usableParentGoodsAddTotalPrice));
-                    } else {
-                        //获取分配的附加
-                        BigDecimal multiply = ratioAmount.multiply(addTotalPrice).setScale(2, BigDecimal.ROUND_HALF_UP);
-                        sellDto.setTotalGoodsPrice(sellDto.getTotalGoodsPrice().add(multiply));
-                        usableParentGoodsAddTotalPrice = usableParentGoodsAddTotalPrice.subtract(multiply);
-                    }
-                    sellDto.setGoodsPrice(sellDto.getTotalGoodsPrice());
-                } else if (cutTotalPrice != null && cutTotalPrice.doubleValue() > 0l) {
-                    //如果是最后一件商品
-                    if (i == integers.size() - 1) {
-                        sellDto.setTotalGoodsPrice(sellDto.getTotalGoodsPrice().subtract(usableParentGoodsCutTotalPrice));
-                    } else {
-                        //获取分配的组合减免金额
-                        BigDecimal multiply = ratioAmount.multiply(cutTotalPrice).setScale(2, BigDecimal.ROUND_HALF_UP);
-                        sellDto.setTotalGoodsPrice(sellDto.getTotalGoodsPrice().subtract(multiply));
-                        usableParentGoodsCutTotalPrice = usableParentGoodsCutTotalPrice.subtract(multiply);
-                    }
-                    sellDto.setGoodsPrice(sellDto.getTotalGoodsPrice());
-                } else {
-                    continue noFreeAmount;
-                }
-            }
-        }
-        for (int i = 0; i < sellOrderList.size(); i++) {
-            SellOrder sellOrder = sellOrderList.get(i);
-            Integer e = null;
-            if (sellOrder.getParentGoodsId() != null) {
-                e = sellOrder.getParentGoodsId();
-            } else {
-                e = sellOrder.getGoodsId();
-            }
-            GoodsSellDto goodsSellDto = collect.get(e).get(0);
-            List<GoodsSellDto> sellDtos = goodsSellDto.getGoodsSellDtos();
-            if (sellDtos != null && sellDtos.size() > 0) {
-                Map<Integer, List<GoodsSellDto>> map = sellDtos.stream().collect(Collectors.groupingBy(GoodsSellDto::getGoodsId));
-                goodsSellDto = map.get(sellOrder.getGoodsId()).get(0);
-            }
-            sellOrder.setOrganId(orderByOrderNo.getOrganId());
-            sellOrder.setTransNo(orderByOrderNo.getTransNo());
-            sellOrder.setOrderId(orderByOrderNo.getId());
-            sellOrder.setOrderNo(orderByOrderNo.getOrderNo());
-            Goods goods = goodsService.get(e);
-            costMap.put("sellCost", goods.getDiscountPrice());
-            if (goods.getAgreeCostPrice() != null) {
-                costMap.put("SellCost2", goods.getAgreeCostPrice());
-            }
-            BigDecimal multiply2 = goodsSellDto.getGoodsPrice().multiply(new BigDecimal(sellOrder.getNum()));
-            //获取比例
-            BigDecimal ratioAmount = multiply2.divide(totalAmount, 6, BigDecimal.ROUND_HALF_UP);
-            //实际支付价格
-            BigDecimal actualAmount = multiply2;
-            //如果有减免金额
-            if (marketAmount.doubleValue() > 0l) {
-                //如果是最后一件商品
-                if (i == sellOrderList.size() - 1) {
-                    actualAmount = multiply2.subtract(usableMarketAmount);
-                } else {
-                    //获取分配的减免金额
-                    BigDecimal multiply = ratioAmount.multiply(marketAmount).setScale(2, BigDecimal.ROUND_HALF_UP);
-                    actualAmount = multiply2.subtract(multiply);
-                    usableMarketAmount = usableMarketAmount.subtract(multiply);
-                }
-            }
-
-            //如果没有使用余额,那么实际金额和预计金额一致
-            if (balancePaymentAmount.doubleValue() == 0l) {
-                sellOrder.setActualAmount(actualAmount);
-                sellOrder.setBalanceAmount(BigDecimal.ZERO);
-            } else {
-                //如果是最后一件商品
-                if (i == sellOrderList.size() - 1) {
-                    sellOrder.setActualAmount(usableAmount);
-                    sellOrder.setBalanceAmount(usableBalance);
-                } else {
-                    //获取分配的余额
-                    BigDecimal multiply = ratioAmount.multiply(balancePaymentAmount).setScale(2, BigDecimal.ROUND_HALF_UP);
-                    //分配的实际支付
-                    BigDecimal multiply1 = ratioAmount.multiply(realityAmount).setScale(2, BigDecimal.ROUND_HALF_UP);
-                    sellOrder.setActualAmount(multiply1);
-                    sellOrder.setBalanceAmount(multiply);
-                    usableAmount = usableAmount.subtract(multiply1);
-                    usableBalance = usableBalance.subtract(multiply);
-                    usableActual = usableActual.subtract(multiply1).subtract(multiply);
-                }
-            }
-            sellOrder.setExpectAmount(sellOrder.getActualAmount().add(sellOrder.getBalanceAmount()));
-//            sellOrder.setSellCost2(JSONObject.toJSONString(costMap));
-            if (SellTypeEnum.ACCESSORIES.getCode().equals(goodsSellDto.getGoodsType()) || SellTypeEnum.INSTRUMENT.getCode().equals(goodsSellDto.getGoodsType())) {
-                sellOrder.setType(SellTypeEnum.valueOf(goodsSellDto.getGoodsType()));
-            } else {
-                sellOrder.setType(SellTypeEnum.OTHER);
-            }
-            sellOrder.setGoodsId(sellOrder.getGoodsId());
-            sellOrder.setGoodsName(goodsSellDto.getGoodsName());
-            sellOrder.setUserId(studentGoodsSell.getUserId());
-            sellOrder.setPaymentChannel(orderByOrderNo.getPaymentChannel());
-            sellOrder.setMerNo(orderByOrderNo.getMerNos());
-            sellOrder.setSellTime(orderByOrderNo.getPayTime());
-            sellOrder.setEduTeacherId(studentGoodsSell.getTeacherId());
-            sellOrder.setCooperationOrganId(studentGoodsSell.getCooperationOrganId());
-        }
-        if (sellOrderList.size() > 0) {
-            //如果有优惠券金额
-            BigDecimal couponMarketAmount = studentGoodsSell.getCouponMarketAmount();
-            if (couponMarketAmount.compareTo(BigDecimal.ZERO) > 0) {
-                BigDecimal reduce = sellOrderList.stream().map(e -> e.getExpectAmount()).reduce(BigDecimal.ZERO, BigDecimal::add);
-                List<SellOrder> sellOrders = sellOrderList.stream().filter(e -> e.getExpectAmount().compareTo(BigDecimal.ZERO) > 0).collect(Collectors.toList());
-                //可用优惠券金额
-                BigDecimal subCouponMarketAmount = couponMarketAmount;
-                for (int i = 0; i < sellOrders.size(); i++) {
-                    SellOrder sellOrder = sellOrders.get(i);
-                    //如果是最后一件商品
-                    if (i == sellOrders.size() - 1) {
-                        sellOrder.setCouponRemitAmount(subCouponMarketAmount);
-                    } else {
-                        //获取比例
-                        BigDecimal ratioAmount = sellOrder.getExpectAmount().divide(reduce, 6, BigDecimal.ROUND_HALF_UP);
-                        //获取分配的减免金额
-                        BigDecimal multiply = couponMarketAmount.multiply(ratioAmount).setScale(2, BigDecimal.ROUND_HALF_UP);
-                        subCouponMarketAmount = subCouponMarketAmount.subtract(multiply);
-                        sellOrder.setCouponRemitAmount(multiply);
-                    }
-                }
-            }
-            sellOrderService.batchInsert(sellOrderList);
-        }
-    }
-
     @Override
     @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
     public Boolean orderCallback(StudentPaymentOrder studentPaymentOrder) {
@@ -1508,29 +1230,10 @@ public class StudentRepairServiceImpl extends BaseServiceImpl<Integer, StudentRe
                 rechargeDetail.setPerAmount(studentPaymentOrder.getPerAmount().negate());
             }
             sysUserCashAccountDetailService.insert(paymentDetail);
-            //优惠券减免金额
-            BigDecimal couponRemitFee = studentPaymentOrder.getCouponRemitFee();
-            if (couponRemitFee.compareTo(BigDecimal.ZERO) > 0 && repairInfo.getAmount().compareTo(BigDecimal.ZERO) > 0) {
-                //获取维修金额
-                BigDecimal repairAmount = repairInfo.getAmount();
-                //获取比例
-                BigDecimal divide = repairAmount.divide(repairAmount.add(couponRemitFee), 6, BigDecimal.ROUND_HALF_UP);
-                BigDecimal bigDecimal = couponRemitFee.multiply(divide).setScale(2, BigDecimal.ROUND_HALF_UP);
-                couponRemitFee = couponRemitFee.subtract(bigDecimal);
-//                repairInfo.setAmount(repairAmount.subtract(bigDecimal));
-//                studentRepairDao.update(repairInfo);
-            }
             //生成销售订单
-            if (StringUtils.isNotBlank(repairInfo.getGoodsJson())) {
-                List<Goods> goods = JSONObject.parseArray(repairInfo.getGoodsJson(), Goods.class);
-                List<Integer> goodsIds = goods.stream().map(Goods::getId).collect(Collectors.toList());
-                if (goodsIds.size() > 0) {
-                    sellOrderService.addSellOrder(studentPaymentOrder.getId(),
-                            null,
-                            goodsIds,
-                            studentPaymentOrder.getExpectAmount().add(repairInfo.getExemptionAmount()),
-                            studentPaymentOrder.getBalancePaymentAmount(), couponRemitFee);
-                }
+            List<StudentPaymentOrderDetail> orderDetails = studentPaymentOrderDetailService.queryOrderDetail(studentPaymentOrder.getId());
+            if (CollectionUtils.isNotEmpty(orderDetails)) {
+                sellOrderService.addOrderDetail2SellOrder(studentPaymentOrderDetailService.queryOrderDetail(studentPaymentOrder.getId()),studentPaymentOrder,null);
             }
 
             String imContent = repairInfo.getStudentName() + "学员您好,您的乐器维修已受理,我们会尽快完成保养维修";
@@ -1556,54 +1259,6 @@ public class StudentRepairServiceImpl extends BaseServiceImpl<Integer, StudentRe
             if (this.update(repairInfo) <= 0) {
                 throw new BizException("维修单更新失败");
             }
-
-            //增加商品库存
-            List<StudentPaymentOrderDetail> studentPaymentOrderDetailList = studentPaymentOrderDetailService.queryOrderDetail(studentPaymentOrder.getId());
-            String goodsIds = studentPaymentOrderDetailList.stream().filter(t -> StringUtils.isNotBlank(t.getMinuendStockGoodsIdList())).map(t -> t.getMinuendStockGoodsIdList()).collect(Collectors.joining(","));
-            if (StringUtils.isNotBlank(goodsIds)) {
-                GoodsProcurement goodsProcurement = null;
-                List<Goods> goodsList = goodsService.getGoodsWithLocked(goodsIds);
-                Map<Integer, Goods> goodsMap = goodsList.stream().collect(Collectors.toMap(Goods::getId, t -> t));
-                Goods goods = null;
-                Map<Integer, Goods> batchUpdateGoodsMap = new HashMap<Integer, Goods>();
-                Map<Long, GoodsProcurement> goodsProcurementMap = new HashMap<Long, GoodsProcurement>();
-
-                for (String goodsIdStr : goodsIds.split(",")) {
-                    if (StringUtils.isBlank(goodsIdStr)) {
-                        continue;
-                    }
-                    goods = goodsMap.get(Integer.parseInt(goodsIdStr));
-                    if (batchUpdateGoodsMap.get(goods.getId()) != null) {
-                        goods = batchUpdateGoodsMap.get(goods.getId());
-                    }
-                    goods.setStockCount(new AtomicInteger(goods.getStockCount()).incrementAndGet());
-                    goods.setSellCount(new AtomicInteger(goods.getSellCount()).decrementAndGet());
-                    goods.setUpdateTime(nowDate);
-
-                    batchUpdateGoodsMap.put(goods.getId(), goods);
-
-                    // 进货清单
-                    goodsProcurement = goodsProcurementDao.getWithStockSurplusProcurement(goods.getId());
-                    if (goodsProcurement != null) {
-                        if (goodsProcurementMap.get(goodsProcurement.getId()) != null) {
-                            goodsProcurement = goodsProcurementMap.get(goodsProcurement.getId());
-                        }
-                        goodsProcurement.setStockSoldNum(new AtomicInteger(goodsProcurement.getStockSoldNum()).decrementAndGet());
-                        goodsProcurement.setUpdateTime(nowDate);
-                        goodsProcurementMap.put(goodsProcurement.getId(), goodsProcurement);
-                    }
-
-                }
-
-                if (goodsProcurementMap.size() > 0) {
-                    goodsProcurementDao.batchUpdate(new ArrayList<GoodsProcurement>(goodsProcurementMap.values()));
-                }
-
-                if (batchUpdateGoodsMap.size() > 0) {
-                    goodsService.batchUpdate(new ArrayList<Goods>(batchUpdateGoodsMap.values()));
-                }
-            }
-
             if (studentPaymentOrder.getBalancePaymentAmount() != null && studentPaymentOrder.getBalancePaymentAmount().compareTo(BigDecimal.ZERO) > 0) {
                 sysUserCashAccountService.updateBalance(studentPaymentOrder.getUserId(), studentPaymentOrder.getBalancePaymentAmount(), PlatformCashAccountDetailTypeEnum.REFUNDS, "乐器维修支付失败");
             }

部分文件因为文件数量过多而无法显示