浏览代码

Merge remote-tracking branch 'origin/saas' into saas

zouxuan 3 年之前
父节点
当前提交
075191c7bf
共有 20 个文件被更改,包括 1559 次插入146 次删除
  1. 1 1
      audio-analysis/src/main/java/com/yonge/netty/dto/UserChannelContext.java
  2. 1 1
      mec-biz/src/main/java/com/ym/mec/biz/dal/dao/GoodsDao.java
  3. 2 0
      mec-biz/src/main/java/com/ym/mec/biz/dal/dao/GoodsProcurementDao.java
  4. 11 0
      mec-biz/src/main/java/com/ym/mec/biz/dal/dto/StudentPaymentOrderExportDto.java
  5. 21 1
      mec-biz/src/main/java/com/ym/mec/biz/dal/entity/StudentPaymentOrderDetail.java
  6. 2 1
      mec-biz/src/main/java/com/ym/mec/biz/dal/enums/OrderDetailTypeEnum.java
  7. 8 7
      mec-biz/src/main/java/com/ym/mec/biz/service/GoodsService.java
  8. 43 18
      mec-biz/src/main/java/com/ym/mec/biz/service/impl/ExportServiceImpl.java
  9. 12 0
      mec-biz/src/main/java/com/ym/mec/biz/service/impl/GoodsServiceImpl.java
  10. 131 17
      mec-biz/src/main/java/com/ym/mec/biz/service/impl/PayServiceImpl.java
  11. 73 23
      mec-biz/src/main/java/com/ym/mec/biz/service/impl/SellOrderServiceImpl.java
  12. 56 0
      mec-biz/src/main/java/com/ym/mec/biz/service/impl/StudentPaymentOrderServiceImpl.java
  13. 201 27
      mec-biz/src/main/java/com/ym/mec/biz/service/impl/StudentRegistrationServiceImpl.java
  14. 458 25
      mec-biz/src/main/java/com/ym/mec/biz/service/impl/StudentRepairServiceImpl.java
  15. 472 19
      mec-biz/src/main/java/com/ym/mec/biz/service/impl/SubjectChangeServiceImpl.java
  16. 45 0
      mec-biz/src/main/resources/config/mybatis/GoodsProcurementMapper.xml
  17. 18 4
      mec-biz/src/main/resources/config/mybatis/StudentPaymentOrderDetailMapper.xml
  18. 2 0
      mec-biz/src/main/resources/config/mybatis/StudentPaymentOrderMapper.xml
  19. 1 1
      mec-biz/src/main/resources/config/mybatis/StudentPaymentRouteOrderMapper.xml
  20. 1 1
      mec-student/src/main/java/com/ym/mec/student/controller/MusicGroupController.java

+ 1 - 1
audio-analysis/src/main/java/com/yonge/netty/dto/UserChannelContext.java

@@ -38,7 +38,7 @@ public class UserChannelContext {
 	//打击乐
 	private final static List<Integer> percussionList = Arrays.asList(23, 113);
 	
-	private final static int MIN_FREQUECY = 100;
+	private final static int MIN_FREQUECY = 43;
 	
 	private final static int MAX_FREQUECY = 2000;
 	

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

@@ -59,7 +59,7 @@ public interface GoodsDao extends BaseDAO<Integer, Goods> {
      * @author Joburgess
      * @date 2020.09.28
      */
-    void batchUpdate(@Param("goodsList") List<Goods> goodsList);
+    int batchUpdate(@Param("goodsList") List<Goods> goodsList);
 
     /**
      * 获取商品列表

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

@@ -10,6 +10,8 @@ import java.util.Map;
 public interface GoodsProcurementDao extends BaseDAO<Long, GoodsProcurement> {
 
     int batchInsert(@Param("goodsProcurements") List<GoodsProcurement> goodsProcurements);
+    
+    int batchUpdate(@Param("goodsProcurements") List<GoodsProcurement> goodsProcurements);
 
     List<GoodsProcurement> queryGoodsProcurements(Map<String, Object> params);
     int countGoodsProcurements(Map<String, Object> params);

+ 11 - 0
mec-biz/src/main/java/com/ym/mec/biz/dal/dto/StudentPaymentOrderExportDto.java

@@ -153,6 +153,9 @@ public class StudentPaymentOrderExportDto extends StudentPaymentOrder {
     //订单金额
     @ApiModelProperty(value = "订单金额",required = true)
     private BigDecimal orderAmount = BigDecimal.ZERO;
+    
+    //内部库存商品销售转化的收入
+    private BigDecimal translatedIncome = BigDecimal.ZERO;
 
     public enum TypeDesc implements BaseEnum<String, StudentPaymentOrderExportDto.TypeDesc> {
 
@@ -551,4 +554,12 @@ public class StudentPaymentOrderExportDto extends StudentPaymentOrder {
     public void setPayingStatus(Integer payingStatus) {
         this.payingStatus = payingStatus;
     }
+
+	public BigDecimal getTranslatedIncome() {
+		return translatedIncome;
+	}
+
+	public void setTranslatedIncome(BigDecimal translatedIncome) {
+		this.translatedIncome = translatedIncome;
+	}
 }

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

@@ -63,7 +63,11 @@ public class StudentPaymentOrderDetail extends BaseEntity {
 	
 	private String incomeItem;
 	
-	private BigDecimal income;
+	private BigDecimal income = BigDecimal.ZERO;
+	
+	private BigDecimal balanceIncome = BigDecimal.ZERO;
+	
+	private String minuendStockGoodsIdList;
 
 	@ApiModelProperty(value = "子商品列表",required = false)
 	private List<Goods> childGoodsList;
@@ -228,4 +232,20 @@ public class StudentPaymentOrderDetail extends BaseEntity {
 	public void setIncome(BigDecimal income) {
 		this.income = income;
 	}
+
+	public BigDecimal getBalanceIncome() {
+		return balanceIncome;
+	}
+
+	public void setBalanceIncome(BigDecimal balanceIncome) {
+		this.balanceIncome = balanceIncome;
+	}
+
+	public String getMinuendStockGoodsIdList() {
+		return minuendStockGoodsIdList;
+	}
+
+	public void setMinuendStockGoodsIdList(String minuendStockGoodsIdList) {
+		this.minuendStockGoodsIdList = minuendStockGoodsIdList;
+	}
 }

+ 2 - 1
mec-biz/src/main/java/com/ym/mec/biz/dal/enums/OrderDetailTypeEnum.java

@@ -29,7 +29,8 @@ public enum OrderDetailTypeEnum implements BaseEnum<String, OrderDetailTypeEnum>
     MAINTENANCE("MAINTENANCE","乐保服务"),
     CLOUD_TEACHER("CLOUD_TEACHER","云教练"),
     CLOUD_TEACHER_PLUS("CLOUD_TEACHER_PLUS","云教练"),
-    THEORY_COURSE("THEORY_COURSE", "乐理课");
+    THEORY_COURSE("THEORY_COURSE", "乐理课"),
+    REPAIR("REPAIR", "乐器维修");
 
     private String code;
 

+ 8 - 7
mec-biz/src/main/java/com/ym/mec/biz/service/GoodsService.java

@@ -1,20 +1,17 @@
 package com.ym.mec.biz.service;
 
+import java.util.List;
+
+import org.springframework.web.multipart.MultipartFile;
+
 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.SellOrder;
 import com.ym.mec.biz.dal.enums.AccountType;
 import com.ym.mec.biz.dal.page.GoodsQuery;
-import com.ym.mec.biz.dal.page.GoodsQueryInfo;
-import com.ym.mec.common.page.PageInfo;
 import com.ym.mec.common.service.BaseService;
 
-import org.apache.ibatis.annotations.Param;
-import org.springframework.web.multipart.MultipartFile;
-
-import java.util.List;
-
 public interface GoodsService extends BaseService<Integer, Goods> {
 
     void addGoods(Goods goods, Integer operatorId);
@@ -126,4 +123,8 @@ public interface GoodsService extends BaseService<Integer, Goods> {
      * @return
      */
     Goods getDetail(Integer goodsId);
+    
+    List<Goods> getGoodsWithLocked(String goodsIds);
+    
+    int batchUpdate(List<Goods> goodsList);
 }

+ 43 - 18
mec-biz/src/main/java/com/ym/mec/biz/service/impl/ExportServiceImpl.java

@@ -26,6 +26,7 @@ import com.ym.mec.util.date.DateUtil;
 import com.ym.mec.util.excel.POIUtil;
 import com.ym.mec.util.ini.IniFileUtil;
 import com.ym.mec.util.upload.UploadUtil;
+
 import org.apache.commons.lang3.StringUtils;
 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
 import org.springframework.beans.factory.annotation.Autowired;
@@ -38,6 +39,7 @@ import org.springframework.util.CollectionUtils;
 
 import javax.annotation.PostConstruct;
 import javax.servlet.http.HttpServletResponse;
+
 import java.io.*;
 import java.lang.reflect.InvocationTargetException;
 import java.math.BigDecimal;
@@ -69,6 +71,8 @@ public class ExportServiceImpl implements ExportService {
     @Autowired
     private MusicGroupDao musicGroupDao;
     @Autowired
+    private SysConfigDao sysConfigDao;
+    @Autowired
     private StoragePluginContext storagePluginContext;
     @Autowired
     private ManagerDownloadDao managerDownloadDao;
@@ -2442,34 +2446,33 @@ public class ExportServiceImpl implements ExportService {
                             row.setMusicGroupCourseFee(row.getMusicGroupCourseFee().add(orderDetail.getPrice()));
                             break;
                         case MUSICAL:
+                        	BigDecimal income = orderDetail.getIncome();
+                        	//扣除内部库存的商品销售收入统计在云教练中
                         	if(StringUtils.equals(orderDetail.getIncomeItem(), OrderDetailTypeEnum.CLOUD_TEACHER.name())){
-                        		row.setCloudTeacherFee(orderDetail.getIncome());
-                        		break;
+                        		row.setTranslatedIncome(row.getTranslatedIncome().add(income.multiply(row.getActualAmount()).divide(row.getExpectAmount(), 2, BigDecimal.ROUND_DOWN)));
                         	}
                             if (orderDetail.getKitGroupPurchaseType() != null && orderDetail.getKitGroupPurchaseType().equals(KitGroupPurchaseTypeEnum.LEASE)) {
-                                BigDecimal leaseFee = orderDetail.getPrice();
+                                BigDecimal leaseFee = orderDetail.getPrice().subtract(income);
                                 if (row.getExpectAmount().compareTo(BigDecimal.ZERO) > 0) {
-                                    leaseFee = orderDetail.getPrice().multiply(row.getActualAmount()).divide(row.getExpectAmount(), 2, BigDecimal.ROUND_DOWN);
+                                    leaseFee = orderDetail.getPrice().subtract(income).multiply(row.getActualAmount()).divide(row.getExpectAmount(), 2, BigDecimal.ROUND_DOWN);
                                 }
                                 row.setLeaseFee(leaseFee);
                             } else {
-                                row.setMusicalFee(orderDetail.getPrice());
+                                row.setMusicalFee(orderDetail.getPrice().subtract(orderDetail.getIncome()));
                             }
                             break;
                         case ACCESSORIES:
                         case TEACHING:
                         	if(StringUtils.equals(orderDetail.getIncomeItem(), OrderDetailTypeEnum.CLOUD_TEACHER.name())){
-                        		row.setCloudTeacherFee(orderDetail.getIncome());
-                        		break;
+                        		row.setTranslatedIncome(row.getTranslatedIncome().add(orderDetail.getIncome().multiply(row.getActualAmount()).divide(row.getExpectAmount(), 2, BigDecimal.ROUND_DOWN)));
                         	}
-                            row.setTeachingFee(row.getTeachingFee().add(orderDetail.getPrice()));
+                            row.setTeachingFee(row.getTeachingFee().add(orderDetail.getPrice().subtract(orderDetail.getIncome())));
                             break;
                         case OTHER:
                         	if(StringUtils.equals(orderDetail.getIncomeItem(), OrderDetailTypeEnum.CLOUD_TEACHER.name())){
-                        		row.setCloudTeacherFee(orderDetail.getIncome());
-                        		break;
+                        		row.setTranslatedIncome(row.getTranslatedIncome().add(orderDetail.getIncome().multiply(row.getActualAmount()).divide(row.getExpectAmount(), 2, BigDecimal.ROUND_DOWN)));
                         	}
-                            row.setOtherFee(row.getOtherFee().add(orderDetail.getPrice()));
+                            row.setOtherFee(row.getOtherFee().add(orderDetail.getPrice().subtract(orderDetail.getIncome())));
                             break;
                         case MAINTENANCE:
                             BigDecimal maintenanceFee = BigDecimal.ZERO;
@@ -2484,7 +2487,7 @@ public class ExportServiceImpl implements ExportService {
                             if (row.getExpectAmount().compareTo(BigDecimal.ZERO) > 0) {
                                 cloudTeacherFee = orderDetail.getPrice().multiply(row.getActualAmount()).divide(row.getExpectAmount(), 2, BigDecimal.ROUND_DOWN);
                             }
-                            row.setCloudTeacherFee(cloudTeacherFee);
+                    		row.setCloudTeacherFee(row.getCloudTeacherFee().add(cloudTeacherFee));
                             break;
                         case DEGREE_REGISTRATION:
                             BigDecimal degreeFee = BigDecimal.ZERO;
@@ -2625,11 +2628,14 @@ public class ExportServiceImpl implements ExportService {
                 }
             } else {
                 StudentPaymentOrderExportDto feeByType = sellOrderDao.getFeeByType(row.getId());
-                BigDecimal childRepairFee = sellOrderDao.getChildRepair(row.getId());
-                row.setMusicalFee(feeByType.getMusicalFee());
-                row.setTeachingFee(feeByType.getTeachingFee().subtract(childRepairFee));
-                row.setMaintenanceProductFee(feeByType.getRepairFee().add(childRepairFee));
-                row.setOtherFee(feeByType.getOtherFee());
+                //兼容历史数据
+                if(row.getCreateTime().before(DateUtil.stringToDate("2022-06-15 00:00:00"))){
+	                BigDecimal childRepairFee = sellOrderDao.getChildRepair(row.getId());
+	                row.setMusicalFee(feeByType.getMusicalFee());
+	                row.setTeachingFee(feeByType.getTeachingFee().subtract(childRepairFee));
+	                row.setMaintenanceProductFee(feeByType.getRepairFee().add(childRepairFee));
+	                row.setOtherFee(feeByType.getOtherFee());
+                }
                 if (row.getGroupType().equals(GroupType.MUSIC)) {
                     StudentRegistration studentRegistration = studentRegistrationDao.findStudentByMusicGroupIdAndUserId(row.getMusicGroupId(), row.getUserId());
                     if (studentRegistration != null) {
@@ -2638,7 +2644,7 @@ public class ExportServiceImpl implements ExportService {
                         row.setCooperationOrganName(studentRegistration.getRemark());
                         row.setEduTeacher(studentRegistration.getName());
                     }
-                    row.setMusicGroupCourseFee(feeByType.getActualAmount().subtract(feeByType.getMusicalFee()).subtract(row.getTeachingFee()).subtract(row.getMaintenanceFee()).subtract(row.getMaintenanceProductFee()).subtract(feeByType.getOtherFee()).subtract(row.getLeaseFee()).subtract(row.getCloudTeacherFee()));
+                    //row.setMusicGroupCourseFee(feeByType.getActualAmount().subtract(feeByType.getMusicalFee()).subtract(row.getTeachingFee()).subtract(row.getMaintenanceFee()).subtract(row.getMaintenanceProductFee()).subtract(feeByType.getOtherFee()).subtract(row.getLeaseFee()).subtract(row.getCloudTeacherFee()));
                 } else if (row.getType().equals(OrderTypeEnum.REPAIR)) {
                     row.setRepairFee(feeByType.getActualAmount().subtract(feeByType.getMusicalFee()).subtract(feeByType.getTeachingFee()).subtract(feeByType.getOtherFee()));
                 } else if (row.getType().equals(OUTORDER)) {
@@ -2686,6 +2692,9 @@ public class ExportServiceImpl implements ExportService {
             row.setPaymentChannel(paymentChannel);
             row.setOrderAmount(row.getExpectAmount().add(row.getCouponRemitFee()));
         }
+        
+		//查询商品收款账户配置
+        String goodsSellReceiptMerNo = sysConfigDao.findConfigValue("goodsSellReceiptMerNo");
 
         Map<Long, List<StudentPaymentOrderExportDto>> orderMap = studentPaymentOrderExportDtos.stream().collect(Collectors.groupingBy(StudentPaymentOrderExportDto::getId));
         orderMap.forEach((orderId, orders) -> {
@@ -2709,6 +2718,22 @@ public class ExportServiceImpl implements ExportService {
                 if (order.getPayTime() == null || order.getPayTime().compareTo(endDate) < 0) {
                     break;
                 }
+                //如果有转化的销售服务
+                if(StringUtils.equals(order.getRouteMerNo(), goodsSellReceiptMerNo) && order.getTranslatedIncome().compareTo(order.getRouteAmount()) == 0){
+                	order.setMusicGroupCourseFee(BigDecimal.ZERO);
+                    order.setVipCourseFee(BigDecimal.ZERO);
+                    order.setPracticeCourseFee(BigDecimal.ZERO);
+                    order.setTheoryCourseFee(BigDecimal.ZERO);
+                    order.setDegreeFee(BigDecimal.ZERO);
+                    order.setMaintenanceFee(BigDecimal.ZERO);
+                    order.setCloudTeacherFee(order.getTranslatedIncome());
+                    order.setRepairFee(BigDecimal.ZERO);
+                    order.setMusicalFee(BigDecimal.ZERO);
+                    order.setTeachingFee(BigDecimal.ZERO);
+                    order.setOtherFee(BigDecimal.ZERO);
+                    order.setLeaseFee(BigDecimal.ZERO);
+                	continue;
+                }
                 if (order.getSaleAmount().compareTo(BigDecimal.ZERO) > 0 && order.getServiceAmount().compareTo(BigDecimal.ZERO) == 0) {
                     order.setMusicGroupCourseFee(BigDecimal.ZERO);
                     order.setVipCourseFee(BigDecimal.ZERO);

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

@@ -20,6 +20,7 @@ import com.ym.mec.common.tenant.TenantContextHolder;
 import com.ym.mec.thirdparty.message.MessageSenderPluginContext;
 import com.ym.mec.util.excel.POIUtil;
 import com.ym.mec.util.ini.IniFileUtil;
+
 import org.apache.commons.lang3.StringUtils;
 import org.apache.poi.ss.usermodel.PictureData;
 import org.slf4j.Logger;
@@ -634,4 +635,15 @@ public class GoodsServiceImpl extends BaseServiceImpl<Integer, Goods>  implement
 		}
 		return goods;
 	}
+
+	@Override
+	public List<Goods> getGoodsWithLocked(String goodsIds) {
+		List<Integer> list = Arrays.stream(goodsIds.split(",")).map(Integer :: valueOf).collect(Collectors.toList());
+		return goodsDao.lockGoods(list);
+	}
+
+	@Override
+	public int batchUpdate(List<Goods> goodsList) {
+		return goodsDao.batchUpdate(goodsList);
+	}
 }

+ 131 - 17
mec-biz/src/main/java/com/ym/mec/biz/service/impl/PayServiceImpl.java

@@ -1,6 +1,7 @@
 package com.ym.mec.biz.service.impl;
 
 import java.math.BigDecimal;
+import java.math.RoundingMode;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Date;
@@ -10,6 +11,7 @@ import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
+import java.util.concurrent.atomic.AtomicInteger;
 import java.util.stream.Collectors;
 
 import org.apache.commons.lang3.StringUtils;
@@ -17,12 +19,14 @@ import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
 
 import com.alibaba.fastjson.JSON;
+import com.ym.mec.biz.dal.dao.GoodsProcurementDao;
 import com.ym.mec.biz.dal.dao.HfMemberDao;
 import com.ym.mec.biz.dal.dao.StudentPaymentRouteOrderDao;
 import com.ym.mec.biz.dal.dao.SysConfigDao;
 import com.ym.mec.biz.dal.dto.AmountChannelDto;
 import com.ym.mec.biz.dal.dto.RouteScaleDto;
 import com.ym.mec.biz.dal.entity.Goods;
+import com.ym.mec.biz.dal.entity.GoodsProcurement;
 import com.ym.mec.biz.dal.entity.HfMember;
 import com.ym.mec.biz.dal.entity.StudentPaymentOrder;
 import com.ym.mec.biz.dal.entity.StudentPaymentOrderDetail;
@@ -72,6 +76,8 @@ public class PayServiceImpl implements PayService {
     private HfMemberDao hfMemberDao;
     @Autowired
     private RedisCache<String, Object> redisCache;
+    @Autowired
+    private GoodsProcurementDao goodsProcurementDao;
 
     @Override
     public Map<String, Object> getPayMap(BigDecimal amount, BigDecimal balanceAmount, String orderNo, String notifyUrl, String returnUrl, String orderSubject, String orderBody, Integer organId, String receiver) throws Exception {
@@ -173,6 +179,8 @@ public class PayServiceImpl implements PayService {
 		BigDecimal subBalance = BigDecimal.ZERO;
 		
 		BigDecimal subCashAmount = BigDecimal.ZERO;
+		
+		RouteScaleDto routeScaleDtoForGoodsSell = null;
     	//忽略的分部
 		List<Integer> ignoreOrganList = Arrays.asList(4, 55, 59);
 		
@@ -187,19 +195,24 @@ public class PayServiceImpl implements PayService {
         	if(sysPaymentConfig != null){
 
     			List<StudentPaymentOrderDetail> batchUpdateList = new ArrayList<StudentPaymentOrderDetail>();
+    			Map<Integer, Goods> batchUpdateGoodsMap = new HashMap<Integer, Goods>();
         		
         		// 如果买了商品或组合商品,商品有内部库存,则将钱转入指定账户已云教练的方式作为收费项目(杭州、齐齐哈尔除外)
         		// 1.查询商品订单明细
         		List<StudentPaymentOrderDetail> studentPaymentOrderDetailList = studentPaymentOrderDetailService.queryOrderDetail(studentPaymentOrder.getId());
         		if (studentPaymentOrderDetailList != null && studentPaymentOrderDetailList.size() > 0) {
         			
+        			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)){
-        				List<Goods> goodsList = goodsService.findGoodsByIds(goodIds);
+        				List<Goods> goodsList = goodsService.getGoodsWithLocked(goodIds);
         				
         				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;
         				
         				for(StudentPaymentOrderDetail spod : studentPaymentOrderDetailList){
         					
@@ -214,6 +227,8 @@ public class PayServiceImpl implements PayService {
         					
         					BigDecimal groupPurchaseAmount = BigDecimal.ZERO;
         					
+        					minuendStockGoodsIdList = new ArrayList<Integer>();
+        					
         					for(String goodsIdStr : spod.getGoodsIdList().split(",")){
         						if(StringUtils.isBlank(goodsIdStr)){
         							continue;
@@ -223,47 +238,112 @@ public class PayServiceImpl implements PayService {
         						if(goods != null){
         							// 是否是组合商品
         							if(StringUtils.isNotBlank(goods.getComplementGoodsIdList())){
-        								goodsList = goodsService.findGoodsByIds(goods.getComplementGoodsIdList());
+        								goodsList = goodsService.getGoodsWithLocked(goods.getComplementGoodsIdList());
         								totalGroupPurchaseAmount =  totalGroupPurchaseAmount.add(goodsList.stream().map(Goods :: getGroupPurchasePrice).reduce(BigDecimal.ZERO,BigDecimal :: add));
         								
         								for(Goods subGoods : goodsList){
+    										
+    										if(batchUpdateGoodsMap.get(subGoods.getId()) != null){
+    											subGoods = batchUpdateGoodsMap.get(subGoods.getId());
+    										}
         									//判断是否有内部库存
         									if(subGoods.getStockCount() > 0){
+        										
         										groupPurchaseAmount = groupPurchaseAmount.add(subGoods.getGroupPurchasePrice());
+        										subGoods.setStockCount(new AtomicInteger(subGoods.getStockCount()).decrementAndGet());
+            									subGoods.setSellCount(new AtomicInteger(subGoods.getSellCount()).incrementAndGet());
+        										subGoods.setUpdateTime(date);
+        										
+        										batchUpdateGoodsMap.put(subGoods.getId(), subGoods);
+        										
+        										minuendStockGoodsIdList.add(subGoods.getId());
+        										
+        										goodsProcurement = goodsProcurementDao.getWithStockSurplusProcurement(subGoods.getId());
+        										if(goodsProcurement != null){
+        											if(goodsProcurementMap.get(goodsProcurement.getId()) != null){
+        												goodsProcurement = goodsProcurementMap.get(goodsProcurement.getId());
+        											}
+        											goodsProcurement.setStockSoldNum(new AtomicInteger(goodsProcurement.getStockSoldNum()).incrementAndGet());
+        											goodsProcurement.setUpdateTime(date);
+        											goodsProcurementMap.put(goodsProcurement.getId(), goodsProcurement);
+        										}
         									}
         								}
         							}else{
     									totalGroupPurchaseAmount = totalGroupPurchaseAmount.add(goods.getGroupPurchasePrice());
+    									
+    									if(batchUpdateGoodsMap.get(goods.getId()) != null){
+    										goods = batchUpdateGoodsMap.get(goods.getId());
+										}
+    									
         								//判断是否有内部库存
         								if(goods.getStockCount() > 0){
+        									
     										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());
+    										
+    										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()).incrementAndGet());
+    											goodsProcurement.setUpdateTime(date);
+    											goodsProcurementMap.put(goodsProcurement.getId(), goodsProcurement);
+    										}
         								}
         							}
         						}
         					}
         					
-							if (groupPurchaseAmount.doubleValue() > 0) {
+							if (groupPurchaseAmount.compareTo(BigDecimal.ZERO) > 0) {
 	        					// 3.是否使用余额
-								if (balanceAmount.doubleValue() > 0) {
-									tempBalance = balanceAmount.multiply(spod.getPrice()).divide(totalAmout).multiply(groupPurchaseAmount)
-											.divide(totalGroupPurchaseAmount);
+								if (balanceAmount.compareTo(BigDecimal.ZERO) > 0) {
+									/*tempBalance = balanceAmount.multiply(spod.getPrice()).divide(totalAmout).multiply(groupPurchaseAmount)
+											.divide(totalGroupPurchaseAmount);*/
+									tempBalance = balanceAmount.multiply(spod.getPrice()).multiply(groupPurchaseAmount)
+											.divide(totalGroupPurchaseAmount.multiply(totalAmout), BigDecimal.ROUND_UP).setScale(2, BigDecimal.ROUND_UP);
+									
+									if(subBalance.add(tempBalance).compareTo(balanceAmount) > 0){
+										tempBalance = balanceAmount.subtract(subBalance);
+									}
 									subBalance = subBalance.add(tempBalance);
 								}
-								tempCashAmount = spod.getPrice().subtract(tempBalance).multiply(groupPurchaseAmount).divide(totalGroupPurchaseAmount);
+								tempCashAmount = spod.getPrice().subtract(tempBalance).multiply(groupPurchaseAmount).divide(totalGroupPurchaseAmount, BigDecimal.ROUND_DOWN).setScale(2, BigDecimal.ROUND_DOWN);
+								if(subCashAmount.add(tempCashAmount).compareTo(amount) > 0){
+									tempCashAmount = amount.subtract(subCashAmount);
+								}
 								subCashAmount = subCashAmount.add(tempCashAmount);
 								spod.setIncomeItem(OrderDetailTypeEnum.CLOUD_TEACHER.name());
 								spod.setIncome(tempCashAmount);
+								spod.setBalanceIncome(tempBalance);
+								if(minuendStockGoodsIdList.size() > 0){
+									spod.setMinuendStockGoodsIdList(minuendStockGoodsIdList.stream().map(t -> t.toString()).collect(Collectors.joining(",")));
+								}
 								batchUpdateList.add(spod);
 							}
         				}
         			}
+        			
+        			if(goodsProcurementMap.size() > 0){
+        				goodsProcurementDao.batchUpdate(new ArrayList<GoodsProcurement>(goodsProcurementMap.values()));
+        			}
         		}
         		
         		if(batchUpdateList.size() > 0){
         			studentPaymentOrderDetailService.batchUpdate(batchUpdateList);
         		}
         		
-        		if(subCashAmount.doubleValue() > 0){
+        		if(batchUpdateGoodsMap.size() > 0){
+        			goodsService.batchUpdate(new ArrayList<Goods>(batchUpdateGoodsMap.values()));
+        		}
+        		
+        		if(subCashAmount.compareTo(BigDecimal.ZERO) > 0){
         			StudentPaymentRouteOrder studentPaymentRouteOrder = new StudentPaymentRouteOrder();
     	            studentPaymentRouteOrder.setOrderNo(orderNo);
     	            studentPaymentRouteOrder.setRouteOrganId(sysPaymentConfig.getOrganId());
@@ -272,16 +352,32 @@ public class PayServiceImpl implements PayService {
     	            studentPaymentRouteOrder.setRouteBalanceAmount(subBalance);
     	            studentPaymentRouteOrder.setMerNo(goodsSellReceiptMerNo);
     	            studentPaymentRouteOrder.setSaleAmount(BigDecimal.ZERO);
-    	            studentPaymentRouteOrder.setServiceAmount(amount);
+    	            studentPaymentRouteOrder.setServiceAmount(subCashAmount);
     	            studentPaymentRouteOrder.setCreateTime(date);
     	            studentPaymentRouteOrder.setUpdateTime(date);
     	            studentPaymentRouteOrderDao.insert(studentPaymentRouteOrder);
+
+    	            routeScaleDtoForGoodsSell = new RouteScaleDto();
+    	            routeScaleDtoForGoodsSell.setAmount(subCashAmount);
+    	            routeScaleDtoForGoodsSell.setOrganId(sysPaymentConfig.getOrganId());
+    	            routeScaleDtoForGoodsSell.setPayType(PaymentChannelEnum.ADAPAY);
+    	            routeScaleDtoForGoodsSell.setScale(100);
+    	            routeScaleDtoForGoodsSell.setMerNo(goodsSellReceiptMerNo);
+    	            routeScaleDtoForGoodsSell.setFeeFlag("Y");
         		}
         	}
         }
 		
-		amount = amount.subtract(subCashAmount);
-		balanceAmount = balanceAmount.subtract(subBalance);
+        if(amount.compareTo(subCashAmount) <= 0){
+        	amount = BigDecimal.ZERO;
+        }else{
+        	amount = amount.subtract(subCashAmount);
+        }
+        if(balanceAmount.compareTo(subBalance) <= 0){
+        	balanceAmount = BigDecimal.ZERO;
+        }else{
+        	balanceAmount = balanceAmount.subtract(subBalance);
+        }
         
         String usePaymentConfig = sysConfigDao.findConfigValue("use_payment_config");// 是否用收费配置(1:使用 0:不使用)
         List<RouteScaleDto> routeScaleDtos = null;
@@ -312,8 +408,24 @@ public class PayServiceImpl implements PayService {
         for (RouteScaleDto routeScaleDto : routeScaleDtos) {
             checkMaxReceipt(routeScaleDto, routeScaleDto.getMerNo());
         }
+        
+        if(routeScaleDtoForGoodsSell != null){
+        	routeScaleDtos.add(routeScaleDtoForGoodsSell);
+        }
+        
+        Map<String, Object> map = getPayRoute(amount, balanceAmount, orderNo, notifyUrl, returnUrl, orderSubject, orderBody, routeScaleDtos, subCashAmount);
+        
+		if (routeScaleDtoForGoodsSell != null) {
+			String routingMerNos = (String) map.get("routingMerNos");
+			List<String> list = new ArrayList<String>(Arrays.asList(routingMerNos.split(",")));
+			if(!list.contains(routeScaleDtoForGoodsSell.getMerNo())){
+				list.add(routeScaleDtoForGoodsSell.getMerNo());
+			}
 
-        return getPayRoute(amount, balanceAmount, orderNo, notifyUrl, returnUrl, orderSubject, orderBody, routeScaleDtos);
+	        map.put("routingMerNos", String.join(",", list));
+		}
+        
+        return map;
     }
 
     @Override
@@ -569,7 +681,7 @@ public class PayServiceImpl implements PayService {
         return amount.add(totalHasReceipt).compareTo(totalMaxReceipt) >= 0;
     }
 
-    private Map<String, Object> getPayRoute(BigDecimal amount, BigDecimal balanceAmount, String orderNo, String notifyUrl, String returnUrl, String orderSubject, String orderBody, List<RouteScaleDto> routeScaleDtos) throws Exception {
+    private Map<String, Object> getPayRoute(BigDecimal amount, BigDecimal balanceAmount, String orderNo, String notifyUrl, String returnUrl, String orderSubject, String orderBody, List<RouteScaleDto> routeScaleDtos, BigDecimal shareAmount) throws Exception {
         Map<String, List<RouteScaleDto>> routeScaleDtosMap = routeScaleDtos.stream().collect(Collectors.groupingBy(RouteScaleDto::getMerNo));
 
         //合并同账号的数据
@@ -663,17 +775,19 @@ public class PayServiceImpl implements PayService {
             routingMerNoSet.add(routeScaleDto.getMerNo());
         }
 
-        if (studentPaymentRouteOrderDao.batchAdd(RouteOrders) <= 0) {
-            throw new BizException("调用支付接口失败");
+        if(RouteOrders.size() > 0) {
+	        if (studentPaymentRouteOrderDao.batchAdd(RouteOrders) <= 0) {
+	            throw new BizException("调用支付接口失败");
+	        }
         }
 
         if (payType.equals(PaymentChannelEnum.YQPAY)) {
             if (tempRoutingList.size() == 1 && YqPayUtil.merNo.equals(tempRoutingList.get(0).get("routingMerNo").toString())) {
                 tempRoutingList = null;
             }
-            payMap = YqPayUtil.getPayMap(amount, orderNo, notifyUrl, returnUrl, orderSubject, orderBody, YqPayUtil.merNo, tempRoutingList);
+            payMap = YqPayUtil.getPayMap(amount.add(shareAmount), orderNo, notifyUrl, returnUrl, orderSubject, orderBody, YqPayUtil.merNo, tempRoutingList);
         } else {
-            payMap = Payment.getPayMap(amount, orderNo, notifyUrl, returnUrl, orderSubject, orderBody);
+            payMap = Payment.getPayMap(amount.add(shareAmount), orderNo, notifyUrl, returnUrl, orderSubject, orderBody);
         }
         String routingMerNos = String.join(",", routingMerNoSet);
 

+ 73 - 23
mec-biz/src/main/java/com/ym/mec/biz/service/impl/SellOrderServiceImpl.java

@@ -1,14 +1,15 @@
 package com.ym.mec.biz.service.impl;
 
 
-import com.alibaba.fastjson.JSONObject;
-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.service.*;
-import com.ym.mec.common.constant.CommonConstants;
-import com.ym.mec.common.dal.BaseDAO;
-import com.ym.mec.common.service.impl.BaseServiceImpl;
+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 org.apache.commons.lang3.StringUtils;
 import org.springframework.beans.factory.annotation.Autowired;
@@ -16,11 +17,39 @@ import org.springframework.stereotype.Service;
 import org.springframework.transaction.annotation.Isolation;
 import org.springframework.transaction.annotation.Transactional;
 
-import java.math.BigDecimal;
-import java.util.*;
-import java.util.stream.Collectors;
-
-import static com.ym.mec.biz.dal.enums.GroupType.GOODS_SELL;
+import com.alibaba.fastjson.JSONObject;
+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.StudentRepair;
+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;
 
 @Service
 public class SellOrderServiceImpl extends BaseServiceImpl<Integer, SellOrder> implements SellOrderService {
@@ -44,6 +73,8 @@ public class SellOrderServiceImpl extends BaseServiceImpl<Integer, SellOrder> im
     private SporadicChargeInfoDao sporadicChargeInfoDao;
     @Autowired
     private StudentRepairDao studentRepairDao;
+    @Autowired
+    private StudentPaymentOrderDetailService studentPaymentOrderDetailService;
 
     @Override
     public BaseDAO<Integer, SellOrder> getDAO() {
@@ -451,6 +482,14 @@ public class SellOrderServiceImpl extends BaseServiceImpl<Integer, SellOrder> im
         if (order == null) {
             return null;
         }
+        
+        List<StudentPaymentOrderDetail> studentPaymentOrderDetailList = studentPaymentOrderDetailService.queryOrderDetail(order.getId());
+        BigDecimal cloudIncome = BigDecimal.ZERO;
+        BigDecimal cloudBalanceIncome = BigDecimal.ZERO;
+        if(studentPaymentOrderDetailList != null) {
+        	cloudIncome = studentPaymentOrderDetailList.stream().filter(t -> StringUtils.isNoneBlank(t.getMinuendStockGoodsIdList()) && StringUtils.equals(t.getIncomeItem(), OrderDetailTypeEnum.CLOUD_TEACHER.name())).map(t -> t.getIncome()).reduce(BigDecimal.ZERO, BigDecimal::add);
+        	cloudBalanceIncome = studentPaymentOrderDetailList.stream().filter(t -> StringUtils.isNoneBlank(t.getMinuendStockGoodsIdList()) && StringUtils.equals(t.getIncomeItem(), OrderDetailTypeEnum.CLOUD_TEACHER.name())).map(t -> t.getBalanceIncome()).reduce(BigDecimal.ZERO, BigDecimal::add);
+        }
 
         //零星支付除了充值其他都是服务费用
         if (order.getType().equals(OrderTypeEnum.SPORADIC)) {
@@ -462,20 +501,20 @@ public class SellOrderServiceImpl extends BaseServiceImpl<Integer, SellOrder> im
         Map<String, BigDecimal> sellAmount = new HashMap<>();
         //乐器销售,声部更改
         if (order.getType().equals(OrderTypeEnum.GOODS_SELL) || order.getType().equals(OrderTypeEnum.SUBJECT_CHANGE)) {
-            sellAmount.put("actualAmount", order.getActualAmount());
-            sellAmount.put("balance", order.getBalancePaymentAmount() == null ? BigDecimal.ZERO : order.getBalancePaymentAmount());
+            sellAmount.put("actualAmount", order.getActualAmount().subtract(cloudIncome));
+            sellAmount.put("balance", order.getBalancePaymentAmount() == null ? BigDecimal.ZERO : order.getBalancePaymentAmount().subtract(cloudBalanceIncome));
             return sellAmount;
         }
         //乐器置换
         if (order.getType().equals(OrderTypeEnum.REPLACEMENT)) {
-            sellAmount.put("actualAmount", order.getActualAmount());
-            sellAmount.put("balance", order.getBalancePaymentAmount() == null ? BigDecimal.ZERO : order.getBalancePaymentAmount());
+            sellAmount.put("actualAmount", order.getActualAmount().subtract(cloudIncome));
+            sellAmount.put("balance", order.getBalancePaymentAmount() == null ? BigDecimal.ZERO : order.getBalancePaymentAmount().subtract(cloudBalanceIncome));
             return sellAmount;
         }
 
         //乐器维修
         if (order.getType().equals(OrderTypeEnum.REPAIR)) {
-            StudentRepair repairInfo = studentRepairDao.getRepairInfo(Integer.parseInt(order.getMusicGroupId()));
+            /*StudentRepair repairInfo = studentRepairDao.getRepairInfo(Integer.parseInt(order.getMusicGroupId()));
 
             if (StringUtils.isBlank(repairInfo.getGoodsJson())) {
                 sellAmount.put("actualAmount", BigDecimal.ZERO);
@@ -512,8 +551,11 @@ public class SellOrderServiceImpl extends BaseServiceImpl<Integer, SellOrder> im
 
             BigDecimal goodsTotalBalance = goodsTotalPrice.multiply(balance).divide(totalAmount, 2, BigDecimal.ROUND_DOWN);
             BigDecimal goodsTotalActualAmount = goodsTotalPrice.multiply(order.getActualAmount()).divide(totalAmount, 2, BigDecimal.ROUND_DOWN);
-            sellAmount.put("actualAmount", goodsTotalActualAmount);
-            sellAmount.put("balance", goodsTotalBalance);
+            sellAmount.put("actualAmount", goodsTotalActualAmount.subtract(cloudIncome));
+            sellAmount.put("balance", goodsTotalBalance.subtract(cloudBalanceIncome));*/
+        	
+            sellAmount.put("actualAmount", order.getActualAmount().subtract(cloudIncome));
+            sellAmount.put("balance", order.getBalancePaymentAmount() == null ? BigDecimal.ZERO : order.getBalancePaymentAmount().subtract(cloudBalanceIncome));
             return sellAmount;
         }
 
@@ -528,9 +570,17 @@ 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);
-
-            sellAmount.put("actualAmount", detailTotalPrice.subtract(detailTotalBalance));
-            sellAmount.put("balance", detailTotalBalance);
+            
+            if(detailTotalBalance.subtract(cloudBalanceIncome).compareTo(BigDecimal.ZERO) < 0) {
+            	detailTotalBalance = cloudBalanceIncome;
+            }
+            
+            if(detailTotalPrice.subtract(detailTotalBalance).subtract(cloudIncome).compareTo(BigDecimal.ZERO) < 0){
+            	sellAmount.put("actualAmount", BigDecimal.ZERO);
+            }else{
+            	sellAmount.put("actualAmount", detailTotalPrice.subtract(detailTotalBalance).subtract(cloudIncome));
+            }
+            sellAmount.put("balance", detailTotalBalance.subtract(cloudBalanceIncome));
             return sellAmount;
         }
 

+ 56 - 0
mec-biz/src/main/java/com/ym/mec/biz/service/impl/StudentPaymentOrderServiceImpl.java

@@ -30,6 +30,7 @@ import com.ym.mec.thirdparty.adapay.Payment;
 import com.ym.mec.thirdparty.yqpay.*;
 import com.ym.mec.util.collection.MapUtil;
 import com.ym.mec.util.date.DateUtil;
+
 import org.apache.commons.collections.CollectionUtils;
 import org.apache.commons.lang3.StringUtils;
 import org.slf4j.Logger;
@@ -43,6 +44,7 @@ import org.springframework.transaction.annotation.Transactional;
 
 import java.math.BigDecimal;
 import java.util.*;
+import java.util.concurrent.atomic.AtomicInteger;
 import java.util.stream.Collectors;
 
 @Service
@@ -84,6 +86,8 @@ public class StudentPaymentOrderServiceImpl extends BaseServiceImpl<Long, Studen
     @Autowired
     private GoodsDao goodsDao;
     @Autowired
+    private GoodsService goodsService;
+    @Autowired
     private StudentInstrumentService studentInstrumentService;
     @Autowired
     private ReplacementInstrumentActivityService replacementInstrumentActivityService;
@@ -109,6 +113,8 @@ public class StudentPaymentOrderServiceImpl extends BaseServiceImpl<Long, Studen
     private SysUserFeignService sysUserFeignService;
     @Autowired
     private TenantConfigService tenantConfigService;
+    @Autowired
+    private GoodsProcurementDao goodsProcurementDao;
 
     @Override
     public BaseDAO<Long, StudentPaymentOrder> getDAO() {
@@ -793,6 +799,56 @@ public class StudentPaymentOrderServiceImpl extends BaseServiceImpl<Long, Studen
         //处理关闭订单
         order.setStatus(DealStatusEnum.CLOSE);
         order.setMemo("关闭订单");
+
+        
+        Date nowDate = new Date();
+        //增加商品库存
+        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;
+				}
+				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()));
+            }
+        }
+        
         //如果是报名订单,订单关闭时需要更改已缴费学员数
         cutSubjectPlan(order);
         if (order.getBalancePaymentAmount() != null && order.getBalancePaymentAmount().compareTo(BigDecimal.ZERO) > 0) {

+ 201 - 27
mec-biz/src/main/java/com/ym/mec/biz/service/impl/StudentRegistrationServiceImpl.java

@@ -1,16 +1,157 @@
 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.atomic.AtomicInteger;
+import java.util.stream.Collectors;
+
+import javax.annotation.Resource;
+
+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.http.HttpStatus;
+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.*;
-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.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.event.source.SendSeoMessageSource;
-import com.ym.mec.biz.service.*;
+import com.ym.mec.biz.service.ClassGroupService;
+import com.ym.mec.biz.service.ClassGroupStudentMapperService;
+import com.ym.mec.biz.service.CloudTeacherOrderService;
+import com.ym.mec.biz.service.ContractService;
+import com.ym.mec.biz.service.CourseScheduleService;
+import com.ym.mec.biz.service.CourseScheduleStudentPaymentService;
+import com.ym.mec.biz.service.GoodsService;
+import com.ym.mec.biz.service.ImGroupMemberService;
+import com.ym.mec.biz.service.MusicGroupPaymentCalenderActivityService;
+import com.ym.mec.biz.service.MusicGroupPaymentCalenderMemberService;
+import com.ym.mec.biz.service.MusicGroupPaymentCalenderRepairService;
+import com.ym.mec.biz.service.MusicGroupPaymentCalenderService;
+import com.ym.mec.biz.service.MusicGroupSubjectPlanService;
+import com.ym.mec.biz.service.StudentPaymentOrderDetailService;
+import com.ym.mec.biz.service.StudentPaymentOrderService;
+import com.ym.mec.biz.service.StudentRegistrationService;
+import com.ym.mec.biz.service.StudentService;
+import com.ym.mec.biz.service.SubjectService;
+import com.ym.mec.biz.service.SysConfigService;
+import com.ym.mec.biz.service.SysCouponCodeService;
+import com.ym.mec.biz.service.SysMessageService;
+import com.ym.mec.biz.service.SysTenantConfigService;
+import com.ym.mec.biz.service.SysUserCashAccountDetailService;
+import com.ym.mec.biz.service.SysUserCashAccountLogService;
+import com.ym.mec.biz.service.SysUserCashAccountService;
 import com.ym.mec.common.dal.BaseDAO;
 import com.ym.mec.common.entity.HttpResponseResult;
 import com.ym.mec.common.entity.ImResult;
@@ -24,27 +165,6 @@ 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.http.HttpStatus;
-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.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 {
@@ -112,6 +232,8 @@ public class StudentRegistrationServiceImpl extends BaseServiceImpl<Long, Studen
     @Autowired
     private GoodsDao goodsDao;
     @Autowired
+    private GoodsService goodsService;
+    @Autowired
     private MusicGroupPaymentCalenderDetailDao musicGroupPaymentCalenderDetailDao;
     @Autowired
     private MusicGroupPaymentCalenderDao musicGroupPaymentCalenderDao;
@@ -129,6 +251,10 @@ public class StudentRegistrationServiceImpl extends BaseServiceImpl<Long, Studen
     private ImGroupDao imGroupDao;
     @Autowired
     private StudentInstrumentDao studentInstrumentDao;
+    
+    @Autowired
+    private GoodsProcurementDao goodsProcurementDao;
+    
     @Autowired
     private MusicGroupPaymentCalenderStudentDetailDao musicGroupPaymentCalenderStudentDetailDao;
     @Autowired
@@ -1243,6 +1369,7 @@ public class StudentRegistrationServiceImpl extends BaseServiceImpl<Long, Studen
             } catch (Exception e) {
                 LOGGER.error("协议生成失败", e);
             }
+            
         }
 
         if (studentPaymentOrder.getStatus().equals(DealStatusEnum.FAILED)) {
@@ -1251,6 +1378,53 @@ public class StudentRegistrationServiceImpl extends BaseServiceImpl<Long, Studen
             studentRegistrationDao.update(studentRegistration);
             //减去缴费人数(器乐收费,0元时不减缴费人数)
             studentPaymentOrderService.cutSubjectPlan(studentPaymentOrder);
+            
+            //增加商品库存
+            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()));
+                }
+            }
 
             //退还优惠券和余额
             studentPaymentOrderService.returnBalanceAndCoupon(studentPaymentOrder,"报名缴费失败");

+ 458 - 25
mec-biz/src/main/java/com/ym/mec/biz/service/impl/StudentRepairServiceImpl.java

@@ -1,18 +1,88 @@
 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.ArrayList;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
+
+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 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.*;
+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.entity.*;
-import com.ym.mec.biz.dal.enums.*;
+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.SellOrder;
+import com.ym.mec.biz.dal.entity.StudentGoodsSell;
+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.StudentRepair;
+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.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.page.RepairStudentQueryInfo;
-import com.ym.mec.biz.service.*;
+import com.ym.mec.biz.service.ContractService;
+import com.ym.mec.biz.service.GoodsService;
+import com.ym.mec.biz.service.PayService;
+import com.ym.mec.biz.service.SellOrderService;
+import com.ym.mec.biz.service.StudentGoodsSellService;
+import com.ym.mec.biz.service.StudentInstrumentService;
+import com.ym.mec.biz.service.StudentPaymentOrderDetailService;
+import com.ym.mec.biz.service.StudentPaymentOrderService;
+import com.ym.mec.biz.service.StudentPaymentRouteOrderService;
+import com.ym.mec.biz.service.StudentRepairService;
+import com.ym.mec.biz.service.SysConfigService;
+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;
@@ -21,22 +91,6 @@ import com.ym.mec.common.service.IdGeneratorService;
 import com.ym.mec.common.service.impl.BaseServiceImpl;
 import com.ym.mec.thirdparty.message.MessageSenderPluginContext;
 import com.ym.mec.util.collection.MapUtil;
-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 org.springframework.transaction.annotation.Isolation;
-import org.springframework.transaction.annotation.Propagation;
-import org.springframework.transaction.annotation.Transactional;
-
-import java.math.BigDecimal;
-import java.util.*;
-import java.util.stream.Collectors;
-
-import static com.ym.mec.biz.dal.enums.CouponDetailTypeEnum.*;
-import static com.ym.mec.biz.dal.enums.DealStatusEnum.*;
 
 @Service
 public class StudentRepairServiceImpl extends BaseServiceImpl<Integer, StudentRepair> implements StudentRepairService {
@@ -54,6 +108,8 @@ public class StudentRepairServiceImpl extends BaseServiceImpl<Integer, StudentRe
     @Autowired
     private StudentPaymentOrderService studentPaymentOrderService;
     @Autowired
+    private StudentPaymentOrderDetailService studentPaymentOrderDetailService;
+    @Autowired
     private SysPaymentConfigService sysPaymentConfigService;
     @Autowired
     private MusicGroupDao musicGroupDao;
@@ -72,6 +128,8 @@ public class StudentRepairServiceImpl extends BaseServiceImpl<Integer, StudentRe
     @Autowired
     private StudentGoodsSellDao studentGoodsSellDao;
     @Autowired
+    private GoodsProcurementDao goodsProcurementDao;
+    @Autowired
     private ContractService contractService;
     @Autowired
     private GoodsService goodsService;
@@ -149,6 +207,54 @@ public class StudentRepairServiceImpl extends BaseServiceImpl<Integer, StudentRe
                 }
                 //退优惠券
                 sysCouponCodeService.quit(orderByOrderNo.getCouponCodeId());
+                
+                Date nowDate = new Date();
+                //增加商品库存
+                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;
+                	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()));
+                    }
+                }
             }
             StudentGoodsSell byOrderNo = studentGoodsSellDao.findByOrderNo(studentGoodsSell.getOrderNo());
             if (byOrderNo != null) {
@@ -199,11 +305,11 @@ public class StudentRepairServiceImpl extends BaseServiceImpl<Integer, StudentRe
             goodsSellDto.setGoodsGroupPrice(groupPriceMap.get(goodsSellDto.getGoodsId()));
             goodsSellDto.setTotalGoodsPrice(map.get(goodsSellDto.getGoodsId()).multiply(new BigDecimal(goodsSellDto.getGoodsNum())));
         }
-        Map<Integer, List<GoodsSellDto>> goodsMap = goodsSellDtos.stream().collect(Collectors.groupingBy(GoodsSellDto::getGoodsId));
+        Map<Integer, List<GoodsSellDto>> goodsSellDtoMap = goodsSellDtos.stream().collect(Collectors.groupingBy(GoodsSellDto::getGoodsId));
         BigDecimal amount = BigDecimal.ZERO;
         BigDecimal groupAmount = BigDecimal.ZERO;
         for (Integer id : goodsIds) {
-            GoodsSellDto goodsSellDto = goodsMap.get(id).get(0);
+            GoodsSellDto goodsSellDto = goodsSellDtoMap.get(id).get(0);
             amount = amount.add(goodsSellDto.getTotalGoodsPrice());
             groupAmount = groupAmount.add(goodsSellDto.getGoodsGroupPrice());
         }
@@ -252,6 +358,75 @@ public class StudentRepairServiceImpl extends BaseServiceImpl<Integer, StudentRe
         studentPaymentOrder.setRoutingOrganId(student.getOrganId());
         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 = 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);
+        }
 
         studentPaymentOrder.setVersion(0);
         BigDecimal balance = BigDecimal.ZERO;
@@ -455,9 +630,12 @@ public class StudentRepairServiceImpl extends BaseServiceImpl<Integer, StudentRe
         repairInfo.setPayStatus(0);
         repairInfo.setCreateTime(date);
         repairInfo.setUpdateTime(date);
+        
+        List<RepairGoodsDto> repairGoodsDtos = null;
+        		
         String goodsJson = repairInfo.getGoodsJson();
         if (StringUtils.isNotEmpty(goodsJson)) {
-            List<RepairGoodsDto> repairGoodsDtos = JSONObject.parseArray(goodsJson, RepairGoodsDto.class);
+            repairGoodsDtos = JSONObject.parseArray(goodsJson, RepairGoodsDto.class);
             List<Integer> goodsIds = repairGoodsDtos.stream().map(e -> e.getId()).collect(Collectors.toList());
             Map<Integer, BigDecimal> map = getMap("goods", "id_", "discount_price_", goodsIds,student.getTenantId(), Integer.class, BigDecimal.class);
             repairGoodsDtos.forEach(e -> {
@@ -466,6 +644,7 @@ public class StudentRepairServiceImpl extends BaseServiceImpl<Integer, StudentRe
             repairInfo.setGoodsJson(JSONObject.toJSONString(repairGoodsDtos));
         }
 
+        BigDecimal goodsPrice = BigDecimal.ZERO;
         if (StringUtils.isNoneBlank(repairInfo.getGoodsJson())) {
             JSONArray goods = JSON.parseArray(repairInfo.getGoodsJson());
             for (Object good : goods) {
@@ -473,6 +652,7 @@ public class StudentRepairServiceImpl extends BaseServiceImpl<Integer, StudentRe
                 BigDecimal groupPurchasePrice = goodObject.getBigDecimal("groupPurchasePrice");
                 if (Objects.nonNull(groupPurchasePrice)) {
                     amount = amount.add(groupPurchasePrice);
+                    goodsPrice = goodsPrice.add(groupPurchasePrice);
                 }
             }
         }
@@ -509,6 +689,78 @@ public class StudentRepairServiceImpl extends BaseServiceImpl<Integer, StudentRe
 
         studentPaymentOrderService.insert(studentPaymentOrder);
         studentPaymentOrder.setVersion(0);
+  
+        
+        List<StudentPaymentOrderDetail> studentPaymentOrderDetailList = new ArrayList<StudentPaymentOrderDetail>();
+        // 添加studentPaymentOrderDetail
+        StudentPaymentOrderDetail studentPaymentOrderDetail = new StudentPaymentOrderDetail();
+        studentPaymentOrderDetail.setCreateTime(date);
+        studentPaymentOrderDetail.setType(OrderDetailTypeEnum.REPAIR);
+        studentPaymentOrderDetail.setGoodsIdList(null);
+        studentPaymentOrderDetail.setPrice(studentPaymentOrder.getExpectAmount().multiply(repairInfo.getAmount()).divide(goodsPrice.add(repairInfo.getAmount()), RoundingMode.UP));
+        studentPaymentOrderDetail.setUpdateTime(date);
+        studentPaymentOrderDetail.setPaymentOrderId(studentPaymentOrder.getId());
+        
+        studentPaymentOrderDetailList.add(studentPaymentOrderDetail);
+
+        BigDecimal totalPrice = studentPaymentOrderDetail.getPrice();
+        BigDecimal repairPrice = studentPaymentOrderDetail.getPrice();
+        
+        if(StringUtils.isNotBlank(repairInfo.getGoodsJson()) && repairGoodsDtos != null){
+        	String goodsIds = repairGoodsDtos.stream().map(t -> t.getId().toString()).collect(Collectors.joining(","));
+        	List<Goods> goodsList = goodsService.findGoodsByIds(goodsIds);
+        	Map<Integer,Goods> goodsMap = goodsList.stream().collect(Collectors.toMap(Goods :: getId, t -> t));
+        	Goods goods = null;
+        	BigDecimal totalGroupPurchasePrice = BigDecimal.ZERO;
+        	for(String goodsIdStr : goodsIds.split(",")){
+        		if(StringUtils.isBlank(goodsIdStr)){
+					continue;
+				}
+				goods = goodsMap.get(Integer.parseInt(goodsIdStr));
+				
+				if(goods != null){
+					totalGroupPurchasePrice = totalGroupPurchasePrice.add(goods.getGroupPurchasePrice());
+				}
+        	}
+        	for(String goodsIdStr : goodsIds.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 = studentPaymentOrder.getExpectAmount().subtract(repairPrice).multiply(goods.getGroupPurchasePrice()).divide(totalGroupPurchasePrice, BigDecimal.ROUND_DOWN).setScale(2, BigDecimal.ROUND_DOWN);
+	                
+	                if(totalPrice.add(tempPrice).compareTo(studentPaymentOrder.getExpectAmount()) > 0 || goodsIds.split(",").length == studentPaymentOrderDetailList.size()){
+	                	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);
+        }
 
         BigDecimal balance = BigDecimal.ZERO;
         if (repairInfo.getUseBalancePayment() && amount.compareTo(BigDecimal.ZERO) > 0) {
@@ -629,18 +881,32 @@ public class StudentRepairServiceImpl extends BaseServiceImpl<Integer, StudentRe
         ) {
             throw new BizException("邮寄信息必填");
         }
+        
+        List<RepairGoodsDto> repairGoodsDtos = null;
         Date date = new Date();
         StudentRepair studentRepair = studentRepairDao.get(repairInfo.getId());
         studentDao.lockUser(studentRepair.getStudentId());
         BigDecimal amount = studentRepair.getAmount();
         String goodsJson = studentRepair.getGoodsJson();
         if (StringUtils.isNotEmpty(goodsJson)) {
-            List<RepairGoodsDto> repairGoodsDtos = JSONObject.parseArray(goodsJson, RepairGoodsDto.class);
+            repairGoodsDtos = JSONObject.parseArray(goodsJson, RepairGoodsDto.class);
             BigDecimal reduce = repairGoodsDtos.stream().map(e -> e.getGroupPurchasePrice()).reduce(BigDecimal.ZERO, BigDecimal::add);
             amount = amount.add(reduce);
         }
         amount = amount.subtract(studentRepair.getExemptionAmount());
 
+        BigDecimal goodsPrice = BigDecimal.ZERO;
+        if (StringUtils.isNoneBlank(goodsJson)) {
+            JSONArray goods = JSON.parseArray(goodsJson);
+            for (Object good : goods) {
+                JSONObject goodObject = (JSONObject) good;
+                BigDecimal groupPurchasePrice = goodObject.getBigDecimal("groupPurchasePrice");
+                if (Objects.nonNull(groupPurchasePrice)) {
+                	goodsPrice = goodsPrice.add(groupPurchasePrice);
+                }
+            }
+        }
+
         String orderNo = idGeneratorService.generatorId("payment") + "";
         studentRepair.setUseBalancePayment(repairInfo.getUseBalancePayment());
         studentRepair.setTransNo(orderNo);
@@ -673,6 +939,77 @@ public class StudentRepairServiceImpl extends BaseServiceImpl<Integer, StudentRe
 
         studentPaymentOrderService.insert(studentPaymentOrder);
         studentPaymentOrder.setVersion(0);
+        
+        List<StudentPaymentOrderDetail> studentPaymentOrderDetailList = new ArrayList<StudentPaymentOrderDetail>();
+        // 添加studentPaymentOrderDetail
+        StudentPaymentOrderDetail studentPaymentOrderDetail = new StudentPaymentOrderDetail();
+        studentPaymentOrderDetail.setCreateTime(date);
+        studentPaymentOrderDetail.setType(OrderDetailTypeEnum.REPAIR);
+        studentPaymentOrderDetail.setGoodsIdList(null);
+        studentPaymentOrderDetail.setPrice(studentPaymentOrder.getExpectAmount().multiply(studentRepair.getAmount()).divide(goodsPrice.add(studentRepair.getAmount()), RoundingMode.UP));
+        studentPaymentOrderDetail.setUpdateTime(date);
+        studentPaymentOrderDetail.setPaymentOrderId(studentPaymentOrder.getId());
+        
+        studentPaymentOrderDetailList.add(studentPaymentOrderDetail);
+
+        BigDecimal totalPrice = studentPaymentOrderDetail.getPrice();
+        BigDecimal repairPrice = studentPaymentOrderDetail.getPrice();
+        
+        if(StringUtils.isNotBlank(studentRepair.getGoodsJson()) && repairGoodsDtos != null){
+        	String goodsIds = repairGoodsDtos.stream().map(t -> t.getId().toString()).collect(Collectors.joining(","));
+        	List<Goods> goodsList = goodsService.findGoodsByIds(goodsIds);
+        	Map<Integer,Goods> goodsMap = goodsList.stream().collect(Collectors.toMap(Goods :: getId, t -> t));
+        	Goods goods = null;
+        	BigDecimal totalGroupPurchasePrice = BigDecimal.ZERO;
+        	for(String goodsIdStr : goodsIds.split(",")){
+        		if(StringUtils.isBlank(goodsIdStr)){
+					continue;
+				}
+				goods = goodsMap.get(Integer.parseInt(goodsIdStr));
+				
+				if(goods != null){
+					totalGroupPurchasePrice = totalGroupPurchasePrice.add(goods.getGroupPurchasePrice());
+				}
+        	}
+        	for(String goodsIdStr : goodsIds.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 = studentPaymentOrder.getExpectAmount().subtract(repairPrice).multiply(goods.getGroupPurchasePrice()).divide(totalGroupPurchasePrice, BigDecimal.ROUND_DOWN).setScale(2, BigDecimal.ROUND_DOWN);
+	                
+	                if(totalPrice.add(tempPrice).compareTo(studentPaymentOrder.getExpectAmount()) > 0 || goodsIds.split(",").length == studentPaymentOrderDetailList.size()){
+	                	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);
+        }
 
         BigDecimal balance = BigDecimal.ZERO;
         if (studentRepair.getUseBalancePayment() && amount.compareTo(BigDecimal.ZERO) > 0) {
@@ -794,7 +1131,55 @@ public class StudentRepairServiceImpl extends BaseServiceImpl<Integer, StudentRe
             //购买的商品加入销售列表
             saveSellOrder(studentPaymentOrder.getOrderNo());
         } else if (studentPaymentOrder.getStatus() == DealStatusEnum.CLOSE || studentPaymentOrder.getStatus() == DealStatusEnum.FAILED) {
-            if (studentPaymentOrder.getBalancePaymentAmount() != null && studentPaymentOrder.getBalancePaymentAmount().compareTo(BigDecimal.ZERO) > 0) {
+            
+        	//增加商品库存
+            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, "乐器购买支付失败");
             }
             sysCouponCodeService.quit(studentPaymentOrder.getCouponCodeId());
@@ -1173,6 +1558,54 @@ 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, "乐器维修支付失败");
             }

+ 472 - 19
mec-biz/src/main/java/com/ym/mec/biz/service/impl/SubjectChangeServiceImpl.java

@@ -1,34 +1,96 @@
 package com.ym.mec.biz.service.impl;
 
-import com.ym.mec.biz.dal.dao.*;
+import static com.ym.mec.biz.dal.enums.DealStatusEnum.SUCCESS;
+import static com.ym.mec.biz.dal.enums.GroupType.SUBJECT_CHANGE;
+
+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.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
+
+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 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.GoodsProcurementDao;
+import com.ym.mec.biz.dal.dao.MusicGroupDao;
+import com.ym.mec.biz.dal.dao.MusicGroupPurchaseListDao;
+import com.ym.mec.biz.dal.dao.SellOrderDao;
+import com.ym.mec.biz.dal.dao.StudentDao;
+import com.ym.mec.biz.dal.dao.StudentPaymentOrderDao;
+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.SysConfigDao;
+import com.ym.mec.biz.dal.dao.SysUserCashAccountLogDao;
 import com.ym.mec.biz.dal.dto.SubjectChangeParamDto;
-import com.ym.mec.biz.dal.entity.*;
-import com.ym.mec.biz.dal.enums.*;
+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.MusicGroupPurchaseList;
+import com.ym.mec.biz.dal.entity.MusicGroupSubjectPlan;
+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.StudentPaymentOrderDetail;
+import com.ym.mec.biz.dal.entity.StudentRegistration;
+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.entity.SysUserCashAccountLog;
+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.KitGroupPurchaseTypeEnum;
+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.ReturnFeeEnum;
+import com.ym.mec.biz.dal.enums.SellTypeEnum;
+import com.ym.mec.biz.dal.enums.StudentMusicGroupStatusEnum;
+import com.ym.mec.biz.dal.enums.SubjectChangeStatusEnum;
 import com.ym.mec.biz.dal.page.SubjectChangeQueryInfo;
-import com.ym.mec.biz.service.*;
+import com.ym.mec.biz.service.ContractService;
+import com.ym.mec.biz.service.GoodsService;
+import com.ym.mec.biz.service.MusicGroupSubjectPlanService;
+import com.ym.mec.biz.service.PayService;
+import com.ym.mec.biz.service.SellOrderService;
+import com.ym.mec.biz.service.StudentInstrumentService;
+import com.ym.mec.biz.service.StudentPaymentOrderDetailService;
+import com.ym.mec.biz.service.StudentPaymentOrderService;
+import com.ym.mec.biz.service.StudentPaymentRouteOrderService;
+import com.ym.mec.biz.service.StudentRegistrationService;
+import com.ym.mec.biz.service.SubjectChangeService;
+import com.ym.mec.biz.service.SysConfigService;
+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;
 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.thirdparty.message.MessageSenderPluginContext;
 import com.ym.mec.util.collection.MapUtil;
 import com.ym.mec.util.date.DateUtil;
-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 org.springframework.transaction.annotation.Isolation;
-import org.springframework.transaction.annotation.Transactional;
-
-import java.math.BigDecimal;
-import java.util.*;
-import java.util.stream.Collectors;
-
-import static com.ym.mec.biz.dal.enums.DealStatusEnum.SUCCESS;
-import static com.ym.mec.biz.dal.enums.GroupType.SUBJECT_CHANGE;
 
 @Service
 public class SubjectChangeServiceImpl extends BaseServiceImpl<Integer, SubjectChange> implements SubjectChangeService {
@@ -54,6 +116,8 @@ public class SubjectChangeServiceImpl extends BaseServiceImpl<Integer, SubjectCh
     @Autowired
     private StudentPaymentOrderDetailDao studentPaymentOrderDetailDao;
     @Autowired
+    private StudentPaymentOrderDetailService studentPaymentOrderDetailService;
+    @Autowired
     private MusicGroupDao musicGroupDao;
     @Autowired
     private SellOrderDao sellOrderDao;
@@ -85,6 +149,8 @@ public class SubjectChangeServiceImpl extends BaseServiceImpl<Integer, SubjectCh
     private SysCouponCodeService sysCouponCodeService;
     @Autowired
     private SysUserCashAccountLogDao sysUserCashAccountLogDao;
+    @Autowired
+    private GoodsProcurementDao goodsProcurementDao;
 
     private final Logger logger = LoggerFactory.getLogger(this.getClass());
 
@@ -147,6 +213,52 @@ public class SubjectChangeServiceImpl extends BaseServiceImpl<Integer, SubjectCh
                 studentPaymentOrder.setUpdateTime(date);
                 studentPaymentOrderService.update(studentPaymentOrder);
                 subjectChange.setStatus(SubjectChangeStatusEnum.WAIT_PAY);
+                //增加商品库存
+                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(date);
+        				
+        				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(date);
+        					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()));
+                    }
+                }
             }
         }
 
@@ -224,6 +336,78 @@ public class SubjectChangeServiceImpl extends BaseServiceImpl<Integer, SubjectCh
         studentPaymentOrderService.update(studentPaymentOrder);
 
         studentPaymentOrder.setVersion(studentPaymentOrder.getVersion() + 1);
+        
+        //添加订单详情
+        List<StudentPaymentOrderDetail> studentPaymentOrderDetailList = new ArrayList<StudentPaymentOrderDetail>();
+        // 添加studentPaymentOrderDetail
+        StudentPaymentOrderDetail studentPaymentOrderDetail = null;
+
+        BigDecimal totalPrice = BigDecimal.ZERO;
+        
+        List<String> changeGoodsList = new ArrayList<String>();
+        
+        if(StringUtils.isNotBlank(subjectChange.getChangeAccessories())){
+        	for(String id : subjectChange.getChangeAccessories().split(",")){
+        		changeGoodsList.add(id);
+        	}
+        	
+        	if(subjectChange.getChangeMusical() != subjectChange.getOriginalMusical()){
+        		changeGoodsList.add(subjectChange.getChangeMusical()+"");
+        	}
+        }
+        
+        if(changeGoodsList != null){
+            String goodsIdsStr = changeGoodsList.stream().map(t -> t.toString()).collect(Collectors.joining(","));
+        	List<Goods> goodsList = goodsService.findGoodsByIds(goodsIdsStr);
+        	Map<Integer,Goods> goodsMap = goodsList.stream().collect(Collectors.toMap(Goods :: getId, t -> t));
+        	Goods goods = null;
+        	BigDecimal goodsTotalGroupPurchasePrice = BigDecimal.ZERO;
+        	
+        	for(String goodsIdStr : goodsIdsStr.split(",")){
+        		if(StringUtils.isBlank(goodsIdStr)){
+					continue;
+				}
+				goods = goodsMap.get(Integer.parseInt(goodsIdStr));
+				goodsTotalGroupPurchasePrice = goodsTotalGroupPurchasePrice.add(goods.getGroupPurchasePrice());
+        	}
+        	
+        	for(String goodsIdStr : goodsIdsStr.split(",")){
+        		if(StringUtils.isBlank(goodsIdStr)){
+					continue;
+				}
+				goods = goodsMap.get(Integer.parseInt(goodsIdStr));
+				
+				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(goods.getId() + "");
+                
+                BigDecimal tempPrice = studentPaymentOrder.getExpectAmount().multiply(goods.getGroupPurchasePrice()).divide(goodsTotalGroupPurchasePrice, 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);
+            }
+        }
 
         if (amount.compareTo(BigDecimal.ZERO) == 0) {
             studentPaymentRouteOrderService.addRouteOrder(orderNo, subjectChange.getOrganId(), studentPaymentOrder.getExpectAmount());
@@ -331,6 +515,9 @@ public class SubjectChangeServiceImpl extends BaseServiceImpl<Integer, SubjectCh
         for (Goods goods : goodies) {
             goodsPrice = goodsPrice.add(goods.getDiscountPrice());
         }
+        
+        Map<Integer,Goods> goodsMap = goodies.stream().collect(Collectors.toMap(Goods :: getId, t -> t));
+        
         subjectChange.setChangeCost(goodsPrice);
         subjectChange.setCostMargin(subjectChange.getChangeCost().subtract(subjectChange.getOriginalCost()));
         //差价 <= 0
@@ -383,6 +570,177 @@ public class SubjectChangeServiceImpl extends BaseServiceImpl<Integer, SubjectCh
             subjectChange.setOrderNo(orderNo);
             subjectChangeDao.update(subjectChange);
 
+            //添加订单详情
+            List<StudentPaymentOrderDetail> studentPaymentOrderDetailList = new ArrayList<StudentPaymentOrderDetail>();
+            StudentPaymentOrderDetail studentPaymentOrderDetail = null;
+        	Goods goods = null;
+			List<Integer> minuendStockGoodsIdList = null;
+			GoodsProcurement goodsProcurement = null;
+			Map<Long, GoodsProcurement> goodsProcurementMap = new HashMap<Long, GoodsProcurement>();
+			Map<Integer, Goods> batchUpdateGoodsMap = new HashMap<Integer, Goods>();
+			
+            for(String goodsIdStr : goodsIds.split(",")){
+        		if(StringUtils.isBlank(goodsIdStr)){
+					continue;
+				}
+				goods = goodsMap.get(Integer.parseInt(goodsIdStr));
+				
+				if(goods != null){
+					studentPaymentOrderDetail = new StudentPaymentOrderDetail();
+	                studentPaymentOrderDetail.setCreateTime(nowDate);
+	                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);
+                	studentPaymentOrderDetail.setPrice(BigDecimal.ZERO);
+	                studentPaymentOrderDetail.setUpdateTime(nowDate);
+	                studentPaymentOrderDetail.setPaymentOrderId(studentPaymentOrder.getId());
+	              
+	                //忽略的分部
+	        		List<Integer> ignoreOrganList = Arrays.asList(4, 55, 59);
+	        		
+	        		//查询商品收款账户配置
+	                String goodsSellReceiptMerNo = sysConfigDao.findConfigValue("goodsSellReceiptMerNo");
+	                
+	                if(!ignoreOrganList.contains(subjectChange.getOrganId()) && StringUtils.isNotBlank(goodsSellReceiptMerNo)){
+	                	//扣减库存
+						
+						BigDecimal totalGroupPurchaseAmount = BigDecimal.ZERO;
+						
+						BigDecimal groupPurchaseAmount = BigDecimal.ZERO;
+						
+						minuendStockGoodsIdList = new ArrayList<Integer>();
+						
+						// 是否是组合商品
+						if(StringUtils.isNotBlank(goods.getComplementGoodsIdList())){
+							List<Goods> goodsList = goodsService.getGoodsWithLocked(goods.getComplementGoodsIdList());
+							totalGroupPurchaseAmount =  totalGroupPurchaseAmount.add(goodsList.stream().map(Goods :: getGroupPurchasePrice).reduce(BigDecimal.ZERO,BigDecimal :: add));
+							
+							for(Goods subGoods : goodsList){
+								
+								if(batchUpdateGoodsMap.get(subGoods.getId()) != null){
+									subGoods = batchUpdateGoodsMap.get(subGoods.getId());
+								}
+								//判断是否有内部库存
+								if(subGoods.getStockCount() > 0){
+									
+									groupPurchaseAmount = groupPurchaseAmount.add(subGoods.getGroupPurchasePrice());
+									subGoods.setStockCount(new AtomicInteger(subGoods.getStockCount()).decrementAndGet());
+									subGoods.setSellCount(new AtomicInteger(subGoods.getSellCount()).incrementAndGet());
+									subGoods.setUpdateTime(nowDate);
+									
+									batchUpdateGoodsMap.put(subGoods.getId(), subGoods);
+									
+									minuendStockGoodsIdList.add(subGoods.getId());
+									
+									goodsProcurement = goodsProcurementDao.getWithStockSurplusProcurement(subGoods.getId());
+									if(goodsProcurement != null){
+										if(goodsProcurementMap.get(goodsProcurement.getId()) != null){
+											goodsProcurement = goodsProcurementMap.get(goodsProcurement.getId());
+										}
+										goodsProcurement.setStockSoldNum(new AtomicInteger(goodsProcurement.getStockSoldNum()).incrementAndGet());
+										goodsProcurement.setUpdateTime(nowDate);
+										goodsProcurementMap.put(goodsProcurement.getId(), goodsProcurement);
+									}
+								}
+							}
+						}else{
+							totalGroupPurchaseAmount = totalGroupPurchaseAmount.add(goods.getGroupPurchasePrice());
+							
+							if(batchUpdateGoodsMap.get(goods.getId()) != null){
+								goods = batchUpdateGoodsMap.get(goods.getId());
+							}
+							
+							//判断是否有内部库存
+							if(goods.getStockCount() > 0){
+								
+								groupPurchaseAmount = groupPurchaseAmount.add(goods.getGroupPurchasePrice());
+								goods.setStockCount(new AtomicInteger(goods.getStockCount()).decrementAndGet());
+								goods.setSellCount(new AtomicInteger(goods.getSellCount()).incrementAndGet());
+								goods.setUpdateTime(nowDate);
+								batchUpdateGoodsMap.put(goods.getId(), goods);
+								
+								minuendStockGoodsIdList.add(goods.getId());
+								
+								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()).incrementAndGet());
+									goodsProcurement.setUpdateTime(nowDate);
+									goodsProcurementMap.put(goodsProcurement.getId(), goodsProcurement);
+								}
+							}
+						}
+						
+						if (minuendStockGoodsIdList.size() > 0) {
+							studentPaymentOrderDetail.setIncomeItem(OrderDetailTypeEnum.CLOUD_TEACHER.name());
+							studentPaymentOrderDetail.setIncome(BigDecimal.ZERO);
+							studentPaymentOrderDetail.setBalanceIncome(BigDecimal.ZERO);
+							if(minuendStockGoodsIdList.size() > 0){
+								studentPaymentOrderDetail.setMinuendStockGoodsIdList(minuendStockGoodsIdList.stream().map(t -> t.toString()).collect(Collectors.joining(",")));
+							}
+						}
+	                }
+	                
+	                studentPaymentOrderDetailList.add(studentPaymentOrderDetail);
+				}
+        	}
+            
+            //原始订单的库存要归还
+            List<StudentPaymentOrderDetail> originalStudentPaymentOrderDetailList = studentPaymentOrderDetailService.queryOrderDetail(subjectChange.getOriginalOrderId().longValue());
+            String originalGoodsIds = originalStudentPaymentOrderDetailList.stream().filter(t -> StringUtils.isNotBlank(t.getMinuendStockGoodsIdList())).map(t -> t.getMinuendStockGoodsIdList()).collect(Collectors.joining(","));
+            if(StringUtils.isNotBlank(originalGoodsIds)){
+            	List<Goods> goodsList = goodsService.getGoodsWithLocked(originalGoodsIds);
+            	goodsMap = goodsList.stream().collect(Collectors.toMap(Goods :: getId, t -> t));
+            	
+            	for(String goodsIdStr : originalGoodsIds.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(studentPaymentOrderDetailList.size() > 0){
+            	studentPaymentOrderDetailService.batchAdd(studentPaymentOrderDetailList);
+            }
+			
+			if(goodsProcurementMap.size() > 0){
+				goodsProcurementDao.batchUpdate(new ArrayList<GoodsProcurement>(goodsProcurementMap.values()));
+			}
+    		
+    		if(batchUpdateGoodsMap.size() > 0){
+    			goodsService.batchUpdate(new ArrayList<Goods>(batchUpdateGoodsMap.values()));
+    		}
+
             //退原订单商品
             sellOrderService.refundByOrderId(subjectChange.getOriginalOrderId().longValue(), false);
 
@@ -697,6 +1055,53 @@ public class SubjectChangeServiceImpl extends BaseServiceImpl<Integer, SubjectCh
                 rechargeDetail.setPerAmount(studentPaymentOrder.getPerAmount().negate());
             }
             sysUserCashAccountDetailService.insert(paymentDetail);
+            
+            //增加商品库存
+            List<StudentPaymentOrderDetail> studentPaymentOrderDetailList = studentPaymentOrderDetailService.queryOrderDetail(subjectChange.getOriginalOrderId().longValue());
+            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.getStatus() == DealStatusEnum.CLOSE || studentPaymentOrder.getStatus() == DealStatusEnum.FAILED) {
@@ -704,6 +1109,54 @@ public class SubjectChangeServiceImpl extends BaseServiceImpl<Integer, SubjectCh
             if (this.update(subjectChange) <= 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, "声部更改支付失败");
             }

+ 45 - 0
mec-biz/src/main/resources/config/mybatis/GoodsProcurementMapper.xml

@@ -92,6 +92,51 @@
 		</set> WHERE id_ = #{id} and tenant_id_ = #{tenantId}
 	</update>
 	
+    <update id="batchUpdate" parameterType="java.util.List">
+        <foreach collection="goodsProcurements" item="item" index="index" open="" close="" separator=";">
+			UPDATE goods_procurement
+			<set>
+				<if test="item.operatorId != null">
+					operator_id_ = #{item.operatorId},
+				</if>
+				<if test="item.agreeCostPrice != null">
+					agree_cost_price_ = #{item.agreeCostPrice},
+				</if>
+				<if test="item.id != null">
+					id_ = #{item.id},
+				</if>
+				<if test="item.goodsCategoryId != null">
+					goods_category_id_ = #{item.goodsCategoryId},
+				</if>
+				<if test="item.taxStockCount != null">
+					tax_stock_count_ = #{item.taxStockCount},
+				</if>
+				<if test="item.supplyChannel != null">
+					supply_channel_ = #{item.supplyChannel},
+				</if>
+				<if test="item.discountPrice != null">
+					discount_price_ = #{item.discountPrice},
+				</if>
+				<if test="item.stockCount != null">
+					stock_count_ = #{item.stockCount},
+				</if>
+				<if test="item.goodsId != null">
+					goods_id_ = #{item.goodsId},
+				</if>
+				<if test="item.batchNo != null">
+					batch_no_ = #{item.batchNo},
+				</if>
+				<if test="item.stockSoldNum != null">
+					stock_sold_num_ = #{item.stockSoldNum},
+				</if>
+				<if test="item.taxStockSoldNum != null">
+					tax_stock_sold_num_ = #{item.taxStockSoldNum},
+				</if>
+					update_time_ = NOW(),
+			</set> WHERE id_ = #{item.id} and tenant_id_ = #{item.tenantId}
+		</foreach>
+	</update>
+	
 	<!-- 根据主键删除一条记录 -->
 	<delete id="delete" >
 		DELETE FROM goods_procurement WHERE id_ = #{id} 

+ 18 - 4
mec-biz/src/main/resources/config/mybatis/StudentPaymentOrderDetailMapper.xml

@@ -21,6 +21,8 @@
         <result column="is_renew_" property="isRenew"/>
         <result column="income_item_" property="incomeItem"/>
         <result column="income_" property="income"/>
+        <result column="balance_income_" property="balanceIncome"/>
+        <result column="minuend_stock_goods_id_list_" property="minuendStockGoodsIdList"/>
         <result column="user_id_" property="userId"/>
         <collection property="goodsList" ofType="com.ym.mec.biz.dal.entity.Goods">
             <result column="goods_id_" property="id"/>
@@ -64,10 +66,10 @@
             keyColumn="id" keyProperty="id">
         INSERT INTO student_payment_order_detail
         (type_,goods_id_list_,price_,create_time_,update_time_,payment_order_id_,kit_group_purchase_type_,
-         student_instrument_id_,is_renew_,income_item_,income_,tenant_id_,remit_fee_)
+         student_instrument_id_,is_renew_,income_item_,income_,balance_income_,minuend_stock_goods_id_list_,tenant_id_,remit_fee_)
         VALUES(#{type,typeHandler=com.ym.mec.common.dal.CustomEnumTypeHandler},#{goodsIdList},#{price},now(),now(),
         #{paymentOrderId},#{kitGroupPurchaseType,typeHandler=com.ym.mec.common.dal.CustomEnumTypeHandler},
-               #{studentInstrumentId},#{isRenew},#{incomeItem},#{income},#{tenantId},#{remitFee})
+               #{studentInstrumentId},#{isRenew},#{incomeItem},#{income},#{balanceIncome},#{minuendStockGoodsIdList},#{tenantId},#{remitFee})
     </insert>
 
     <!-- 根据主键查询一条记录 -->
@@ -102,6 +104,12 @@
             <if test="income != null">
                 income_ = #{income},
             </if>
+            <if test="balanceIncome != null">
+                balance_income_ = #{balanceIncome},
+            </if>
+            <if test="minuendStockGoodsIdList != null">
+                minuend_stock_goods_id_list_ = #{minuendStockGoodsIdList},
+            </if>
         </set>
         WHERE id_ = #{id} and tenant_id_ = #{tenantId}
     </update>
@@ -138,6 +146,12 @@
 	            <if test="item.income != null">
 	                income_ = #{item.income},
 	            </if>
+	            <if test="item.balanceIncome != null">
+	                balance_income_ = #{item.balanceIncome},
+	            </if>
+	            <if test="item.minuendStockGoodsIdList != null">
+	                minuend_stock_goods_id_list_ = #{item.minuendStockGoodsIdList},
+	            </if>
 	        </set>
 	        WHERE id_ = #{item.id} and tenant_id_ = #{item.tenantId}
         </foreach>
@@ -165,13 +179,13 @@
     <insert id="batchAdd" parameterType="java.util.List" useGeneratedKeys="true" keyProperty="id_">
         INSERT INTO student_payment_order_detail
         (type_,goods_id_list_,price_,remit_fee_,create_time_,update_time_,payment_order_id_,
-         kit_group_purchase_type_,student_instrument_id_,is_renew_,income_item_,income_,tenant_id_)
+         kit_group_purchase_type_,student_instrument_id_,is_renew_,income_item_,income_,balance_income_,minuend_stock_goods_id_list_,tenant_id_)
         VALUE
         <foreach collection="studentPaymentOrderDetailList" item="orderDetail" separator=",">
             (#{orderDetail.type,typeHandler=com.ym.mec.common.dal.CustomEnumTypeHandler},
             #{orderDetail.goodsIdList},#{orderDetail.price},#{orderDetail.remitFee},now(),now(),#{orderDetail.paymentOrderId},
             #{orderDetail.kitGroupPurchaseType,typeHandler=com.ym.mec.common.dal.CustomEnumTypeHandler},
-            #{orderDetail.studentInstrumentId},#{orderDetail.isRenew},#{orderDetail.incomeItem},#{orderDetail.income},#{orderDetail.tenantId})
+            #{orderDetail.studentInstrumentId},#{orderDetail.isRenew},#{orderDetail.incomeItem},#{orderDetail.income},#{orderDetail.balanceIncome},#{orderDetail.minuendStockGoodsIdList},#{orderDetail.tenantId})
         </foreach>
     </insert>
 

+ 2 - 0
mec-biz/src/main/resources/config/mybatis/StudentPaymentOrderMapper.xml

@@ -595,6 +595,8 @@
             <result column="detail_type_" property="type"/>
             <result column="detail_price_" property="price"/>
             <result column="detail_kit_group_purchase_type_" property="kitGroupPurchaseType"/>
+            <result column="income_item_" property="incomeItem"/>
+            <result column="income_" property="income"/>
         </collection>
         <collection property="goodsList" ofType="com.ym.mec.biz.dal.entity.Goods">
             <result column="goods_id" property="id"/>

+ 1 - 1
mec-biz/src/main/resources/config/mybatis/StudentPaymentRouteOrderMapper.xml

@@ -289,7 +289,7 @@ calender_id_,create_time_,create_by_,update_time_,update_by_,tenant_id_,type_
     <select id="ExportQueryPage" resultMap="com.ym.mec.biz.dal.dao.StudentPaymentOrderDao.orderAndDetail"
             parameterType="map">
         SELECT spo.*,u.username_,spod.id_ detail_id_,spod.type_ detail_type_,spod.price_
-        detail_price_,spod.kit_group_purchase_type_ detail_kit_group_purchase_type_,
+        detail_price_,spod.kit_group_purchase_type_ detail_kit_group_purchase_type_,spod.income_item_,spod.income_,
         sci.charge_type_,g.id_ goods_id, g.name_ goods_name,o.name_ organ_name,spro.route_amount_
         routeAmount,spro.route_balance_amount_ routeBalance,spro.sale_amount_,spro.service_amount_,spro.service_fee_,
         spro.mer_no_ routeMerNo,spro.fee_flag_ feeFlag

+ 1 - 1
mec-student/src/main/java/com/ym/mec/student/controller/MusicGroupController.java

@@ -154,7 +154,7 @@ public class MusicGroupController extends BaseController {
                 MusicGroupPaymentCalender paymentCalender = musicGroupPaymentCalenderService.getApplyCalenderByMusicId(musicGroupId);
                 HashMap<String, Object> calenderDetail = new HashMap<>(5);
                 musicGroupPaymentCalenderService.getCalenderDetail(calenderDetail,paymentCalender.getId());
-                boolean flag = false;
+                boolean flag = true;
                 //是否购买乐团课
                 if(Objects.nonNull(calenderDetail.get("course"))){
                     if(typeList.contains(OrderDetailTypeEnum.COURSE)