package com.cim.idm.service.Impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cim.idm.dao.DeliveryDao;
import com.cim.idm.data.ErpMessageLog;
import com.cim.idm.exception.GlobalException;
import com.cim.idm.framework.IDMFrameServiceProxy;
import com.cim.idm.framework.data.EventInfo;
import com.cim.idm.framework.util.time.TimeStampUtil;
import com.cim.idm.model.OutStockDto;
import com.cim.idm.model.dto.delivery.StoreDetailDto;
import com.cim.idm.model.po.delivery.MaterialDelivery;
import com.cim.idm.model.po.delivery.MaterialDeliveryReceive;
import com.cim.idm.mwmsextend.materialpacking.service.MaterialPackingServiceImpl;
import com.cim.idm.service.IMaterialShipService;
import com.cim.idm.service.impl.MESServiceImpl;
import com.cim.idm.util.MessageLogUtil;
import com.cim.idm.util.ToSAPMessageUtil;
import com.cim.idm.utils.AjaxResult;
import com.cim.idm.utils.CodeGenerator;
import com.cim.idm.utils.CommonUtils;
import com.cim.idm.utils.EventInfoUtil;
import com.cim.idm.wmsextend.generic.errorHandler.CustomException;
import com.cim.idm.wmspackage.materialpacking.MaterialPackingServiceProxy;
import com.cim.idm.wmspackage.materialpacking.management.data.MaterialPacking;
import com.cim.idm.wmspackage.materialpacking.management.data.MaterialPackingKey;
import com.cim.idm.wmspackage.materialpacking.management.info.CreateInfo;
import com.cim.idm.wmspackage.materialpacking.management.info.SetEventInfo;
import com.cim.idm.wmspackage.materialshiprequest.MaterialShipRequestServiceProxy;
import com.cim.idm.wmspackage.materialshiprequest.management.info.CreateMaterialShipRequestInfo;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;


@Service("MaterialShip")
public class MaterialShipServiceImpl implements IMaterialShipService {

	private CommonUtils untils=new CommonUtils();

	@Autowired
	private ToSAPMessageUtil toSAPMessageUtil;

	private EventInfo makeEventInfo;
	@Autowired
	private DeliveryDao deliveryDao;

	SDKMaterialPackingServiceImpl SDKMP = new SDKMaterialPackingServiceImpl();
	/**
	 * 出库方法实现
	 */
	@Override
	public Map<String, Object> outStock(OutStockDto outStockDto)  throws Throwable  {
		// 参数非空校验
		String site = outStockDto.getSite();
		String barCode = outStockDto.getBarCode();
		String billNo = outStockDto.getBillNo();
		String detailRowNo = outStockDto.getDetailRowNo();
		String userId = outStockDto.getUserId();
		String storageName = outStockDto.getStorageName();
		
		if(Objects.isNull(site)) {
			throw new GlobalException("site不能为空！");
		}
		if(Objects.isNull(barCode)) {
			throw new GlobalException("barCode不能为空！");
		}
		if(Objects.isNull(billNo)) {
			throw new GlobalException("billNo不能为空！");
		}
		if(Objects.isNull(detailRowNo)) {
			throw new GlobalException("detailRowNo不能为空！");
		}
		if(Objects.isNull(userId)) {
			throw new GlobalException("userId不能为空！");
		}
		Map<String, Object> map = new HashMap<String, Object>();
		// 将前端传入的参数和存储过程中的参数对应起来
		map.put("V_SITE",site);
		map.put("V_BILLNO",billNo);
		map.put("V_DETAILROWNO",detailRowNo);
		map.put("V_BARCODE",barCode);
		map.put("V_USERID",userId);
		map.put("V_KW","");
		map.put("V_RESULT","");
		String procedureName = "CALL SHIP_OUTSTOCK(:V_SITE, :V_BILLNO, :V_DETAILROWNO, :V_BARCODE, :V_KW, :V_USERID,  :V_RESULT)";
		try {
			// 调用存储过程返回参数
			Map<String, Object> queryResult = IDMFrameServiceProxy.getSqlTemplate().queryForMap(procedureName,map);
			
			if(Objects.nonNull(queryResult)) {
				return queryResult;
			}
			throw new GlobalException("未查询到对应参数");
			
		}catch(Throwable e) {
			throw e;
		}
	
	}
	
	/**
	 * 取消出库方法
	 */
	@Override
	public Map<String, Object> cancle(OutStockDto outStockDto) throws Throwable {
		// 参数非空校验
		String site = outStockDto.getSite();
		String barCode = outStockDto.getBarCode();
		String billNo = outStockDto.getBillNo();
		String detailRowNo = outStockDto.getDetailRowNo();
		String userId = outStockDto.getUserId();
		String storageName = outStockDto.getStorageName();

		if(Objects.isNull(site)) {
			throw new GlobalException("site不能为空！");
		}
		if(Objects.isNull(barCode)) {
			throw new GlobalException("barCode不能为空！");
		}
		if(Objects.isNull(billNo)) {
			throw new GlobalException("billNo不能为空！");
		}
		
		if(Objects.isNull(userId)) {
			throw new GlobalException("userId不能为空！");
		}
		Map<String, Object> map = new HashMap<String, Object>();
		// 将前端传入的参数和存储过程中的参数对应起来
		map.put("V_SITE",site);
		map.put("V_BILLNO",billNo);
		map.put("V_BARCODE",barCode);
		map.put("V_USERID",userId);
		//map.put("V_KW",storageName);
		map.put("V_RESULT","");
		String procedureName = "CALL SHIP_OUTSTOCK_CANCEL(:V_SITE, :V_BILLNO, :V_BARCODE, :V_USERID, :V_RESULT)";
		try {
			// 调用存储过程返回参数
			Map<String, Object> queryResult = IDMFrameServiceProxy.getSqlTemplate().executeProcedure(procedureName,map);
			if(Objects.nonNull(queryResult)) {
				return queryResult;
			}
			throw new GlobalException("未查询到对应参数");
			
		}catch(Throwable e) {
			throw e;
		}
	
	}

	/**
	 * 出库前校验
	 */
	@Override
	public String outStockCheck(OutStockDto outStockDto) throws GlobalException {
		
		/**
		 * 
			0.如果无记录，则提示，此物料不在出库列表中;
			0.1 如果DFQTY<0,则提示，此物料已出库完成，无发出库
			1。STOCKSTATE，如果不是Stocked，则提示不在仓库
			2.如果ISRELEASE=0，则提示未释放,单号：LASTEVENTBILLNO
			3.如果DJCK不为空，继续判断TMCK与DJCK不一致，则提示，此条码的仓库不属于调出仓
			4.如果ALLOWOVERPICK=Y,且MATERIALQUANTITY大于DFQTY，则提示此不允许超发;
		 */
		String shipRequestName = outStockDto.getBillNo(); // 单号
		String materialPackingName = outStockDto.getBarCode(); // 条码编号
		String detailRowNo = outStockDto.getDetailRowNo();
		if(Objects.isNull(shipRequestName)) {
			throw new GlobalException("shipRequestName不能为空！");
			}
		if(Objects.isNull(materialPackingName)) {
			throw new GlobalException("materialPackingName不能为空！");
		}
		// 获取物料前校验
		String sql = "SELECT m.SHIPREQUESTNAME,m1.SHIPREQUESTDETAILNAME,m2.STOCKSTATE,m1.ERPLOCATION DJCK,"
				+ " m2.ERPLOCATION TMCK, "
				+ "m2.ISRELEASE,m2.LASTEVENTBILLNO , "
				+ " m2.MATERIALQUANTITY, NVL(m3.ALLOWOVERPICK,'N') ALLOWOVERPICK,m1.REQUESTQUANTITY - NVL(m1.ASSIGNEDQUANTITY,0) DFQTY  " + 
				"FROM MATERIALSHIPREQUEST m   " + 
				"JOIN MATERIALSHIPREQUESTDETAIL m1 ON m.SITENAME=m1.SITENAME  AND m.SHIPREQUESTNAME =m1.SHIPREQUESTNAME " + 
				"JOIN MATERIALPACKING m2 ON m1.SITENAME=m2.SITENAME AND m1.MATERIALSPECNAME=m2.MATERIALSPECNAME " + 
				"JOIN MATERIALSPEC m3 ON m3.SITENAME =m1.SITENAME  AND m3.MATERIALSPECNAME =m1.MATERIALSPECNAME  " + 
				"WHERE m.SHIPREQUESTNAME =:SHIPREQUESTNAME AND  m2.MATERIALPACKINGNAME=:MATERIALPACKINGNAME";
		
		Map<String, Object> bindMap = new HashMap<String, Object>();
		bindMap.put("SHIPREQUESTNAME",shipRequestName); 
		bindMap.put("MATERIALPACKINGNAME",materialPackingName); 
		// 如果无记录，则提示，此物料不在出库列表中;
		List<Map<String,Object>> list = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, bindMap);
		
		if(Objects.isNull(list) || list.isEmpty()) {
			throw new GlobalException("此物料不在出库列表中！");
			}
		
		Map map = list.get(0);
		// 0.1 如果DFQTY<0,则提示，此物料已出库完成，无发出库
		float dfqty = Float.parseFloat(map.get("DFQTY").toString());
		if(dfqty <= 0) {
			throw new GlobalException("此物料已出库完成，无发出库！");
		}
		
		// 1.STOCKSTATE，如果不是Stocked，则提示不在仓库
		String stockState = map.get("STOCKSTATE").toString();
		if(!stockState.equals("Stocked")) {
			throw new GlobalException("该物料不在仓库！");
		}
		
		// 2.如果ISRELEASE=0，则提示未释放
		Integer isRelease = Integer.parseInt(map.get("ISRELEASE").toString());
		if(isRelease == 0) {		
			String lastEventBillNo = map.get("LASTEVENTBILLNO").toString();
			throw new GlobalException("该条码未释放！单号：" + lastEventBillNo);
		}
		String RowNo = map.get("SHIPREQUESTDETAILNAME").toString();
		if (detailRowNo == null || !detailRowNo.equals(RowNo)) {
			throw new GlobalException("所选行号与物料不一致！");
		}
		
		//3.如果DJCK不为空，继续判断TMCK与DJCK不一致，则提示，此条码的仓库不属于调出仓
		/*
		 * String dbck = map.get("DBCK").toString(); String tmck =
		 * map.get("TMCK").toString(); if(Objects.nonNull(dbck)) {
		 * if(!dbck.equals(tmck)) { throw new GlobalException("此条码的仓库不属于调出仓！"); } }
		 */
		
		// 4.如果ALLOWOVERPICK=Y,且MATERIALQUANTITY大于DFQTY，则提示此不允许超发;
		String allowOverPick = map.get("ALLOWOVERPICK").toString();
		Float materialQuantity = Float.parseFloat(map.get("MATERIALQUANTITY").toString());
		if(allowOverPick.equals("Y") && materialQuantity > dfqty ) {
			throw new GlobalException("此物料不允许超发！");
			
		}
		String shipRequestDetailName = map.get("SHIPREQUESTDETAILNAME").toString();
		
		return shipRequestDetailName;
		 
	}

	/**
	 * 确认备货
	 * @param eventInfo 事件信息
	 * @param siteName 现地
	 * @param shipRequestName 单号
	 * @param boxList 出库的物料信息
	 * @return
	 */
	public AjaxResult MaterialShipRequestAuxiliaryConfirmStocking(EventInfo eventInfo, String siteName, String shipRequestName,
														   String user, List<LinkedHashMap<String,String>> boxList) {
		if(null != boxList && boxList.size() > 0){
			for (int i = 0; i < boxList.size(); i++) {
				LinkedHashMap<String, String> boxlinkedHashMap = boxList.get(i);
				String boxShipRequestName = (String) boxlinkedHashMap.get("SHIPREQUESTNAME");
				String boxShipRequestDetailName = (String) boxlinkedHashMap.get("SHIPREQUESTDETAILNAME");
				String materialSpecName = (String) boxlinkedHashMap.get("MATERIALSPECNAME");
				String sdkId = (String) boxlinkedHashMap.get("SDK_ID");
				String phase = (String) boxlinkedHashMap.get("PHASE");
				//用户输入的出库数量
				String thisacceptNumber = (String) boxlinkedHashMap.get("THISACCEPTNUMBER");
				BigDecimal StockOutQty = new BigDecimal(thisacceptNumber);
				//String erpFactory = (String) boxlinkedHashMap.get("SDK_ID");
				String erpLocation = (String) boxlinkedHashMap.get("ERPLOCATION");
				String locationName = (String) boxlinkedHashMap.get("ERPLOCATIONNAMEDES");
				String erpFactory = (String) boxlinkedHashMap.get("ERPFACTORY");
				//汇总单据的剩余数量
				String djSql = "SELECT M.SHIPREQUESTNAME,M.SHIPREQUESTDETAILNAME , M.REQUESTQUANTITY - M.ASSIGNEDQUANTITY MINQTY \n" +
						"FROM MATERIALSHIPREQUESTDETAIL M WHERE M.SHIPREQUESTNAME = :SHIPREQUESTNAME AND M.REQUESTQUANTITY - M.ASSIGNEDQUANTITY > 0 \n" +
						"AND M.MATERIALSPECNAME = :MATERIALSPECNAME AND (M.SDK_ID = :SDK_ID OR :SDK_ID IS NULL) AND (M.PHASE = :PHASE OR :PHASE IS NULL)\n" +
						"UNION \n" +
						"SELECT T.RECEIVEREQUESTNAME SHIPREQUESTNAME,T.RECEIVEREQUESTDETAILNAME SHIPREQUESTDETAILNAME , T.REQUESTQUANTITY - T.RECEIVEDQUANTITY MINQTY \n" +
						"FROM MATERIALRECEIVEREQUESTDETAIL T WHERE T.RECEIVEREQUESTNAME = :SHIPREQUESTNAME AND T.RECEIVEREQUESTDETAILNAME = :SHIPREQUESTDETAILNAME AND T.REQUESTQUANTITY - T.RECEIVEDQUANTITY > 0 \n" +
						"AND T.MATERIALSPECNAME = :MATERIALSPECNAME AND (T.SDK_ID = :SDK_ID OR :SDK_ID IS NULL) AND (T.PHASE = :PHASE OR :PHASE IS NULL)";
				Map<String, Object> bindMap1 = new HashMap<String, Object>();
				bindMap1.put("SHIPREQUESTNAME",boxShipRequestName);
				bindMap1.put("SHIPREQUESTDETAILNAME",boxShipRequestDetailName);
				bindMap1.put("MATERIALSPECNAME",materialSpecName);
				bindMap1.put("SDK_ID",sdkId);
				bindMap1.put("PHASE",phase);
				bindMap1.put("ERPFACTORY",erpFactory);
				bindMap1.put("SITENAME",siteName);
				bindMap1.put("ERPLOCATION",erpLocation);
				bindMap1.put("LOCATIONNAME",locationName);
				List<Map<String,Object>> list = IDMFrameServiceProxy.getSqlTemplate().queryForList(djSql, bindMap1);
				for (Map<String, Object> map : list) {
					//根据条件去找库存，满足库存的全部备货
					BigDecimal minQty = new BigDecimal(map.get("MINQTY").toString());//单据需求数量
					// 检查最小数量是否为零，如果是，则跳出循环
					if (minQty.compareTo(BigDecimal.ZERO) == 0) {
						break;
					}

					// 检查请求数量是否为零，如果是，则跳出循环
					if (StockOutQty.compareTo(BigDecimal.ZERO) == 0) {
						break;
					}

					// 比较请求数量和最小数量，根据结果调整数量
					if (StockOutQty.compareTo(minQty) >= 0) {
						// 如果请求数量大于或等于最小数量，则减少请求数量
						StockOutQty = StockOutQty.subtract(minQty);
					} else {
						// 如果请求数量小于最小数量，则将最小数量设置为请求数量，并将请求数量置为零
						minQty = StockOutQty;
						StockOutQty = BigDecimal.ZERO;
					}
					String shipRequestDetailName = map.get("SHIPREQUESTDETAILNAME").toString();
					//汇总满足条件的box
					String boxListSql = " SELECT\r\n" +
							"						A.MATERIALPACKINGNAME,A.MATERIALQUANTITY \r\n" +
							"					FROM\r\n" +
							"						MATERIALPACKING A\r\n" +
							"					LEFT JOIN SDK_SPEC SS ON\r\n" +
							"						A.SDK_ID = SS.SDK_ID ,\r\n" +
							"						MATERIALSPEC B\r\n" +
							"					WHERE\r\n" +
							"						A.MATERIALSPECNAME = :MATERIALSPECNAME\r\n" +
							"						AND A.MATERIALSPECNAME = B.MATERIALSPECNAME\r\n" +
							"						AND A.SITENAME = B.SITENAME\r\n" +
							"						AND A.SITENAME =:SITENAME\r\n" +
							"						AND A.MATERIALPACKINGTYPE = 'Box'\r\n" +
							"						AND (:ERPLOCATION IS NULL OR A.ERPLOCATION = :ERPLOCATION)\r\n" +
							"						AND (:LOCATIONNAME IS NULL OR A.LOCATIONNAME = :LOCATIONNAME)\r\n" +
							"						AND (:SDK_ID IS NULL\r\n" +
							"							OR A.SDK_ID = :SDK_ID)\r\n" +
							"						AND (:PHASE IS NULL\r\n" +
							"							OR A.PHASE = :PHASE)\r\n" +
							"						AND ( A.ERPFACTORY = :ERPFACTORY)\r\n" +
							"						AND A.SHIPREQUESTNAME IS NULL\r\n" +
							"						AND A.SHIPREQUESTDETAILNAME IS NULL\r\n" +
							"						AND A.STOCKSTATE = 'Stocked'\r\n" +
							"						AND A.PACKINGSTATE = 'Released'\r\n" +
							"						AND A.HOLDSTATE = 'N'\r\n" +
							"						AND A.PACKINGGRADE IN ('OK', 'OKEY')\r\n" +
							"						AND A.MATERIALQUANTITY <> '0'\r\n" +
							"						AND (A.NPFLAG <> 'Y'\r\n" +
							"							OR A.NPFLAG IS NULL)\r\n" +
							"						AND (A.ETCSTATE IS NULL\r\n" +
							"							OR A.ETCSTATE = 'EtcIn')\r\n" +
							"						AND A.OQARESULTSTATE <> 'PREOQA'\r\n" +
							"						AND to_char(A.EXPIRINGDATE, 'yyyymmdd') >= to_char(SYSDATE, 'yyyymmdd')\r\n" +
							"		 ORDER BY to_char(A.RECEIVETIME, 'yyyymmdd') ";
					bindMap1.put("SHIPREQUESTDETAILNAME",shipRequestDetailName);
					List<Map<String,Object>> list2 = IDMFrameServiceProxy.getSqlTemplate().queryForList(boxListSql, bindMap1);
					if(null != list2 && list2.size() > 0){
						for (Map<String, Object> map2 : list2) {
							String string = map2.get("MATERIALQUANTITY").toString();
							String materialPackingName = map2.get("MATERIALPACKINGNAME").toString();
							BigDecimal pcQty = new BigDecimal(string);//批次数量
							//如果需求数量大于批次数量，则要求全部备货。小于则表示只能备货这一批次内数量，并且将批次结果传递到前端可以扫描备货
							int compareTo = minQty.compareTo(pcQty);
							MaterialPackingKey materialPackingKey = new MaterialPackingKey("SDK",materialPackingName);
							com.cim.idm.wmspackage.materialpacking.management.data.MaterialPacking selectByKey = MaterialPackingServiceProxy.getMaterialPackingService().selectByKey(materialPackingKey);
							if (minQty.compareTo(BigDecimal.ZERO) == 0) {
								break;
							}
							if (compareTo >= 0) {//要求该批次全备货
								try {
									AuxiliaryReserve(eventInfo,selectByKey, shipRequestName,shipRequestDetailName,materialSpecName,sdkId,phase, "Assign", siteName, user,"");
									minQty = minQty.subtract(pcQty);
								} catch (CustomException e) {
									e.printStackTrace();
									return AjaxResult.me().setSuccess(false).setMessage(e.toString()).setErrorCode(400);
								}
							} else  {
								try {
									AuxiliaryReserve(eventInfo,selectByKey, shipRequestName,shipRequestDetailName,materialSpecName,sdkId,phase, "Assign", siteName, user,minQty + "");
								} catch (CustomException e) {
									e.printStackTrace();
									return AjaxResult.me().setSuccess(false).setMessage(e.toString()).setErrorCode(400);
								}
								minQty = minQty.subtract(minQty);
								break;
							}
						}
					} else {
						return AjaxResult.me().setSuccess(false).setMessage("未匹配到发货单号：" + shipRequestName + "行项目：" + shipRequestDetailName + "物料编号：" + materialSpecName + "的库存").setErrorCode(400);
					}

					if (StockOutQty.compareTo(BigDecimal.ZERO) == 0) {
						break;
					}
				}
			}
		}


		/*CreateMaterialShipRequestInfo info = new CreateMaterialShipRequestInfo();

		info.setSiteName(siteName);
		info.setShipRequestName(shipRequestName);
		info.setShipRequestState(shipRequestState);
		info.setShipRequestType(shipRequestType);
		info.setShipRequestDetailType(shipRequestDetailType);
		info.setCustomerNO(customerNO);
		info.setDeliveryType(deliveryType);
		info.setWorkOrderId(workOrderId);
		info.setSystemType(systemType);

		// Timestamp planShipDateTime =
		// ConvertUtil.convertToTimeStamp(shipPlanDate);

		Timestamp planShipDateTime = new Timestamp(System.currentTimeMillis());
		if (!shipPlanDate.equals("")) {
			shipPlanDate = shipPlanDate + " 00:00:00";
			if (siteName.equalsIgnoreCase("B4"))
				shipPlanDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS").format(new Date());
			planShipDateTime = Timestamp.valueOf(shipPlanDate);
		}
		info.setShipPlanDate(planShipDateTime);

		Map<String, Object> bindMap = new HashMap<String, Object>();
		bindMap.put("exportNo", exportNo);
		bindMap.put("saleReason", saleReason);
		bindMap.put("saleReasonDescription", saleReasonDescription);
		bindMap.put("erpFactoryName", erpFactoryName);
		bindMap.put("erpReceiveFactory", erpReceiveFactory);
		bindMap.put("erpReceiveLocation", erpReceiveLocation);
		bindMap.put("customsDeclare", customsDeclare);
		bindMap.put("costCenter", costCenter);
		bindMap.put("receiver", receiver);
		bindMap.put("grund", grund);
		bindMap.put("zf_State", zf_State);
		info.setUserColumns(bindMap);

		eventInfo.setEventName("Create");

		MaterialShipRequestServiceProxy.getMaterialShipRequestService().create(
				eventInfo, info);*/
		return AjaxResult.me().setSuccess(true).setErrorCode(200);
	}
	/**
	 * 取消确认备货
	 * @param eventInfo 事件信息
	 * @param siteName 现地
	 * @param shipRequestName 单号
	 * @return
	 */
	public AjaxResult MaterialShipRequestAuxiliaryCancelConfirmStocking(EventInfo eventInfo, String siteName, String shipRequestName,
																  String user) {
		String ressSql = "SELECT\r\n" +
				"	A.MATERIALPACKINGNAME ,A.MATERIALSPECNAME,A.MATERIALQUANTITY, CASE WHEN MATERIALQUANTITY2 > 0 THEN A.MATERIALQUANTITY2  " +
				"				   ELSE A.MATERIALQUANTITY END    MATERIALQUANTITY2,A.AREANAME ,A.SHELFNAME ,\r\n" +
				"	A.CHARGE ,\r\n" +
				"	TO_CHAR(A.RECEIVETIME, 'YYYY-MM-DD') RECEIVETIME,A.SDK_ID,A.PHASE,\r\n" +
				"	be.DESCRIPTION ERPLOCATION,\r\n" +
				"	s.DESCRIPTION LOCATIONNAME,\r\n" +
				"	'Y' BHFLG, A.SHIPREQUESTNAME,MS.RECEIVEREQUESTDETAILNAME SHIPREQUESTDETAILNAME, \r\n" +
				"					'N' IS_CHECK\r\n" +
				"FROM\r\n" +
				"	 MATERIALPACKINGSUB MS\n" +
				"\tLEFT JOIN MATERIALPACKING A ON MS.MATERIALPACKINGNAME = A.MATERIALPACKINGNAME AND MS.RECEIVEREQUESTNAME  = A.SHIPREQUESTNAME \r\n" +
				"LEFT JOIN SDK_SPEC SS ON\r\n" +
				"	A.SDK_ID = SS.SDK_ID\r\n" +
				"LEFT JOIN \r\n" +
				"	MATERIALSPEC B ON\r\n" +
				"	A.MATERIALSPECNAME = B.MATERIALSPECNAME\r\n" +
				"LEFT JOIN BS_ERPLOCATION be ON\r\n" +
				"	A.ERPLOCATION = be.ERPLOCATIONNAME\r\n" +
				"LEFT JOIN STORAGESPEC s ON\r\n" +
				"	A.LOCATIONNAME = s.STORAGENAME AND A.ERPFACTORY = s.ERPFACTORY AND A.ERPLOCATION = s.ERPLOCATION \r\n" +
				"WHERE\r\n" +
				"	1 = 1\r\n" +
				"	AND A.MATERIALSPECNAME = B.MATERIALSPECNAME\r\n" +
				"	AND A.SITENAME = B.SITENAME\r\n" +
				"	AND A.SITENAME =:SITENAME\r\n" +
				"	AND A.SHIPREQUESTNAME = :SHIPREQUESTNAME\r\n" +
				"	AND A.STOCKSTATE = 'Stocked'\r\n" +
				"	AND A.PACKINGSTATE = 'Released'\r\n" +
				"	AND A.HOLDSTATE = 'N'\r\n" +
				"	AND A.PACKINGGRADE IN ('OK', 'OKEY')\r\n" +
				"	AND A.MATERIALQUANTITY <> '0'\r\n" +
				"	AND (A.NPFLAG <> 'Y'\r\n" +
				"		OR A.NPFLAG IS NULL)\r\n" +
				"	AND (A.ETCSTATE IS NULL\r\n" +
				"		OR A.ETCSTATE = 'EtcIn')\r\n" +
				"	AND A.OQARESULTSTATE <> 'PREOQA'\r\n" +
				"	AND to_char(A.EXPIRINGDATE, 'yyyymmdd') >= to_char(SYSDATE, 'yyyymmdd')";
		Map<String, Object> hashMap = new HashMap<String,Object> ();
		hashMap.put("SITENAME", "SDK");
		hashMap.put("SHIPREQUESTNAME", shipRequestName);
		List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(ressSql, hashMap);
		//通过单据找到所有的已备货信息
		for (Map<String, Object> map : queryForList) {
			String materialQuery2 = map.get("MATERIALQUANTITY2")== null ? "" : map.get("MATERIALQUANTITY2").toString();
			String materialSpecName = map.get("MATERIALSPECNAME")== null ? "" : map.get("MATERIALSPECNAME").toString();
			String sdk_id = map.get("SDK_ID") == null ? "" : map.get("SDK_ID").toString();
			String phase = map.get("PHASE")== null ? "" : map.get("PHASE").toString();
			String materialPackingName = map.get("MATERIALPACKINGNAME")== null ? "" : map.get("MATERIALPACKINGNAME").toString();
			String shipRequestDetailName = map.get("SHIPREQUESTDETAILNAME") == null ? "" : map.get("SHIPREQUESTDETAILNAME").toString();
			MaterialPackingKey materialPackingKey = new MaterialPackingKey("SDK",materialPackingName);
			com.cim.idm.wmspackage.materialpacking.management.data.MaterialPacking selectByKey = MaterialPackingServiceProxy.getMaterialPackingService().selectByKey(materialPackingKey);
			try {
				AuxiliaryReserve(eventInfo,selectByKey, shipRequestName,shipRequestDetailName,materialSpecName,sdk_id,phase, "Dessign", siteName, user,materialQuery2);
			} catch (CustomException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		return AjaxResult.me().setSuccess(true).setErrorCode(200);
	}
	/**
	 * 辅材出库-（备货/取消备货）
	 * @param materialPacking
	 * @param shipReuqestName
	 * @param shipRequestDetailName
	 * @param materialSpecName
	 * @param sdk_id
	 * @param phase
	 * @param type
	 * @param siteName
	 * @param user
	 * @param materialQuantity2
	 * @throws CustomException
	 */
	@Transactional
	public void AuxiliaryReserve (EventInfo eventInfo, MaterialPacking materialPacking, String shipReuqestName, String shipRequestDetailName,
								  String materialSpecName, String sdk_id, String phase,
								  String type, String siteName, String user, String materialQuantity2) throws CustomException {
		String materialPackingName = materialPacking.getMaterialPackingName();//条码
		Double materialQuantity = materialPacking.getMaterialQuantity();
		if(!"".equals(materialQuantity2)) {
			materialQuantity = Double.parseDouble(materialQuantity2);
		}
		String charge = materialPacking.getCharge();//批次

		//1.绑定
		//校验Box有没有被其他订单绑过
		if ("Assign".equals(type)) {
			String sql = "SELECT SHIPREQUESTNAME FROM MATERIALPACKING T WHERE T.MATERIALPACKINGNAME = :MATERIALPACKINGNAME";
			Map<String, Object> hashMap = new HashMap<String,Object> ();
			hashMap.put("MATERIALPACKINGNAME", materialPackingName);
			List<Map<String,Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, hashMap);
			if (queryForList == null || queryForList.size() < 1) {
				throw new CustomException("条码在系统中不存在");
			} else {
				String invoice = queryForList.get(0).get("SHIPREQUESTNAME") == null ? "" : queryForList.get(0).get("SHIPREQUESTNAME").toString().toString();
				if (!"".equals(invoice) && !invoice.equals(shipReuqestName)) {
					throw new CustomException("条码已被" + invoice + "备货");
				}
				//更新Box绑定关系、Box发货数量、拆分到条码明细表
				SetEventInfo setEventInfo = new SetEventInfo();
				Map<String, Object> hashMap2 = new HashMap<String,Object> ();
				//更新实际实际出库数量到库存表
				MaterialPackingKey materialPackingKey = new MaterialPackingKey(siteName, materialPackingName);
				hashMap2.put("shipRequestName", shipReuqestName);
				hashMap2.put("shipRequestDetailName", shipRequestDetailName);
				hashMap2.put("materialQuantity2", materialQuantity);
				setEventInfo.setUserColumns(hashMap2);
				MaterialPackingServiceProxy.getMaterialPackingService().setEvent(materialPackingKey, eventInfo, setEventInfo);
				//更新备货数量
				//					BigDecimal QTY = new BigDecimal(materialQuantity);
				String updateSql= " UPDATE MATERIALSHIPREQUESTDETAIL m SET m.ASSIGNEDQUANTITY = m.ASSIGNEDQUANTITY + :QTY WHERE m.SITENAME = :SITENAME"
						+ " AND m.SHIPREQUESTNAME = :SHIPREQUESTNAME AND m.MATERIALSPECNAME = :MATERIALSPECNAME "
						+ " AND (:SDK_ID IS NULL OR SDK_ID = :SDK_ID) AND (:PHASE IS NULL OR PHASE = :PHASE) AND m.SHIPREQUESTDETAILNAME = :RECEIVEREQUESTDETAILNAME  ";
				String updateTh = "UPDATE MATERIALRECEIVEREQUESTDETAIL m SET m.RECEIVEDQUANTITY = m.RECEIVEDQUANTITY + :QTY WHERE m.SITENAME = :SITENAME \r\n" +
						"						  AND m.RECEIVEREQUESTNAME = :SHIPREQUESTNAME AND m.MATERIALSPECNAME = :MATERIALSPECNAME \r\n" +
						"						  AND (:SDK_ID IS NULL OR SDK_ID = :SDK_ID) AND (:PHASE IS NULL OR PHASE = :PHASE) AND m.RECEIVEREQUESTDETAILNAME = :RECEIVEREQUESTDETAILNAME ";
				//增加过账条码表记录
				String insertSql = "INSERT INTO MATERIALPACKINGSUB t (t.MATERIALPACKINGNAME,t.RECEIVEREQUESTNAME,t.RECEIVEREQUESTDETAILNAME,t.QTY)\n" +
						"VALUES (:MATERIALPACKINGNAME,:RECEIVEREQUESTNAME,:RECEIVEREQUESTDETAILNAME,:QTY)";
				Map<String, Object> bindMap = new HashMap<String, Object>();
				bindMap.put("QTY", materialQuantity);
				bindMap.put("SITENAME", siteName);
				bindMap.put("SHIPREQUESTNAME", shipReuqestName);
				bindMap.put("MATERIALPACKINGNAME", materialPackingName);
				bindMap.put("MATERIALSPECNAME", materialSpecName);
				bindMap.put("SDK_ID", sdk_id);
				bindMap.put("PHASE", phase);
				bindMap.put("MATERIALPACKINGNAME", materialPackingName);
				bindMap.put("RECEIVEREQUESTNAME", shipReuqestName);
				bindMap.put("RECEIVEREQUESTDETAILNAME", shipRequestDetailName);
				IDMFrameServiceProxy.getSqlTemplate().update(updateSql, bindMap);
				IDMFrameServiceProxy.getSqlTemplate().update(updateTh, bindMap);
				IDMFrameServiceProxy.getSqlTemplate().update(insertSql, bindMap);
			}

		} else 	if ("Dessign".equals(type)) {
			String sql = "SELECT SHIPREQUESTNAME FROM MATERIALPACKING T WHERE T.MATERIALPACKINGNAME = :MATERIALPACKINGNAME";
			Map<String, Object> hashMap = new HashMap<String,Object> ();
			hashMap.put("MATERIALPACKINGNAME", materialPackingName);
			List<Map<String,Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, hashMap);
			if (queryForList == null || queryForList.size() < 1) {
				throw new CustomException("条码在系统中不存在");
			} else {
				String invoice = queryForList.get(0).get("SHIPREQUESTNAME") == null ? "" : queryForList.get(0).get("SHIPREQUESTNAME").toString().toString();
				if (!"".equals(shipReuqestName) && !invoice.equals(shipReuqestName)) {
					throw new CustomException("条码已被" + invoice + "备货");
				}
				//更新Box绑定关系、Box发货数量、拆分到条码明细表
				SetEventInfo setEventInfo = new SetEventInfo();
				Map<String, Object> hashMap2 = new HashMap<String,Object> ();
				//更新实际实际出库数量到库存表
				MaterialPackingKey materialPackingKey = new MaterialPackingKey(siteName, materialPackingName);
				hashMap2.put("shipRequestName", "");
				hashMap2.put("shipRequestDetailName", "");
				hashMap2.put("materialQuantity2", "0");
				setEventInfo.setUserColumns(hashMap2);
				MaterialPackingServiceProxy.getMaterialPackingService().setEvent(materialPackingKey, eventInfo, setEventInfo);
				//更新备货数量
				//					BigDecimal QTY = new BigDecimal(materialQuantity);
				//更新备货数量
				String updateSql= " UPDATE MATERIALSHIPREQUESTDETAIL m SET m.ASSIGNEDQUANTITY = m.ASSIGNEDQUANTITY - :QTY WHERE m.SITENAME = :SITENAME"
						+ " AND m.SHIPREQUESTNAME = :SHIPREQUESTNAME AND m.MATERIALSPECNAME = :MATERIALSPECNAME "
						+ "AND (:SDK_ID IS NULL OR SDK_ID = :SDK_ID) AND (:PHASE IS NULL OR PHASE = :PHASE) AND m.SHIPREQUESTDETAILNAME = :RECEIVEREQUESTDETAILNAME  ";
				String updateTh = "UPDATE MATERIALRECEIVEREQUESTDETAIL m SET m.RECEIVEDQUANTITY = m.RECEIVEDQUANTITY - :QTY WHERE m.SITENAME = :SITENAME \r\n" +
						"						  AND m.RECEIVEREQUESTNAME = :SHIPREQUESTNAME AND m.MATERIALSPECNAME = :MATERIALSPECNAME \r\n" +
						"						  AND (:SDK_ID IS NULL OR SDK_ID = :SDK_ID) AND (:PHASE IS NULL OR PHASE = :PHASE) AND m.RECEIVEREQUESTDETAILNAME = :RECEIVEREQUESTDETAILNAME ";
				String deleteSql = "DELETE FROM MATERIALPACKINGSUB t WHERE t.MATERIALPACKINGNAME = :MATERIALPACKINGNAME AND RECEIVEREQUESTNAME = :RECEIVEREQUESTNAME AND " +
						"RECEIVEREQUESTDETAILNAME = :RECEIVEREQUESTDETAILNAME";
				Map<String, Object> bindMap = new HashMap<String, Object>();
				bindMap.put("QTY", materialQuantity2);
				bindMap.put("SITENAME", siteName);
				bindMap.put("SHIPREQUESTNAME", shipReuqestName);
				bindMap.put("MATERIALPACKINGNAME", materialPackingName);
				bindMap.put("MATERIALSPECNAME", materialSpecName);
				bindMap.put("SDK_ID", sdk_id);
				bindMap.put("PHASE", phase);
				bindMap.put("RECEIVEREQUESTNAME", shipReuqestName);
				bindMap.put("RECEIVEREQUESTDETAILNAME", shipRequestDetailName);
				IDMFrameServiceProxy.getSqlTemplate().update(updateSql, bindMap);
				IDMFrameServiceProxy.getSqlTemplate().update(updateTh, bindMap);
				IDMFrameServiceProxy.getSqlTemplate().update(deleteSql, bindMap);
			}
		}

	}

	/**
	 * 辅材出库过账
	 * @param eventInfo 事件信息
	 * @param siteName 现地
	 * @param shipRequestName 单号
	 * @param boxList 出库的物料信息
	 * @return
	 */
	@Transactional
	public AjaxResult MaterialShipRequestAuxiliaryStockOut(EventInfo eventInfo, String siteName, String shipRequestName,
																  String user, List<LinkedHashMap<String,String>> boxList, String commitDate) throws Exception {
		//判断单据类型调用不同的NC接口
		String sql = "SELECT m.SHIPREQUESTTYPE,m.SHIPREQUESTDETAILTYPE FROM MATERIALSHIPREQUEST m WHERE m.SHIPREQUESTNAME = :SHIPREQUESTNAME";
		Map<String, Object> hashMap = new HashMap<String,Object> ();
		hashMap.put("SHIPREQUESTNAME", shipRequestName);
		List<String> materialPackingKeyList = new ArrayList<> ();
		List<MaterialPackingKey> arrayList = new ArrayList<MaterialPackingKey> ();
		List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, hashMap);
		String shipRequestType = queryForList.get(0).get("SHIPREQUESTTYPE").toString();
		String detailype = queryForList.get(0).get("SHIPREQUESTDETAILTYPE").toString();
		if ("4C".equals(shipRequestType)) {
			String sql222 = "SELECT SUM(m.REQUESTQUANTITY - m.ASSIGNEDQUANTITY)  QTY,MATERIALSPECNAME FROM MATERIALSHIPREQUESTDETAIL m WHERE m.SHIPREQUESTNAME  = :SHIPREQUESTNAME GROUP BY MATERIALSPECNAME";
			List<Map<String, Object>> queryForList2 = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql222, hashMap);
			for (int i = 0; i < queryForList2.size(); i++) {
				String string = queryForList2.get(i).get("QTY").toString();
				String MATERIALSPECNAME = queryForList2.get(i).get("MATERIALSPECNAME").toString();
				BigDecimal bigDecimal = new BigDecimal(string);
				if (bigDecimal.compareTo(BigDecimal.ZERO) < 0 ) {
					return AjaxResult.me().setSuccess(false).setMessage("销售不允许超发物料编号："  + MATERIALSPECNAME).setErrorCode(400);
				}
			}
		}

		//备份过账条码表的信息，并删除
		String bfSql = "INSERT\r\n" +
				"	INTO\r\n" +
				"	MATERIALPACKINGSUBHISTORY T (T.MATERIALPACKINGNAME,\r\n" +
				"	T.RECEIVEREQUESTNAME,\r\n" +
				"	T.RECEIVEREQUESTDETAILNAME,\r\n" +
				"	T.QTY)\r\n" +
				"SELECT\r\n" +
				"	M.MATERIALPACKINGNAME,\r\n" +
				"	M.RECEIVEREQUESTNAME,\r\n" +
				"	M.RECEIVEREQUESTDETAILNAME,\r\n" +
				"	M.QTY\r\n" +
				"FROM\r\n" +
				"	MATERIALPACKINGSUB M\r\n" +
				"WHERE\r\n" +
				"	M.RECEIVEREQUESTNAME = :SHIPREQUESTNAME";
		IDMFrameServiceProxy.getSqlTemplate().update(bfSql, hashMap);
		String scSql = "DELETE FROM MATERIALPACKINGSUB WHERE RECEIVEREQUESTNAME  = :SHIPREQUESTNAME";
		IDMFrameServiceProxy.getSqlTemplate().update(scSql, hashMap);

		//循环过账批次
		for (int i = 0; i < boxList.size(); ++ i) {
			LinkedHashMap<String, String> boxlinkedHashMap = boxList.get(i);
			String materialPackingName = (String) boxlinkedHashMap.get("MATERIALPACKINGNAME");
			String sdk_ID = (String) boxlinkedHashMap.get("SDK_ID");
			String phase = (String) boxlinkedHashMap.get("PHASE");
			String materialSpecName = (String) boxlinkedHashMap.get("MATERIALSPECNAME");
			String materialQuantity2 = (String) boxlinkedHashMap.get("MATERIALQUANTITY2");
			//			float materialQuantity = list.get(i).getMaterialQuantity();
			//重新获取下数量，通过sql查询取数
			String SLsQL = "SELECT m.MATERIALPACKINGNAME,m.MATERIALQUANTITY,"
					+ "DECODE(NVL(m.MATERIALQUANTITY2,0), 0 ,m.MATERIALQUANTITY,m.MATERIALQUANTITY2) MATERIALQUANTITY2  FROM MATERIALPACKING m"
					+ " WHERE m.SHIPREQUESTNAME = :SHIPRQEUESTNAME AND MATERIALPACKINGNAME = :MATERIALPACKINGNAME ";
			Map<String, Object> hashMap2 = new HashMap<String,Object> ();
			hashMap2.put("SHIPRQEUESTNAME", shipRequestName);
			hashMap2.put("MATERIALPACKINGNAME", materialPackingName);

			List<Map<String, Object>> queryForList3 = IDMFrameServiceProxy.getSqlTemplate().queryForList(SLsQL, hashMap2);
			if (queryForList3 != null && queryForList3.size() > 0) {
				materialQuantity2 = queryForList3.get(0).get("MATERIALQUANTITY2").toString();
			} else {
				return AjaxResult.me().setSuccess(false).setMessage("单号：" + shipRequestName + "与库存标签ID："  + materialPackingName  + "的绑定关系不存在").setErrorCode(400);
			}
			//循环单据查询过帐表
			String pcSql = "SELECT SHIPREQUESTNAME, SHIPREQUESTDETAILNAME,\r\n" +
					"	m.MATERIALSPECNAME ,\r\n" +
					"	m.PHASE ,\r\n" +
					"	m.SDK_ID ,\r\n" +
					"	m.REQUESTQUANTITY ,\r\n" +
					"	m.ASSIGNEDQUANTITY ,\r\n" +
					"	(m.REQUESTQUANTITY - nvl(m.SALEOUTQUANTITY, 0) ) SALEOUTQUANTITY\r\n" +
					"FROM\r\n" +
					"	MATERIALSHIPREQUESTDETAIL m\r\n" +
					"WHERE\r\n" +
					"	m.MATERIALSPECNAME = :MATERIALSPECNAME\r\n" +
//					"	AND (:SDK_ID IS NULL\r\n" +
//					"		OR SDK_ID = :SDK_ID)\r\n" +
//					"	AND (:PHASE IS NULL\r\n" +
//					"		OR PHASE = :PHASE)\r\n" +
					"	AND SHIPREQUESTNAME = :SHIPREQUESTNAME  ORDER BY TO_NUMBER(SHIPREQUESTDETAILNAME) ASC ";
			//AND (m.REQUESTQUANTITY - nvl(m.SALEOUTQUANTITY, 0)) > 0
			hashMap.put("MATERIALSPECNAME", materialSpecName);
			hashMap.put("SDK_ID", sdk_ID);
			hashMap.put("PHASE", phase);
			List<Map<String, Object>> queryForList2 = IDMFrameServiceProxy.getSqlTemplate().queryForList(pcSql, hashMap);
			BigDecimal pcQty = new BigDecimal(materialQuantity2);//批次数量
			BigDecimal temp;
			for (int j = 0; j < queryForList2.size(); j++) {
				String sq = queryForList2.get(j).get("SALEOUTQUANTITY").toString();//剩余发货数量
				String shipRequestDetailName = queryForList2.get(j).get("SHIPREQUESTDETAILNAME").toString();//行项
				BigDecimal saleQty = new BigDecimal(sq);//需要发货数量
				//修复Bug:发货刚好满足数量时，如有超发则不会写入SUB表.zd.2024.9.26
				//bugfix:销售出库  lxh 20240927
				if (pcQty.compareTo(BigDecimal.ZERO) == 0
						|| (saleQty.compareTo(BigDecimal.ZERO) == 0  && (j != queryForList2.size() - 1) )
				) {
					continue;
				}
				int compareTo = saleQty.compareTo(pcQty);//大于等于0则批次全发,小于0则需要拆分
				int compareToZero=saleQty.compareTo(BigDecimal.ZERO);
				if (compareTo >= 0) {
					untils.fahuoSplit(materialPackingName, shipRequestName, shipRequestDetailName, pcQty);
					break;
				} else {//需要拆行
					if( (j != queryForList2.size() - 1) &&  compareToZero>0) {//判断是否是最后一行，不是最后一行就不允许超发，发货数量等于请求数量即拆
						untils.fahuoSplit(materialPackingName, shipRequestName, shipRequestDetailName, saleQty);
						pcQty = pcQty.subtract(saleQty);
						continue;
					} else {
						untils.fahuoSplit(materialPackingName, shipRequestName, shipRequestDetailName, pcQty);
						break;
					}
				}
			}
			materialPackingKeyList.add(materialPackingName);
//			MaterialPackingKey materialPackingKey = new MaterialPackingKey("SDK",materialPackingName);
//			arrayList.add(materialPackingKey);
		}

		//判断会有多少个仓库发货，不同仓库需要分开走账
		StringBuffer cklx = new StringBuffer();
		cklx.append("SELECT m.MATERIALPACKINGNAME,m.SITENAME,m2.MATERIALTYPE FROM MATERIALPACKING m LEFT JOIN MATERIALSPEC m2 ON m2.MATERIALSPECNAME = m.MATERIALSPECNAME WHERE m.MATERIALPACKINGNAME IN ");
		String str = "";
		str += "(";
		for (String materialPacking : materialPackingKeyList) {
			str += "'" + materialPacking + "',";
		}
		str += "'')";
		List<Map<String, Object>> packingQueryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(cklx.toString() + str, hashMap);
		String billCode = "";
		switch (shipRequestType) {
			case "NLCC" : //STO调拨出库
				// 辅材出库
//				拆条码，查询MATERIALQUANTITY 与 MATERIALQUANTITY2是否相等，如果相等则未修改了数量，不相等则修改了数量
//				 如果已修改数量，则进行拆条码
				for (int z = 0; z < packingQueryForList.size(); z++) {
					String MATERIALPACKINGNAME = packingQueryForList.get(z).get("MATERIALPACKINGNAME").toString();
					Object[] bindSet = {MATERIALPACKINGNAME};
					String qtysql = "WHERE MATERIALPACKINGNAME = ?";
					List<MaterialPacking> qtyQueryForList = MaterialPackingServiceProxy.getMaterialPackingService().select(qtysql, bindSet);

					String qty = String.valueOf(qtyQueryForList.get(0).getMaterialQuantity());

					String qty2 = new Double(qtyQueryForList.get(0).getMaterialQuantity2()) == null ? "0" : String.valueOf(qtyQueryForList.get(0).getMaterialQuantity2());
					String materialPackingName = qtyQueryForList.get(0).getMaterialPackingName();
//					String charge = qtyQueryForList.get(z).getCharge(); // 辅材出库无批次
					List<String> boxId = MaterialPackingServiceImpl.generateBoxID("LabelId", siteName,
							"1", qtyQueryForList.get(0).getMakeDate().toString(),packingQueryForList.get(z).get("MATERIALTYPE").toString(),qtyQueryForList.get(0).getErpFactory());
					BigDecimal bigQty = new BigDecimal(qty);
					// 已拆数量
					BigDecimal bigQty2 = new BigDecimal(qty2);

					// 如果已拆数量不等于原数量，并且已拆数量为0(未拆分数量)
					if(bigQty.compareTo(bigQty2) != 0 && !"0".equals(qty2)) {
						// 剩余数量
						BigDecimal restQty = bigQty.subtract(bigQty2);

						// 生成新的拆分条码
						String stringBigQty2 = bigQty2.toString();
						String newPalletNo = CodeGenerator.packingGenerateCode(materialPackingName,stringBigQty2,boxId.get(0));

						// 写入拆分的新条码，更新原数据库
						List<MaterialPacking> boxList2 = new ArrayList<MaterialPacking>();
//							MaterialPackingKey materialpackingKey = new MaterialPackingKey();
						MaterialPacking materialpackingNew = new MaterialPacking();
//							materialpackingKey.setSiteName("SDK");
//							materialpackingKey.setMaterialPackingName(newPalletNo);
//							materialpackingNew.setKey(materialpackingKey);

						// 复制一个当前的原标签数据
						materialpackingNew.setKey(qtyQueryForList.get(0).getKey());
//							MaterialPacking materialpackingNew = qtyQueryForList.get(z);
						// 设置新为标签和数量
						materialpackingNew.setMaterialPackingName(newPalletNo);
						// bigQty2 转double类型
						materialpackingNew.setMaterialQuantity(bigQty2.doubleValue());
						boxList2.add(qtyQueryForList.get(0));
						boxList2.add(materialpackingNew);
						boolean moveTransformOut = packingChargeSplit(boxList2, user);
						if (moveTransformOut != true) {
							throw new RuntimeException("修改数量拆分失败");
						}
//						记录到拆分表
						String shipRequestDetailName = qtyQueryForList.get(0).getShipRequestDetailName() == null ? "" : qtyQueryForList.get(0).getShipRequestDetailName().toString();
						untils.fahuoSplit(newPalletNo, shipRequestName, shipRequestDetailName, bigQty2);

						// 原条码扣减拆出的数量，用剩余数量更新原条码，条码不变，数量更新,并且解绑单据
						SetEventInfo setEventInfo = new SetEventInfo();
						Map<String, Object> pakHashMap = new HashMap<>();
						pakHashMap.put("materialQuantity", restQty.doubleValue());
						pakHashMap.put("materialQuantity2", 0);
						pakHashMap.put("shipRequestName", "");
						pakHashMap.put("shipRequestDetailName", "");

						EventInfo eventInfo2 = new EventInfoUtil().makeEventInfo("调拨出库", user, "辅材出库拆分");
						setEventInfo.setUserColumns(pakHashMap);

						MaterialPackingServiceProxy.getMaterialPackingService().setEvent(new MaterialPackingKey( "SDK",MATERIALPACKINGNAME), eventInfo2, setEventInfo);

						// 删除被拆分的原条码数据，用拆分出的新条码覆盖，进行后面的过账，现场仓过账只过账已拆分出的数量，剩余数量的原条码不过账
						boolean deletePacking = materialPackingKeyList.remove(MATERIALPACKINGNAME);
						if (deletePacking) {
							materialPackingKeyList.add(newPalletNo);
						}
					}
				}
				billCode=TransferStockOut_NLCC(shipRequestName, "SDK", user,materialPackingKeyList,  commitDate);
//				makeEventInfo = eventInfoUtil.makeEventInfo("CompleteShipRequest", eventUser, "CompleteShipRequest:"+shipRequestType);
				untils.SaveUnDoInfo_ForSap(materialPackingKeyList, billCode, eventInfo);
//				untils.SaveSplitUnDoInfo_ForSap(materialPackingKeyList, billCode, eventInfo);
				break;

			case "01"://生产领料
			case "02"://生产补料
				// 判断是否是现场仓
				String IsSql = "SELECT m.ERPRECEIVELOCATION,m.ERPLOCATION,m.ERPRECEIVEFACTORY FROM MATERIALSHIPREQUESTDETAIL m WHERE  SHIPREQUESTNAME = :SHIPREQUESTNAME";
				Map<String,Object> bpc=new HashMap<>();
				bpc.put("SHIPREQUESTNAME", shipRequestName);
				List<Map<String,Object>> receiveList = IDMFrameServiceProxy.getSqlTemplate().queryForList(IsSql, bpc);
				String ERPRECEIVELOCATION = receiveList.get(0).get("ERPRECEIVELOCATION") == null ? "" : receiveList.get(0).get("ERPRECEIVELOCATION").toString();
				String ERPLOCATION = receiveList.get(0).get("ERPLOCATION") == null ? "" : receiveList.get(0).get("ERPLOCATION").toString();
				String ERPRECEIVEFACTORY = receiveList.get(0).get("ERPRECEIVEFACTORY") == null ? "" : receiveList.get(0).get("ERPRECEIVEFACTORY").toString();

				//判断是否为MES需要接收的物料
				String sqlc=" SELECT e.ENUMVALUE FROM MES_ENUMDEFVALUE e \r\n" +
						" WHERE e.ENUMNAME ='ConfirmReceiveArea'\r\n" +
						" AND e.ENUMVALUE in(\r\n" +
						" SELECT p.AREANAME FROM MES_PRODUCTREQUEST p \r\n" +
						" WHERE p.PRODUCTREQUESTNAME =(SELECT m.RECEIVEPRODUCTIONORDERNUMBER FROM MATERIALSHIPREQUESTDETAIL m \r\n" +
						" WHERE m.SHIPREQUESTNAME=:SHIPREQUESTNAME AND RECEIVEPRODUCTIONORDERNUMBER IS NOT NULL AND ROWNUM=1))";

				List<Map<String,Object>> src=IDMFrameServiceProxy.getSqlTemplate().queryForList(sqlc, bpc);


				//MES需要接收，则只抛送数据。 或如果是现场仓,先移到现场仓
				if(src.size()>0 || !ERPRECEIVELOCATION.isEmpty()) {
					//new MESServiceImpl().NeedReceiveMaterialInfoSend_NEW(shipRequestName, "SDK", materialPackingKeyList);
					billCode="Y";
					String sqlZK=" SELECT\r\n" +
							"	t.MATERIALSPECNAME,m.MATERIALPACKINGNAME,\r\n" +
							"	t.ERPFACTORY,\r\n" +
							"	t.ERPLOCATION,\r\n" +
							"	m2.SHIPREQUESTDETAILTYPE,\r\n" +
							"	t.UNIT,\r\n" +
							"	m1.COSTCENTER,\r\n" +
							"	m1.SHIPREQUESTNAME,\r\n" +
							"	m1.SHIPREQUESTDETAILNAME,\r\n" +
							"	m1.ERPRECEIVELOCATION,\r\n" +
							"	m1.ERPRECEIVEFACTORY,\r\n" +
							"	m1.SENDSALESORDER ,m1.SENDSALESORDERDETAILNO,\r\n" +
							"	CASE WHEN m1.SENDSALESORDER IS NOT NULL THEN 'E' ELSE '' END SOBKZ,\r\n" +
							"	(\r\n" +
							"	SELECT\r\n" +
							"		RECEIVEPRODUCTIONORDERNUMBER\r\n" +
							"	FROM\r\n" +
							"		MATERIALSHIPREQUESTDETAIL m5\r\n" +
							"	WHERE\r\n" +
							"		m5.SHIPREQUESTNAME =:SHIPREQUESTNAME\r\n" +
							"		AND m5.MATERIALSPECNAME = t.MATERIALSPECNAME\r\n" +
							"	ORDER BY\r\n" +
							"		m5.USEDATE,\r\n" +
							"		m5.SHIPREQUESTDETAILNAME FETCH FIRST ROW ONLY)RECEIVEPRODUCTIONORDERNUMBER,\r\n" +
							"	SUM(m.QTY) AS MATERIALQUANTITY\r\n" +
							" FROM \r\n" +
							"		 MATERIALPACKINGSUB m\r\n" +
							" LEFT JOIN MATERIALPACKING T ON \r\n" +
							"		 m.MATERIALPACKINGNAME = T.MATERIALPACKINGNAME\r\n" +
							"	AND m.RECEIVEREQUESTNAME = T.SHIPREQUESTNAME\r\n" +
							" LEFT JOIN MATERIALSHIPREQUESTDETAIL M1  \r\n" +
							"		  ON \r\n" +
							"		 m.RECEIVEREQUESTNAME = M1.SHIPREQUESTNAME\r\n" +
							"	AND m.RECEIVEREQUESTDETAILNAME = M1.SHIPREQUESTDETAILNAME\r\n" +
							" LEFT JOIN MATERIALSHIPREQUEST M2  \r\n" +
							"		  ON \r\n" +
							"		 M1.SHIPREQUESTNAME = M2.SHIPREQUESTNAME\r\n" +
							" WHERE \r\n" +
							"		 T.SHIPREQUESTNAME = :SHIPREQUESTNAME\r\n" +
							"	AND T.SITENAME = :SITENAME\r\n" +
							"	AND T.STOCKSTATE = 'Stocked'\r\n" +
							"	AND T.MATERIALPACKINGNAME IN (:BOXLIST)\r\n" +
							" GROUP BY\r\n" +
							"	t.MATERIALSPECNAME,\r\n" +
							"	t.ERPFACTORY,\r\n" +
							"	t.ERPLOCATION,\r\n" +
							"	m2.SHIPREQUESTDETAILTYPE,\r\n" +
							"	t.UNIT,\r\n" +
							"	m1.COSTCENTER,\r\n" +
							"	m1.SHIPREQUESTNAME,m1.SENDSALESORDER ,m1.SENDSALESORDERDETAILNO,\r\n" +
							"	m1.SHIPREQUESTDETAILNAME,\r\n" +
							"	m1.ERPRECEIVELOCATION,\r\n" +
							"	m1.ERPRECEIVEFACTORY,m.MATERIALPACKINGNAME";

					// 转库到线边仓
//					String sqlZK = "SELECT b.MATERIALPACKINGNAME FROM MATERIALPACKINGSUB b WHERE b.MATERIALPACKINGNAME IN (:BOXLIST)";
					Map<String, Object> hashMapZK = new HashMap<String, Object>();
					hashMapZK.put("BOXLIST", materialPackingKeyList);
					hashMapZK.put("SHIPREQUESTNAME", shipRequestName);
					hashMapZK.put("SITENAME", siteName);
					List<Map<String, Object>> ZKqueryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sqlZK.toString(), hashMapZK);

					for (int z = 0; z < ZKqueryForList.size(); z++) {
						String materialPackingName = ZKqueryForList.get(z).get("MATERIALPACKINGNAME").toString();
						materialPackingKeyList.add(materialPackingName);
						MaterialPackingKey materialPackingKey = new MaterialPackingKey("SDK",materialPackingName);
						arrayList.add(materialPackingKey);
					}
//					billCode = UnSourcedChangeLocation(arrayList,ERPRECEIVEFACTORY,
//							ERPRECEIVELOCATION, "", eventUser );

					List<MaterialPackingKey> mpKeyList = new ArrayList<MaterialPackingKey> ();
					SetEventInfo setEventInfo = new SetEventInfo();
					for (MaterialPackingKey materialPacking : arrayList) {
						MaterialPackingKey key = materialPacking;
						mpKeyList.add(key);
					}

					Map<String, Object> hashMapPack = new HashMap<String,Object> ();
					hashMapPack.put("erpLocation", ERPRECEIVELOCATION == null  ? "" : ERPRECEIVELOCATION);
					hashMapPack.put("erpFactory",  ERPRECEIVEFACTORY == null  ? "" : ERPRECEIVEFACTORY);
					hashMapPack.put("locationName", "");
					hashMapPack.put("lastEventUser", user);
//					hashMapPack.put("unDoID", billCode);
					setEventInfo.setUserColumns(hashMapPack);
					MaterialPackingServiceProxy.getMaterialPackingService().setEvent(mpKeyList, eventInfo, setEventInfo);
					//抛送MES数据
					untils.sendMaterialInfoToMES_NEW2(shipRequestName, "", materialPackingKeyList,billCode,user);

					WlySaveUnDoInfo( billCode,commitDate);
				}
				else
				{

					billCode=ProductionStockOut_NEW(shipRequestName, "SDK", user,materialPackingKeyList,commitDate);
					if (billCode.isEmpty()) {
						return AjaxResult.me().setSuccess(false).setMessage("SAP过账异常！").setErrorCode(400);
					}
//					billCode=toSAPService.ProductionStockOut_NEW(shipRequestName, "SDK", eventUser,materialPackingKeyList);
					//抛送MES数据
					untils.sendMaterialInfoToMES_NEW(shipRequestName, "", materialPackingKeyList,billCode,user);
					//billCode = NCWServiceImpl.SaleOut2(shipRequestName, "SDK", eventUser,materialPackingKeyList,"");
					untils.SaveUnDoInfo_ForSap(materialPackingKeyList, billCode, eventInfo);

				}
				break;

			case "06"://成本中心领料
			case "09"://研发领料
//				billCode=toSAPService.orderStockOut(shipRequestName, "SDK", eventUser,materialPackingKeyList);
				billCode=orderStockOut(shipRequestName, "SDK", user,materialPackingKeyList,commitDate);
				//更新MES管芯数据
				new MESServiceImpl().updateDurable_ByCostcenter(shipRequestName, "SDK", user, materialPackingKeyList);
				//billCode = NCWServiceImpl.SaleOut2(shipRequestName, "SDK", eventUser,materialPackingKeyList,"");
				untils.SaveUnDoInfo_ForSap(materialPackingKeyList, billCode, eventInfo);
				break;
			case "ZLF0"://销售出库确认 （单据类型ZLF0~ZLF8） SD023(销售回传)
			case "ZLF1":
			case "ZLF2":
			case "ZLF3":
			case "ZLF4":
			case "ZLF5":
			case "ZLF6":
			case "ZLF7":
			case "ZLF8":
//				billCode=toSAPService.saleStockOut_NEW(shipRequestName, "SDK", eventUser,materialPackingKeyList);
				billCode=saleStockOut_NEW(shipRequestName, "SDK", user,materialPackingKeyList);
				untils.SaveUnDoInfo_ForSap(materialPackingKeyList, billCode, eventInfo);
				break;

			case "OEM":
//				billCode=toSAPService.oemStockOut_NEW(shipRequestName, "SDK", eventUser,materialPackingKeyList);
				billCode=oemStockOut_NEW(shipRequestName, "SDK", user,materialPackingKeyList);
				untils.SaveUnDoInfo_ForSap(materialPackingKeyList, billCode, eventInfo);
				break;
			default :
				break;
		}
		String deleteSql = "DELETE FROM MATERIALPACKINGSUB WHERE RECEIVEREQUESTNAME  = :SHIPREQUESTNAME";
		IDMFrameServiceProxy.getSqlTemplate().update(deleteSql, hashMap);
		return AjaxResult.me().setSuccess(true).setErrorCode(200);

	}

	public String TransferStockOut_NLCC(String shipRequestName, String siteName, String user,List<String> boxList,String commitDate) throws Exception {
		String rcode;
		String undoId = "";
		String key01 = "";
		String rmsg = null;
		String sql="    SELECT    \r\n" +
				"            count(*) AS ZROL,    \r\n" +
				"            m1.SHIPREQUESTDETAILNAME ,    \r\n" +
				"            t.ERPLOCATION,          \r\n" +
				"            sum(m.QTY)MATERIALQUANTITY          \r\n" +
				"            FROM \r\n" +
				"		 MATERIALPACKINGSUB m \r\n" +
				"		 LEFT JOIN MATERIALPACKING T ON \r\n" +
				"		 m.MATERIALPACKINGNAME = T.MATERIALPACKINGNAME AND m.RECEIVEREQUESTNAME = T.SHIPREQUESTNAME \r\n" +
				"		 LEFT JOIN MATERIALSHIPREQUESTDETAIL M1  \r\n" +
				"		  ON \r\n" +
				"		 m.RECEIVEREQUESTNAME = M1.SHIPREQUESTNAME \r\n" +
				"		 AND m.RECEIVEREQUESTDETAILNAME = M1.SHIPREQUESTDETAILNAME \r\n" +
				"		 LEFT JOIN MATERIALSHIPREQUEST M2  \r\n" +
				"		  ON \r\n" +
				"		 M1.SHIPREQUESTNAME = M2.SHIPREQUESTNAME \r\n" +
				"		 WHERE \r\n" +
				"		 T.SHIPREQUESTNAME = :SHIPREQUESTNAME \r\n" +
				"		 AND T.SITENAME = :SITENAME  \r\n" +
				"		  AND T.STOCKSTATE = 'Stocked' AND   T.MATERIALPACKINGNAME IN (:BOXLIST)\r\n" +
				"		  GROUP BY m1.SHIPREQUESTDETAILNAME ,    t.ERPLOCATION";

		Map<String, Object> hashMap = new HashMap<String, Object>();
		hashMap.put("SHIPREQUESTNAME", shipRequestName);
		hashMap.put("SITENAME", siteName);
		hashMap.put("BOXLIST", boxList);
		List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql.toString(), hashMap);
		try {

			JSONObject sendData = new JSONObject(true);
			JSONObject header = new JSONObject(true);
			sendData.put("HEAD", header);
			JSONObject body = new JSONObject(true);
			sendData.put("BODY", body);
			JSONArray itemArray = new JSONArray();

            /*
             HEAD
             */
			header.put("DEST_SYSTEM", "SAP");
			header.put("INTF_ID", "SD023");
			header.put("SRC_SYSTEM", "WMS");
			String uniqueID = UUID.randomUUID().toString();
			header.put("SRC_MSGID", uniqueID);
			header.put("BACKUP1", uniqueID);
			header.put("BACKUP2", uniqueID);



            /*
             BODY
             */
			//交货单号
			body.put("VBELN", shipRequestName);

			SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd");
			SimpleDateFormat outputFormat = new SimpleDateFormat("yyyyMMdd");
			Date date = inputFormat.parse(commitDate);
			String outputDate = outputFormat.format(date);
			//实际过账日期
			body.put("WADAT_IST", outputDate);//yyyyMMddhhmmss
			//发送日期
			body.put("Z_SENDDATE", outputDate);
			//操作类型（过账）
			body.put("Z_OPTION", "1");

			if (queryForList.size() >= 1) {
				for (Map<String, Object> mm : queryForList) {
					JSONObject item = new JSONObject(true);

					//交货单行号
					item.put("POSNR", mm.get("SHIPREQUESTDETAILNAME"));
					//交货数量
					item.put("PIKMG", mm.get("MATERIALQUANTITY"));
					//库存地点
					item.put("LGORT", mm.get("ERPLOCATION"));
					//实际发货卷数
					item.put("Z_ROL", mm.get("ZROL"));
					//实际发货平方米
					item.put("Z_SQUE", mm.get("MATERIALQUANTITY"));

					itemArray.add(item);
				}
				body.put("ITEMS", itemArray);
			}else {
				for (Map<String, Object> mm : queryForList) {

					//交货单行号
					body.put("POSNR", mm.get("SHIPREQUESTDETAILNAME"));
					//交货数量
					body.put("PIKMG", mm.get("MATERIALQUANTITY")); //SUM
					//库存地点
					body.put("LGORT", mm.get("ERPLOCATION"));
					//实际发货卷数
					body.put("Z_ROL", mm.get("ZROL"));   //COUNT
					//实际发货平方米
					body.put("Z_SQUE", mm.get("MATERIALQUANTITY"));

				}
			}

//			log.info("SendTOSAP >>>>" + sendData);
			String sapreturn = toSAPMessageUtil.sendHttpPost(toSAPMessageUtil.DNUrl, "", sendData.toJSONString());
			org.json.JSONObject receiveJsonObject = new org.json.JSONObject(sapreturn);

			//销售交货单过账不返回物料凭证,且RETURN为JsonArray
			org.json.JSONObject returnJsonObject = (org.json.JSONObject) receiveJsonObject.get("RETURN");
			rcode = returnJsonObject.get("STATUS").toString();
			rmsg = returnJsonObject.get("MSGTXT").toString();
			key01 = returnJsonObject.get("KEY01") == null ? "" : returnJsonObject.get("KEY01").toString();  // 返回单号，后面用单号冲销

			if ("S".equals(rcode)) {
				if(key01.isEmpty()) {
					undoId = "S";
				}else {
					undoId = key01;
				}

			}
			//将log写到表里
			ErpMessageLog erplog = new ErpMessageLog();
			erplog.setEventUser(user);
			erplog.setServerName("WmsToErp");
			erplog.setEventName("辅材出库-调拨出库(NLCC)");
			erplog.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
			erplog.setMessageId(UUID.randomUUID().toString());
			erplog.setSendMsg(sendData.toJSONString());
			erplog.setSendMsg2(sendData.toJSONString());
			erplog.setReturnMsg2(sapreturn);
			erplog.setResultCode(rcode);
			MessageLogUtil.writeMessageLog(erplog);
		} catch (Exception e) {
//			log.info(e.getMessage(), e);
			throw new RuntimeException("SAP返回" + rmsg);
		}
		if (!"S".equals(rcode)) {
			throw new RuntimeException("SAP返回" + rmsg);
		}
		return undoId;
	}

	public void WlySaveUnDoInfo( String undoid,String commitDate) {

		String insertUnDOMaterialPackingInfo = "insert into BS_MATERIALPACKINGUNDOINFO (unDoID,preundoid,UNDODETAILNAME,undoidstate,UNDOIDDATE,"
				+ "SITENAME, MATERIALPACKINGNAME, MATERIALPACKINGTYPE, CONTENTMATERIALTYPE,"
				+ "MATERIALTYPE, MATERIALSPECNAME, SUPERMATERIALPACKINGNAME, PACKINGGRADE, SUBPACKINGQUANTITY, MATERIALCREATEQUANTITY,"
				+ "MATERIALQUANTITY, PACKINGSTATE, OLDPACKINGSTATE, STOCKSTATE, OLDSTOCKSTATE, HOLDSTATE, AREANAME, LOCATIONNAME,"
				+ "DURABLENAME, MATERIALPROCESSGROUPNAME, LASTEVENTNAME, LASTEVENTTIMEKEY, LASTEVENTTIME, LASTEVENTUSER,"
				+ "LASTEVENTCOMMENT, CREATETIME, CREATEUSER, RECEIVEREQUESTNAME, RECEIVEREQUESTDETAILNAME,"
				+ "MAKEDATE, RECEIVEACTNO, STOCKINTYPE, RECEIVETIME, RECEIVEUSER, SHIPREQUESTNAME, SHIPREQUESTDETAILNAME, SHIPTIME,"
				+ "SHIPUSER, REASONCODETYPE, OQARESULTSTATE, OQARESULT, ERPLOCATION, ERPFACTORY, REASONCODE, CHARGE, SUPPLIERNAME,ETCSTATE,ERPEVENTTIME,NPFLAG)"
				+ "select unDoID,'' as preundoid,UNDODETAILNAME,'Completed' as undoidstate,:commitDate AS UNDOIDDATE," //
				+ "SITENAME, MATERIALPACKINGNAME, MATERIALPACKINGTYPE, CONTENTMATERIALTYPE,"
				+ "MATERIALTYPE, MATERIALSPECNAME, SUPERMATERIALPACKINGNAME, PACKINGGRADE, SUBPACKINGQUANTITY, MATERIALCREATEQUANTITY,"
				+ "MATERIALQUANTITY, PACKINGSTATE, OLDPACKINGSTATE, STOCKSTATE, OLDSTOCKSTATE, HOLDSTATE, AREANAME, LOCATIONNAME,"
				+ "DURABLENAME, MATERIALPROCESSGROUPNAME, LASTEVENTNAME, LASTEVENTTIMEKEY, LASTEVENTTIME, LASTEVENTUSER,"
				+ "LASTEVENTCOMMENT, CREATETIME, CREATEUSER, RECEIVEREQUESTNAME, RECEIVEREQUESTDETAILNAME,"
				+ "MAKEDATE, RECEIVEACTNO, STOCKINTYPE, RECEIVETIME, RECEIVEUSER, SHIPREQUESTNAME, SHIPREQUESTDETAILNAME, SHIPTIME,"
				+ "SHIPUSER, REASONCODETYPE, OQARESULTSTATE, OQARESULT, ERPLOCATION, ERPFACTORY, REASONCODE, CHARGE, SUPPLIERNAME,ETCSTATE,ERPEVENTTIME,NPFLAG"
				+ " from MATERIALPACKING  "
				+ " where unDoID=:UNDOID";

		Map<String, Object> bindMap_insert = new HashMap<String, Object>();
		bindMap_insert.put("UNDOID", undoid);
		bindMap_insert.put("commitDate",commitDate);
		IDMFrameServiceProxy.getSqlTemplate()
				.update(insertUnDOMaterialPackingInfo, bindMap_insert);

	}

	public String ProductionStockOut_NEW(String shipRequestName, String siteName, String user,List<String> boxList,String commitDate) throws Exception {

		String rcode;
		String undoId = "";
		String rmsg = null;
		String sql=" SELECT\r\n" +
				"	t.MATERIALSPECNAME,\r\n" +
				"	t.ERPFACTORY,\r\n" +
				"	t.ERPLOCATION,\r\n" +
				"	m2.SHIPREQUESTDETAILTYPE,\r\n" +
				"	t.UNIT,\r\n" +
				"	m1.COSTCENTER,\r\n" +
				"	m1.SHIPREQUESTNAME,\r\n" +
				"	m1.SHIPREQUESTDETAILNAME,\r\n" +
				"	m1.ERPRECEIVELOCATION,\r\n" +
				"	m1.ERPRECEIVEFACTORY,\r\n" +
				"	m1.SENDSALESORDER ,m1.SENDSALESORDERDETAILNO,\r\n" +
				"	CASE WHEN m1.SENDSALESORDER IS NOT NULL THEN 'E' ELSE '' END SOBKZ,\r\n" +
				"	(\r\n" +
				"	SELECT\r\n" +
				"		RECEIVEPRODUCTIONORDERNUMBER\r\n" +
				"	FROM\r\n" +
				"		MATERIALSHIPREQUESTDETAIL m5\r\n" +
				"	WHERE\r\n" +
				"		m5.SHIPREQUESTNAME =:SHIPREQUESTNAME\r\n" +
				"		AND m5.MATERIALSPECNAME = t.MATERIALSPECNAME\r\n" +
				"	ORDER BY\r\n" +
				"		m5.USEDATE,\r\n" +
				"		m5.SHIPREQUESTDETAILNAME FETCH FIRST ROW ONLY)RECEIVEPRODUCTIONORDERNUMBER,\r\n" +
				"	SUM(m.QTY) AS MATERIALQUANTITY\r\n" +
				" FROM \r\n" +
				"		 MATERIALPACKINGSUB m\r\n" +
				" LEFT JOIN MATERIALPACKING T ON \r\n" +
				"		 m.MATERIALPACKINGNAME = T.MATERIALPACKINGNAME\r\n" +
				"	AND m.RECEIVEREQUESTNAME = T.SHIPREQUESTNAME\r\n" +
				" LEFT JOIN MATERIALSHIPREQUESTDETAIL M1  \r\n" +
				"		  ON \r\n" +
				"		 m.RECEIVEREQUESTNAME = M1.SHIPREQUESTNAME\r\n" +
				"	AND m.RECEIVEREQUESTDETAILNAME = M1.SHIPREQUESTDETAILNAME\r\n" +
				" LEFT JOIN MATERIALSHIPREQUEST M2  \r\n" +
				"		  ON \r\n" +
				"		 M1.SHIPREQUESTNAME = M2.SHIPREQUESTNAME\r\n" +
				" WHERE \r\n" +
				"		 T.SHIPREQUESTNAME = :SHIPREQUESTNAME\r\n" +
				"	AND T.SITENAME = :SITENAME\r\n" +
				"	AND T.STOCKSTATE = 'Stocked'\r\n" +
				"	AND T.MATERIALPACKINGNAME IN (:BOXLIST)\r\n" +
				" GROUP BY\r\n" +
				"	t.MATERIALSPECNAME,\r\n" +
				"	t.ERPFACTORY,\r\n" +
				"	t.ERPLOCATION,\r\n" +
				"	m2.SHIPREQUESTDETAILTYPE,\r\n" +
				"	t.UNIT,\r\n" +
				"	m1.COSTCENTER,\r\n" +
				"	m1.SHIPREQUESTNAME,m1.SENDSALESORDER ,m1.SENDSALESORDERDETAILNO,\r\n" +
				"	m1.SHIPREQUESTDETAILNAME,\r\n" +
				"	m1.ERPRECEIVELOCATION,\r\n" +
				"	m1.ERPRECEIVEFACTORY";
		Map<String, Object> hashMap = new HashMap<String, Object>();
		hashMap.put("SHIPREQUESTNAME", shipRequestName);
		hashMap.put("SITENAME", siteName);
		hashMap.put("BOXLIST", boxList);
		List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql.toString(), hashMap);

		String sqlGetBWART = "SELECT M.SHIPREQUESTDETAILTYPE FROM MATERIALSHIPREQUEST M " +
				"WHERE M.SHIPREQUESTNAME = :SHIPREQUESTNAME AND M.SITENAME = :SITENAME";

		List<Map<String, Object>> checkResultList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sqlGetBWART, hashMap);
		String bwart = "";
		for(Map<String, Object> map : checkResultList) {
			bwart = MapUtils.getString(map, "SHIPREQUESTDETAILTYPE");
		}
		if(bwart == null || bwart == "") {
			throw new CustomException("ERROR","下发单据时，请务必填入移动类型");
		}

		try {

			JSONObject sendData = new JSONObject(true);
			JSONObject header = new JSONObject(true);
			sendData.put("HEAD", header);
			JSONObject body = new JSONObject(true);
			sendData.put("BODY", body);
			JSONArray itemArray = new JSONArray();

            /*
             HEAD
             */
			header.put("INTF_ID", "MM067");
			String uniqueID = UUID.randomUUID().toString();
			header.put("REQ_KEYID", uniqueID);
			header.put("SRC_MSGID", uniqueID);
			header.put("SRC_SYSTEM", "WMS");
			header.put("DEST_SYSTEM", "SAP");
			header.put("REQUSER", user);

            /*
             BODY
             */
			body.put("ITEM", itemArray);
			body.put("ITEMID", uniqueID);
			//过账日期
			SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd");
			SimpleDateFormat outputFormat = new SimpleDateFormat("yyyyMMdd");
			Date date = inputFormat.parse(commitDate);
			String outputDate = outputFormat.format(date);
			body.put("BUDAT", outputDate);
			//凭证日期
			body.put("BLDAT", outputDate);
			//凭证抬头文本
			body.put("BKTXT", uniqueID);
			//用户名
			body.put("USNAM", user);

			for (Map<String, Object> mm : queryForList) {

				JSONObject item = new JSONObject(true);
				// MATNR 发货物料号
				item.put("MATNR", mm.get("MATERIALSPECNAME"));
				// WERKS 收货工厂
				item.put("WERKS", mm.get("ERPFACTORY"));
				// LGORT 发货库存地点
				item.put("LGORT", mm.get("ERPLOCATION"));
				//MENGE 数量
				item.put("MENGE", mm.get("MATERIALQUANTITY"));
				//MENGE 单位
				item.put("MEINS", mm.get("UNIT"));
//                //KOSTL 成本中心
//                item.put("KOSTL", mm.get("COSTCENTER"));
//                //GRUND 移动原因 (201,202回传)
//                item.put("GRUND", mm.get("SHIPREQUESTDETAILTYPE"));

				if(bwart.equals("261")) {
					//BWART 移动类型
					item.put("BWART", mm.get("SHIPREQUESTDETAILTYPE"));
					//ZLLORDER 自定义领料单号
					item.put("ZLLORDER", mm.get("SHIPREQUESTNAME"));
					//ZLLITEM 自定义领料单行号
					item.put("ZLLITEM", mm.get("SHIPREQUESTDETAILNAME"));
					//AUFNR 订单号
					item.put("AUFNR", mm.get("RECEIVEPRODUCTIONORDERNUMBER"));
				}
				if(bwart.equals("311")) {
					//BWART 移动类型
					item.put("BWART", mm.get("SHIPREQUESTDETAILTYPE"));
					//UMMAT 收货物料
					item.put("UMMAT", mm.get("MATERIALSPECNAME"));//传什么
					//UMLGO 收货库存地点
					item.put("UMLGO", mm.get("ERPRECEIVELOCATION"));
					//UMWRK 收货工厂
					item.put("UMWRK", mm.get("ERPRECEIVEFACTORY"));
				}
				item.put("SOBKZ", mm.get("SOBKZ"));//特殊库存标识
				item.put("MAT_KDAUF", mm.get("SENDSALESORDER"));//发货销售订单号
				item.put("MAT_KDPOS", mm.get("SENDSALESORDERDETAILNO"));//发货销售订单行项

				itemArray.add(item);

			}
//			log.info("SendTOSAP >>>>" + sendData);
			String dataString = sendData.toJSONString();
			String sapreturn = toSAPMessageUtil.sendHttpPost(toSAPMessageUtil.materialChangeLocationUrl, "", sendData.toJSONString());
			org.json.JSONObject receiveJsonObject = new org.json.JSONObject(sapreturn);
			org.json.JSONObject returnJsonObject = (org.json.JSONObject) receiveJsonObject.get("RETURN");
			rcode = returnJsonObject.get("STATUS").toString();
			rmsg = returnJsonObject.get("MSGTXT").toString();

			if ("S".equals(rcode)) {
				undoId = returnJsonObject.get("MBLNR").toString()+"_"+returnJsonObject.get("MJAHR").toString();//将物料凭证号与凭证年度拼在一起
			}
			//将log写到表里
			ErpMessageLog erplog = new ErpMessageLog();
			erplog.setEventUser("");
			erplog.setServerName("WmsToErp");
			erplog.setEventName("生产领料出库261/311");
			erplog.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
			erplog.setMessageId(UUID.randomUUID().toString());
			erplog.setSendMsg(sendData.toJSONString());
			erplog.setSendMsg2(sendData.toJSONString());
			erplog.setReturnMsg2(sapreturn);
			erplog.setResultCode(rcode);
			MessageLogUtil.writeMessageLog(erplog);
		} catch (Exception e) {
//			log.info(e.getMessage(), e);
			throw new GlobalException("SAP返回" + rmsg);
		}
		if (!"S".equals(rcode)) {
			throw new GlobalException("SAP返回" + rmsg);
//			throw new CustomException("SAP返回" + rmsg);
		}
		return undoId;
	}

	public String orderStockOut(String shipRequestName, String siteName, String user,List<String> boxList, String commitDate) throws Exception {

		String rcode;
		String undoId = "";
		String rmsg = null;
		String sql=" SELECT      MP.MATERIALSPECNAME,       \r\n" +
				"        			MP.ERPFACTORY,       \r\n" +
				"        			MP.ERPLOCATION,       \r\n" +
				"        			MS.SHIPREQUESTDETAILTYPE,       \r\n" +
				"        			MP.UNIT,       \r\n" +
				"        			MD.COSTCENTER,       \r\n" +
				"        			MD.RECEIVEPRODUCTIONORDERNUMBER,       \r\n" +
				"        			MP.SHIPREQUESTNAME,       \r\n" +
				"        			MD.SHIPREQUESTDETAILNAME,       \r\n" +
				"        			MD.ERPRECEIVELOCATION,       \r\n" +
				"        			MD.ERPRECEIVEFACTORY,       \r\n" +
				"        			MD.CAUSEOFMOVEMENT,       \r\n" +
				"        			SUM(t.QTY) AS MATERIALQUANTITY       \r\n" +
				"        		FROM       \r\n" +
				"        			MATERIALPACKING MP \r\n" +
				"        		LEFT JOIN MATERIALPACKINGSUB T\r\n" +
				"        		ON mp.MATERIALPACKINGNAME =t.MATERIALPACKINGNAME \r\n" +
				"        		AND mp.SHIPREQUESTNAME =t.RECEIVEREQUESTNAME \r\n" +
				"        		LEFT JOIN MATERIALSHIPREQUESTDETAIL MD        \r\n" +
				"        				 ON       \r\n" +
				"        			MP.SHIPREQUESTNAME = MD.SHIPREQUESTNAME       \r\n" +
				"        			AND MP.SITENAME = MD.SITENAME       \r\n" +
				"        			AND t.RECEIVEREQUESTDETAILNAME = MD.SHIPREQUESTDETAILNAME       \r\n" +
				"        		LEFT JOIN MATERIALSHIPREQUEST MS        \r\n" +
				"        				 ON       \r\n" +
				"        			MD.SHIPREQUESTNAME = MS.SHIPREQUESTNAME       \r\n" +
				"        		WHERE       \r\n" +
				"        			MP.SHIPREQUESTNAME = :SHIPREQUESTNAME       \r\n" +
				"        			AND MP.SITENAME = :SITENAME       \r\n" +
				"        			AND MP.STOCKSTATE = 'Stocked'\r\n" +
				"        			AND MP.MATERIALPACKINGNAME IN (:BOXLIST)\r\n" +
				"        		GROUP BY        \r\n" +
				"        			MP.MATERIALSPECNAME,       \r\n" +
				"        			MP.ERPFACTORY,       \r\n" +
				"        			MP.ERPLOCATION,       \r\n" +
				"        			MS.SHIPREQUESTDETAILTYPE,       \r\n" +
				"        			MP.UNIT,       \r\n" +
				"        			MD.COSTCENTER,       \r\n" +
				"        			MD.RECEIVEPRODUCTIONORDERNUMBER,       \r\n" +
				"        			MP.SHIPREQUESTNAME, \r\n" +
				"        			MD.SHIPREQUESTDETAILNAME,\r\n" +
				"        			MD.ERPRECEIVELOCATION,       \r\n" +
				"        			MD.ERPRECEIVEFACTORY,       \r\n" +
				"        			MD.CAUSEOFMOVEMENT       ";
		Map<String, Object> hashMap = new HashMap<String, Object>();
		hashMap.put("SHIPREQUESTNAME", shipRequestName);
		hashMap.put("SITENAME", siteName);
		hashMap.put("BOXLIST", boxList);
		List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql.toString(), hashMap);


		try {

			JSONObject sendData = new JSONObject(true);
			JSONObject header = new JSONObject(true);
			sendData.put("HEAD", header);
			JSONObject body = new JSONObject(true);
			sendData.put("BODY", body);
			JSONArray itemArray = new JSONArray();

            /*
             HEAD
             */
			header.put("INTF_ID", "MM067");
			String uniqueID = UUID.randomUUID().toString();
			header.put("REQ_KEYID", uniqueID);
			header.put("SRC_MSGID", uniqueID);
			header.put("SRC_SYSTEM", "WMS");
			header.put("DEST_SYSTEM", "SAP");
			header.put("REQUSER", user);

            /*
             BODY
             */
			body.put("ITEM", itemArray);
			body.put("ITEMID", uniqueID);
			//过账日期
			SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd");
			SimpleDateFormat outputFormat = new SimpleDateFormat("yyyyMMdd");
			Date date = inputFormat.parse(commitDate);
			String outputDate = outputFormat.format(date);
			body.put("BUDAT", outputDate);
			//凭证日期
			body.put("BLDAT", outputDate);
			//凭证抬头文本
			body.put("BKTXT", uniqueID);
			//用户名
			body.put("USNAM", user);

			for (Map<String, Object> mm : queryForList) {

				JSONObject item = new JSONObject(true);
				//BWART 移动类型
				item.put("BWART",  mm.get("SHIPREQUESTDETAILTYPE"));
				// MATNR 发货物料号
				item.put("MATNR", mm.get("MATERIALSPECNAME"));
				// WERKS 收货工厂
				item.put("WERKS", mm.get("ERPFACTORY"));
				// LGORT 发货库存地点
				item.put("LGORT", mm.get("ERPLOCATION"));
				//MENGE 数量
				item.put("MENGE", mm.get("MATERIALQUANTITY"));
				//MENGE 单位
				item.put("MEINS", mm.get("UNIT"));
				//KOSTL 成本中心
				item.put("KOSTL", mm.get("COSTCENTER"));
				//AUFNR 订单号
				item.put("AUFNR", mm.get("RECEIVEPRODUCTIONORDERNUMBER"));
				//GRUND 移动原因 (201,202回传)
				item.put("GRUND", mm.get("CAUSEOFMOVEMENT"));
				//ZLLORDER 自定义领料单号
				item.put("ZLLORDER", mm.get("SHIPREQUESTNAME"));
				//ZLLITEM 自定义领料单行号
				item.put("ZLLITEM", mm.get("SHIPREQUESTDETAILNAME"));

				itemArray.add(item);

			}
//			log.info("SendTOSAP >>>>" + sendData);
			String sapreturn = toSAPMessageUtil.sendHttpPost(toSAPMessageUtil.materialChangeLocationUrl, "", sendData.toJSONString());
			org.json.JSONObject receiveJsonObject = new org.json.JSONObject(sapreturn);
			org.json.JSONObject returnJsonObject = (org.json.JSONObject) receiveJsonObject.get("RETURN");
			rcode = returnJsonObject.get("STATUS").toString();
			rmsg = returnJsonObject.get("MSGTXT").toString();

			if ("S".equals(rcode)) {
				undoId = returnJsonObject.get("MBLNR").toString()+"_"+returnJsonObject.get("MJAHR").toString();//将物料凭证号与凭证年度拼在一起
			}
			//将log写到表里
			ErpMessageLog erplog = new ErpMessageLog();
			erplog.setEventUser("");
			erplog.setServerName("WmsToErp");
			erplog.setEventName("成本中心/研发领料");
			erplog.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
			erplog.setMessageId(UUID.randomUUID().toString());
			erplog.setSendMsg(sendData.toJSONString());
			erplog.setSendMsg2(sendData.toJSONString());
			erplog.setReturnMsg2(sapreturn);
			erplog.setResultCode(rcode);
			MessageLogUtil.writeMessageLog(erplog);
		} catch (Exception e) {
//			log.info(e.getMessage(), e);
			throw new RuntimeException("SAP返回" + rmsg);
		}
		if (!"S".equals(rcode)) {
			throw new RuntimeException("SAP返回" + rmsg);
		}
		return undoId;
	}
	//重写销售交货单过账。zd.2024.8.14
	public String saleStockOut_NEW(String shipRequestName, String siteName, String user,List<String> boxList) throws Exception {
		String rcode;
		String undoId = "";
		String rmsg = null;
		String sql="    SELECT    \r\n" +
				"            count(*) AS ZROL,    \r\n" +
				"            m1.SHIPREQUESTDETAILNAME ,    \r\n" +
				"            t.ERPLOCATION,          \r\n" +
				"            sum(m.QTY)MATERIALQUANTITY          \r\n" +
				"            FROM \r\n" +
				"		 MATERIALPACKINGSUB m \r\n" +
				"		 LEFT JOIN MATERIALPACKING T ON \r\n" +
				"		 m.MATERIALPACKINGNAME = T.MATERIALPACKINGNAME AND m.RECEIVEREQUESTNAME = T.SHIPREQUESTNAME \r\n" +
				"		 LEFT JOIN MATERIALSHIPREQUESTDETAIL M1  \r\n" +
				"		  ON \r\n" +
				"		 m.RECEIVEREQUESTNAME = M1.SHIPREQUESTNAME \r\n" +
				"		 AND m.RECEIVEREQUESTDETAILNAME = M1.SHIPREQUESTDETAILNAME \r\n" +
				"		 LEFT JOIN MATERIALSHIPREQUEST M2  \r\n" +
				"		  ON \r\n" +
				"		 M1.SHIPREQUESTNAME = M2.SHIPREQUESTNAME \r\n" +
				"		 WHERE \r\n" +
				"		 T.SHIPREQUESTNAME = :SHIPREQUESTNAME \r\n" +
				"		 AND T.SITENAME = :SITENAME  \r\n" +
				"		  AND T.STOCKSTATE = 'Stocked' AND   T.MATERIALPACKINGNAME IN (:BOXLIST)\r\n" +
				"		  GROUP BY m1.SHIPREQUESTDETAILNAME ,    t.ERPLOCATION";

		Map<String, Object> hashMap = new HashMap<String, Object>();
		hashMap.put("SHIPREQUESTNAME", shipRequestName);
		hashMap.put("SITENAME", siteName);
		hashMap.put("BOXLIST", boxList);
		List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql.toString(), hashMap);
		try {

			JSONObject sendData = new JSONObject(true);
			JSONObject header = new JSONObject(true);
			sendData.put("HEAD", header);
			JSONObject body = new JSONObject(true);
			sendData.put("BODY", body);
			JSONArray itemArray = new JSONArray();

            /*
             HEAD
             */
			header.put("DEST_SYSTEM", "SAP");
			header.put("INTF_ID", "SD023");
			header.put("SRC_SYSTEM", "WMS");
			String uniqueID = UUID.randomUUID().toString();
			header.put("SRC_MSGID", uniqueID);
			header.put("BACKUP1", uniqueID);
			header.put("BACKUP2", uniqueID);



            /*
             BODY
             */
			//交货单号
			body.put("VBELN", shipRequestName);
			//实际过账日期
			body.put("WADAT_IST", TimeStampUtil.getCurrentTime("yyyyMMdd"));//yyyyMMddhhmmss
			//发送日期
			body.put("Z_SENDDATE", TimeStampUtil.getCurrentTime("yyyyMMdd"));
			//操作类型（过账）
			body.put("Z_OPTION", "1");

			if (queryForList.size() >= 1) {
				for (Map<String, Object> mm : queryForList) {
					JSONObject item = new JSONObject(true);

					//交货单行号
					item.put("POSNR", mm.get("SHIPREQUESTDETAILNAME"));
					//交货数量
					item.put("PIKMG", mm.get("MATERIALQUANTITY"));
					//库存地点
					item.put("LGORT", mm.get("ERPLOCATION"));
					//实际发货卷数
					item.put("Z_ROL", mm.get("ZROL"));
					//实际发货平方米
					item.put("Z_SQUE", mm.get("MATERIALQUANTITY"));

					itemArray.add(item);
				}
				body.put("ITEMS", itemArray);//销售过账需放ITEMS
			}else {
				for (Map<String, Object> mm : queryForList) {

					//交货单行号
					body.put("POSNR", mm.get("SHIPREQUESTDETAILNAME"));
					//交货数量
					body.put("PIKMG", mm.get("MATERIALQUANTITY")); //SUM
					//库存地点
					body.put("LGORT", mm.get("ERPLOCATION"));
					//实际发货卷数
					body.put("Z_ROL", mm.get("ZROL"));   //COUNT
					//实际发货平方米
					body.put("Z_SQUE", mm.get("MATERIALQUANTITY"));

				}
			}

//			log.info("SendTOSAP >>>>" + sendData);
			String sapreturn = toSAPMessageUtil.sendHttpPost(toSAPMessageUtil.DNUrl, "", sendData.toJSONString());
			org.json.JSONObject receiveJsonObject = new org.json.JSONObject(sapreturn);

			//销售交货单过账不返回物料凭证,且RETURN为JsonArray
			org.json.JSONObject returnJsonObject = (org.json.JSONObject) receiveJsonObject.get("RETURN");
			rcode = returnJsonObject.get("STATUS").toString();
			rmsg = returnJsonObject.get("MSGTXT").toString();

			if ("S".equals(rcode)) {
				undoId = "S";
			}
			//将log写到表里
			ErpMessageLog erplog = new ErpMessageLog();
			erplog.setEventUser("");
			erplog.setServerName("WmsToErp");
			erplog.setEventName("调拨出库(NLCC)");
			erplog.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
			erplog.setMessageId(UUID.randomUUID().toString());
			erplog.setSendMsg(sendData.toJSONString());
			erplog.setSendMsg2(sendData.toJSONString());
			erplog.setReturnMsg2(sapreturn);
			erplog.setResultCode(rcode);
			MessageLogUtil.writeMessageLog(erplog);
		} catch (Exception e) {
//			log.info(e.getMessage(), e);
			throw new RuntimeException("SAP返回" + rmsg);
		}
		if (!"S".equals(rcode)) {
			throw new RuntimeException("SAP返回" + rmsg);
		}
		return undoId;
	}
	//重写委外发料。zd.2024.8.17
	public String oemStockOut_NEW(String shipRequestName, String siteName, String user,List<String> boxList) throws Exception
	{

		String rcode;
		String undoId = "";
		String rmsg = null;
		String sql="SELECT       \r\n" +
				"        			MS.DELIVERYADDRESS,       \r\n" +
				"        			MP.MATERIALSPECNAME,       \r\n" +
				"        			MP.ERPFACTORY,       \r\n" +
				"        			MP.ERPLOCATION,       \r\n" +
				"        			MS.SHIPREQUESTDETAILTYPE,       \r\n" +
				"        			MP.UNIT,       \r\n" +
				"        			MD.COSTCENTER,       \r\n" +
				"        			MD.RECEIVEPRODUCTIONORDERNUMBER,       \r\n" +
				"        			MP.SHIPREQUESTNAME,       \r\n" +
				"        			MP.SHIPREQUESTDETAILNAME,       \r\n" +
				"        			MD.ERPRECEIVELOCATION,       \r\n" +
				"        			MD.ERPRECEIVEFACTORY,       \r\n" +
				"        			SUM(M.QTY) AS MATERIALQUANTITY       \r\n" +
				"        		FROM       \r\n" +
				"        			MATERIALPACKING MP  \r\n" +
				"        		LEFT JOIN MATERIALPACKINGSUB m \r\n" +
				"        		ON mp.MATERIALPACKINGNAME =m.MATERIALPACKINGNAME \r\n" +
				"        		AND mp.SHIPREQUESTNAME =m.RECEIVEREQUESTNAME \r\n" +
				"        		LEFT JOIN MATERIALSHIPREQUESTDETAIL MD        \r\n" +
				"        				 ON       \r\n" +
				"        			MP.SHIPREQUESTNAME = MD.SHIPREQUESTNAME       \r\n" +
				"        			AND MP.SITENAME = MD.SITENAME \r\n" +
				"        			AND m.RECEIVEREQUESTDETAILNAME =md.SHIPREQUESTDETAILNAME \r\n" +
				"        		LEFT JOIN MATERIALSHIPREQUEST MS        \r\n" +
				"        				 ON       \r\n" +
				"        			MD.SHIPREQUESTNAME = MS.SHIPREQUESTNAME \r\n" +
				"        		WHERE       \r\n" +
				"        			MP.SHIPREQUESTNAME = :SHIPREQUESTNAME       \r\n" +
				"        			AND MP.SITENAME = :SITENAME       \r\n" +
				"        			AND MP.STOCKSTATE = 'Stocked'\r\n" +
				"        			AND mp.MATERIALPACKINGNAME IN (:BOXLIST)\r\n" +
				"        		GROUP BY        \r\n" +
				"        			MS.DELIVERYADDRESS,       \r\n" +
				"        			MP.MATERIALSPECNAME,       \r\n" +
				"        			MP.ERPFACTORY,       \r\n" +
				"        			MP.ERPLOCATION,       \r\n" +
				"        			MS.SHIPREQUESTDETAILTYPE,       \r\n" +
				"        			MP.UNIT,       \r\n" +
				"        			MD.COSTCENTER,       \r\n" +
				"        			MD.RECEIVEPRODUCTIONORDERNUMBER,       \r\n" +
				"        			MP.SHIPREQUESTNAME,       \r\n" +
				"        			MP.SHIPREQUESTDETAILNAME,     \r\n" +
				"        			MD.ERPRECEIVELOCATION,       \r\n" +
				"        			MD.ERPRECEIVEFACTORY       ";


		Map<String, Object> hashMap = new HashMap<String, Object>();
		hashMap.put("SHIPREQUESTNAME", shipRequestName);
		hashMap.put("SITENAME", siteName);
		hashMap.put("BOXLIST", boxList);
		List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql.toString(), hashMap);



		try {

			JSONObject sendData = new JSONObject(true);
			JSONObject header = new JSONObject(true);
			sendData.put("HEAD", header);
			JSONObject body = new JSONObject(true);
			sendData.put("BODY", body);
			JSONArray itemArray = new JSONArray();

            /*
             HEAD
             */
			header.put("INTF_ID", "MM067");
			String uniqueID = UUID.randomUUID().toString();
			header.put("REQ_KEYID", uniqueID);
			header.put("SRC_MSGID", uniqueID);
			header.put("SRC_SYSTEM", "WMS");
			header.put("DEST_SYSTEM", "SAP");
			header.put("REQUSER", user);

            /*
             BODY
             */
			body.put("ITEM", itemArray);
			body.put("ITEMID", uniqueID);
			//过账日期
			body.put("BUDAT", TimeStampUtil.getCurrentTime("yyyyMMdd"));
			//凭证日期
			body.put("BLDAT", TimeStampUtil.getCurrentTime("yyyyMMdd"));
			//凭证抬头文本
			body.put("BKTXT", uniqueID);
			//用户名
			body.put("USNAM", user);

			for (Map<String, Object> mm : queryForList) {

				JSONObject item = new JSONObject(true);

				// MATNR 发货物料号
				item.put("MATNR", mm.get("MATERIALSPECNAME"));
				// WERKS 收货工厂
				item.put("WERKS", mm.get("ERPFACTORY"));
				// LGORT 发货库存地点
				item.put("LGORT", mm.get("ERPLOCATION"));
				//BWART 移动类型
				item.put("BWART", "541O");
				//SOBKZ 特殊库存标识
//                item.put("SOBKZ", "O");
				//LIFNR 供应商编码
				item.put("LIFNR", mm.get("DELIVERYADDRESS"));
				//MENGE 数量
				item.put("MENGE", mm.get("MATERIALQUANTITY"));
				//MENGE 单位
				item.put("MEINS", mm.get("UNIT"));

				itemArray.add(item);

				updateOEMINVENTORY(mm.get("ERPFACTORY") == null ?  "" : mm.get("ERPFACTORY").toString(),mm.get("DELIVERYADDRESS") == null ?  "" : mm.get("DELIVERYADDRESS").toString(),
						mm.get("MATERIALSPECNAME") == null ?  "" : mm.get("MATERIALSPECNAME").toString(),mm.get("MATERIALQUANTITY") == null ?  "" : mm.get("MATERIALQUANTITY").toString());

			}
//			log.info("SendTOSAP >>>>" + sendData);
			String sapreturn = toSAPMessageUtil.sendHttpPost(toSAPMessageUtil.materialChangeLocationUrl, "", sendData.toJSONString());
			org.json.JSONObject receiveJsonObject = new org.json.JSONObject(sapreturn);
			org.json.JSONObject returnJsonObject = (org.json.JSONObject) receiveJsonObject.get("RETURN");
			rcode = returnJsonObject.get("STATUS").toString();
			rmsg = returnJsonObject.get("MSGTXT").toString();

			if ("S".equals(rcode)) {
				undoId = returnJsonObject.get("MBLNR").toString()+"_"+returnJsonObject.get("MJAHR").toString();//将物料凭证号与凭证年度拼在一起
			}
			//将log写到表里
			UUID uuid = UUID.randomUUID();
			ErpMessageLog erplog = new ErpMessageLog();
			erplog.setEventUser("");
			erplog.setServerName("WmsToErp");
			erplog.setEventName("委外发料541O");
			erplog.setId(uuid.toString());
			erplog.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
			erplog.setMessageId(UUID.randomUUID().toString());
			erplog.setSendMsg(sendData.toJSONString());
			erplog.setSendMsg2(sendData.toJSONString());
			erplog.setReturnMsg2(sapreturn);
			erplog.setResultCode(rcode);
			MessageLogUtil.writeMessageLog(erplog);
		} catch (Exception e) {
//			log.info(e.getMessage(), e);
			throw new RuntimeException("SAP返回" + rmsg);
		}
		if (!"S".equals(rcode)) {
			throw new RuntimeException("SAP返回" + rmsg);
		}
		return undoId;
	}

	//更新OEMINVENTORY。zd.2024.8.7
	public void updateOEMINVENTORY(String erpFactory,String supplierNo,String materialSpecName,String qty) throws Exception
	{
		String sqls="SELECT o.MATERIALSPECNAME FROM OEMINVENTORY o \r\n" +
				" WHERE o.ERPFACTORY =:ERPFACTORY\r\n" +
				" AND o.MATERIALSPECNAME =:MATERIALSPECNAME\r\n" ;
//				" AND o.SUPPLIERNO =:SUPPLIERNO";
		Map<String, Object> bp=new HashMap<>();
		bp.put("ERPFACTORY", erpFactory);
		bp.put("MATERIALSPECNAME", materialSpecName);
		bp.put("SUPPLIERNO", supplierNo);
		bp.put("QTY", qty);
		List<Map<String, Object>> sr=IDMFrameServiceProxy.getSqlTemplate().queryForList(sqls, bp);
		if(sr.size()>0)
		{
			String sqlu="UPDATE OEMINVENTORY o SET o.QTY =o.QTY + :QTY\r\n" +
					" WHERE o.ERPFACTORY =:ERPFACTORY\r\n" +
					" AND o.MATERIALSPECNAME =:MATERIALSPECNAME\r\n" ;
//					" AND o.SUPPLIERNO =:SUPPLIERNO";
			IDMFrameServiceProxy.getSqlTemplate().update(sqlu, bp);
		}
		else
		{
			String sqli="INSERT INTO OEMINVENTORY(ERPFACTORY,MATERIALSPECNAME,SUPPLIERNO,QTY)\r\n" +
					" VALUES (:ERPFACTORY,:MATERIALSPECNAME,:SUPPLIERNO,:QTY)";
			IDMFrameServiceProxy.getSqlTemplate().update(sqli, bp);
		}

	}
	public boolean packingChargeSplit(List<MaterialPacking> boxList, String user) {

		String condition="";
		String newBoxId1 = boxList.get(1).getMaterialPackingName();
//		String pc = "('" + materialpackingname + "')";
		String sql = "SELECT 1 FROM MATERIALPACKING WHERE MATERIALPACKINGNAME IN (:MATERIALPACKINGNAME1)";
		Map<String, Object> hashMap2 = new HashMap<String,Object> ();
		hashMap2.put("MATERIALPACKINGNAME1", newBoxId1);
		List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, hashMap2);
		List<MaterialPacking> MaterialPackingList = null;
		if (queryForList != null && queryForList.size() > 0) {
			String[] bindSet={newBoxId1};
			condition="WHERE MATERIALPACKINGNAME IN (?)";
			MaterialPackingList = MaterialPackingServiceProxy.getMaterialPackingService().select(condition, bindSet);
		}
		//解析条码,根据远条码信息更新目标条码数量和库存状态
		SetEventInfo setEventInfo = new SetEventInfo();
		EventInfoUtil eventInfoUtil = new EventInfoUtil();
		makeEventInfo = eventInfoUtil.makeEventInfo("ChargeSplit", user, "ChargeSplit" );
		//找到原来标签的相关信息
//		String receiveTime = "";
//		String makeDate = "";
//		String expireDate = "";
		String holdState = "";
		String oqaResult = "";
		String oqaResultState = "";
		String packingGrade = "";
		String trueGg = "";
		String erpFactory = "";
		String erpLocation = "";
		String locationName = "";
		String shelfName = "";
		String areaName = "";
		String durableName = "";;
		String CAREER_ASSISTANCE = "";
		String SALESPERSON = "";
		String CUSTOMNO = "";
		String DEVIATION = "";
		String DIAMETER = "";
		String WIDTH = "";
		String WEIGHT = "";
		String PRODUCTLINE = "";
		String UNIT = "";
		String MJPC = "";
		String BUSINESS_UNIT = "";

		String MATERIALSPECNAME = "";
//	    String SUBPACKINGQUANTITY = "";
//	    String MATERIALCREATEQUANTITY = "";
		String CHARGE = "";
		String SDK_ID = "";
		String PHASE = "";
		String RECEIVEREQUESTNAME = "";
		String RECEIVEREQUESTDETAILNAME = "";
		String REMARK = "";
		String SHIPREQUESTNAME = "";
		String SHIPREQUESTDETAILNAME = "";
		String MATERIALTYPE = "";
		String RECEIVEACTNO = "";
		String UNDOID = "";
		String	FIFOFLAG = "";

		String ypcSql = "SELECT M.RECEIVETIME,M.MAKEDATE,M.EXPIRINGDATE,M.HOLDSTATE,M.OQARESULTSTATE ,\r\n" +
				"		M.OQARESULT ,M.PACKINGGRADE ,M.TRUEGG ,M.ERPFACTORY ,M.ERPLOCATION ,M.LOCATIONNAME ,\r\n" +
				"		M.SHELFNAME ,M.MATERIALTYPE,M.AREANAME ,M.DURABLENAME ,M.CAREER_ASSISTANCE ,M.SALESPERSON ,M.CUSTOMNO,M.SDK_ID,M.PHASE,M.SHIPREQUESTNAME,M.SHIPREQUESTDETAILNAME,M.RECEIVEREQUESTNAME,M.RECEIVEREQUESTDETAILNAME,"
				+ "     M.DEVIATION ,M.DIAMETER ,M.WIDTH ,M.WEIGHT ,M.PRODUCTLINE,UNIT ,MJPC,BUSINESS_UNIT,M.MATERIALSPECNAME, M.SUBPACKINGQUANTITY, M.MATERIALCREATEQUANTITY, M.MATERIALQUANTITY, M.CHARGE, M.REMARK" +
				"		FROM MATERIALPACKING M WHERE M.MATERIALPACKINGNAME  = :MATERIALPACKINGNAME "; //AND M.CHARGE  = :CHARGE
		Map<String, Object> hashMap4 = new HashMap<String,Object> ();
		hashMap4.put("MATERIALPACKINGNAME", boxList.get(0).getMaterialPackingName());
//		hashMap4.put("CHARGE", boxList.get(0).getCharge());
		List<Map<String, Object>> queryForList3 = IDMFrameServiceProxy.getSqlTemplate().queryForList(ypcSql, hashMap4);

		if (queryForList3 != null && queryForList3.size() > 0) {
			Map<String, Object> map = queryForList3.get(0);
			holdState = map.get("HOLDSTATE") == null ? "N" : map.get("HOLDSTATE").toString();
			oqaResult = map.get("OQARESULT") == null ? "" : map.get("OQARESULT").toString();
			oqaResultState = map.get("OQARESULTSTATE") == null ? "END" : map.get("OQARESULTSTATE").toString();
			packingGrade = map.get("PACKINGGRADE") == null ? "" : map.get("PACKINGGRADE").toString();
			trueGg = map.get("TRUEGG") == null ? "" : map.get("TRUEGG").toString();
			erpFactory = map.get("ERPFACTORY") == null ? "" : map.get("ERPFACTORY").toString();
			erpLocation = map.get("ERPLOCATION") == null ? "" : map.get("ERPLOCATION").toString();
			locationName = map.get("LOCATIONNAME") == null ? "" : map.get("LOCATIONNAME").toString();
			shelfName = map.get("SHELFNAME") == null ? "" : map.get("SHELFNAME").toString();
			areaName = map.get("AREANAME") == null ? "" : map.get("AREANAME").toString();
			durableName = map.get("DURABLENAME") == null ? "" : map.get("DURABLENAME").toString();
			CAREER_ASSISTANCE = map.get("CAREER_ASSISTANCE") == null ? "" : map.get("CAREER_ASSISTANCE").toString();
			SALESPERSON = map.get("SALESPERSON") == null ? "" : map.get("SALESPERSON").toString();
			CUSTOMNO = map.get("CUSTOMNO") == null ? "" : map.get("CUSTOMNO").toString();
			DEVIATION = map.get("DEVIATION") == null ? "" : map.get("DEVIATION").toString();
			DIAMETER = map.get("DIAMETER") == null ? "" : map.get("DIAMETER").toString();
			WIDTH = map.get("WIDTH") == null ? "" : map.get("WIDTH").toString();
			WEIGHT = map.get("WEIGHT") == null ? "" : map.get("WEIGHT").toString();
			PRODUCTLINE = map.get("PRODUCTLINE") == null ? "" : map.get("PRODUCTLINE").toString();
			UNIT = map.get("UNIT") == null ? "" : map.get("UNIT").toString();
			MJPC = map.get("MJPC") == null ? "" : map.get("MJPC").toString();
			BUSINESS_UNIT = map.get("BUSINESS_UNIT") == null ? "" : map.get("BUSINESS_UNIT").toString();
			MATERIALSPECNAME = map.get("MATERIALSPECNAME") == null ? "" : map.get("MATERIALSPECNAME").toString();
//	         SUBPACKINGQUANTITY = map.get("SUBPACKINGQUANTITY") == null ? "" : map.get("SUBPACKINGQUANTITY").toString();
//	         MATERIALCREATEQUANTITY = map.get("MATERIALCREATEQUANTITY") == null ? "" : map.get("MATERIALCREATEQUANTITY").toString();
			CHARGE = map.get("CHARGE") == null ? "" : map.get("CHARGE").toString();
			SDK_ID = map.get("SDK_ID") == null ? "" : map.get("SDK_ID").toString();
			PHASE = map.get("PHASE") == null ? "" : map.get("PHASE").toString();
			REMARK = map.get("REMARK") == null ? "" : map.get("REMARK").toString();
			SHIPREQUESTNAME = map.get("SHIPREQUESTNAME") == null ? "" : map.get("SHIPREQUESTNAME").toString();
			SHIPREQUESTDETAILNAME = map.get("SHIPREQUESTDETAILNAME") == null ? "" : map.get("SHIPREQUESTDETAILNAME").toString();
			MATERIALTYPE = map.get("MATERIALTYPE") == null ? "" : map.get("MATERIALTYPE").toString();
			RECEIVEACTNO = map.get("RECEIVEACTNO") == null ? "" : map.get("RECEIVEACTNO").toString();
			UNDOID = map.get("UNDOID") == null ? "" : map.get("UNDOID").toString();
			FIFOFLAG = map.get("FIFOFLAG") == null ? "" : map.get("FIFOFLAG").toString();
		}

		if (MaterialPackingList != null && MaterialPackingList.size() > 0) {
			throw new RuntimeException("拆分批次的标签已存在！");
		}else {
//			创建标签1
			CreateInfo createInfo1 = new CreateInfo();
			createInfo1.setSiteName("SDK");
			createInfo1.setMaterialPackingName(newBoxId1);// 新生成的box id
			createInfo1.setMaterialPackingType("Box");
			createInfo1.setContentMaterialType("");

			Map<String, Object> bindMap = new HashMap<String, Object>();
			bindMap.put("MaterialSpecName", MATERIALSPECNAME);
			bindMap.put("PackingGrade", packingGrade);
			bindMap.put("oqaResult", oqaResult);
			bindMap.put("oqaResultState", oqaResultState);
			bindMap.put("SubPackingQuantity",boxList.get(1).getMaterialQuantity());
			bindMap.put("MaterialCreateQuantity",boxList.get(1).getMaterialQuantity());
			bindMap.put("MaterialQuantity", boxList.get(1).getMaterialQuantity());// 数量
			bindMap.put("PackingState", "Released");
			bindMap.put("OldPackingState", "Released");
			bindMap.put("stockState", "Stocked");
			bindMap.put("OldStockState", "Created");
			bindMap.put("HoldState", holdState);
			bindMap.put("LocationName", locationName);
//			bindMap.put("charge",CHARGE);  // 无批次不需要标签
			bindMap.put("MaterialProcessGroupName","");
			bindMap.put("LastEventTimeKey",TimeStampUtil.getCurrentEventTimeKey());

			bindMap.put("MakeDate", queryForList3.get(0).get("MAKEDATE"));
			bindMap.put("expiringDate", queryForList3.get(0).get("EXPIRINGDATE"));
			bindMap.put("ReceiveTime", queryForList3.get(0).get("RECEIVETIME"));
			bindMap.put("unit", queryForList3.get(0).get("UNIT"));

			bindMap.put("ReceiveUser", makeEventInfo.getEventUser());
			bindMap.put("ErpLocation", erpLocation);
			bindMap.put("ErpFactory", erpFactory);
			bindMap.put("locationName", locationName);
			bindMap.put("StockInType", "Normal");
			bindMap.put("SDK_ID", SDK_ID);
			bindMap.put("PHASE", PHASE);
			bindMap.put("remark", REMARK);

			bindMap.put("shipRequestName", SHIPREQUESTNAME);
			bindMap.put("shipRequestDetailName",SHIPREQUESTDETAILNAME);

			bindMap.put("receiveRequestName", RECEIVEREQUESTNAME);
			bindMap.put("receiveRequestDetailName",RECEIVEREQUESTDETAILNAME);
			bindMap.put("materialType", MATERIALTYPE);
			bindMap.put("receiveActNo", RECEIVEACTNO);
			bindMap.put("unDoID", UNDOID);
			bindMap.put("fifoFlag", FIFOFLAG);

			bindMap.put("CAREER_ASSISTANCE", CAREER_ASSISTANCE);//业助信息
			bindMap.put("BUSINESS_UNIT", BUSINESS_UNIT);//业务
			bindMap.put("SALESPERSON", SALESPERSON);//事业部
			bindMap.put("MJPC", MJPC);//母卷批次
			bindMap.put("truegg", trueGg);
			bindMap.put("durableName", durableName);
			bindMap.put("areaName", areaName);
			bindMap.put("PRODUCTLINE", PRODUCTLINE);
			bindMap.put("WIDTH", WIDTH);
			bindMap.put("DEVIATION", DEVIATION);
			bindMap.put("WEIGHT", WEIGHT);
			bindMap.put("DIAMETER", DIAMETER);
			bindMap.put("shelfName", shelfName);
			bindMap.put("split", "Y");
			createInfo1.setUserColumns(bindMap);

			MaterialPackingServiceProxy.getMaterialPackingService().create(makeEventInfo, createInfo1);

			//更新原标签批次的库位状态为出库
//			MaterialPackingKey materialPackingKey = new MaterialPackingKey("SDK",boxList.get(0).getMaterialPackingName());
//			Map<String, Object> hashMap3 = new HashMap<String,Object> ();
//			hashMap3.put("stockState", "StockOut");
//			setEventInfo.setUserColumns(hashMap3);
//			MaterialPackingServiceProxy.getMaterialPackingService().setEvent(materialPackingKey, makeEventInfo, setEventInfo);
		}
		return true;
	}

	/**
	 * 2025-05-20
	 * 根据到货单号更新入库单数量
	 * @param eventInfo 事件信息
	 * @param materialDelivery 到货单信息
	 */
	public void DeliveryStockInUpdateReceiveRequestQty(EventInfo eventInfo, MaterialDelivery materialDelivery) throws Exception{
		//获取到货单关联的所有入库单
		StoreDetailDto storeDetailDto = new StoreDetailDto();
		storeDetailDto.setDocumentName(materialDelivery.getDeliveryName());
		List<MaterialDeliveryReceive> materialDeliveryReceivesList = deliveryDao.getRelByDelivery(storeDetailDto);
		//更新入库单信息
		for (MaterialDeliveryReceive materialDeliveryReceive : materialDeliveryReceivesList) {
			String updateReceiveRequestQtySql = " UPDATE MATERIALRECEIVEREQUESTDETAIL m \n" +
					"SET m.RECEIVEDQUANTITY = m.RECEIVEDQUANTITY - :QTY" +
					" , m.LASTEVENTNAME =:LASTEVENTNAME \n" +
					" , m.LASTEVENTTIMEKEY =:LASTEVENTTIMEKEY \n" +
					" , m.LASTEVENTTIME =:LASTEVENTTIME \n" +
					" , m.LASTEVENTUSER =:LASTEVENTUSER \n" +
					" , m.LASTEVENTCOMMENT =:LASTEVENTCOMMENT \n" +
					"WHERE\n" +
					"\tm.SITENAME = :SITENAME \n" +
					"\tAND m.RECEIVEREQUESTNAME = :RECEIVEREQUESTNAME \n" +
					"\tAND m.MATERIALSPECNAME = :MATERIALSPECNAME \n" +
					"\tAND m.RECEIVEREQUESTDETAILNAME = :RECEIVEREQUESTDETAILNAME ";
			Map<String, Object> updateReceiveRequestQtyMap = new HashMap<String, Object>();
			updateReceiveRequestQtyMap.put("QTY", materialDeliveryReceive.getDeliveryNum());
			updateReceiveRequestQtyMap.put("SITENAME", materialDelivery.getSiteName());
			updateReceiveRequestQtyMap.put("MATERIALSPECNAME", materialDeliveryReceive.getMaterialSpecName());
			updateReceiveRequestQtyMap.put("RECEIVEREQUESTNAME", materialDeliveryReceive.getReceiveRequestName());
			updateReceiveRequestQtyMap.put("RECEIVEREQUESTDETAILNAME", materialDeliveryReceive.getReceiveRequestDetailName());
			updateReceiveRequestQtyMap.put("LASTEVENTNAME", eventInfo.getEventUser());
			updateReceiveRequestQtyMap.put("LASTEVENTTIMEKEY", eventInfo.getEventTimeKey());
			updateReceiveRequestQtyMap.put("LASTEVENTTIME", eventInfo.getEventTime());
			updateReceiveRequestQtyMap.put("LASTEVENTUSER", eventInfo.getEventUser());
			updateReceiveRequestQtyMap.put("LASTEVENTCOMMENT", eventInfo.getEventComment());
			IDMFrameServiceProxy.getSqlTemplate().update(updateReceiveRequestQtySql, updateReceiveRequestQtyMap);

			// 更新单据状态
			SDKMP.updateOrderState(materialDeliveryReceive.getReceiveRequestName());
		}
	}
}
