package com.cim.idm.controller;

import com.alibaba.fastjson.JSONObject;
import com.cim.idm.data.ErpMessageLog;
import com.cim.idm.framework.IDMFrameServiceProxy;
import com.cim.idm.framework.data.EventInfo;
import com.cim.idm.framework.util.sys.SystemPropHelper;
import com.cim.idm.framework.util.time.TimeStampUtil;
import com.cim.idm.framework.util.time.TimeUtils;
import com.cim.idm.model.SAPToWMSRequest;
import com.cim.idm.model.WMSToSAPReturn;
import com.cim.idm.mwmsextend.materialreceiverequest.service.MaterialReceiveRequestServiceImpl;
import com.cim.idm.util.MessageLogUtil;
import com.cim.idm.wmsextend.generic.errorHandler.CustomException;
import com.cim.idm.wmspackage.invoice.MaterialReceiveRequestServiceProxy;
import com.cim.idm.wmspackage.invoice.management.data.MaterialReceiveRequestKey;
import com.cim.idm.wmspackage.invoice.management.info.CreateReceiveRequestInfo;
import com.cim.idm.wmspackage.invoice.management.info.SetEventInfo;
import com.cim.idm.wmspackage.materialpacking.management.data.MaterialPackingStockInfo;
import com.cim.idm.wmspackage.materialshiprequest.MaterialShipRequestServiceProxy;
import com.cim.idm.wmspackage.materialshiprequest.management.data.MaterialShipRequest;
import com.cim.idm.wmspackage.materialshiprequest.management.data.MaterialShipRequestKey;
import com.cim.idm.wmspackage.materialshiprequest.management.info.CreateMaterialShipRequestInfo;
import com.cim.idm.wmspackage.materialshiprequest.management.info.MaterialShipRequestSetEventInfo;
import com.cim.idm.wmspackage.materialshiprequestdetail.MaterialShipRequestDetailServiceProxy;
import com.cim.idm.wmspackage.materialshiprequestdetail.management.data.MaterialShipRequestDetail;
import com.cim.idm.wmspackage.materialshiprequestdetail.management.data.MaterialShipRequestDetailKey;
import com.cim.idm.wmspackage.materialshiprequestdetail.management.info.CreateMaterialShipRequestDetailInfo;
import com.cim.idm.wmspackage.materialshiprequestdetail.management.info.MaterialShipRequestDetailSetEventInfo;
import com.cim.idm.wmspackage.materialshiprequestdetail.management.info.NonPrimaryKeyValueInfo;
import com.cim.idm.wmspackage.receiverequestdetail.ReceiveRequestDetailServiceProxy;
import com.cim.idm.wmspackage.receiverequestdetail.management.data.MaterialReceiveRequestDetail;
import com.cim.idm.wmspackage.receiverequestdetail.management.data.MaterialReceiveRequestDetailKey;
import com.cim.idm.wmspackage.receiverequestdetail.management.info.CreateReceiveRequestDetailInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/api/wms")
@Slf4j
public class SAPToWMSController {
	

	//预留字段
	String ZRSV01 = "";
	String ZRSV02 = "";
	String ZRSV03 = "";
	String ZRSV04 = "";
	String ZRSV05 = "";
	String ZRSV06 = "";
	String ZRSV07 = "";
	String ZRSV08 = "";
	String ZRSV09 = "";
	String ZRSV10 = "";
	
	// 物料主数据
	@RequestMapping(value = "/materialspec", method = RequestMethod.POST)
	public WMSToSAPReturn GetMaterialSpec(HttpServletRequest httpRequest, @RequestBody SAPToWMSRequest request) {
		Map<String,Object> head = request.getHEAD();
		
		try {
			IDMFrameServiceProxy.getTransactionManager().beginTransaction();

			EventInfo eventInfo = new EventInfo();
		
			ArrayList<Map<String,Object>> data = request.getBODY();
			// 主表
			String insertSql="INSERT INTO MATERIALSPEC (sitename, materialspecname, materialgroup, materialgroupdescription, materialunit, materialunitdesc, deliverycycle, minorderqty, phase, materialtype, mstae, oldmaterialspecname, highvalueflag, commonmaterialflag, purchasetype, width, financialtype, createtime, createuser, lasteventtime, lasteventuser, lasteventtimekey, lasteventname,  lasteventcomment,desc_en,IS_CON_TEMP ,MATURATIONTIME ,MATURATIONFLAG ,DEGREE,EXPIRATION_RULES, ZTURENAME, ZMDQ, IS_CON_TEMP_T, MATURATIONTIME_T, MATURATIONFLAG_T) " + SystemPropHelper.CR +
					"VALUES(:sitename, :materialspecname, :materialgroup, :materialgroupdescription, :materialunit, :materialunitdesc,:deliverycycle, :minorderqty, :phase, :materialtype, :mstae, :oldmaterialspecname, :highvalueflag, :commonmaterialflag, :purchasetype, :width, :financialtype, :createtime, :createuser, :lasteventtime, :lasteventuser, :lasteventtimekey, :lasteventname, :lasteventcomment,:desc_en,:IS_CON_TEMP ,:MATURATIONTIME ,:MATURATIONFLAG ,:DEGREE,:EXPIRATION_RULES, :zturename, :zmdq, :IS_CON_TEMP_T, :MATURATIONTIME_T, :MATURATIONFLAG_T)";
			String updateSql = "UPDATE MATERIALSPEC SET materialgroup = :materialgroup,desc_en=:desc_en,IS_CON_TEMP=:IS_CON_TEMP ,MATURATIONTIME=:MATURATIONTIME ,MATURATIONFLAG=:MATURATIONFLAG ,DEGREE=:DEGREE,EXPIRATION_RULES=:EXPIRATION_RULES, materialgroupdescription = :materialgroupdescription, materialunit = :materialunit, materialunitdesc = :materialunitdesc, deliverycycle = :deliverycycle, minorderqty = :minorderqty, phase = :phase, materialtype = :materialtype, mstae = :mstae, oldmaterialspecname = :oldmaterialspecname, highvalueflag = highvalueflag, commonmaterialflag = :commonmaterialflag, purchasetype = :purchasetype, width = :width, financialtype = :financialtype, createtime = :createtime, createuser = :createuser, lasteventtime = :lasteventtime, lasteventuser = :lasteventuser, lasteventtimekey = :lasteventtimekey, lasteventname = :lasteventname, lasteventcomment = :lasteventcomment, zturename = :zturename, zmdq = :zmdq, IS_CON_TEMP_T = :IS_CON_TEMP_T, MATURATIONTIME_T = :MATURATIONTIME_T, MATURATIONFLAG_T = :MATURATIONFLAG_T where materialspecname = :materialspecname and sitename = :sitename";
			// 附加单位
			String insertMarmSql = "insert into BS_MATERIALUNIT (materialspecname, additionalunit, modulecule, denominator) "
					+ "VALUES(:materialspecname, :additionalunit, :modulecule, :denominator)";
			String updateMarmSql = "update BS_MATERIALUNIT set additionalunit = :additionalunit, modulecule = :modulecule, denominator = :denominator where materialspecname = :materialspecname and additionalunit = :additionalunit";
			// 物料描述
			String insertMaktSql = "insert into BS_MATERIALDESCRIPTION (materialspecname, language, description) "
					+ "VALUES(:materialspecname, :language, :description)";
			
			String updateMaktSql = "update BS_MATERIALDESCRIPTION set language = :language, description = :description where materialspecname = :materialspecname";

			// 物料描述
			String insertMarcSql = "insert into BS_MATERIALFACTORY (materialspecname, erpfactory, erpfactorydec, materialgroupone, materialgrouptwo, materialstate, poreceivelocation, purchasegroupcode, purchasegroupdec, pounit, costunit, taxflag, versionflag, sourcelist, erplocation, safestockqty, iqcflag, purchasetype, undoflag, chargeflag, bklas, profitcenter,mhdhb, bstme, vrkme, bstmi, bstrf, raube, tempb, plifz, webaz) "+SystemPropHelper.CR
					+ "VALUES(:materialspecname, :erpfactory, :erpfactorydec, :materialgroupone, :materialgrouptwo, :materialstate, :poreceivelocation, :purchasegroupcode, :purchasegroupdec, :pounit, :costunit, :taxflag, :versionflag, :sourcelist, :erplocation, :safestockqty, :iqcflag, :purchasetype, :undoflag, :chargeflag, :bklas, :profitcenter,:mhdhb, :bstme, :vrkme, :bstmi, :bstrf, :raube, :tempb, :plifz, :webaz)";
			
			String updateMarcSql = "update BS_MATERIALFACTORY SET materialgroupone = :materialgroupone, mhdhb=:mhdhb,erpfactorydec = :erpfactorydec, materialgrouptwo = :materialgrouptwo, materialstate = :materialstate, poreceivelocation = :poreceivelocation, purchasegroupcode = :purchasegroupcode, purchasegroupdec = :purchasegroupdec, pounit = :pounit, costunit = :costunit, taxflag = :taxflag, versionflag = :versionflag, sourcelist = :sourcelist, erplocation = :erplocation, safestockqty = :safestockqty, iqcflag = :iqcflag, purchasetype = :purchasetype, undoflag = :undoflag, chargeflag = :chargeflag, bklas = :bklas, profitcenter = :profitcenter, bstme = :bstme, vrkme = :vrkme, bstmi = :bstmi, bstrf = :bstrf, raube = :raube, tempb = :tempb, plifz = :plifz, webaz =:webaz where materialspecname = :materialspecname and erpfactory = :erpfactory";

			
			
			String insertHistorySql="INSERT INTO materialspechistory (sitename, materialspecname, timekey, eventtime, eventname, consumabletype, consumeunit, eventuser, eventcomment, erpfactory, consumabletypedescription, consumableadmitflag, consumablegroup, consumblename, consumablegroupdescription, consumablenetweight, purchasegroup, purchaseunit, netweightunit, erplocation, createdate, description,expirationday,ltext)" + SystemPropHelper.CR +
					"VALUES(:sitename, :materialspecname, :timekey, :eventtime, :eventname, :consumabletype, :consumeunit, :eventuser, :eventcomment, :erpfactory, :consumabletypedescription, :consumableadmitflag, :consumablegroup, :consumblename, :consumablegroupdescription, :consumablenetweight, :purchasegroup, :purchaseunit, :netweightunit, :erplocation, :createdate, :description,:expirationday,:ltext)";
			//String updateSql="UPDATE materialspec SET materialtype = :materialtype, description = :description, lasteventtime=:lasteventtime, lasteventuser=:lasteventuser, consumeunit=:consumeunit, erpfactory=:erpfactory, consumabletypedescription=:consumabletypedescription, consumableadmitflag=:consumableadmitflag, consumablegroup=:consumablegroup, consumblename=:consumblename, consumablegroupdescription=:consumablegroupdescription, consumablenetweight=:consumablenetweight, purchasegroup=:purchasegroup, purchaseunit=:purchaseunit, netweightunit=:netweightunit, erplocation=:erplocation, createdate=:createdate,expirationday=:expirationday,ltext=:ltext WHERE consumablespecname=:consumablespecname AND factoryname=:factoryname";
			
			for (Map<String, Object> materialSpec : data) {
				String matnr = MapUtils.getString(materialSpec, "MATNR"); // 物料号
				String matkl = MapUtils.getString(materialSpec, "MATKL"); // 物料组
				String wgbez = MapUtils.getString(materialSpec, "WGBEZ"); // 物料组描述
				String meins = MapUtils.getString(materialSpec, "MEINS"); // 基本计量单位
				//String description = MapUtils.getString(materialSpec, "MAKTX"); // 物料描述
				String msehl = MapUtils.getString(materialSpec, "MSEHL"); // 单位描述
				String zjfq = MapUtils.getString(materialSpec, "ZJFZQ"); // 交付周期
				String aumng = MapUtils.getString(materialSpec, "AUMNG"); // 最小订购量
				String zjd = MapUtils.getString(materialSpec, "ZJD"); // 阶段
				
				String mtart = MapUtils.getString(materialSpec, "MTART"); // 物料类型
				String zmakltx = MapUtils.getString(materialSpec, "ZMAKLTX"); // 物料长描述
				String mstae = MapUtils.getString(materialSpec, "MSTAE"); // 跨工厂物料状态
				String lvorm = MapUtils.getString(materialSpec, "LVORM"); // 删除标识
				String bismt = MapUtils.getString(materialSpec, "BISMT"); // 旧物料号
				String zgjz = MapUtils.getString(materialSpec, "ZGJZ"); // 是否高价值
				String ztyl = MapUtils.getString(materialSpec, "ZTYL"); // 是否通用料
				String zcgfl = MapUtils.getString(materialSpec, "ZCGFL"); // 采购分类
				String zkd = MapUtils.getString(materialSpec, "ZKD"); // 宽度
				String zhd = MapUtils.getString(materialSpec, "ZHD"); // 厚度
//				String zjd = MapUtils.getString(materialSpec, "ZJD"); // 阶段
				String zcwfl = MapUtils.getString(materialSpec, "ZCWFL"); // 财务分类
				
				//增加字段zd.2024.8.12.ZRAUBE 存储条件   ZTEMPB 温度条件  ZDAY 仓库熟化天数  ZBZQTYPE 保质期类型
				String ZTEMPB = MapUtils.getString(materialSpec, "ZTEMPB");//温度条件
				String ZDAY = MapUtils.getString(materialSpec, "ZDAY");//仓库熟化天数
				String ZRAUBE = MapUtils.getString(materialSpec, "ZRAUBE");//存储条件
				String ZBZQTYPE = MapUtils.getString(materialSpec, "ZBZQTYPE");//保质期类型
				// 预留字段
				ZRSV01 = MapUtils.getString(materialSpec, "ZRSV01") != null ? MapUtils.getString(materialSpec, "ZRSV01") : "";
				ZRSV02 = MapUtils.getString(materialSpec, "ZRSV02") != null ? MapUtils.getString(materialSpec, "ZRSV02") : "";
				ZRSV03 = MapUtils.getString(materialSpec, "ZRSV03") != null ? MapUtils.getString(materialSpec, "ZRSV03") : ""; 
				ZRSV04 = MapUtils.getString(materialSpec, "ZRSV04") != null ? MapUtils.getString(materialSpec, "ZRSV04") : ""; 
				ZRSV05 = MapUtils.getString(materialSpec, "ZRSV05") != null ? MapUtils.getString(materialSpec, "ZRSV05") : ""; 
				ZRSV06 = MapUtils.getString(materialSpec, "ZRSV06") != null ? MapUtils.getString(materialSpec, "ZRSV06") : ""; 
				ZRSV07 = MapUtils.getString(materialSpec, "ZRSV07") != null ? MapUtils.getString(materialSpec, "ZRSV07") : ""; 
				ZRSV08 = MapUtils.getString(materialSpec, "ZRSV08") != null ? MapUtils.getString(materialSpec, "ZRSV08") : ""; 
				ZRSV09 = MapUtils.getString(materialSpec, "ZRSV09") != null ? MapUtils.getString(materialSpec, "ZRSV09") : ""; 
				ZRSV10 = MapUtils.getString(materialSpec, "ZRSV10") != null ? MapUtils.getString(materialSpec, "ZRSV10") : ""; 

				
				
				String currentEventTimeKey = new TimeUtils().getCurrentEventTimeKey();
				Timestamp currentTimestamp = TimeStampUtil.getCurrentTimestamp();
				
				HashMap<String, Object> map = new HashMap<String,Object>();
				map.put("sitename", System.getProperty("company"));
				map.put("materialspecname", matnr);
				map.put("materialgroup", matkl);
				map.put("materialgroupdescription", wgbez);
				map.put("materialunit", meins);
				map.put("desc_en", zmakltx);

				map.put("materialunitdesc", msehl);
				map.put("deliverycycle", zjfq);
				map.put("minorderqty", aumng);
				map.put("phase", zjd);
				
				//m.IS_CON_TEMP ,m.MATURATIONTIME ,m.MATURATIONFLAG ,m.DEGREE,m.EXPIRATION_RULES
				//增加字段zd.2024.8.12.ZRAUBE 存储条件   ZTEMPB 温度条件  ZDAY 仓库熟化天数  ZBZQTYPE 保质期类型
				//保质期类型ZBZQTYPE SAP 01出厂保质期  02到厂保质期; NC中0代表入，1代表出
				if(StringUtils.equals(ZBZQTYPE, "01")) 
				{
					ZBZQTYPE="1";
				}
				else if(StringUtils.equals(ZBZQTYPE, "02")) 
				{
					ZBZQTYPE="0";
				}
				//存储条件ZRAUBE 01普通 02恒温 03冷藏 04干膜
				/*if(StringUtils.equals(ZRAUBE, "02"))
				{
					ZRAUBE="Y";
				}
				else 
				{
					ZRAUBE="N";
				}
				
				//温度条件 ZTEMPB 01不熟化 02常温 03低温 04中温 05高温
				String MATURATIONFLAG="Y";
				if(StringUtils.equals(ZTEMPB, "01")) 
				{
					
					MATURATIONFLAG="N";
				}*/
				
				map.put("IS_CON_TEMP", ZRAUBE);
				map.put("IS_CON_TEMP_T", ZRAUBE);
				map.put("MATURATIONTIME", ZDAY);
				map.put("MATURATIONTIME_T", ZDAY);
				map.put("MATURATIONFLAG", ZTEMPB);
				map.put("MATURATIONFLAG_T", ZTEMPB);
				map.put("DEGREE", ZTEMPB);
				map.put("EXPIRATION_RULES", ZBZQTYPE);
				
				map.put("materialtype", mtart);
				map.put("mstae", mstae); // 跨工厂物料状态
				map.put("oldmaterialspecname", bismt);
				map.put("highvalueflag", zgjz);
				map.put("commonmaterialflag", ztyl);
				map.put("purchasetype", zcgfl);
				map.put("width", zkd);
				map.put("thickness", zhd);
//				map.put("phase", zjd);
				map.put("financialtype", zcwfl);
				map.put("createtime", currentTimestamp);
				map.put("createuser", "SAP");
				map.put("lasteventtime", currentTimestamp);
				map.put("lasteventtimekey", currentEventTimeKey);
				map.put("lasteventname", "GetMaterialSpecFromSAP");
				map.put("lasteventuser", "SAP");
				map.put("lasteventcomment", "");

				// 250409 添加缺少字段
				String zturename = MapUtils.getString(materialSpec, "ZTURENAME");
				String zmdq = MapUtils.getString(materialSpec, "ZMDQ"); // 装车最小装载量
				map.put("zturename", zturename);
				map.put("zmdq", zmdq);

				if("X".equals(lvorm)) {
					//IDMFrameServiceProxy.getSqlTemplate().update(insertHistorySql, map);
					
					String sql="DELETE FROM materialspec WHERE materialspecname=? AND sitename=?";
					Object[] obj=new Object[] {matnr,System.getProperty("company")};
					IDMFrameServiceProxy.getSqlTemplate().update(sql, obj);
				}
				else {
					String selectSql="SELECT count(1) num FROM materialspec WHERE materialspecname = :MATERIALSPECNAME AND sitename = :SITENAME";
					Object[] selectObj=new Object[] {matnr,System.getProperty("company")};
					Map<String, Object> hashMap = new HashMap<String,Object> ();
					hashMap.put("MATERIALSPECNAME", matnr);
					hashMap.put("SITENAME", System.getProperty("company"));
					List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(selectSql, hashMap);
					String string = queryForList.get(0).get("NUM").toString();
					if("0".equals(string)) {	
						IDMFrameServiceProxy.getSqlTemplate().update(insertSql, map);
						//IDMFrameServiceProxy.getSqlTemplate().update(insertHistorySql, map);
					}
					else {						
						IDMFrameServiceProxy.getSqlTemplate().update(updateSql, map);
						//IDMFrameServiceProxy.getSqlTemplate().update(insertHistorySql, map);
					}
				}
				
				if (materialSpec.containsKey("MARM")) {
					// marm 附加单位
					ArrayList<Map<String,Object>> marmItems = (ArrayList<Map<String,Object>>)materialSpec.get("MARM");
					
					for (Map<String, Object> marmItem : marmItems) {
						String meinh = MapUtils.getString(marmItem, "MEINH"); // 附加单位
						float umrez   = Float.parseFloat(MapUtils.getString(marmItem, "UMREZ")); // 分子
						float umren   = Float.parseFloat(MapUtils.getString(marmItem, "UMREN")); // 分母
						
						// 附加单位
						HashMap<String, Object> mapMarm = new HashMap<String,Object>();
						mapMarm.put("materialspecname", matnr);
						mapMarm.put("additionalunit", meinh);
						mapMarm.put("modulecule", String.valueOf(umrez));
						mapMarm.put("denominator", String.valueOf(umren));
						
						String selectSql="SELECT materialspecname FROM BS_MATERIALUNIT WHERE materialspecname = ? and additionalunit = ?";
						Object[] selectObj=new Object[] {matnr,meinh};
						List<Map<String, Object>> selectList = IDMFrameServiceProxy.getSqlTemplate().queryForList(selectSql, selectObj);
						if(selectList.size() == 0) {	
							IDMFrameServiceProxy.getSqlTemplate().update(insertMarmSql, mapMarm);
							//IDMFrameServiceProxy.getSqlTemplate().update(insertHistorySql, mapMarm);
						}
						else {						
							IDMFrameServiceProxy.getSqlTemplate().update(updateMarmSql, mapMarm);
							//IDMFrameServiceProxy.getSqlTemplate().update(insertHistorySql, map);
						}
					}
				}

				if (materialSpec.containsKey("MAKT")) {
					// makt 描述数据
					ArrayList<Map<String,Object>> maktItems = (ArrayList<Map<String,Object>>)materialSpec.get("MAKT");
					
					for (Map<String, Object> maktItem : maktItems) {
						String spras = MapUtils.getString(maktItem, "SPRAS"); // 语言
						String maktxItem = MapUtils.getString(maktItem, "MAKTX")==null?"":MapUtils.getString(maktItem, "MAKTX"); // 物料描述
						
						if(maktxItem.length()>0) 
						{
							String sqlu= "";
							String[] des=maktxItem.split("@");
							HashMap<String, Object> bp = new HashMap<String,Object>();
							if("ZH".equals(spras)) {
								sqlu="UPDATE MATERIALSPEC m SET m.DESCRIPTION =:DESCRIPTION,m.DESC_CN =:DESC_CN WHERE m.MATERIALSPECNAME =:MATERIALSPECNAME";
								bp.put("DESCRIPTION", maktxItem);
								bp.put("DESC_CN", des[0]);
							}else {
								sqlu="UPDATE MATERIALSPEC m SET m.DESC_EN =:DESC_EN WHERE m.MATERIALSPECNAME =:MATERIALSPECNAME";
								bp.put("DESC_EN", maktxItem);
							}

							bp.put("MATERIALSPECNAME", matnr);
							IDMFrameServiceProxy.getSqlTemplate().update(sqlu, bp);
						}
						// 描述数据
						HashMap<String, Object> mapMakt = new HashMap<String,Object>();
						mapMakt.put("materialspecname", matnr);
						mapMakt.put("language", spras);
						mapMakt.put("description", maktxItem);
						
						
						String selectSql="SELECT materialspecname FROM BS_MATERIALDESCRIPTION WHERE materialspecname = ? and language = ?";
						Object[] selectObj=new Object[] {matnr,spras};
						List<Map<String, Object>> selectList = IDMFrameServiceProxy.getSqlTemplate().queryForList(selectSql, selectObj);
						if(selectList.size() == 0) {	
							IDMFrameServiceProxy.getSqlTemplate().update(insertMaktSql, mapMakt);
							//IDMFrameServiceProxy.getSqlTemplate().update(insertHistorySql, mapMarm);
						}
						else {						
							IDMFrameServiceProxy.getSqlTemplate().update(updateMaktSql, mapMakt);
							//IDMFrameServiceProxy.getSqlTemplate().update(insertHistorySql, map);
						}
					}
				}
				
				if (materialSpec.containsKey("MARC")) {
					// marc 工厂数据
					ArrayList<Map<String,Object>> marcItems = (ArrayList<Map<String,Object>>)materialSpec.get("MARC");
					for (Map<String, Object> marcItem : marcItems) {
						
						String matnrItem = MapUtils.getString(marcItem, "MATNR"); // 物料号
						String werksItem = MapUtils.getString(marcItem, "WERKS"); // ERP工厂
						String name1 = MapUtils.getString(marcItem, "NAME1"); // ERP工厂描述
						
						String mvgr1 = MapUtils.getString(marcItem, "MVGR1"); // 物料组1
						String mvgr2 = MapUtils.getString(marcItem, "MVGR2"); // 物料组1
						String mmsta = MapUtils.getString(marcItem, "MMSTA"); // 物料状态
						String lvormItem = MapUtils.getString(marcItem, "LVORM"); // 删除标识
						String lgfsb = MapUtils.getString(marcItem, "LGFSB"); // 采购收货库存地
						String ekgrp = MapUtils.getString(marcItem, "EKGRP"); // 采购组编码
						String eknam = MapUtils.getString(marcItem, "EKNAM"); // 采购组描述                  
						String korod = MapUtils.getString(marcItem, "KOROD"); // 源清单
						String lgpro = MapUtils.getString(marcItem, "LGPRO"); // 发货仓库地点  ERP库位
						String eisbe = MapUtils.getString(marcItem, "EISBE"); // 安全库存
						String insmk = MapUtils.getString(marcItem, "INSMK"); // 过账到质检库存，质检标识
						if("X".equals(insmk))
						{
							insmk="Y";//SAP启用质检标记为X，转换为Y存入数据库。zd.2024.8.2
						}
						String beskz = MapUtils.getString(marcItem, "BESKZ"); // 采购类型
						String rgekz = MapUtils.getString(marcItem, "RGEKZ"); // 反冲
						String xcharge = MapUtils.getString(marcItem, "XCHARGE"); // 是否批次管理
						String bklas = MapUtils.getString(marcItem, "BKLAS"); // 评估类
						String plifz = MapUtils.getString(marcItem, "PLIFZ"); // 计划交货时间
						String webaz = MapUtils.getString(marcItem, "WEBAZ"); // 收货处理时间
						String mhdhb = MapUtils.getString(marcItem, "MHDHB"); // 货架寿命
						String prctr = MapUtils.getString(marcItem, "PRCTR"); // 利润中心
						
						
						SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
						
						//Timestamp planDate = new Timestamp(format.parse(plifz).getTime());
						
						//Timestamp receiveTime = new Timestamp(format.parse(webaz).getTime());
						
						//Timestamp expiredDate = new Timestamp(format.parse(mhdhb).getTime());

						
						// 描述数据
						HashMap<String, Object> mapMarc = new HashMap<String,Object>();
						mapMarc.put("materialspecname", matnr);
						mapMarc.put("erpfactory", werksItem);
						mapMarc.put("erpfactorydec", name1);
						mapMarc.put("materialgroupone", mvgr1);
						mapMarc.put("materialgrouptwo", mvgr2);
						
						mapMarc.put("materialstate", mmsta);
						mapMarc.put("poreceivelocation", lgfsb);
						mapMarc.put("purchasegroupcode", ekgrp);
						mapMarc.put("purchasegroupdec", eknam);
						
						mapMarc.put("pounit", "");
						mapMarc.put("costunit", "");
						mapMarc.put("taxflag", "");
						mapMarc.put("versionflag", "");
						
						mapMarc.put("sourcelist", korod);
						
						mapMarc.put("erplocation", lgpro);
						mapMarc.put("safestockqty", eisbe);
						mapMarc.put("iqcflag", insmk);
						mapMarc.put("purchasetype", beskz);
						
						mapMarc.put("undoflag", rgekz);
						mapMarc.put("chargeflag", xcharge);
						mapMarc.put("bklas", bklas);
						//mapMarc.put("plandate", planDate);
						
						//mapMarc.put("receivetime", receiveTime);
						mapMarc.put("mhdhb", mhdhb);//增加货架寿命存储。Add By zd.2024.7.31
						mapMarc.put("profitcenter", prctr);

						// 250409 添加缺少字段
						String bstme = MapUtils.getString(marcItem, "BSTME");
						String vrkme = MapUtils.getString(marcItem, "VRKME");
						String bstmi = MapUtils.getString(marcItem, "BSTMI");
						String bstrf = MapUtils.getString(marcItem, "BSTRF");
						String raube = MapUtils.getString(marcItem, "RAUBE");
						String tempb = MapUtils.getString(marcItem, "TEMPB");
						mapMarc.put("bstme", bstme);
						mapMarc.put("vrkme", vrkme);
						mapMarc.put("bstmi", bstmi);
						mapMarc.put("bstrf", bstrf);
						mapMarc.put("raube", raube);
						mapMarc.put("tempb", tempb);
						mapMarc.put("plifz", plifz);
						mapMarc.put("webaz", webaz);


						if("X".equals(lvormItem)) {
							//IDMFrameServiceProxy.getSqlTemplate().update(insertHistorySql, map);
							
							String sql="DELETE FROM BS_MATERIALFACTORY WHERE materialspecname = ? AND erpfactory = ?";
							Object[] obj=new Object[] {matnr,werksItem};
							IDMFrameServiceProxy.getSqlTemplate().update(sql, obj);
						}else {
							String selectSql="SELECT COUNT(1) NUM FROM BS_MATERIALFACTORY WHERE materialspecname = ? AND erpfactory = ?";
							Object[] selectObj=new Object[] {matnr,werksItem};
							List<Map<String, Object>> selectList = IDMFrameServiceProxy.getSqlTemplate().queryForList(selectSql, selectObj);
							if("0".equals(selectList.get(0).get("NUM").toString())) {	
								IDMFrameServiceProxy.getSqlTemplate().update(insertMarcSql, mapMarc);
								//IDMFrameServiceProxy.getSqlTemplate().update(insertHistorySql, mapMarm);
							}
							else {						
								IDMFrameServiceProxy.getSqlTemplate().update(updateMarcSql, mapMarc);
								//IDMFrameServiceProxy.getSqlTemplate().update(insertHistorySql, map);
							}
						}	
					}	
				}
			}
				
			Map<String, Object> oKReturn = new HashMap<>();
			
			oKReturn.put("STATUS", "S");
			oKReturn.put("MSGTXT", "物料主数据下发成功");
			oKReturn.put("ZRSV01", "");
			oKReturn.put("ZRSV02", "");
			oKReturn.put("ZRSV03", "");
			oKReturn.put("ZRSV04", "");
			oKReturn.put("ZRSV05", "");
			oKReturn.put("ZRSV06", "");
			oKReturn.put("ZRSV07", "");
			oKReturn.put("ZRSV08", "");
			oKReturn.put("ZRSV09", "");
			oKReturn.put("ZRSV10", "");
			
			WMSToSAPReturn WMSToSAPReturn = new WMSToSAPReturn(head, oKReturn);		
//			MessageLogUtil.insertSapMessageLog(httpRequest.getRequestURL().toString(), "S", request, "materialspec", WMSToSAPReturn);
			ErpMessageLog erpMessageLog = new ErpMessageLog();
			erpMessageLog.setServerName(System.getProperty("Seq"));
			erpMessageLog.setEventName(httpRequest.getRequestURL().toString());
			erpMessageLog.setId(new TimeUtils().getCurrentEventTimeKey());
			erpMessageLog.setResultCode("S");
			erpMessageLog.setSendMsg(JSONObject.toJSONString(request));
			erpMessageLog.setMessageId("materialspec");
			erpMessageLog.setReturnMsg(JSONObject.toJSONString(WMSToSAPReturn));
			erpMessageLog.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
			MessageLogUtil.writeMessageLog(erpMessageLog);
			IDMFrameServiceProxy.getTransactionManager().commitTransaction();
			return WMSToSAPReturn;
		} catch (Exception e) {
			IDMFrameServiceProxy.getTransactionManager().rollbackTransaction();
			Map<String, Object> errorReturn = new HashMap<>();
			errorReturn.put("STATUS", "E");
			errorReturn.put("MSGTXT", "物料主数据下发失败 " + e.getMessage());
			errorReturn.put("HEAD", request.getHEAD());
			//errorReturn.put("BODY", request.getBODY());
			
			WMSToSAPReturn WMSToSAPReturn = new WMSToSAPReturn(head, errorReturn);
			ErpMessageLog erpMessageLog = new ErpMessageLog();
			erpMessageLog.setServerName(System.getProperty("Seq"));
			erpMessageLog.setEventName(httpRequest.getRequestURL().toString());
			erpMessageLog.setId(new TimeUtils().getCurrentEventTimeKey());
			erpMessageLog.setResultCode("E");
			erpMessageLog.setSendMsg(JSONObject.toJSONString(request));
			erpMessageLog.setMessageId("materialspec");
			erpMessageLog.setReturnMsg(JSONObject.toJSONString(WMSToSAPReturn));
			erpMessageLog.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
			MessageLogUtil.writeMessageLog(erpMessageLog);
			return WMSToSAPReturn;
		}
	}

	// 采购订单下发
	@RequestMapping("/materialReceiveRequest")
	public WMSToSAPReturn GetMaterialReceiveRequest(HttpServletRequest httpRequest, @RequestBody SAPToWMSRequest request) {
		Map<String,Object> head = request.getHEAD();
		boolean isOEM = false; //设置该单据是否是OEM委外订单的标识
		IDMFrameServiceProxy.getTransactionManager().beginTransaction();
		try {
			ArrayList<Map<String,Object>> datas = request.getBODY();
			String sitename = System.getProperty("company");
			for (Map<String, Object> data : datas) {
				String receiveRequestName = MapUtils.getString(data, "EBELN");  // 采购订单号
		        if(StringUtils.isEmpty(receiveRequestName)) {
		        	throw new Exception("ERP发送过来的采购订单号不存在");
		        }
				String receiveRequestType = MapUtils.getString(data, "BSART");  // 订单类型
		        String receiveRequestTypeDes = MapUtils.getString(data, "BATXT");  // 订单类型描述
		        String startDate = MapUtils.getString(data, "KDATB");  // 有效开始时间
		        String endDate = MapUtils.getString(data, "KDATE");  // 有效结束时间
		        String frgsx = MapUtils.getString(data, "FRGSX");  // 审批策略
		        String frgzu = MapUtils.getString(data, "FRGZU");  // 发布状态
		        String supplierNo = MapUtils.getString(data, "LIFNR"); // 供应商编码
		        String supplierName = MapUtils.getString(data, "NAME1"); // 供应商名称
		        String bedat = MapUtils.getString(data, "BEDAT");  // 凭证日期
		        String bukrs = MapUtils.getString(data, "BUKRS");  // 公司代码
		        String butxt = MapUtils.getString(data, "BUTXT");  // 公司名称
		        String purchaseOrgnization = MapUtils.getString(data, "EKORG");  // 采购组织
		        String purchaseOrgnizationDes = MapUtils.getString(data, "EKOTX");  // 采购组织描述
		        String purchaseOrderGroup = MapUtils.getString(data, "EKGRP");  // 采购组
		        String purchaseOrgnizationGroupDes = MapUtils.getString(data, "EKNAM");  // 采购组描述
		        String inco1 = MapUtils.getString(data, "INCO1");  // 国际贸易条款
		        String inco2 = MapUtils.getString(data, "INCO2");  // 国际贸易位置
				
		        String currentEventTimeKey = TimeStampUtil.getCurrentEventTimeKey();
				Timestamp currentTimestamp = TimeStampUtil.getCurrentTimestamp();

				String sqlCheck ="SELECT * FROM materialreceiverequest WHERE receiverequestname =:receiverequestname";
				Map<String, Object> selectMap= new HashMap<String, Object>();
				selectMap.put("receiverequestname", receiveRequestName);
				List<Map<String, Object>> checkResultList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sqlCheck, selectMap);
				if(checkResultList == null || checkResultList.size() == 0) {
					CreateReceiveRequestInfo createInfo = new CreateReceiveRequestInfo();
					createInfo.setSiteName(sitename);
					createInfo.setReceiveRequestName(receiveRequestName);
					createInfo.setReceiveRequestType(receiveRequestType);
					createInfo.setSupplierNO(supplierNo);
					createInfo.setPurchaseOrderGroup(purchaseOrderGroup);
					createInfo.setReceiveRequestState("Created");
					createInfo.setSystemType("ERP");
					Map<String, Object> bindMap = new HashMap<String, Object>();
					bindMap.put("stockOrgNo", bukrs);
					bindMap.put("purOrgNo", purchaseOrgnization);
					bindMap.put("orderDate",TimeStampUtil.getTimestamp(bedat)); //凭证日期
					bindMap.put("effectiveStartTime", TimeStampUtil.getTimestamp(startDate));
					bindMap.put("effectiveEndTime", TimeStampUtil.getTimestamp(endDate));
					createInfo.setUserColumns(bindMap);
					
					EventInfo eventInfo = new EventInfo();
					eventInfo.setEventName("MaterialReceiveRequestSAPToWMS");
					eventInfo.setEventUser("SAP");
					
					MaterialReceiveRequestServiceProxy.getMaterialReceiveRequestService().create(eventInfo, createInfo); 
					
					MaterialReceiveRequestServiceImpl receiveRequestImpl = new MaterialReceiveRequestServiceImpl();
					receiveRequestImpl.createSupplier(supplierNo, supplierName, "", "", "", "", "", "");
				}else {
					SetEventInfo info = new SetEventInfo();
					
					MaterialReceiveRequestKey key = new MaterialReceiveRequestKey();
					key.setSiteName(sitename); 
					key.setReceiveRequestName(receiveRequestName);
					
					Map<String, Object> bindMap = new HashMap<String, Object>();
					bindMap.put("receiveRequestType", receiveRequestType);
					bindMap.put("supplierNO", supplierNo);
					bindMap.put("purchaseOrderGroup", purchaseOrderGroup);
					bindMap.put("purOrgNo", purchaseOrgnization);
					bindMap.put("stockOrgNo", bukrs);
					bindMap.put("orderDate",TimeStampUtil.getTimestamp(bedat)); //凭证日期
					bindMap.put("effectiveStartTime", TimeStampUtil.getTimestamp(startDate));
					bindMap.put("effectiveEndTime", TimeStampUtil.getTimestamp(endDate));
					info.setUserColumns(bindMap);
					
					EventInfo eventInfo = new EventInfo();
					eventInfo.setEventName("UpdateMaterialReceiveRequest");
					eventInfo.setEventUser("SAP");
					MaterialReceiveRequestServiceProxy.getMaterialReceiveRequestService().setEvent(key, eventInfo, info);
				}
				if(data.containsKey("ITEM")) {
					// 详情
					ArrayList Items = (ArrayList)data.get("ITEM");
					
					for (int i=0; i < Items.size(); i++) {
						Map<String,Object> item = (Map<String,Object>)Items.get(i);
						String receiveRequestDetailName = MapUtils.getString(item, "EBELP");  // 订单行项目
				        String pstyp = MapUtils.getString(item, "PSTYP");  // 项目类别  L表示委外订单(O库存),    K是寄售(K库存） --供应商
				        String knttp = MapUtils.getString(item, "KNTTP");  // 科目分配类别  E/M代表销售
				        String materialSpecName = MapUtils.getString(item, "MATNR");  // 物料编号
				        String description = MapUtils.getString(item, "TXZ01");  //物料描述
				        String requestQty = MapUtils.getString(item, "MENGE"); // 订单数量
				        String unit = MapUtils.getString(item, "MEINS");  // 单位
				        String erpFactory = MapUtils.getString(item, "WERKS");  // ERP工厂
				        String erpFactoryName = MapUtils.getString(item, "NAME1");  // ERP工厂名称
				        String erpLocation = MapUtils.getString(item, "LGORT");  // ERP库存地点
				        String erpLocationDes = MapUtils.getString(item, "LGOBE");  // ERP库存地点描述
				        String deliveryDate = MapUtils.getString(item, "EINDT");  // 交货日期

				        String zywy = MapUtils.getString(item, "ZYWY");  // 业务员
				        String zywzl = MapUtils.getString(item, "ZYWZL");  // 业务助理
				        String zsyb = MapUtils.getString(item, "ZSYB");  // 事业部
				        String applicant = MapUtils.getString(item, "AFRAM");  // 申请人
				        String returnFlag = MapUtils.getString(item, "RETPO");  // 退货标识, 退货项目  EKPO
				        String innerOrder = MapUtils.getString(item, "AUFNR"); //内部定单号
				        String freeFlag = MapUtils.getString(item, "UMSON");  // 免费标识
				        String finishFlag = MapUtils.getString(item, "ELIKZ"); // 交货完成标识 EKPO
				        String costCenter = MapUtils.getString(item, "KOSTL");  // 成本中心
				        String costCenterDes = MapUtils.getString(item, "KTEXT");  // 成本中心没描述
				        String orderChangeDate = MapUtils.getString(item, "AEDAT");  // 订单更改日期

				        String zwmscharg = MapUtils.getString(item, "ZWMSCHARG");  // 退货WMS批次号
				        String zpotaxt = MapUtils.getString(item, "ZPOTAXT"); // 采购申请备注信息
				        String banfn = MapUtils.getString(item, "BANFN");  // 采购申请单号
				        String bnfpo = MapUtils.getString(item, "BNFPO");  // 采购申请行号
				        String loekz = MapUtils.getString(item, "LOEKZ");  // 订单行项目删除标识
				        String zzywy = MapUtils.getString(item, "ZZYWY");  // 业务员
				        String zzywzl = MapUtils.getString(item, "ZZYWZL");  // 业务助理
				        String zzsyb = MapUtils.getString(item, "ZZSYB");  // 事业部
						if("X".equals(loekz)) {					
							String sql="DELETE FROM materialreceivedetail WHERE receiverequestname=? AND receiverequestdetailname=?";
							Object[] obj=new Object[] {receiveRequestName, receiveRequestDetailName};
							IDMFrameServiceProxy.getSqlTemplate().update(sql, obj);
						}else {
							String sqlItemCheck ="SELECT * FROM materialreceiverequestdetail WHERE receiverequestname =:receiverequestname and receiverequestdetailname = :receiverequestdetailname";
							Map<String, Object> selectItemMap= new HashMap<String, Object>();
							selectItemMap.put("receiverequestname", receiveRequestName);
							selectItemMap.put("receiverequestdetailname", receiveRequestDetailName);
							
							List<Map<String, Object>> checkItemResultList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sqlItemCheck, selectItemMap);

							MaterialReceiveRequestDetail mrd =new MaterialReceiveRequestDetail();
							MaterialReceiveRequestDetailKey mrdk=new MaterialReceiveRequestDetailKey();
							mrdk.setSiteName(sitename);
							mrdk.setReceiveRequestName(receiveRequestName);
							mrdk.setReceiveRequestDetailName(receiveRequestDetailName);
							
							if (checkItemResultList == null || checkItemResultList.size() == 0) {
								CreateReceiveRequestDetailInfo createInfo = new CreateReceiveRequestDetailInfo();
								/*
								 * createInfo.setSiteName(sitename); createInfo.setReceiveRequestName(ebeln);
								 * createInfo.setReceiveRequestDetailName(ebelp);
								 */
								createInfo.setSiteName(sitename);
								createInfo.setReceiveRequestName(receiveRequestName);
								createInfo.setReceiveRequestDetailName(receiveRequestDetailName);
								createInfo.setReceiveRequestDetailType(knttp); //针对销售订单  E库存
								createInfo.setPocategory(pstyp); //针对 供应商的， L表示委外订单， K表示寄售
								createInfo.setMaterialSpecName(materialSpecName);
								createInfo.setErpLocation(erpLocation);
								createInfo.setRequestQuantity(Float.parseFloat(requestQty));
								createInfo.setReceivedQuantity(0);
								createInfo.setCreateUser("SAP");
								createInfo.setIqcFlag("");
								createInfo.setHoldState("");
								createInfo.setCreateTime(currentTimestamp);
								//createInfo.setPlanDate(ConvertUtil.convertToTimeStamp(eindt));
								createInfo.setFreeFlag(freeFlag);
								createInfo.setForceCompletedFlag("");
								createInfo.setReturnFlag(returnFlag); //退货标识
								
								if (StringUtils.isNotEmpty(deliveryDate)) {
									createInfo.setPlanDate(TimeStampUtil.getTimestamp(deliveryDate));
								}
								Map<String, Object> bindMapItem = new HashMap<String, Object>();
								bindMapItem.put("erpFactory", erpFactory); // 工厂
								bindMapItem.put("materialUnit", unit);
								bindMapItem.put("innerOrder", innerOrder); // 内部定单号
								bindMapItem.put("finishFlag", finishFlag); //交货完成标识
								bindMapItem.put("costCenter", costCenter); //成本中心
								bindMapItem.put("orderChangeDate", TimeStampUtil.getTimestamp(orderChangeDate)); //订单更改日期
								bindMapItem.put("wmsReturnChargeNo", zwmscharg);
								bindMapItem.put("purchaseRequestNote", zpotaxt);
								bindMapItem.put("purchaseRequestNo", banfn);
								bindMapItem.put("purchaseRequestDetailNo", bnfpo);
								bindMapItem.put("deleteDetailFlag", loekz);
								bindMapItem.put("salesman", zzywy);
								bindMapItem.put("salesAssistant", zzywzl);
								bindMapItem.put("businessDivision", zzsyb);
								
								//bindMapItem.put("salesOrder", ""); // 销售订单
								//bindMapItem.put("salesOrderDetailNo", "" ); // 销售订单行项目
								//bindMapItem.put("costCenter", costCenter ); // 成本中心
								//bindMapItem.put("unit", unit);  // 订单单位
								//bindMapItem.put("charge", "");
								//bindMapItem.put("description", description);
								//bindMapItem.put("modelName", "");
								//bindMapItem.put("assignqty", Float.parseFloat(receivedQuantity));
								createInfo.setUserColumns(bindMapItem);
								EventInfo eventInfo = new EventInfo();
								eventInfo.setEventTime(TimeStampUtil.getCurrentTimestamp());
								eventInfo.setEventUser("SAP");
								eventInfo.setEventName("CreateMaterialReceiveRequestDetail");
								
								mrd = ReceiveRequestDetailServiceProxy.getReceiveRequestDetailService().create(mrdk, eventInfo, createInfo);
								
								
							} else {
								// 注：判断是否已收货，已收不可更新
								com.cim.idm.wmspackage.receiverequestdetail.management.info.SetEventInfo info = new com.cim.idm.wmspackage.receiverequestdetail.management.info.SetEventInfo();
								
								mrd = ReceiveRequestDetailServiceProxy.getReceiveRequestDetailService().selectByKey(mrdk);
								//float assignQty = mrd.getAssignqty();
								if(!"Y".equals(mrd.getFinishFlag())) {
									Map<String, Object> bindMapItem = new HashMap<String, Object>();
//									bindMapItem.put("receiveRequestDetailType", knttp);
//									bindMapItem.put("pocategory", pstyp);
									bindMapItem.put("materialSpecName", materialSpecName);
									bindMapItem.put("erpLocation", erpLocation);
									bindMapItem.put("createUser", "SAP");
									bindMapItem.put("createTime",currentTimestamp);
									bindMapItem.put("freeFlag", freeFlag);
									bindMapItem.put("iqcFlag", "");
									bindMapItem.put("erpFactory", erpFactory); // 工厂
									bindMapItem.put("requestQuantity", Float.parseFloat(requestQty));
									bindMapItem.put("materialUnit", unit);
									bindMapItem.put("innerOrder", innerOrder); // 内部定单号
									bindMapItem.put("finishFlag", finishFlag); //交货完成标识
									bindMapItem.put("costCenter", costCenter); //成本中心
									bindMapItem.put("orderChangeDate", TimeStampUtil.getTimestamp(orderChangeDate)); //订单更改日期
									bindMapItem.put("wmsReturnChargeNo", zwmscharg);
									bindMapItem.put("purchaseRequestNote", zpotaxt);
									bindMapItem.put("purchaseRequestNo", banfn);
									bindMapItem.put("purchaseRequestDetailNo", bnfpo);
									bindMapItem.put("deleteDetailFlag", loekz);
									bindMapItem.put("salesman", zzywy);
									bindMapItem.put("salesAssistant", zzywzl);
									bindMapItem.put("businessDivision", zzsyb);
									//bindMapItem.put("salesOrder", "" ); // 销售订单
									//bindMapItem.put("salesOrderDetailNo", "" ); // 销售订单行项目
									//bindMapItem.put("passState", passState); // 退货项目
									//bindMapItem.put("costCenter", costCenter ); // 成本中心
									//bindMapItem.put("unit", unit);  // 订单单位
									//bindMapItem.put("description",description);
									//bindMapItem.put("modelName", "");
									if (StringUtils.isNotEmpty(deliveryDate)) {
										Timestamp planTime = TimeStampUtil.getTimestamp(deliveryDate);
										bindMapItem.put("planDate", planTime);
									}
									bindMapItem.put("returnFlag", returnFlag);  // 退货PO标识
									info.setUserColumns(bindMapItem);
									EventInfo eventInfo = new EventInfo();
									eventInfo.setEventTime(TimeStampUtil.getCurrentTimestamp());
									eventInfo.setEventUser("SAP");
									eventInfo.setEventName("UpdateMaterialReceiveRequest");
									ReceiveRequestDetailServiceProxy.getReceiveRequestDetailService().setEvent(mrdk, eventInfo, info);
								}
								
							}	
						}
						// ET_BOM表结构
						String insertETBOMSql = "INSERT INTO ET_BOM (RECEIVEREQUESTNAME, RECEIVEREQUESTDETAILNAME, ETBOMNO, MATERIALSPECNAME, MATERIALDEC, REQUESTQTY, UNIT, ERPFACTORY, ERPLOCATION, ERPLOCATIONDEC) " +
								"VALUES(:RECEIVEREQUESTNAME, :RECEIVEREQUESTDETAILNAME, :ETBOMNO, :MATERIALSPECNAME, :MATERIALDEC, :REQUESTQTY, :UNIT, :ERPFACTORY, :ERPLOCATION, :ERPLOCATIONDEC)";

						String updateETBOMSql = "UPDATE ET_BOM SET MATERIALSPECNAME = :MATERIALSPECNAME, MATERIALDEC = :MATERIALDEC, REQUESTQTY = :REQUESTQTY, UNIT = :UNIT, ERPFACTORY = :ERPFACTORY, ERPLOCATION = :ERPLOCATION, ERPLOCATIONDEC = :ERPLOCATIONDEC " +
								"WHERE RECEIVEREQUESTNAME = :RECEIVEREQUESTNAME AND RECEIVEREQUESTDETAILNAME = :RECEIVEREQUESTDETAILNAME AND ETBOMNO = :ETBOMNO";
						if (item.containsKey("ET_BOM")) {
							// 因BOM 用于物料发料，类似于领料出库， 故将信息存到 MaterialShipRequest 与 MaterialShipReqeustDetail 中
							if(StringUtils.equals(pstyp, "3")) { //L表示委外采购订单
								isOEM = true;
								String sql =" SELECT * FROM materialshiprequest m WHERE shiprequestname =:SHIPREQUESTNAME ";
								Map<String, Object> bindMap= new HashMap<String, Object>();
								bindMap.put("SHIPREQUESTNAME", receiveRequestName);
								List<Map<String, Object>> resultList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, bindMap);
								if(resultList != null && resultList.size() > 0) {
									//找到委外采购订单已存在，更新现有的MaterialShipRequest中的委外采购订单
									MaterialShipRequestSetEventInfo info = new MaterialShipRequestSetEventInfo();
									MaterialShipRequestKey key = new MaterialShipRequestKey();
									key.setSiteName(sitename);
									key.setShipRequestName(receiveRequestName);

									MaterialShipRequest shipRequest=MaterialShipRequestServiceProxy.getMaterialShipRequestService().selectByKey(key);

									if (!shipRequest.getShipRequestState().equalsIgnoreCase("Created")) {
										throw new CustomException("ERROR","交货单已确认，禁止修改!");
									}

									Map<String, Object> bind = new HashMap<String, Object>();
									//bindMap.put("salesGroup", saleGroup);
									bind.put("shipRequestType", "OEM");
									bind.put("shipRequestDetailType", "541");
									bind.put("createUser", applicant);
									bind.put("createTime", orderChangeDate);
									bind.put("erpFactory", erpFactory);
									//供应商编码，用于委外发料回传
									bind.put("deliveryAddress", supplierNo);

									info.setUserColumns(bind);

									EventInfo eventInfo = new EventInfo();
									eventInfo.setEventName("UpdateMaterialShipRequest");
									eventInfo.setEventUser("SAP");
									MaterialShipRequestServiceProxy.getMaterialShipRequestService().setEvent(key, eventInfo, info);
								} else {
									//未发现委外采购订单， 创建委外采购订单至 MaterialShipRequest
									CreateMaterialShipRequestInfo createInfo = new CreateMaterialShipRequestInfo();
									createInfo.setSiteName(sitename);
									createInfo.setShipRequestName(receiveRequestName);
									createInfo.setShipRequestType("OEM");
									createInfo.setShipRequestDetailType("541");
									createInfo.setShipRequestState("Created");
									createInfo.setSystemType("ERP");
									Map<String, Object> bind = new HashMap<String, Object>();
									bind.put("createUser", applicant);
									bind.put("createTime", orderChangeDate);
									bind.put("erpFactory", erpFactory);
									//供应商编码，用于委外发料回传
									bind.put("deliveryAddress", supplierNo);
									createInfo.setUserColumns(bind);

									EventInfo eventInfo = new EventInfo();
									eventInfo.setEventName("MaterialShipRequestSAPToWMS");
									eventInfo.setEventUser("SAP");

									MaterialShipRequestServiceProxy.getMaterialShipRequestService().create(eventInfo, createInfo);
								}
							}
							List<Map<String,Object>> etBomItems = (List<Map<String,Object>>)item.get("ET_BOM");
							for (int k = 0; k < etBomItems.size(); k++) {
								Map<String,Object> etItem = etBomItems.get(k);
								String rspos = MapUtils.getString(etItem, "RSPOS");  // 组件项目
						        String matnr = MapUtils.getString(etItem, "MATNR");  // 组件物料编码
						        String maktx = MapUtils.getString(etItem, "MAKTX");  // 组件物料描述
						        String etBomQty = MapUtils.getString(etItem, "BDMNG");  // 需求数量
						        String unit1 = MapUtils.getString(etItem, "MEINS");  // 单位，重复
								String erpfactoryItem = MapUtils.getString(etItem, "WERKS");  // erp工厂,item
								String erplocationItem = MapUtils.getString(etItem, "LGORT");  // erp库位,item
								String erplocationItemDec = MapUtils.getString(etItem, "LGOBE");  // erp库位描述
								
								Map<String, Object> etBomMap = new HashMap<String, Object>();
								etBomMap.put("RECEIVEREQUESTNAME", receiveRequestName);
								etBomMap.put("RECEIVEREQUESTDETAILNAME", receiveRequestDetailName);
								etBomMap.put("ETBOMNO", rspos);
								etBomMap.put("MATERIALSPECNAME", matnr);
								etBomMap.put("MATERIALDEC", maktx);
								etBomMap.put("REQUESTQTY", etBomQty);
								etBomMap.put("UNIT", unit1);
								etBomMap.put("ERPFACTORY", erpfactoryItem);
								etBomMap.put("ERPLOCATION", erplocationItem);
								etBomMap.put("ERPLOCATIONDEC", erplocationItemDec);
								
								String selectSql="SELECT RECEIVEREQUESTNAME, RECEIVEREQUESTDETAILNAME, ETBOMNO "
										+ "FROM ET_BOM eb " + SystemPropHelper.CR +
										"WHERE eb.RECEIVEREQUESTNAME = ? "
										+ "AND RECEIVEREQUESTDETAILNAME = ? "
										+ "AND ETBOMNO = ?  " ;
								Object[] selectObj=new Object[] {receiveRequestName, receiveRequestDetailName, rspos};
								List<Map<String, Object>> selectList = IDMFrameServiceProxy.getSqlTemplate().queryForList(selectSql, selectObj);
//								IDMFrameServiceProxy.getSqlTemplate().update(insertETBOMSql, etBomMap);
								if(selectList.size() == 0) {	
									IDMFrameServiceProxy.getSqlTemplate().update(insertETBOMSql, etBomMap);
								} else {						
									IDMFrameServiceProxy.getSqlTemplate().update(updateETBOMSql, etBomMap);
								}


							}
						}

					}
				}
				//如果是 OEM， 则将 BOM信息存到 MATERIALSHIPREQUEST 与 MATERIALSHIPREQUESTDETAIL
				//将委外采购订单ET_BOM 存到 MaterialShipRequestDetail
				if(isOEM) { //L表示委外采购订单
					StringBuffer sqlsb = new StringBuffer();
					sqlsb.append(SystemPropHelper.CR)
					  .append("SELECT MATERIALSPECNAME, ERPFACTORY, UNIT, SUM(REQUESTQTY) REQUESTQTY") .append(SystemPropHelper.CR)
					  .append("  FROM ET_BOM ").append(SystemPropHelper.CR)
					  .append(" WHERE RECEIVEREQUESTNAME = :RECEIVEREQUESTNAME").append(SystemPropHelper.CR)
					  .append("GROUP BY MATERIALSPECNAME, ERPFACTORY, UNIT").append(SystemPropHelper.CR)
					  .append("ORDER BY MATERIALSPECNAME, ERPFACTORY, UNIT");
					Map<String,Object> binding = new HashMap<>();
					binding.put("RECEIVEREQUESTNAME", receiveRequestName);
					List<Map<String, Object>> list = IDMFrameServiceProxy.getSqlTemplate().queryForList(sqlsb.toString(), binding);
					if(list!=null && list.size()>0) {
						for(int j = 0; j< list.size(); j++) {
							String checkExitSql = "SELECT 1 FROM MATERIALSHIPREQUESTDETAIL WHERE SHIPREQUESTNAME = :SHIPREQUESTNAME AND MATERIALSPECNAME = :MATERIALSPECNAME and UNIT = :UNIT AND ERPFACTORY = :ERPFACTORY";
							binding.clear();
							binding.put("SHIPREQUESTNAME", receiveRequestName);
							binding.put("MATERIALSPECNAME", list.get(j).get("MATERIALSPECNAME"));
							binding.put("UNIT", list.get(j).get("UNIT"));
							binding.put("ERPFACTORY", list.get(j).get("ERPFACTORY"));
							List<Map<String, Object>> checkExistResult = IDMFrameServiceProxy.getSqlTemplate().queryForList(checkExitSql, binding);
							if(checkExistResult == null || checkExistResult.size() ==0) {
								//将信息存到 MaterialShipRequestDetail
								CreateMaterialShipRequestDetailInfo createInfo = new CreateMaterialShipRequestDetailInfo();
								createInfo.setSiteName(sitename);
								createInfo.setShipRequestName(receiveRequestName);
								createInfo.setShipRequestDetailName(String.valueOf(j+1));
								createInfo.setMaterialSpecName((String)list.get(j).get("MATERIALSPECNAME"));
								createInfo.setRequestQuantity(((BigDecimal)list.get(j).get("REQUESTQTY")).floatValue());
								createInfo.setAssignedQuantity(0);
								Map<String, Object> bindMapItem = new HashMap<String, Object>();
								bindMapItem.put("erpFactory", list.get(j).get("ERPFACTORY")); // 工厂
								//
								bindMapItem.put("unit", list.get(j).get("UNIT"));

								createInfo.setUserColumns(bindMapItem);
								EventInfo eventInfo = new EventInfo();
								eventInfo.setEventTime(TimeStampUtil.getCurrentTimestamp());
								eventInfo.setEventUser("SAP");
								eventInfo.setEventName("CreateMaterialShipRequest");

								MaterialShipRequestDetailServiceProxy.getMaterialShipRequestDetailService().create( createInfo);
							}else {
								//MaterialShipRequestDetail信息已存在，进行更新
								String updateSql = "UPDATE MATERIALSHIPREQUESTDETAIL SET REQUESTQUANTITY = :REQUESTQUANTITY" +SystemPropHelper.CR +
								"WHERE SHIPREQUESTNAME = :SHIPREQUESTNAME AND MATERIALSPECNAME = :MATERIALSPECNAME and UNIT = :UNIT AND ERPFACTORY = :ERPFACTORY";
								Map<String, Object> bindMapItem = new HashMap<String, Object>();
								bindMapItem.put("REQUESTQUANTITY", list.get(j).get("REQUESTQTY"));
								bindMapItem.put("ERPFACTORY", list.get(j).get("ERPFACTORY"));// 工厂
								bindMapItem.put("SHIPREQUESTNAME",receiveRequestName );
								bindMapItem.put("MATERIALSPECNAME", (String)list.get(j).get("MATERIALSPECNAME"));
								bindMapItem.put("UNIT", list.get(j).get("UNIT"));
								IDMFrameServiceProxy.getSqlTemplate().update(updateSql, bindMapItem);
							}
						}
					}
				}
			}
			
			Map<String, Object> oKReturn = new HashMap<>();
			
			oKReturn.put("STATUS", "S");
			oKReturn.put("MSGTXT", "采购订单下发成功");
			oKReturn.put("ZRSV01", "");
			oKReturn.put("ZRSV02", "");
			oKReturn.put("ZRSV03", "");
			oKReturn.put("ZRSV04", "");
			oKReturn.put("ZRSV05", "");
			oKReturn.put("ZRSV06", "");
			oKReturn.put("ZRSV07", "");
			oKReturn.put("ZRSV08", "");
			oKReturn.put("ZRSV09", "");
			oKReturn.put("ZRSV10", "");
			
			WMSToSAPReturn WMSToSAPReturn = new WMSToSAPReturn(head, oKReturn);	
//			MessageLogUtil.insertSapMessageLog(httpRequest.getRequestURL().toString(), "S", request, "materialReceiveRequest", WMSToSAPReturn);
			ErpMessageLog erpMessageLog = new ErpMessageLog();
			erpMessageLog.setServerName(System.getProperty("Seq"));
			erpMessageLog.setEventName(httpRequest.getRequestURL().toString());
			erpMessageLog.setId(new TimeUtils().getCurrentEventTimeKey());
			erpMessageLog.setResultCode("S");
			erpMessageLog.setSendMsg(JSONObject.toJSONString(request));
			erpMessageLog.setMessageId("materialReceiveRequest");
			erpMessageLog.setReturnMsg(JSONObject.toJSONString(WMSToSAPReturn));
			erpMessageLog.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
			MessageLogUtil.writeMessageLog(erpMessageLog);
			IDMFrameServiceProxy.getTransactionManager().commitTransaction();
			return WMSToSAPReturn;
		} catch (Exception e) {
			IDMFrameServiceProxy.getTransactionManager().rollbackTransaction();
			Map<String, Object> errorReturn = new HashMap<>();
			errorReturn.put("STATUS", "E");
			errorReturn.put("MSGTXT", "采购订单下发失败 " + e.getMessage());
			errorReturn.put("HEAD", request.getHEAD());
			//errorReturn.put("BODY", request.getBODY());
			
			WMSToSAPReturn WMSToSAPReturn = new WMSToSAPReturn(head, errorReturn);
//			MessageLogUtil.insertSapMessageLog(httpRequest.getRequestURL().toString(), "E", request, "materialReceiveRequest", WMSToSAPReturn);

			ErpMessageLog erpMessageLog = new ErpMessageLog();
			erpMessageLog.setServerName(System.getProperty("Seq"));
			erpMessageLog.setEventName(httpRequest.getRequestURL().toString());
			erpMessageLog.setId(new TimeUtils().getCurrentEventTimeKey());
			erpMessageLog.setResultCode("E");
			erpMessageLog.setSendMsg(JSONObject.toJSONString(request));
			erpMessageLog.setMessageId("materialReceiveRequest");
			erpMessageLog.setReturnMsg(JSONObject.toJSONString(WMSToSAPReturn));
			erpMessageLog.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
			MessageLogUtil.writeMessageLog(erpMessageLog);
			return WMSToSAPReturn;
		}
	}
	
	// 预留单、领料单下发
	@RequestMapping("/materialShipRequest")
	public WMSToSAPReturn materialShipRequest(HttpServletRequest httpRequest, @RequestBody SAPToWMSRequest request) {
		Map<String,Object> head = request.getHEAD();
		IDMFrameServiceProxy.getTransactionManager().beginTransaction();
		try {
			String shipRequestName ="";
			ArrayList<Map<String,Object>> datas = request.getBODY();
			String sitename = System.getProperty("company");
			for (Map<String, Object> data : datas) {
				shipRequestName = MapUtils.getString(data, "ZDNUM");  // 领料单、预留订单号
				String erpFactory = MapUtils.getString(data, "WERKS");  // ERP工厂
				String shipRequestType =  MapUtils.getString(data, "ZDTYP");  // 单据类型
				String createUser = MapUtils.getString(data, "ZZDR");  // 制单人
				String createDate = MapUtils.getString(data, "CRDAT"); // 创建日期
				String createTime = MapUtils.getString(data, "CRTIM"); // 创建时间
				String moveState = MapUtils.getString(data, "BWART"); //移动类型 BWART
				String sqlCheck =" SELECT * FROM materialshiprequest m WHERE shiprequestname =:SHIPREQUESTNAME ";
				Map<String, Object> selectMap= new HashMap<String, Object>();
				selectMap.put("SHIPREQUESTNAME", shipRequestName);
				List<Map<String, Object>> checkResultList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sqlCheck, selectMap);
				
				if(checkResultList == null || checkResultList.size() == 0) {
					CreateMaterialShipRequestInfo createInfo = new CreateMaterialShipRequestInfo();
					createInfo.setSiteName(sitename);
					createInfo.setShipRequestName(shipRequestName);
					createInfo.setShipRequestType(shipRequestType);
//					createInfo.setShipRequestDetailType(shiprequesttype);
					createInfo.setShipRequestDetailType(moveState);
					createInfo.setShipRequestState("Created");
					createInfo.setSystemType("ERP");			
					Map<String, Object> bindMap = new HashMap<String, Object>();
					bindMap.put("createUser", createUser);
					bindMap.put("createTime", createDate+" "+createTime);
					bindMap.put("erpFactory", erpFactory);
					createInfo.setUserColumns(bindMap);
					
					EventInfo eventInfo = new EventInfo();
					eventInfo.setEventName("MaterialShipRequestSAPToWMS");
					eventInfo.setEventUser(createUser);
					
					MaterialShipRequestServiceProxy.getMaterialShipRequestService().create(eventInfo, createInfo);
				}else {
					MaterialShipRequestSetEventInfo info = new MaterialShipRequestSetEventInfo();
					MaterialShipRequestKey key = new MaterialShipRequestKey();
					key.setSiteName(sitename); 
					key.setShipRequestName(shipRequestName);
					
					MaterialShipRequest shipRequest=MaterialShipRequestServiceProxy.getMaterialShipRequestService().selectByKey(key);
					
					if (!shipRequest.getShipRequestState().equalsIgnoreCase("Created")) {
						throw new CustomException("ERROR","交货单已确认，禁止修改!");
					}
					
					Map<String, Object> bindMap = new HashMap<String, Object>();
					//bindMap.put("salesGroup", saleGroup);
					bindMap.put("shipRequestType", shipRequestType);
					bindMap.put("shipRequestDetailType", moveState);
					bindMap.put("createUser", createUser);
					bindMap.put("createTime", createTime);
					bindMap.put("erpFactory", erpFactory);
					
					info.setUserColumns(bindMap);
					
					EventInfo eventInfo = new EventInfo();
					eventInfo.setEventName("UpdateMaterialShipRequest");
					eventInfo.setEventUser(createUser);
					MaterialShipRequestServiceProxy.getMaterialShipRequestService().setEvent(key, eventInfo, info);
				}
				String bwart="";//移动类型。因领料单下发未发送移动类型，故再单独更新,当LGORT2为空时更新为261，否则更新为311。zd.2024.8.7
				if (data.containsKey("ITEM")) {
					// 详情
					ArrayList Items = (ArrayList)data.get("ITEM");
					for (int i=0; i < Items.size(); i++) {

						Map<String,Object> item = (Map<String,Object>)Items.get(i);
						
						String shipRequestDetailName = MapUtils.getString(item, "ZITEM");  //单据行号
						String reservedNumber = MapUtils.getString(item, "RSNUM");  // 预留编号
						String reservedProjectNumb = MapUtils.getString(item, "RSPOS");  // 预留项目号
						String receiveProductionOrderNumber =StringUtils.substring(MapUtils.getString(item, "AUFNR1"),4) ;  // 接收生产订单编号

						String issueProductionOrderNumber = MapUtils.getString(item, "AUFNR2");  // 发出生产订单编号
						String combinationOrderNumber = MapUtils.getString(item, "AUFNR3");  // 组合订单编号
						String productionSupervisor = MapUtils.getString(item, "FEVOR");  // 生产主管
						String costCenter = MapUtils.getString(item, "KOSTL");  // 成本中心
						String materialSpecName = MapUtils.getString(item, "MATNR");  // 物料号
						String werks1 = MapUtils.getString(item, "WERKS1"); // 发出工厂
						String lgort1 = MapUtils.getString(item, "LGORT1"); // 发出仓库
						String werks2 = MapUtils.getString(item, "WERKS2"); // 接收工厂
						String lgort2 = MapUtils.getString(item, "LGORT2"); // 接收仓库
						
						if(StringUtils.isEmpty(moveState)) 
						{
							if(StringUtils.isEmpty(lgort2)) 
							{
								bwart="261";
							}
							else 
							{
								bwart="311";
							}
						}
						String zspec = MapUtils.getString(item, "ZSPEC"); // 规格
						String useDate = MapUtils.getString(item, "ZXQRQ"); // 需用日期
						String requestQuantity = MapUtils.getString(item, "ZSQSL"); // 数量
						String unit = MapUtils.getString(item, "MEINS"); // 单位
						String charge = MapUtils.getString(item, "ZBATCH");  // 批次
						String sendSalesOrder = MapUtils.getString(item, "KDAUF1");  // 发出销售订单号
						String sendSalesOrderDetailNo = MapUtils.getString(item, "KDPOS1");  // 发出销售订单行号
						String receiveSalesOrder = MapUtils.getString(item, "KDAUF2");  // 接收销售订单号
						String receiveSalesOrderDetailNo = MapUtils.getString(item, "KDPOS2");  // 接收销售订单行号
                        String causeOfMovement = MapUtils.getString(item, "GRUND");  // 移动原因
						String ummat = MapUtils.getString(item, "UMMAT");  // 形态转换->目标物料类型

						String  xloek= MapUtils.getString(item, "xloek"); // 删除标识
						
						MaterialShipRequestDetail mrd =new MaterialShipRequestDetail();
						MaterialShipRequestDetailKey mrdk=new MaterialShipRequestDetailKey();
						mrdk.setSiteName(sitename);
						mrdk.setShipRequestName(shipRequestName);
						mrdk.setShipRequestDetailName(shipRequestDetailName);
						
						try {
							mrd=MaterialShipRequestDetailServiceProxy.getMaterialShipRequestDetailService().selectByKey(mrdk);
							if (mrd.getAssignedQuantity()!=0) {
								throw new CustomException("ERROR","行项目已在拣配途中!");
							}
						} catch (Exception e) {
							// TODO: handle exception
						}
						
						
							if("X".equals(xloek)) {
								String sql="DELETE FROM materialshiprequestdetail WHERE shiprequestname =? and shiprequestdetailname =?";
								Object[] obj=new Object[] {shipRequestName, shipRequestDetailName};
								IDMFrameServiceProxy.getSqlTemplate().update(sql, obj);
							}else {

								// 根据料号获取阶段
								String materialSql = "SELECT m.PHASE FROM MATERIALSPEC m WHERE MATERIALSPECNAME = :MATERIALSPECNAME";
								Map<String, Object> materialMap= new HashMap<String, Object>();
								materialMap.put("MATERIALSPECNAME", materialSpecName);
								List<Map<String, Object>> phaseList = IDMFrameServiceProxy.getSqlTemplate().queryForList(materialSql, materialMap);
								String phase = phaseList.get(0).get("PHASE") != null ? phaseList.get(0).get("PHASE").toString() : "";

								String sqlItemCheck ="SELECT * FROM materialshiprequestdetail WHERE shiprequestname =:SHIPREQUESTNAME and shiprequestdetailname = :SHIPREQUESTDETAILNAME";
								
								Map<String, Object> selectItemMap= new HashMap<String, Object>();
								selectItemMap.put("SHIPREQUESTNAME", shipRequestName);
								selectItemMap.put("SHIPREQUESTDETAILNAME", shipRequestDetailName);
								
								List<Map<String, Object>> checkItemResultList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sqlItemCheck, selectItemMap);

								if (checkItemResultList == null || checkItemResultList.size() == 0) {
									CreateMaterialShipRequestDetailInfo createInfo = new CreateMaterialShipRequestDetailInfo();
									
									createInfo.setSiteName(sitename);
									createInfo.setShipRequestName(shipRequestName);
									createInfo.setShipRequestDetailName(shipRequestDetailName);
									createInfo.setMaterialSpecName(materialSpecName);
									createInfo.setRequestQuantity(Float.parseFloat(requestQuantity));
									createInfo.setAssignedQuantity(0);
									
									
									Map<String, Object> bindMapItem = new HashMap<String, Object>();
									bindMapItem.put("erpFactory", werks1); // 工厂
									bindMapItem.put("erpLocation", lgort1); // 库位
									//bindMapItem.put("salesorder", salesorder ); // 发出销售订单
									//bindMapItem.put("salesorderdetailno", salesorderdetailno ); // 发出销售订单行项目
									//bindMapItem.put("desc_cn", description ); // 成本中心
									bindMapItem.put("charge", charge);
									//
									bindMapItem.put("unit", unit);
									bindMapItem.put("erpReceiveFactory", werks2);
									bindMapItem.put("erpReceiveLocation", lgort2);
									//新增
									bindMapItem.put("reservedNumber", reservedNumber);
									bindMapItem.put("reservedProjectNumb", reservedProjectNumb);
									bindMapItem.put("receiveProductionOrderNumber", receiveProductionOrderNumber);
									bindMapItem.put("issueProductionOrderNumber", issueProductionOrderNumber);
									bindMapItem.put("productionSupervisor", productionSupervisor);
									bindMapItem.put("costCenter", costCenter);
									bindMapItem.put("combinationOrderNumber", combinationOrderNumber);
									bindMapItem.put("zspec", zspec);
									bindMapItem.put("useDate", useDate);
									bindMapItem.put("sendSalesOrder", sendSalesOrder);
									bindMapItem.put("sendSalesOrderDetailNo", sendSalesOrderDetailNo);
									bindMapItem.put("receiveSalesOrder", receiveSalesOrder);
									bindMapItem.put("receiveSalesOrderDetailNo", receiveSalesOrderDetailNo);
                                    bindMapItem.put("causeOfMovement", causeOfMovement);
									bindMapItem.put("goalMaterialSpec", ummat);
									bindMapItem.put("phase", phase);

									createInfo.setUserColumns(bindMapItem);
									EventInfo eventInfo = new EventInfo();
									eventInfo.setEventTime(TimeStampUtil.getCurrentTimestamp());
									eventInfo.setEventUser(createUser);
									eventInfo.setEventName("CreateMaterialShipRequest");
									
									MaterialShipRequestDetailServiceProxy.getMaterialShipRequestDetailService().create( createInfo);
								}else {
									
									NonPrimaryKeyValueInfo nonPrimaryKeyValueInfo = new NonPrimaryKeyValueInfo();
									Map<String, Object> bindMapItem = new HashMap<String, Object>();
									bindMapItem.put("erpFactory", werks1); // 工厂
									bindMapItem.put("erpLocation", lgort1); // 库位
									//bindMapItem.put("salesorder", salesorder ); // 销售订单
									//bindMapItem.put("salesorderdetailno", salesorderdetailno ); // 销售订单行项目
									//bindMapItem.put("desc_cn", description ); // 成本中心
									bindMapItem.put("charge", charge);
									bindMapItem.put("materialSpecName", materialSpecName);
									bindMapItem.put("requestQuantity", requestQuantity);
									bindMapItem.put("unit", unit);
									bindMapItem.put("erpReceiveFactory", werks2);
									bindMapItem.put("erpReceiveLocation", lgort2);

									bindMapItem.put("reservedNumber", reservedNumber);
									bindMapItem.put("reservedProjectNumb", reservedProjectNumb);
									bindMapItem.put("receiveProductionOrderNumber", receiveProductionOrderNumber);
									bindMapItem.put("issueProductionOrderNumber", issueProductionOrderNumber);
									bindMapItem.put("productionSupervisor", productionSupervisor);
									bindMapItem.put("costCenter", costCenter);
									bindMapItem.put("combinationOrderNumber", combinationOrderNumber);
									bindMapItem.put("zspec", zspec);
									bindMapItem.put("useDate", useDate);
									bindMapItem.put("sendSalesOrder", sendSalesOrder);
									bindMapItem.put("sendSalesOrderDetailNo", sendSalesOrderDetailNo);
									bindMapItem.put("receiveSalesOrder", receiveSalesOrder);
									bindMapItem.put("receiveSalesOrderDetailNo", receiveSalesOrderDetailNo);
                                    bindMapItem.put("causeOfMovement", causeOfMovement);
									bindMapItem.put("goalMaterialSpec", ummat);
									bindMapItem.put("phase", phase);

									nonPrimaryKeyValueInfo.setUserColumns(bindMapItem);
									EventInfo eventInfo = new EventInfo();
									eventInfo.setEventTime(TimeStampUtil.getCurrentTimestamp());
									eventInfo.setEventUser(createUser);
									eventInfo.setEventName("updateMaterialShipRequest");
									
									MaterialShipRequestDetailServiceProxy.getMaterialShipRequestDetailService().setEvent(mrdk, nonPrimaryKeyValueInfo);
									
								}
							}
					}
				}
				
				if(bwart.length()>0) 
				{
					String sqlu="UPDATE MATERIALSHIPREQUEST m SET m.SHIPREQUESTDETAILTYPE =:SHIPREQUESTDETAILTYPE WHERE m.SHIPREQUESTNAME =:SHIPREQUESTNAME";
					Map<String, Object> bp = new HashMap<String, Object>();
					bp.put("SHIPREQUESTDETAILTYPE", bwart); 
					bp.put("SHIPREQUESTNAME", shipRequestName); 
					IDMFrameServiceProxy.getSqlTemplate().update(sqlu, bp);
				}
		    }
			Map<String, Object> oKReturn = new HashMap<>();
			oKReturn.put("STATUS", "S");
			oKReturn.put("MSGTXT", "预留单/领料单下发成功");
			oKReturn.put("ZRSV01", "");
			oKReturn.put("ZRSV02", "");
			oKReturn.put("ZRSV03", "");
			oKReturn.put("ZRSV04", "");
			oKReturn.put("ZRSV05", "");
			oKReturn.put("ZRSV06", "");
			oKReturn.put("ZRSV07", "");
			oKReturn.put("ZRSV08", "");
			oKReturn.put("ZRSV09", "");
			oKReturn.put("ZRSV10", "");
			
			WMSToSAPReturn WMSToSAPReturn = new WMSToSAPReturn(head, oKReturn);		
//			MessageLogUtil.insertSapMessageLog(httpRequest.getRequestURL().toString(), "S", request, "materialspec", WMSToSAPReturn);
			ErpMessageLog erpMessageLog = new ErpMessageLog();
			erpMessageLog.setServerName(System.getProperty("Seq"));
			erpMessageLog.setEventName(httpRequest.getRequestURL().toString());
			erpMessageLog.setId(new TimeUtils().getCurrentEventTimeKey());
			erpMessageLog.setResultCode("S");
			erpMessageLog.setSendMsg(JSONObject.toJSONString(request));
			erpMessageLog.setMessageId("materialShipRequest");
			erpMessageLog.setReturnMsg(JSONObject.toJSONString(WMSToSAPReturn));
			erpMessageLog.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
			MessageLogUtil.writeMessageLog(erpMessageLog);
			IDMFrameServiceProxy.getTransactionManager().commitTransaction();
			return WMSToSAPReturn;
		} catch (Exception e) {
			IDMFrameServiceProxy.getTransactionManager().rollbackTransaction();
			Map<String, Object> errorReturn = new HashMap<>();
			errorReturn.put("STATUS", "E");
			errorReturn.put("MSGTXT", "预留单/领料单下发失败  " + e.getMessage());
			errorReturn.put("HEAD", request.getHEAD());
			//errorReturn.put("BODY", request.getBODY());
			
			WMSToSAPReturn WMSToSAPReturn = new WMSToSAPReturn(head, errorReturn);
//			MessageLogUtil.insertSapMessageLog(httpRequest.getRequestURL().toString(), "E", request, "materialReceiveRequest", WMSToSAPReturn);
			ErpMessageLog erpMessageLog = new ErpMessageLog();
			erpMessageLog.setServerName(System.getProperty("Seq"));
			erpMessageLog.setEventName(httpRequest.getRequestURL().toString());
			erpMessageLog.setId(new TimeUtils().getCurrentEventTimeKey());
			erpMessageLog.setResultCode("E");
			erpMessageLog.setSendMsg(JSONObject.toJSONString(request));
			erpMessageLog.setMessageId("materialShipRequest");
			erpMessageLog.setReturnMsg(JSONObject.toJSONString(WMSToSAPReturn));
			erpMessageLog.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
			MessageLogUtil.writeMessageLog(erpMessageLog);
			return WMSToSAPReturn;
		}
	}
	
	// 待退供应商批次查询
	@RequestMapping("/getAwaitSupplierCharge")
	public WMSToSAPReturn getInventoryRequest(HttpServletRequest httpRequest, @RequestBody SAPToWMSRequest request) throws CustomException {
		HashMap<String, Object> returnObj = new HashMap<String, Object>();
	    List<MaterialPackingStockInfo> resultList = new ArrayList<MaterialPackingStockInfo>();
	    
		Map<String,Object> head = request.getHEAD();
	    ArrayList data = (ArrayList)request.getBODY();
		
		for (int k = 0; k < data.size(); k++) {
			List<MaterialPackingStockInfo> mpList = new ArrayList<MaterialPackingStockInfo>();

			Map<String,Object> item = (Map<String,Object>)data.get(k);
			String erpFactory = MapUtils.getString(item, "WERKS"); // ERP工厂
			String erpLocation = MapUtils.getString(item, "LGORT");  // ERP库位
			String materialSpecName = MapUtils.getString(item, "MATNR");  // 物料号
			String charge = MapUtils.getString(item, "CHARG");  // 批次
			
			if(erpFactory != "")
			{
				try
				{
					String querySql="SELECT M.ERPFACTORY,M.MATERIALSPECNAME,M.ERPLOCATION,M.CHARGE, "
						+"SUM(CASE WHEN (PACKINGGRADE='OK' AND (OQARESULTSTATE IS NULL OR OQARESULTSTATE<>'PREOQA') ) THEN MATERIALQUANTITY ELSE NULL END) OKQUANTITY, "
						+"SUM(CASE WHEN PACKINGGRADE='NG' THEN MATERIALQUANTITY ELSE NULL END) NGQUANTITY, "
						+"SUM(CASE WHEN OQARESULTSTATE='PREOQA' THEN MATERIALQUANTITY ELSE NULL END ) PREOQAQUANTITY FROM MATERIALPACKING M "
						+"WHERE M.ERPFACTORY=:ERPFACTORY "
						+"AND (:MATERIALSPECNAME IS NULL OR M.MATERIALSPECNAME=:MATERIALSPECNAME) "
						+"AND (:CHARGE IS NULL OR M.CHARGE=:CHARGE) "
						+"AND (:ERPLOCATION IS NULL OR M.ERPLOCATION=:ERPLOCATION) "
						+"AND M.STOCKSTATE='Stocked' "
						+"AND M.SPECIALSTATE='2' "
						+"AND M.MATERIALPACKINGTYPE='Box' "
						+"GROUP BY M.ERPFACTORY,M.MATERIALSPECNAME,M.ERPLOCATION,M.CHARGE ";
					Map<String,Object> map=new HashMap<String, Object>();
					map.put("MATERIALSPECNAME", materialSpecName);
					map.put("ERPFACTORY", erpFactory);
					map.put("CHARGE", charge);
					map.put("ERPLOCATION", erpLocation);
					List<Map<String, Object>> result = IDMFrameServiceProxy.getSqlTemplate().queryForList(querySql, map);
					if(result!=null &&result.size()>0)
					{
						for(int i=0;i<result.size();i++)
						{
							MaterialPackingStockInfo mp=new MaterialPackingStockInfo();
							mp.setMaterialSpecName(result.get(i).get("MATERIALSPECNAME").toString());
							mp.setErpFactory(result.get(i).get("ERPFACTORY").toString());
							mp.setErpLocation(result.get(i).get("ERPLOCATION")!=null?result.get(i).get("ERPLOCATION").toString():"");
							mp.setCharge(result.get(i).get("CHARGE")!=null?result.get(i).get("CHARGE").toString():"");
							mp.setOkQuantity(result.get(i).get("OKQUANTITY")!=null?result.get(i).get("OKQUANTITY").toString():"");
							mp.setNgQuantity(result.get(i).get("NGQUANTITY")!=null?result.get(i).get("NGQUANTITY").toString():"");
							mp.setPreOqaQuantity(result.get(i).get("PREOQAQUANTITY")!=null?result.get(i).get("PREOQAQUANTITY").toString():"");
							mpList.add(mp);
						}
					}
					resultList.addAll(mpList);
				}catch (Exception e) {
					// TODO: handle exception
				}
			}
			else {
				throw new CustomException("E","ERP工厂不能为空！");	
			}
		}
		Map<String, Object> oKReturn = new HashMap<>();
		oKReturn.put("STATUS", "S");
		oKReturn.put("MSGTXT", "查询成功");
		oKReturn.put("ITEM", resultList);
		WMSToSAPReturn WMSToSAPReturn = new WMSToSAPReturn(head, oKReturn);		
//		MessageLogUtil.insertSapMessageLog(httpRequest.getRequestURL().toString(), "S", request, "getAwaitSupplierCharge", WMSToSAPReturn);
		ErpMessageLog erpMessageLog = new ErpMessageLog();
		erpMessageLog.setServerName(System.getProperty("Seq"));
		erpMessageLog.setEventName(httpRequest.getRequestURL().toString());
		erpMessageLog.setId(new TimeUtils().getCurrentEventTimeKey());
		erpMessageLog.setResultCode("S");
		erpMessageLog.setSendMsg(JSONObject.toJSONString(request));
		erpMessageLog.setMessageId("getAwaitSupplierCharge");
		erpMessageLog.setReturnMsg(JSONObject.toJSONString(WMSToSAPReturn));
		erpMessageLog.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
		MessageLogUtil.writeMessageLog(erpMessageLog);
		
		return WMSToSAPReturn;
	}
	
	// 销售订单下发
	@RequestMapping("/materialShipRequestForDN")
	public WMSToSAPReturn materialShipRequestForDN(HttpServletRequest httpRequest, @RequestBody SAPToWMSRequest request) {
		Map<String,Object> head = request.getHEAD();
		IDMFrameServiceProxy.getTransactionManager().beginTransaction();
		try {


			ArrayList<Map<String,Object>> datas = request.getBODY();

			String siteName = System.getProperty("company");

//			//存放所有单据号，body遍历结束后，更新成Created
//			List<String> shipRequestList = new ArrayList<>();


			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			
			for (Map<String, Object> data : datas) {
				String shipRequestName = MapUtils.getString(data, "VBELN");  // 交货单号
				String shipRequestType =  MapUtils.getString(data, "LFART");  // 交货单类型
				String shiprequestdec =  MapUtils.getString(data, "VTEXT");  // 交货单描述
				String orderDate = MapUtils.getString(data, "ERDAT"); // 交货单创建日期
				String planDate = MapUtils.getString(data, "WADAT"); // 计划交货日期
				String createUser = MapUtils.getString(data, "ERNAM");  // 创建人
				String receiveUser =  MapUtils.getString(data, "KUNNR");  //收货方（客户编码）
				String provinceAndCity =  MapUtils.getString(data, "BEZEI");  //省市
				String deliveryAddress =  MapUtils.getString(data, "STREET");  //收货地址
				String customerName =  MapUtils.getString(data, "NAME");  //收货方名称
				String customerOrder =  MapUtils.getString(data, "BSTKD");  //客户订单号
				String remark =  MapUtils.getString(data, "Z001");  //发货备注
				String customerArea =  MapUtils.getString(data, "Z_REGION");  //客户大区
				String carFlag =  MapUtils.getString(data, "Z_SSEND");//是否需要专车派送
				String factoryName =  MapUtils.getString(data, "WERKS");  //工厂

				String sqlCheck =" SELECT * FROM materialshiprequest m WHERE shiprequestname =:SHIPREQUESTNAME ";
				Map<String, Object> selectMap= new HashMap<String, Object>();
				selectMap.put("SHIPREQUESTNAME", shipRequestName);
				List<Map<String, Object>> checkResultList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sqlCheck, selectMap);

				if(checkResultList == null || checkResultList.size() == 0) {
					CreateMaterialShipRequestInfo createInfo = new CreateMaterialShipRequestInfo();
					createInfo.setSiteName(siteName);
					createInfo.setShipRequestName(shipRequestName);
					createInfo.setShipRequestType(shipRequestType);
					createInfo.setShipRequestDetailType(shipRequestType);
					createInfo.setCustomerNO(receiveUser);

					createInfo.setShipRequestState("Created");
//					shipRequestList.add(shipRequestName);

					createInfo.setSystemType("ERP");
					Map<String, Object> bindMap = new HashMap<String, Object>();
					bindMap.put("shipRequestDec", shiprequestdec);
					bindMap.put("bezei", provinceAndCity);
					bindMap.put("deliveryAddress", deliveryAddress);
					bindMap.put("customName", customerName);
					bindMap.put("deliveryRemark", remark);
					bindMap.put("orderDateStr", orderDate);
					bindMap.put("erpFactory", factoryName);
					bindMap.put("planDate", planDate);//计划交货日期
					//NEW
					bindMap.put("customerOrder", customerOrder);//客户订单号
					bindMap.put("customerArea", customerArea);//客户大区
					bindMap.put("carFlag", carFlag);//是否需要专车派送


//					bindMap.put("erpReceiveFactory", receiveUser);

					createInfo.setUserColumns(bindMap);

					EventInfo eventInfo = new EventInfo();
					eventInfo.setEventName("MaterialShipRequestForDNSAPToWMS");
					eventInfo.setEventUser(createUser);

					MaterialShipRequestServiceProxy.getMaterialShipRequestService().create(eventInfo, createInfo);
				}else {
					MaterialShipRequestSetEventInfo info = new MaterialShipRequestSetEventInfo();

					MaterialShipRequestKey key = new MaterialShipRequestKey();
					key.setSiteName(siteName);
					key.setShipRequestName(shipRequestName);

					MaterialShipRequest shipRequest=MaterialShipRequestServiceProxy.getMaterialShipRequestService().selectByKey(key);

					if (!shipRequest.getShipRequestState().equalsIgnoreCase("Created")) {
						throw new CustomException("ERROR","交货单已确认，禁止修改!");
					}

					Map<String, Object> bindMap = new HashMap<String, Object>();
					bindMap.put("createUser", createUser);
					bindMap.put("shipRequestDec", shiprequestdec);
					bindMap.put("deliveryAddress", deliveryAddress);
					bindMap.put("customName", customerName);
					bindMap.put("bezei", provinceAndCity);
					bindMap.put("deliveryRemark", remark);
					bindMap.put("orderDateStr", orderDate);
					bindMap.put("erpFactory", factoryName);
					bindMap.put("planDate", planDate);//计划交货日期
					//NEW
					bindMap.put("customerOrder", customerOrder);//客户订单号
					bindMap.put("customerArea", customerArea);//客户大区
					bindMap.put("carFlag", carFlag);//是否需要专车派送

					info.setUserColumns(bindMap);

					EventInfo eventInfo = new EventInfo();
					eventInfo.setEventName("ModifyMaterialShipRequest");
					eventInfo.setEventUser(createUser);
					MaterialShipRequestServiceProxy.getMaterialShipRequestService().setEvent(key, eventInfo, info);
				}

				String shipRequestDetailName = MapUtils.getString(data, "POSNR");  // 交货单行号
				String materialSpecName = MapUtils.getString(data, "MATNR");  // 物料编码
				String width = MapUtils.getString(data, "ZZKF");  // 宽幅
				String length = MapUtils.getString(data, "ZZCD");  // 长度
				String volume = MapUtils.getString(data, "ZZJS");  // 卷数
				String unit = MapUtils.getString(data, "MEINS");  // 单位
				String requestQuantity = MapUtils.getString(data, "LFIMG");  //  交货数量
				String salesorder = MapUtils.getString(data, "VGBEL");  // 销售订单号，参考凭证销售订单
				String salesorderdetailno = MapUtils.getString(data, "VGPOS");  // 销售订单行号，参考凭证销售订单行项目
				String shippingNote = MapUtils.getString(data, "Z002"); //发货备注
				String customerMaterial = MapUtils.getString(data, "KDMAT"); //客户料号
				String customerProduct = MapUtils.getString(data, "ZZCUS_DEC"); // 客户品名
				String texture = MapUtils.getString(data, "ZZMATRAIL"); //材质
				String color = MapUtils.getString(data, "ZZCOLOUR"); //颜色
				String releaseForce = MapUtils.getString(data, "ZZFORCE"); //离型力
				String tubeCore = MapUtils.getString(data, "Z_DIE"); //管芯
				String customerStash = MapUtils.getString(data, "Z_LGORT"); //客户仓库

				String sendSaleOrder=MapUtils.getString(data, "VBELV"); //销售订单号
				String sendSaleOrderDetailNo=MapUtils.getString(data, "POSNV"); //销售订单行号
				String sourceNo=MapUtils.getString(data, "Z_LGORT"); //原单号
				String  xloek= MapUtils.getString(data, ""); // 删除标识

				MaterialShipRequestDetail mrd =new MaterialShipRequestDetail();
				MaterialShipRequestDetailKey mrdk=new MaterialShipRequestDetailKey();
				mrdk.setSiteName(siteName);
				mrdk.setShipRequestName(shipRequestName);
				mrdk.setShipRequestDetailName(shipRequestDetailName);

				try {
					mrd=MaterialShipRequestDetailServiceProxy.getMaterialShipRequestDetailService().selectByKey(mrdk);
					if (mrd.getAssignedQuantity()!=0) {
						throw new CustomException("ERROR","行项目已在拣配途中!");
					}
				} catch (Exception e) {
					// TODO: handle exception
				}


				if("X".equals(xloek)) {
					String sql="DELETE FROM materialshiprequestdetail WHERE shiprequestname =? and shiprequestdetailname =?";
					Object[] obj=new Object[] {shipRequestName, shipRequestDetailName};
					IDMFrameServiceProxy.getSqlTemplate().update(sql, obj);
				}else {

					String sqlItemCheck ="SELECT * FROM materialshiprequestdetail " +
							"WHERE shiprequestname =:SHIPREQUESTNAME and shiprequestdetailname = :SHIPREQUESTDETAILNAME";
					Map<String, Object> selectItemMap= new HashMap<String, Object>();
					selectItemMap.put("SHIPREQUESTNAME", shipRequestName);
					selectItemMap.put("SHIPREQUESTDETAILNAME", shipRequestDetailName);
					List<Map<String, Object>> checkItemResultList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sqlItemCheck, selectItemMap);

					if (checkItemResultList == null || checkItemResultList.size() == 0) {
						CreateMaterialShipRequestDetailInfo createInfo = new CreateMaterialShipRequestDetailInfo();

						createInfo.setSiteName(siteName);
						createInfo.setShipRequestName(shipRequestName);
						createInfo.setShipRequestDetailName(shipRequestDetailName);
						createInfo.setMaterialSpecName(materialSpecName);
						createInfo.setRequestQuantity(Float.parseFloat(requestQuantity));
						createInfo.setAssignedQuantity(0);

						Map<String, Object> bindMapItem = new HashMap<String, Object>();
						bindMapItem.put("erpFactory", factoryName); // 工厂
						bindMapItem.put("unit", unit); // 单位
						bindMapItem.put("requestQuantity", requestQuantity); // 交货数量
						bindMapItem.put("remark", shippingNote); // 发货备注
						//新建
						bindMapItem.put("width", width); // 宽幅
						bindMapItem.put("length", length); // 长度
						bindMapItem.put("volume", volume); // 卷数
						bindMapItem.put("salesorder", salesorder); // 销售订单号，参考凭证销售订单
						bindMapItem.put("salesorderdetailno", salesorderdetailno); // 销售订单行号，参考凭证销售订单行项目
						bindMapItem.put("customerMaterial", customerMaterial); // 客户料号
						bindMapItem.put("customerProduct", customerProduct); // 客户品名
						bindMapItem.put("texture", texture); // 材质
						bindMapItem.put("color", color); // 颜色
						bindMapItem.put("releaseForce", releaseForce); // 离型力
						bindMapItem.put("tubeCore", tubeCore); // 管芯
						bindMapItem.put("customerStash", customerStash); // 客户仓库
						
						bindMapItem.put("sendSalesOrder", sendSaleOrder); // 销售订单
						bindMapItem.put("sendSalesOrderDetailNo", sendSaleOrderDetailNo); // 销售订单行号
						bindMapItem.put("sourceNo", sourceNo); // 原单号

						createInfo.setUserColumns(bindMapItem);
						EventInfo eventInfo = new EventInfo();
						eventInfo.setEventUser(createUser);
						eventInfo.setEventName("Create");
						MaterialShipRequestDetailServiceProxy.getMaterialShipRequestDetailService().create(createInfo);
					}else {
						NonPrimaryKeyValueInfo nonPrimaryKeyValueInfo = new NonPrimaryKeyValueInfo();
						Map<String, Object> bindMapItem = new HashMap<String, Object>();
						bindMapItem.put("erpFactory", factoryName); // 工厂
						bindMapItem.put("materialSpecName", materialSpecName);
						bindMapItem.put("requestQuantity", requestQuantity);

						//需要新建
						bindMapItem.put("width", width); // 宽幅
						bindMapItem.put("length", length); // 长度
						bindMapItem.put("volume", volume); // 卷数
						bindMapItem.put("salesorder", salesorder); // 销售订单号，参考凭证销售订单
						bindMapItem.put("salesorderdetailno", salesorderdetailno); // 销售订单行号，参考凭证销售订单行项目
						bindMapItem.put("customerMaterial", customerMaterial); // 客户料号
						bindMapItem.put("customerProduct", customerProduct); // 客户品名
						bindMapItem.put("texture", texture); // 材质
						bindMapItem.put("color", color); // 颜色
						bindMapItem.put("releaseForce", releaseForce); // 离型力
						bindMapItem.put("tubeCore", tubeCore); // 管芯
						bindMapItem.put("customerStash", customerStash); // 客户仓库
						//

						bindMapItem.put("sendSalesOrder", sendSaleOrder); // 销售订单
						bindMapItem.put("sendSalesOrderDetailNo", sendSaleOrderDetailNo); // 销售订单行号
						bindMapItem.put("sourceNo", sourceNo); // 原单号
						
						nonPrimaryKeyValueInfo.setUserColumns(bindMapItem);
						EventInfo eventInfo = new EventInfo();
						eventInfo.setEventUser(createUser);
						eventInfo.setEventName("update");

						MaterialShipRequestDetailServiceProxy.getMaterialShipRequestDetailService().setEvent(mrdk, nonPrimaryKeyValueInfo);
					}
				}
			}
//			for(String ship : shipRequestList) {
//				MaterialShipRequestKey materialShipRequestKey = new MaterialShipRequestKey();
//				materialShipRequestKey.setSiteName(siteName);
//				materialShipRequestKey.setShipRequestName(ship);
//				MaterialShipRequest	materialShipRequest = MaterialShipRequestServiceProxy.getMaterialShipRequestService().selectByKey(materialShipRequestKey);
//				if(materialShipRequest.getShipRequestState().equalsIgnoreCase("beforeCreated")){
//					//sap发给wms去掉了item项，防止一个单据出现多次，第二次遍历到时，state为Created报错
//					materialShipRequest.setShipRequestState("Created");
//					MaterialShipRequestServiceProxy.getMaterialShipRequestService().update(materialShipRequest);
//				}
//			}


			Map<String, Object> oKReturn = new HashMap<>();
			oKReturn.put("STATUS", "S");
			oKReturn.put("MSGTXT", "销售发货单下发成功");
			oKReturn.put("ZRSV01", "");
			oKReturn.put("ZRSV02", "");
			oKReturn.put("ZRSV03", "");
			oKReturn.put("ZRSV04", "");
			oKReturn.put("ZRSV05", "");
			oKReturn.put("ZRSV06", "");
			oKReturn.put("ZRSV07", "");
			oKReturn.put("ZRSV08", "");
			oKReturn.put("ZRSV09", "");
			oKReturn.put("ZRSV10", "");

			WMSToSAPReturn WMSToSAPReturn = new WMSToSAPReturn(head, oKReturn);
//			MessageLogUtil.insertSapMessageLog(httpRequest.getRequestURL().toString(), "S", request, "materialShipRequestForDN", WMSToSAPReturn);
			ErpMessageLog erpMessageLog = new ErpMessageLog();
			erpMessageLog.setServerName(System.getProperty("Seq"));
			erpMessageLog.setEventName(httpRequest.getRequestURL().toString());
			erpMessageLog.setId(new TimeUtils().getCurrentEventTimeKey());
			erpMessageLog.setResultCode("S");
			erpMessageLog.setSendMsg(JSONObject.toJSONString(request));
			erpMessageLog.setMessageId("materialShipRequestForDN");
			erpMessageLog.setReturnMsg(JSONObject.toJSONString(WMSToSAPReturn));
			erpMessageLog.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
			MessageLogUtil.writeMessageLog(erpMessageLog);
			IDMFrameServiceProxy.getTransactionManager().commitTransaction();
			return WMSToSAPReturn;
		} catch (Exception e) {
			IDMFrameServiceProxy.getTransactionManager().rollbackTransaction();
			Map<String, Object> errorReturn = new HashMap<>();
			errorReturn.put("STATUS", "E");
			errorReturn.put("MSGTXT", "销售发货单下发失败 " + e.getMessage());
			errorReturn.put("HEAD", request.getHEAD());
			//errorReturn.put("BODY", request.getBODY());

			WMSToSAPReturn WMSToSAPReturn = new WMSToSAPReturn(head, errorReturn);
			log.info(httpRequest.getRequestURL().toString());
			log.info(request.toString());
			//log.info(request.getHeader().getInterfaceNo());
			log.info(WMSToSAPReturn.toString());
//			MessageLogUtil.insertSapMessageLog(httpRequest.getRequestURL().toString(), "E", request, "materialShipRequestForDN", WMSToSAPReturn);
			ErpMessageLog erpMessageLog = new ErpMessageLog();
			erpMessageLog.setServerName(System.getProperty("Seq"));
			erpMessageLog.setEventName(httpRequest.getRequestURL().toString());
			erpMessageLog.setId(new TimeUtils().getCurrentEventTimeKey());
			erpMessageLog.setResultCode("E");
			erpMessageLog.setSendMsg(JSONObject.toJSONString(request));
			erpMessageLog.setMessageId("materialShipRequestForDN");
			erpMessageLog.setReturnMsg(JSONObject.toJSONString(WMSToSAPReturn));
			erpMessageLog.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
			MessageLogUtil.writeMessageLog(erpMessageLog);
			return WMSToSAPReturn;
		}
	}

	// 生产单据关闭接口
	@RequestMapping("/CloseMaterialShipRequest")
	public WMSToSAPReturn CloseMaterialShipRequest(HttpServletRequest httpRequest, @RequestBody SAPToWMSRequest request) {
		Map<String,Object> head = request.getHEAD();
		IDMFrameServiceProxy.getTransactionManager().beginTransaction();
		try {

			ArrayList<Map<String,Object>> datas = request.getBODY();
			String sitename = System.getProperty("company");
			for (Map<String, Object> data : datas) {
				String shipRequestName = MapUtils.getString(data, "ZDNUM");  // 生产单据编号
				String shipRequestDetailName = MapUtils.getString(data, "ZITEM");  // 单据行号
				String sqlCheck =" SELECT m.* FROM MATERIALSHIPREQUESTDETAIL m " +
						"WHERE m.SHIPREQUESTNAME =:SHIPREQUESTNAME  AND m.SHIPREQUESTDETAILNAME = :SHIPREQUESTDETAILNAME ";
				Map<String, Object> selectMap= new HashMap<String, Object>();
				selectMap.put("SHIPREQUESTNAME", shipRequestName);
				selectMap.put("SHIPREQUESTDETAILNAME", shipRequestDetailName);
				List<Map<String, Object>> checkResultList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sqlCheck, selectMap);

				if(checkResultList == null || checkResultList.size() == 0) {
					throw new CustomException("ERROR","存在未下发过的单据，请确认!");
				}else {
					MaterialShipRequestDetailSetEventInfo info = new MaterialShipRequestDetailSetEventInfo();
					MaterialShipRequestDetailKey key = new MaterialShipRequestDetailKey();
					key.setSiteName(sitename);
					key.setShipRequestName(shipRequestName);
					key.setShipRequestDetailName(shipRequestDetailName);

					Map<String, Object> bindMap = new HashMap<String, Object>();
					bindMap.put("closedFlag", "Y");
					info.setUserColumns(bindMap);

					NonPrimaryKeyValueInfo nonPrimaryKeyValueInfo = new NonPrimaryKeyValueInfo();
					nonPrimaryKeyValueInfo.setUserColumns(bindMap);
					EventInfo eventInfo = new EventInfo();
					eventInfo.setEventName("CloseMaterialShipRequestDetail");

					MaterialShipRequestDetailServiceProxy.getMaterialShipRequestDetailService().setEvent(key, nonPrimaryKeyValueInfo);
				}
			}
			Map<String, Object> oKReturn = new HashMap<>();
			oKReturn.put("STATUS", "S");
			oKReturn.put("MSGTXT", "生产单据关闭成功");
			oKReturn.put("ZRSV01", "");
			oKReturn.put("ZRSV02", "");
			oKReturn.put("ZRSV03", "");
			oKReturn.put("ZRSV04", "");
			oKReturn.put("ZRSV05", "");
			oKReturn.put("ZRSV07", "");
			oKReturn.put("ZRSV08", "");
			oKReturn.put("ZRSV09", "");
			oKReturn.put("ZRSV10", "");

			WMSToSAPReturn WMSToSAPReturn = new WMSToSAPReturn(head, oKReturn);
//			MessageLogUtil.insertSapMessageLog(httpRequest.getRequestURL().toString(), "S", request, "materialspec", WMSToSAPReturn);
			ErpMessageLog erpMessageLog = new ErpMessageLog();
			erpMessageLog.setServerName(System.getProperty("Seq"));
			erpMessageLog.setEventName(httpRequest.getRequestURL().toString());
			erpMessageLog.setId(new TimeUtils().getCurrentEventTimeKey());
			erpMessageLog.setResultCode("S");
			erpMessageLog.setSendMsg(JSONObject.toJSONString(request));
			erpMessageLog.setMessageId("CanselMaterialShipRequest");
			erpMessageLog.setReturnMsg(JSONObject.toJSONString(WMSToSAPReturn));
			erpMessageLog.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
			MessageLogUtil.writeMessageLog(erpMessageLog);
			IDMFrameServiceProxy.getTransactionManager().commitTransaction();
			return WMSToSAPReturn;
		} catch (Exception e) {
			IDMFrameServiceProxy.getTransactionManager().rollbackTransaction();
			Map<String, Object> errorReturn = new HashMap<>();
			errorReturn.put("STATUS", "E");
			errorReturn.put("MSGTXT", "生产单据关闭失败" + e.getMessage());
//			errorReturn.put("HEAD", request.getHEAD());
			//errorReturn.put("BODY", request.getBODY());
			WMSToSAPReturn WMSToSAPReturn = new WMSToSAPReturn(head, errorReturn);
//			MessageLogUtil.insertSapMessageLog(httpRequest.getRequestURL().toString(), "E", request, "materialReceiveRequest", WMSToSAPReturn);
			ErpMessageLog erpMessageLog = new ErpMessageLog();
			erpMessageLog.setServerName(System.getProperty("Seq"));
			erpMessageLog.setEventName(httpRequest.getRequestURL().toString());
			erpMessageLog.setId(new TimeUtils ().getCurrentEventTimeKey());
			erpMessageLog.setResultCode("E");
			erpMessageLog.setSendMsg(JSONObject.toJSONString(request));
			erpMessageLog.setMessageId("CanselMaterialShipRequest");
			erpMessageLog.setReturnMsg(JSONObject.toJSONString(WMSToSAPReturn));
			erpMessageLog.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
			MessageLogUtil.writeMessageLog(erpMessageLog);
			return WMSToSAPReturn;
		}
	}

}
