package com.cim.idm.mwmsextend.materialpacking.service;

import java.io.ByteArrayOutputStream;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.cim.idm.utils.ClientServiceUtil;
import com.cim.idm.wmsextend.generic.GenericServiceProxy;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import com.cim.idm.framework.IDMFrameServiceProxy;
import com.cim.idm.framework.data.EventInfo;
import com.cim.idm.framework.exception.IDMFrameDBErrorSignal;
import com.cim.idm.framework.exception.ext.NotFoundSignal;
import com.cim.idm.framework.orm.service.CommonServiceDAO;
import com.cim.idm.framework.util.time.TimeStampUtil;
import com.cim.idm.framework.util.xml.JdomUtils;
import com.cim.idm.mwmsextend.erpinterface.service.ERPInterfaceServiceImpl;
import com.cim.idm.wmsextend.generic.errorHandler.CustomException;
import com.cim.idm.mwmsextend.generic.esb.ESBService;
import com.cim.idm.mwmsextend.generic.util.CommonValidation;
import com.cim.idm.wmsextend.generic.util.SMessageUtil;
import com.cim.idm.mwmsextend.materialpackingstockin.service.MaterialPackingNoPOStockInImpl;
import com.cim.idm.mwmsextend.materialpackingstockin.service.MaterialPackingStockInImpl;
import com.cim.idm.mwmsextend.materialpackingstockin.service.MaterialPackingStockInUtil;
import com.cim.idm.mwmsextend.materialpackingstockin.service.MaterialStockInClass;
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.RemoveReceiveRequestInfo;
import com.cim.idm.wmspackage.material.MaterialServiceProxy;
import com.cim.idm.wmspackage.material.management.data.MaterialSpec;
import com.cim.idm.wmspackage.material.management.data.MaterialSpecKey;
import com.cim.idm.wmspackage.materialpacking.MaterialPackingServiceProxy;
import com.cim.idm.wmspackage.materialpacking.management.data.MaterialPacking;
import com.cim.idm.wmspackage.materialpacking.management.data.MaterialPackingFromTQMS;
import com.cim.idm.wmspackage.materialpacking.management.data.MaterialPackingKey;
import com.cim.idm.wmspackage.materialpacking.management.data.MaterialPackingToTQMS;
import com.cim.idm.wmspackage.materialpacking.management.info.CreateInfo;
import com.cim.idm.wmspackage.materialpacking.management.info.MaterialPackingAssignShipRequestInfo;
import com.cim.idm.wmspackage.materialpacking.management.info.SetEventInfo;
import com.cim.idm.wmspackage.materialreceiverequestact.MaterialReceiveRequestActServiceProxy;
import com.cim.idm.wmspackage.materialreceiverequestact.management.info.CreateReceiveRequestBatchInfo;
import com.cim.idm.wmspackage.materialreceiverequestactdetail.MaterialReceiveRequestActDetailServiceProxy;
import com.cim.idm.wmspackage.materialreceiverequestactdetail.management.info.ActDetailIncreaseInfo;
import com.cim.idm.wmspackage.materialreceiverequestactdetail.management.info.CreateActDetailInfo;
import com.cim.idm.wmspackage.materialreceivetactdetail.management.data.MaterialReceiveActDetailKey;
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.MaterialShipRequestMakeCompletedInfo;
import com.cim.idm.wmspackage.materialshiprequest.management.info.MaterialShipRequestMakeReservedInfo;
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.MakeShipDetailDecreaseAssignedInfo;
import com.cim.idm.wmspackage.materialshiprequestdetail.management.info.MakeShipDetailIncreaseAssignedInfo;
import com.cim.idm.wmspackage.materialshiprequesttooem.MaterialShipRequestToOEMServiceProxy;
import com.cim.idm.wmspackage.materialshiprequesttooem.management.data.MaterialShipRequestToOEMKey;
import com.cim.idm.wmspackage.materialshiprequesttooem.management.info.MakeOEMAssignedInfo;
import com.cim.idm.wmspackage.materialshiprequesttooem.management.info.MakeOEMDecreaseAssignedInfo;
import com.cim.idm.wmspackage.materialundo.info.MaterialUnDoinfo;
import com.cim.idm.wmspackage.name.NameServiceProxy;
//import com.cim.idm.wmspackage.productshiprequest.management.impl.ShipRequestDetailServiceImpl;
import com.cim.idm.wmspackage.receiverequestbatch.management.data.MaterialReceiveAct;
import com.cim.idm.wmspackage.receiverequestbatch.management.data.MaterialReceiveActKey;
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.MakeDetailDecreaseReceivedInfo;
import com.cim.idm.wmspackage.receiverequestdetail.management.info.MakeDetailIncreaseReceivedInfo;
import com.cim.idm.wmspackage.receiverequestdetail.management.info.RemoveRequestDetailInfo;
import com.cim.idm.wmspackage.storage.StorageServiceProxy;
import com.cim.idm.wmspackage.storage.management.data.StorageKey;
import com.cim.idm.wmspackage.storage.management.info.MakeEmptyInfo;
import com.cim.idm.wmspackage.storage.management.info.MakeNotFullInfo;
import com.fasterxml.jackson.databind.ObjectMapper;

public class MaterialPackingServiceImpl extends
		CommonServiceDAO<MaterialPackingKey, MaterialPacking> {

	private static Log log = LogFactory
			.getLog(MaterialPackingServiceImpl.class);

	private String oicPulishSubject = getPublishSubject();

	/**
	 * 无源标签打印
	 * @param eventInfo
	 * @param siteName    				SDK
	 * @param materialquantity 			总数量
	 * @param materialcreatequantity	标签数量
	 * @param makeDate					生产日期
	 * @param erpFactory				组织
	 * @param materialSpecName			料号
	 * @param sdkid						规格
	 * @param phase						阶段
	 * @param unit						单位
	 * @return
	 * @throws Exception
	 */
	public static String PackingLoael(EventInfo eventInfo, String siteName, String materialquantity, String materialcreatequantity,
									  String makeDate, String erpFactory, String materialSpecName, String sdkid, String phase, String unit, String sunremainder,
									  String truegg,String remark) throws Exception {
		String expirationDay = "";

		String lastEventTimeKey = "";
		List<CreateInfo> listMaterialPacking = new ArrayList<CreateInfo>();
		SimpleDateFormat sDateFormat=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		SimpleDateFormat sourceFormat = new SimpleDateFormat("yyyy-MM-dd");
		List<String> boxId;
		float EveryBoxQuantity1 = 0;
//		BigDecimal everyQty = new BigDecimal(receiveQty);
		BigDecimal sumQty = BigDecimal.ZERO;
		try {
//			if (boxFlag.equals("Y")) {
//				float tempV = Math.round((Float.valueOf(receiveQty) - (Float
//						.valueOf(boxQuantity) - 1)
//						* Float.valueOf(EveryBoxQuantity)) * 100);
			// float v=(float) (tempV/100.00);
//				EveryBoxQuantity1 = (float) (tempV / 100.00);
			// float num=(float)(Math.round(totalPrice*100)/100)
//			}
			String is_oven = "N";
			MaterialSpec materialSpec = new MaterialSpec();
			MaterialSpecKey materialSpecKey = new MaterialSpecKey();
			materialSpecKey.setMaterialSpecName(materialSpecName);
			materialSpecKey.setSiteName(siteName);
			materialSpec = MaterialServiceProxy.getMaterialSpecService().selectByKey(materialSpecKey);
//			String maturationflag = materialSpec.getMATURATIONFLAG();//熟化标识
//			String is_CON_TEMP = materialSpec.getIS_CON_TEMP();//恒温恒湿
			//判断仓库是否启用了货位，但货位为空
//			String sql = "SELECT be.USE_LOCATION,be.CONST_TEMP,be.IS_OVEN FROM BS_ERPLOCATION be WHERE be.ERPLOCATIONNAME = :ERPLOCATION";
//			Map<String, Object> hashMap = new HashMap<String,Object> ();
//			hashMap.put("ERPLOCATION", erpLocation);
//			hashMap.put("LOCATIONNAME", locationName);
//			List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, hashMap);
//			if (queryForList == null || queryForList.size() < 1) {
//				throw new Exception("仓库不存在");
//			} else {
//				String string = queryForList.get(0).get("USE_LOCATION") == null ? "" : queryForList.get(0).get("USE_LOCATION").toString();//启用货位
//				String const_temp = queryForList.get(0).get("CONST_TEMP") == null ? "" : queryForList.get(0).get("CONST_TEMP").toString(); //恒温标识
//				is_oven = queryForList.get(0).get("IS_OVEN") == null ? "" : queryForList.get(0).get("IS_OVEN").toString(); //熟化标识
//				if ("Y".equals(string) && ("".equals(locationName) || locationName == null ))  {
//					throw new Exception("仓库启用了货位，但货位为空");
//				}
//				if ("N".equals(string) && (!"".equals(locationName)) )  {
//					throw new Exception("仓库未启用货位，货位为空");
//				}
//				if (!"".equals(locationName)) {
//					String sql2 = "SELECT * FROM STORAGESPEC S WHERE S.STORAGENAME = :LOCATIONNAME AND S.ERPLOCATION = :ERPLOCATION ";
//					List<Map<String, Object>> queryForList2 = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql2, hashMap);
//					if (queryForList2 == null || queryForList2.size() < 1) {
//						throw new Exception("仓库与货位对应关系不正确");
//					}
//				}
//				String ckhw = "Y".equals(const_temp) ? "恒温恒湿" : "非恒温恒湿";
//				String wlhw = "Y".equals(is_CON_TEMP) ? "恒温恒湿" : "非恒温恒湿";
//
//
//				String cksh = "Y".equals(is_oven) ? "熟化" : "非熟化";
//				String wlsh = "Y".equals(maturationflag) ? "熟化" : "非熟化";
//				if (!const_temp.equals(is_CON_TEMP)) {
//					throw new Exception("仓库" + ckhw + "; 物料" + wlhw);
//				}
//
//				if (!is_oven.equals(maturationflag)) {
//					throw new Exception("仓库" + cksh + "; 物料" + wlsh);
//				}
//			}
//			boxId = MaterialPackingServiceImpl.generateBoxID("LabelId", siteName,
//					boxQuantity, makeDate,"WL");
			String materialType = materialSpec.getMaterialType();
			if ("1030".equals(materialType) || "1060".equals(materialType)) {
				materialType = "JS";
			} else {
				materialType = "WL";
			}
			boxId = MaterialPackingServiceImpl.generateBoxID("LabelId", siteName,
					materialcreatequantity, makeDate,materialType,erpFactory);
			Map<String, Object> box_quantity = new HashMap<String, Object>();
			int i = 0;
			for (; i < boxId.size(); i++) {
				CreateInfo materialPacking = new CreateInfo();
				if (i == boxId.size() - 1) {
//				    BigDecimal bigReceiveQty = new BigDecimal(receiveQty);
					BigDecimal bigEveryBoxQuantity = new BigDecimal(materialquantity);
					BigDecimal bigBoxIdSizeMinusOne = new BigDecimal(boxId.size() - 1);
//		            BigDecimal result = bigReceiveQty.subtract(bigEveryBoxQuantity.multiply(bigBoxIdSizeMinusOne));
//					EveryBoxQuantity =result.toString();
				}
				materialPacking.setSiteName(siteName);
				materialPacking.setContentMaterialType("");
				materialPacking.setMaterialPackingType("Box");

				Map<String, Object> bindMap = new HashMap<String, Object>();
				if (Double.valueOf(sunremainder) > 0) {
					sunremainder = String.valueOf(Double.valueOf(sunremainder) - 1);
					bindMap.put("materialQuantity", String.valueOf(Double.valueOf(materialquantity)));
					//470110856|1|C|75mm*1000m|SHBP01JT1202305240009|20230524|11|75
					String newBoxId = materialSpecName + "|1|" + phase + "|" + truegg + "|" + boxId.get(i) + "|"
							+ makeDate.replace("-", "").substring(0, 8) + "|" + unit + "|" + String.valueOf(Double.valueOf(materialquantity) + 1);
					materialPacking.setMaterialPackingName(newBoxId);
				} else {
					bindMap.put("materialQuantity", materialquantity);
					//470110856|1|C|75mm*1000m|SHBP01JT1202305240009|20230524|11|75
					String newBoxId = materialSpecName + "|1|" + phase + "|" + truegg + "|" + boxId.get(i) + "|"
							+ makeDate.replace("-", "").substring(0, 8) + "|" + unit + "|" + materialquantity;
					materialPacking.setMaterialPackingName(newBoxId);
				}
				bindMap.put("materialCreateQuantity", materialquantity);
				bindMap.put("packingState", "Created");// 标记Box是刚创建的
				bindMap.put("materialType", materialSpec.getMaterialType());
				bindMap.put("materialSpecName", materialSpecName);
				bindMap.put("stockState", "Created");
				bindMap.put("holdState", "N");
//				bindMap.put("areaName", areaName);
				bindMap.put("createUser", eventInfo.getEventUser());
				bindMap.put("createTime", eventInfo.getEventTime());
//				receiveRequestName = receiveRequestName.equals("") ? shipRequestName
//						: receiveRequestName;
//				receiveRequestDetailName = receiveRequestDetailName.equals("") ? shipRequestDetailName
//						: receiveRequestDetailName;
				bindMap.put("ReceiveTime", eventInfo.getEventTime());
				bindMap.put("ReceiveUser", eventInfo.getEventUser());
//				bindMap.put("receiveRequestName", receiveRequestName);
//				bindMap.put("receiveRequestDetailName",	receiveRequestDetailName);
//				bindMap.put("receiveRequestDetailName",	receiveRequestDetailName);
				bindMap.put("SDK_ID", sdkid);

				bindMap.put("unit", unit);
//				bindMap.put("fqty", fqty);
				bindMap.put("truegg", truegg);
				bindMap.put("remark", remark);
				if("Y".equals(is_oven)) {
					bindMap.put("MATURATIONINTIME", eventInfo.getEventTime());
				}
				// bindMap.put("receiveRequestName", shipRequestName);
				// bindMap.put("receiveRequestDetailName",
				// shipRequestDetailName);
				if(expirationDay==null||expirationDay.equals("")){
					if(materialSpec.getExpirationDay()>0){
						Date endTime = sourceFormat.parse(makeDate);
//						String format2 = sDateFormat.format(parse2);
//						Date endTime=sDateFormat.parse(makeDate);


						Calendar rightNow = Calendar.getInstance();
						rightNow.setTime(endTime);
						if(siteName.equals("TM1"))
						{
							rightNow.add(Calendar.MONTH, materialSpec.getExpirationDay());
							rightNow.set(Calendar.DAY_OF_MONTH,rightNow.get(Calendar.DAY_OF_MONTH)-1);
						}
						else{
							rightNow.add(Calendar.DATE, materialSpec.getExpirationDay());
						}
						Date dt1 = rightNow.getTime();
						expirationDay = sDateFormat.format(dt1);
					}
					else
					{
						Date endTime=sDateFormat.parse(makeDate);
						Calendar rightNow = Calendar.getInstance();
						rightNow.setTime(endTime);
						rightNow.add(Calendar.MONTH, 48);
						Date dt1 = rightNow.getTime();
						expirationDay = "2099-12-31 00:00:00";

						//endTime.add(Calendar.MONTH, materialSpec.getExpirationDay());
						//endTime = (endTime).(materialSpec.getExpirationDay());
					}
					//endTime.add(Calendar.MONTH, materialSpec.getExpirationDay());
					//endTime = (endTime).(materialSpec.getExpirationDay());
				}


				//this.txtEndTime.Text = dt.ToString("yyyy年MM月dd日", System.Globalization.DateTimeFormatInfo.InvariantInfo);
//				new SimpleDateFormat().
				Date parse2 = sourceFormat.parse(makeDate);
				String format2 = sDateFormat.format(parse2);
				bindMap.put("makeDate", format2);
				bindMap.put("expiringDate", expirationDay.substring(0,expirationDay.indexOf(" "))+" 00:00:00");
//				bindMap.put("receiveActNo", receiveActNo);
//				bindMap.put("reasonCodeType", reasonCodeType);
//				bindMap.put("reasonCode", reasonCode);
//				bindMap.put("erpLocation", erpLocation);
				bindMap.put("erpFactory", erpFactory);
				bindMap.put("stockInType", "");
//				bindMap.put("unit", materialUnit);
//				if ("是".equals(IS_BATCH)) {
				bindMap.put("charge", boxId.get(i));
//				}
//				if ("否".equals(IQCFLAG)) {
//					bindMap.put("oqaResultState",GenericServiceProxy.getConstantMap().OQA_State_End);
//					bindMap.put("oqaResult","OK");
//					bindMap.put("packingGrade", "OK");
//				} else {
//					bindMap.put("oqaResultState",GenericServiceProxy.getConstantMap().OQA_State_Pre);
//				}
				bindMap.put("PHASE", phase);
				//bindMap.put("supplierCharge", supplierCharge);
//				bindMap.put("supplierName", supplierName);
//				bindMap.put("npFlag", NPFlag);
//				bindMap.put("locationName", locationName );
				materialPacking.setUserColumns(bindMap);

				listMaterialPacking.add(materialPacking);

				box_quantity.put(boxId.get(i), materialquantity);  // 防大数据float精度丢失

//				/** 计算最后一箱的数量 */
//				BigDecimal nextQty = new BigDecimal(EveryBoxQuantity);
//				sumQty = sumQty.add(nextQty);
//				if(nextQty.compareTo(everyQty.subtract(sumQty)) > 0) {
//					EveryBoxQuantity = everyQty.subtract(sumQty).toString();
//				}

			}

			if (EveryBoxQuantity1 > 0) {
				CreateInfo materialPacking = new CreateInfo();
				Map<String, Object> bindMap = new HashMap<String, Object>();
				bindMap.put("materialQuantity", EveryBoxQuantity1);
				bindMap.put("materialCreateQuantity", EveryBoxQuantity1);
				bindMap.put("packingState", "Created");// 标记Box是刚创建的

				materialPacking = listMaterialPacking.get(boxId.size() - 1);
				materialPacking.setUserColumns(bindMap);

				listMaterialPacking.remove(boxId.size() - 1);
				listMaterialPacking.add(materialPacking);
			}


			MaterialPackingServiceProxy.getMaterialPackingService().create(eventInfo, listMaterialPacking);

//			因为float精度问题，再更新一次
			try {
//				for(CreateInfo creatInfo : listMaterialPacking) {
//					String updateSql= " UPDATE MATERIALPACKING SET MATERIALCREATEQUANTITY = :QTY,MATERIALQUANTITY = :QTY"
//							+ " WHERE MATERIALPACKINGNAME = :MATERIALPACKINGNAME AND SITENAME = :SITENAME";
//					Map<String, Object> updateMap = new HashMap<String, Object>();
//					updateMap.put("QTY", box_quantity.get(creatInfo.getMaterialPackingName()));
//					updateMap.put("MATERIALPACKINGNAME", creatInfo.getMaterialPackingName());
//					updateMap.put("SITENAME", siteName);
//					IDMFrameServiceProxy.getSqlTemplate().update(updateSql, updateMap);
//				}
			} catch (IDMFrameDBErrorSignal e) {
//				e.printStackTrace();
				log.info("创建BOX，更新大数据时失败 ==========> ");
			}

			lastEventTimeKey = eventInfo.getEventTimeKey();

		} catch (CustomException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();

		}
		return lastEventTimeKey;
	}

	public static void checkMaterialPackingExist(String materialPackingName) {
		String sql = "SELECT M.STOCKSTATE,M.RECEIVEACTNO FROM MATERIALPACKING M WHERE M.MATERIALPACKINGNAME = :MATERIALPACKINGNAME";

		Map<String, Object> bindMap = new HashMap<String, Object>();
		bindMap.put("MATERIALPACKINGNAME",materialPackingName);
		List<Map<String,Object>> list = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, bindMap);
		if(list.size() > 1) {
			throw new RuntimeException("条码已存在且不止一个,自动入库失败！请联系IT处理！");
		}
		if (list.size() == 1) {
			for (Map<String, Object> map : list) {
				if (!"Created".equals(map.get("STOCKSTATE").toString())) {
					throw new RuntimeException("条码已存在且不为创建状态,请联系IT处理！");
				}
			}
		}

	}

	private String getPublishSubject() {
		String company = System.getProperty("company");
		String factory = System.getProperty("factory");
		String cim = System.getProperty("cim");
		String mode = System.getProperty("mode");
		return company + "." + factory + "." + cim + "." + mode
				+ ".OIC.DashBoardView";
	}
	
	
	
	// （1）MaterialPackingServiceImpl.java文件中增加MaterialPackingOqaResul方法
    public String MaterialPackingOqaResult(String siteName, String sourceMaterialPackingName) {
        MaterialPackingKey materialPackingKey = new MaterialPackingKey();
        materialPackingKey
                .setMaterialPackingName(sourceMaterialPackingName);
        materialPackingKey.setSiteName(siteName);
        // 找出原BOX信息
        MaterialPacking materialPackingData = MaterialPackingServiceProxy
                .getMaterialPackingService()
                .selectByKey(materialPackingKey);
        String Oqaresult = "";
        if (materialPackingData.getOqaResult() == "") {
            Oqaresult = "OQApropelling";
        }
        return Oqaresult;

    }
	
	
	
	//復盤功能
	public Document OICSearchRecheckBox(Document doc,List<String> materialPackingNameList,String siteName) throws Exception {
		try {
			List<MaterialPacking> boxList= new ArrayList<MaterialPacking>();
			
			for (int j = 0; j < materialPackingNameList.size(); j++) {
				MaterialPackingKey keyInfoBox = new MaterialPackingKey();
				MaterialPacking materialPacking = new MaterialPacking();
				keyInfoBox.setMaterialPackingName(materialPackingNameList.get(j));
				keyInfoBox.setSiteName(siteName);
				materialPacking = MaterialPackingServiceProxy.getMaterialPackingService().selectByKey(keyInfoBox);
				boxList.add(materialPacking);	
			}
			doc = new MaterialPackingServiceUtil()
					.writeDocWithMaterialPackingList(doc, boxList);

			return doc;
		} catch (IDMFrameDBErrorSignal ex) {
			ex.printStackTrace();
			throw ex;
		}
	}

	// materialPacking表已经修改其他字段状态，还未修改undoid
	public static String insertUnDOMaterialPackingInfo_v1 = "insert into BS_MATERIALPACKINGUNDOINFO (unDoID,preundoid,UNDODETAILNAME,undoidstate,UNDOIDDATE,ERPEVENTTIME,"
			+ " SITENAME, MATERIALPACKINGNAME, MATERIALPACKINGTYPE, CONTENTMATERIALTYPE,"
			+ "MATERIALTYPE, MATERIALSPECNAME, SUPERMATERIALPACKINGNAME, PACKINGGRADE, SUBPACKINGQUANTITY, MATERIALCREATEQUANTITY,"
			+ "MATERIALQUANTITY, PACKINGSTATE, OLDPACKINGSTATE, STOCKSTATE, OLDSTOCKSTATE, HOLDSTATE, AREANAME, LOCATIONNAME,"
			+ "DURABLENAME, MATERIALPROCESSGROUPNAME, LASTEVENTNAME, LASTEVENTTIMEKEY, LASTEVENTTIME, LASTEVENTUSER,"
			+ "LASTEVENTCOMMENT, CREATETIME, CREATEUSER, RECEIVEREQUESTNAME, RECEIVEREQUESTDETAILNAME,"
			+ "MAKEDATE, RECEIVEACTNO, STOCKINTYPE, RECEIVETIME, RECEIVEUSER, SHIPREQUESTNAME, SHIPREQUESTDETAILNAME, SHIPTIME,"
			+ "SHIPUSER, REASONCODETYPE, OQARESULTSTATE, OQARESULT, ERPLOCATION, ERPFACTORY, REASONCODE, CHARGE, SUPPLIERNAME,ETCSTATE)"
			+ "select :unDoID as unDoID,undoid as preundoid,:unDoDetailName as unDoDetailName,'Created' as undoidstate, :UNDOIDDATE AS UNDOIDDATE,ERPEVENTTIME," //
			+ "SITENAME, MATERIALPACKINGNAME, MATERIALPACKINGTYPE, CONTENTMATERIALTYPE,"
			+ "MATERIALTYPE, MATERIALSPECNAME, SUPERMATERIALPACKINGNAME, PACKINGGRADE, SUBPACKINGQUANTITY, MATERIALCREATEQUANTITY,"
			+ "MATERIALQUANTITY, PACKINGSTATE, OLDPACKINGSTATE, STOCKSTATE, OLDSTOCKSTATE, HOLDSTATE, AREANAME, LOCATIONNAME,"
			+ "DURABLENAME, MATERIALPROCESSGROUPNAME, LASTEVENTNAME, LASTEVENTTIMEKEY, LASTEVENTTIME, LASTEVENTUSER,"
			+ "LASTEVENTCOMMENT, CREATETIME, CREATEUSER, RECEIVEREQUESTNAME, RECEIVEREQUESTDETAILNAME,"
			+ "MAKEDATE, RECEIVEACTNO, STOCKINTYPE, RECEIVETIME, RECEIVEUSER, SHIPREQUESTNAME, SHIPREQUESTDETAILNAME, SHIPTIME,"
			+ "SHIPUSER, REASONCODETYPE, OQARESULTSTATE, OQARESULT, ERPLOCATION, ERPFACTORY, REASONCODE, CHARGE, SUPPLIERNAME,ETCSTATE"
			+ " from MATERIALPACKING m "
			+ " where (sitename,materialpackingname,LASTEVENTTIMEKEY) in ( ";
	// //materialPacking表已经修改全部状态包括undoid
	public static String insertUnDOMaterialPackingInfo_v2 = "insert into BS_MATERIALPACKINGUNDOINFO (unDoID,preundoid,UNDODETAILNAME,undoidstate,UNDOIDDATE,ERPEVENTTIME,"
			+ "SITENAME, MATERIALPACKINGNAME, MATERIALPACKINGTYPE, CONTENTMATERIALTYPE,"
			+ "MATERIALTYPE, MATERIALSPECNAME, SUPERMATERIALPACKINGNAME, PACKINGGRADE, SUBPACKINGQUANTITY, MATERIALCREATEQUANTITY,"
			+ "MATERIALQUANTITY, PACKINGSTATE, OLDPACKINGSTATE, STOCKSTATE, OLDSTOCKSTATE, HOLDSTATE, AREANAME, LOCATIONNAME,"
			+ "DURABLENAME, MATERIALPROCESSGROUPNAME, LASTEVENTNAME, LASTEVENTTIMEKEY, LASTEVENTTIME, LASTEVENTUSER,"
			+ "LASTEVENTCOMMENT, CREATETIME, CREATEUSER, RECEIVEREQUESTNAME, RECEIVEREQUESTDETAILNAME,"
			+ "MAKEDATE, RECEIVEACTNO, STOCKINTYPE, RECEIVETIME, RECEIVEUSER, SHIPREQUESTNAME, SHIPREQUESTDETAILNAME, SHIPTIME,"
			+ "SHIPUSER, REASONCODETYPE, OQARESULTSTATE, OQARESULT, ERPLOCATION, ERPFACTORY, REASONCODE, CHARGE, SUPPLIERNAME,ETCSTATE)"
			+ "select unDoID,:oldUndoid as preundoid,UNDODETAILNAME,'Created' as undoidstate,:UNDOIDDATE AS UNDOIDDATE,ERPEVENTTIME," //
			+ "SITENAME, MATERIALPACKINGNAME, MATERIALPACKINGTYPE, CONTENTMATERIALTYPE,"
			+ "MATERIALTYPE, MATERIALSPECNAME, SUPERMATERIALPACKINGNAME, PACKINGGRADE, SUBPACKINGQUANTITY, MATERIALCREATEQUANTITY,"
			+ "MATERIALQUANTITY, PACKINGSTATE, OLDPACKINGSTATE, STOCKSTATE, OLDSTOCKSTATE, HOLDSTATE, AREANAME, LOCATIONNAME,"
			+ "DURABLENAME, MATERIALPROCESSGROUPNAME, LASTEVENTNAME, LASTEVENTTIMEKEY, LASTEVENTTIME, LASTEVENTUSER,"
			+ "LASTEVENTCOMMENT, CREATETIME, CREATEUSER, RECEIVEREQUESTNAME, RECEIVEREQUESTDETAILNAME,"
			+ "MAKEDATE, RECEIVEACTNO, STOCKINTYPE, RECEIVETIME, RECEIVEUSER, SHIPREQUESTNAME, SHIPREQUESTDETAILNAME, SHIPTIME,"
			+ "SHIPUSER, REASONCODETYPE, OQARESULTSTATE, OQARESULT, ERPLOCATION, ERPFACTORY, REASONCODE, CHARGE, SUPPLIERNAME,ETCSTATE"
			+ " from MATERIALPACKING  " + " where UNDOID=:unDoID ";
	
	// materialPacking表已经修改其他字段状态，还未修改undoid
	public static String insertUnDOMaterialPackingInfo_v3 = "insert into BS_MATERIALPACKINGUNDOINFO (unDoID,preundoid,UNDODETAILNAME,undoidstate,UNDOIDDATE,ERPEVENTTIME,"
			+ " SITENAME, MATERIALPACKINGNAME, MATERIALPACKINGTYPE, CONTENTMATERIALTYPE,"
			+ "MATERIALTYPE, MATERIALSPECNAME, SUPERMATERIALPACKINGNAME, PACKINGGRADE, SUBPACKINGQUANTITY, MATERIALCREATEQUANTITY,"
			+ "MATERIALQUANTITY, PACKINGSTATE, OLDPACKINGSTATE, STOCKSTATE, OLDSTOCKSTATE, HOLDSTATE, AREANAME, LOCATIONNAME,"
			+ "DURABLENAME, MATERIALPROCESSGROUPNAME, LASTEVENTNAME, LASTEVENTTIMEKEY, LASTEVENTTIME, LASTEVENTUSER,"
			+ "LASTEVENTCOMMENT, CREATETIME, CREATEUSER, RECEIVEREQUESTNAME, RECEIVEREQUESTDETAILNAME,"
			+ "MAKEDATE, RECEIVEACTNO, STOCKINTYPE, RECEIVETIME, RECEIVEUSER, SHIPREQUESTNAME, SHIPREQUESTDETAILNAME, SHIPTIME,"
			+ "SHIPUSER, REASONCODETYPE, OQARESULTSTATE, OQARESULT, ERPLOCATION, ERPFACTORY, REASONCODE, CHARGE, SUPPLIERNAME,ETCSTATE)"
			+ "select :unDoID as unDoID,undoid as preundoid,:unDoDetailName as unDoDetailName,'Created' as undoidstate, :UNDOIDDATE AS UNDOIDDATE,ERPEVENTTIME," //
			+ "SITENAME, MATERIALPACKINGNAME, MATERIALPACKINGTYPE, CONTENTMATERIALTYPE,"
			+ "MATERIALTYPE, MATERIALSPECNAME, SUPERMATERIALPACKINGNAME, PACKINGGRADE, SUBPACKINGQUANTITY, MATERIALCREATEQUANTITY,"
			+ "MATERIALQUANTITY, PACKINGSTATE, OLDPACKINGSTATE, STOCKSTATE, OLDSTOCKSTATE, HOLDSTATE, AREANAME, LOCATIONNAME,"
			+ "DURABLENAME, MATERIALPROCESSGROUPNAME, :LASTEVENTNAME, LASTEVENTTIMEKEY, LASTEVENTTIME, LASTEVENTUSER,"
			+ ":LASTEVENTCOMMENT, CREATETIME, CREATEUSER, RECEIVEREQUESTNAME, RECEIVEREQUESTDETAILNAME,"
			+ "MAKEDATE, RECEIVEACTNO, STOCKINTYPE, RECEIVETIME, RECEIVEUSER, SHIPREQUESTNAME, SHIPREQUESTDETAILNAME, SHIPTIME,"
			+ "SHIPUSER, REASONCODETYPE, OQARESULTSTATE, OQARESULT, ERPLOCATION, ERPFACTORY, REASONCODE, CHARGE, SUPPLIERNAME,ETCSTATE"
			+ " from MATERIALPACKING m "
			+ " where (sitename,materialpackingname,LASTEVENTTIMEKEY) in ( ";

	/*
	 * Name : makePreScrapped Desc : This function is makeMaterialPreScrapped
	 * Author : boe cim dev. Date : 2016.01.27
	 */
	public void makePreScrapped(List<String> siteNameList,
			List<String> materialPackingNameList,
			List<String> materialSpecNameList, List<String> unDoDetailNameList,
			List<String> unDoMaterialSpecNameList, String factory,
			String erpLocation, String erpEventTime, EventInfo eventInfo,
			String shipRequestName, List<String> erpLocationList,
			List<String> undoDetalErpLocationList,String receiveActNo,List<String> undoDetalChargeList, List<String> chargeList,String valueERPFactory) throws Exception {
		try {
			
			if (materialPackingNameList.size() == 0) {
				throw new CustomException("PK-0001", "", "");
			}
			CommonValidation cv = new CommonValidation();
			String erpEventTime1 = cv.getDate(erpEventTime) + " 00:00:00";
			EventInfo eventInfoForStockOut=new EventInfo();
			eventInfoForStockOut=eventInfo;
			eventInfoForStockOut.setReasonCode("0001");
			eventInfoForStockOut.setReasonCodeType("valueStockOut");
			for (int i = 0; i < unDoDetailNameList.size(); i++) {
				List<MaterialPacking> mpList = new ArrayList<MaterialPacking>();
				for (int j = 0; j < materialPackingNameList.size(); j++) {
					if (unDoMaterialSpecNameList.get(i).equals(
							materialSpecNameList.get(j))
							&& undoDetalErpLocationList.get(i).equals(
									erpLocationList.get(j))&& undoDetalChargeList.get(i).equals(
											chargeList.get(j))) {
						MaterialPacking materialPacking = new MaterialPacking();
						MaterialPackingKey keyInfo = new MaterialPackingKey();
						if ((undoDetalErpLocationList.get(i)).substring(3, 4)
								.equals("N")) {
							erpLocation = erpLocation.substring(0, 3) + "N";

						} else {
							erpLocation = erpLocation.substring(0, 3) + "B";

						}
						SetEventInfo setEventInfo = new SetEventInfo();
						keyInfo.setMaterialPackingName(materialPackingNameList
								.get(j));
						keyInfo.setSiteName(siteNameList.get(j));
						eventInfoForStockOut.setEventName("ScrapOut");
						Map<String, Object> bindMap= new HashMap<String, Object>();
						bindMap.put("shipRequestName","");
						setEventInfo.setUserColumns(bindMap);
						MaterialPackingServiceProxy.getMaterialPackingService().setEvent(keyInfo, eventInfoForStockOut, setEventInfo);
						materialPacking = MaterialPackingServiceProxy
								.getMaterialPackingService().selectByKey(
										keyInfo);
						if(valueERPFactory.equals("2000")||valueERPFactory.equals("2001"))
						{
							String CHARG = "";
							if(valueERPFactory.equals("2000"))
							{
								CHARG="KSBMD001";
								
							}
							if(valueERPFactory.equals("2001"))
							{
								CHARG="BSBMD001";
								
							}
							materialPacking.setCharge(CHARG);
							
						}
						//add by wt 20180703 B11099工厂启用批次管理，批次值为B1和F  start
						if(valueERPFactory.equals("1000")||valueERPFactory.equals("1099"))
						{
							String CHARG = "";
							
							if ("150N".equals(erpLocation.toString()) || "150B".equals(erpLocation.toString())) {
								CHARG="B1";
							} 
							else if ("190N".equals(erpLocation.toString()) || "190B".equals(erpLocation.toString())) {
								CHARG="F";
							}
							else {
								CHARG="";
							}
							materialPacking.setCharge(CHARG);
						}

						materialPacking.setUnDoDetailName(Integer
								.toString(i + 1));
						materialPacking.setErpFactory(factory);
						materialPacking.setErpLocation(erpLocation);
						materialPacking.setPackingGrade("OK");
						materialPacking.setOqaResult("OK");
						materialPacking
								.setLastEventName("MakeMaterialPreScraped");
						materialPacking
								.setLastEventComment("MakeMaterialPreScraped");
						materialPacking.setReceiveActNo(receiveActNo);
						//materialPacking.setShipRequestName(shipRequestName);
						materialPacking.setReceiveRequestName(shipRequestName);	
						materialPacking.setLastEventTime(eventInfo
								.getEventTime());
						materialPacking.setLastEventUser(eventInfo
								.getEventUser());
						materialPacking.setErpEventTime(Timestamp
								.valueOf(erpEventTime1));
						materialPacking
								.setReasonCode("0001");
						materialPacking.setReasonCodeType("511");
						mpList.add(materialPacking);
					}
				}

				MaterialShipRequestKey materialShipRequestKey = new MaterialShipRequestKey();
				materialShipRequestKey.setShipRequestName(shipRequestName);
				materialShipRequestKey.setSiteName(siteNameList.get(0));

				MaterialShipRequestMakeCompletedInfo makeCompletedInfo = new MaterialShipRequestMakeCompletedInfo();
				MaterialShipRequestServiceProxy.getMaterialShipRequestService()
						.makeCompleted(materialShipRequestKey, eventInfo,
								makeCompletedInfo);
				MaterialPackingServiceProxy.getMaterialPackingService().update(
						mpList);
			}
			eventInfo.setEventName("MakeMaterialPreScraped");
			eventInfo.setReasonCode("0001");
			eventInfo.setReasonCodeType("511");
		} catch (IDMFrameDBErrorSignal ex) {
			log.error(ex, ex);
			throw ex;
		} catch (NotFoundSignal ex) {
			log.error(ex, ex);
			throw ex;
		}

	}

	/*
	 * Name : makeUnPreScrapped Desc : This function is
	 * makeMaterialUnPreScrapped Author : boe cim dev. Date : 2016.01.27
	 */
	public void makeUnPreScrapped(EventInfo eventInfo,
			List<MaterialUnDoinfo> newUnDoList, String UnDoID,
			String erpEventTime, List<String> siteNameList,
			List<String> unDoDetailNameList) throws Exception {
		CommonValidation cv = new CommonValidation();
		if (unDoDetailNameList.size() == 0) {
			throw new CustomException("PK-0001", "", "");
		}
		try {
			String sql_selUndoBoxInfo = " SELECT SITENAME,MATERIALPACKINGNAME ,RECEIVEREQUESTNAME AS SHIPREQUESTNAME "
					+ "FROM MATERIALPACKING "
					+ "WHERE (SITENAME,MATERIALPACKINGNAME) IN( "
					+ "SELECT SITENAME,DESTMATERIALPACKINGNAMENAME AS MATERIALPACKINGNAME  "
					+ "FROM BS_MATERIALPACKINGSPLITMERGE "
					+ "CONNECT BY  MATERIALPACKINGNAME=PRIOR DESTMATERIALPACKINGNAMENAME "
					+ "START WITH (SITENAME,MATERIALPACKINGNAME) IN( "
					+ "SELECT SITENAME,MATERIALPACKINGNAME "
					+ " FROM BS_MATERIALPACKINGUNDOINFO BS "
					+ " WHERE BS.UNDOID=:UNDOID AND "
					+ "BS.SITENAME=:sitename AND BS.UNDODETAILNAME=:undodetailname "
					+ " AND LASTEVENTNAME<>'MToM' )"
					+ " union "
					+ "SELECT SITENAME,MATERIALPACKINGNAME "
					+ "FROM BS_MATERIALPACKINGUNDOINFO BS "
					+ "WHERE BS.UNDOID=:UNDOID AND "
					+ "BS.SITENAME=:sitename AND BS.UNDODETAILNAME=:undodetailname "
					+ "AND LASTEVENTNAME<>'MToM' "
					+ ")"
					+ "and PACKINGSTATE<>'Emptied'";
			String sql_selPreUndoInfo = "select DISTINCT ERPLOCATION,ERPFACTORY,PACKINGGRADE "
					+ "FROM BS_MATERIALPACKINGUNDOINFO A "
					+ "WHERE A.UNDOID IN( "
					+ "SELECT B.PREUNDOID FROM BS_MATERIALPACKINGUNDOINFO B "
					+ "WHERE B.UNDOID=:OLDUNDOID AND B.UNDODETAILNAME=:OLDUNDODETAILNAME "
					+ ") "
					+ "AND A.MATERIALPACKINGNAME IN( "
					+ "SELECT MATERIALPACKINGNAME FROM BS_MATERIALPACKINGSPLITMERGE "
                    + "                           CONNECT BY MATERIALPACKINGNAME = PRIOR DESTMATERIALPACKINGNAMENAME "
                    + "                             START WITH (DESTMATERIALPACKINGNAMENAME) IN (SELECT B.MATERIALPACKINGNAME "
                    + "                     FROM BS_MATERIALPACKINGUNDOINFO B "
                    + "                   WHERE  B.UNDOID = :OLDUNDOID "
                    + "                        AND B.UNDODETAILNAME =:OLDUNDODETAILNAME) "
                    + "                             UNION "
                    + "                           SELECT B.MATERIALPACKINGNAME "
                    + "                   FROM BS_MATERIALPACKINGUNDOINFO B "
                    + "                  WHERE     B.UNDOID = :OLDUNDOID "
                    + "                        AND B.UNDODETAILNAME = "
                    + "                               :OLDUNDODETAILNAME "
					+ ")";
			HashMap<String, String> unDoDetailNameListMap = new HashMap<String, String>();
			for (int i = 0; i < newUnDoList.size(); i++) {
				unDoDetailNameListMap.put(Integer.toString(i + 1),
						unDoDetailNameList.get(i));

			}

			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Date erpdate = sdf.parse(cv.getDate(erpEventTime));
			for (int i = 0; i < newUnDoList.size(); i++) {
				List<MaterialPackingKey> materialPackingKeyList = new ArrayList<MaterialPackingKey>();
				Map<String, Object> bindMap_selUndoBoxInfo = new HashMap<String, Object>();
				Map<String, Object> bindMap_sql_selPreUndoInfo = new HashMap<String, Object>();
				bindMap_selUndoBoxInfo.put("sitename", siteNameList.get(i));
				bindMap_selUndoBoxInfo.put("UNDOID", UnDoID);
				bindMap_selUndoBoxInfo.put("undodetailname",
						unDoDetailNameListMap.get(newUnDoList.get(i).getSeq().substring(15)));
				bindMap_sql_selPreUndoInfo.put("OLDUNDOID", UnDoID);
				bindMap_sql_selPreUndoInfo.put("OLDUNDODETAILNAME",
						unDoDetailNameListMap.get(newUnDoList.get(i).getSeq().substring(15)));
				// bindMap_UndoBoxInfo.put("REQUESTDETAILNAME",requestDetailName);
				List<Map<String, Object>> queryResult_BoxInfo = IDMFrameServiceProxy
						.getSqlTemplate()
						
						.queryForList(sql_selUndoBoxInfo,
								bindMap_selUndoBoxInfo);
				List<Map<String, Object>> queryResult_PreUndoInfo = IDMFrameServiceProxy
						.getSqlTemplate()
						
						.queryForList(sql_selPreUndoInfo,
								bindMap_sql_selPreUndoInfo);
				for (int j = 0; j < queryResult_BoxInfo.size(); j++) {
					MaterialPackingKey keyInfo = new MaterialPackingKey();
					keyInfo.setMaterialPackingName(queryResult_BoxInfo.get(j)
							.get("MATERIALPACKINGNAME").toString());
					keyInfo.setSiteName(queryResult_BoxInfo.get(j)
							.get("SITENAME").toString());
					// keyInfo=(materialPackingList.get(i).getKey());
					materialPackingKeyList.add(keyInfo);
				}
				String shipRequestName = queryResult_BoxInfo.get(0)
						.get("SHIPREQUESTNAME").toString();
				String siteName = siteNameList.get(0);
				MaterialShipRequestKey materialShipRequestKey = new MaterialShipRequestKey();
				materialShipRequestKey.setShipRequestName(shipRequestName);
				materialShipRequestKey.setSiteName(siteName);

				MaterialShipRequestMakeReservedInfo makeReservedInfo = new MaterialShipRequestMakeReservedInfo();
				String sql_updateDetail="UPDATE MATERIALSHIPREQUESTDETAIL SET ASSIGNEDQUANTITY=0 WHERE SHIPREQUESTNAME=:SHIPREQUESTNAME AND SITENAME=:SITENAME";
				Map<String, Object> bindMap1 = new HashMap<String, Object>();
				bindMap1.put("SHIPREQUESTNAME", shipRequestName);
				bindMap1.put("SITENAME", siteName);
				IDMFrameServiceProxy.getSqlTemplate().update(sql_updateDetail, bindMap1);
				SetEventInfo setEventInfo = new SetEventInfo();
				Map<String, Object> bindMap = new HashMap<String, Object>();
				bindMap.put("packingState", "Released");
				bindMap.put("erpEventTime", erpdate);
				bindMap.put("erpState","SUCCESS");
				bindMap.put("unDoID", newUnDoList.get(i).getUnDoID());
				bindMap.put("unDoDetailName", newUnDoList.get(i)
						.getUnDoDetailName());
				bindMap.put("erpLocation",
						queryResult_PreUndoInfo.get(0).get("ERPLOCATION"));
				bindMap.put("erpFactory",
						queryResult_PreUndoInfo.get(0).get("ERPFACTORY"));
				bindMap.put("packingGrade",
						queryResult_PreUndoInfo.get(0).get("PACKINGGRADE")==null?"":queryResult_PreUndoInfo.get(0).get("PACKINGGRADE").toString());
				setEventInfo.setUserColumns(bindMap);
				MaterialShipRequestServiceProxy.getMaterialShipRequestService()
						.makeReserved(materialShipRequestKey, eventInfo,
								makeReservedInfo);
				MaterialPackingServiceProxy.getMaterialPackingService()
						.setEvent(materialPackingKeyList, eventInfo,
								setEventInfo);
			}

			String sql_UndoBoxInfo = " UPDATE BS_MATERIALPACKINGUNDOINFO A SET UNDOIDSTATE='N' WHERE A.UNDOID=:UNDOID AND MATERIALPACKINGNAME IN (SELECT MATERIALPACKINGNAME"
					+ " FROM BS_MATERIALPACKINGUNDOINFO BS"
					+ " WHERE BS.UNDOID=:UNDOID AND("
					+ " ("
					+ " BS.UNDODETAILNAME=:UNDODETAILNAME"
					+ " AND BS.SITENAME=:SITENAME"
					+ " )"
					+ " AND UNDOIDSTATE<>'N'" + " AND LASTEVENTNAME<>'MToM'))";
			String sql_insert = insertUnDOMaterialPackingInfo_v2
					+ " AND UNDODETAILNAME = :unDoDetailName ";
			for (int i = 0; i < unDoDetailNameList.size(); i++) {
				Map<String, Object> bindMap_UndoBoxInfo = new HashMap<String, Object>();
				Map<String, Object> bindMap_insert = new HashMap<String, Object>();
				bindMap_UndoBoxInfo.put("SITENAME", siteNameList.get(i));
				bindMap_UndoBoxInfo.put("UNDOID", UnDoID);
				bindMap_UndoBoxInfo.put("UNDODETAILNAME",
						unDoDetailNameList.get(i));
				bindMap_insert.put("unDoID", newUnDoList.get(i).getUnDoID());
				bindMap_insert.put("oldUndoid", UnDoID);
				bindMap_insert.put("UNDOIDDATE", newUnDoList.get(i)
						.getUnDoIdDate());
				bindMap_insert.put("unDoDetailName", newUnDoList.get(i)
						.getUnDoDetailName());
				IDMFrameServiceProxy.getSqlTemplate()
						.update(sql_UndoBoxInfo, bindMap_UndoBoxInfo);
				IDMFrameServiceProxy.getSqlTemplate()
						.update(sql_insert, bindMap_insert);

			}

		} catch (IDMFrameDBErrorSignal ex) {
			log.error(ex, ex);
			throw ex;
		} catch (NotFoundSignal ex) {
			log.error(ex, ex);
			throw ex;
		}
	}

	/*
	 * Name : makeScrapped Desc : This function is makeMaterialScrapped Author :
	 * boe cim dev. Date : 2016.01.27
	 */
	public void NoValueStockOut(String requestDetailName,
			EventInfo eventInfo,String receiveActNo) throws Exception {
		String sql = "select MATERIALPACKINGNAME,SITENAME "
				+ "from MATERIALPACKING bs "
				+ "where "
				+ "(BS.SITENAME,BS.MATERIALPACKINGNAME) in ( "
				+ "select regexp_substr(id ,  '[^|]+', 1, 1) AS c1,regexp_substr(id  , '[^|]+', 1, 2 ) AS c2 "
				+ "from (select regexp_substr(id, '[^,]+' ,1 ,rownum) id from (select  :REQUESTDETAILNAME id from dual) a "
				+ "connect by rownum- 1 <= length(regexp_replace(id, '[^,]+')) "
				+ ") ) ";
		try {
			Map<String, Object> bindMap = new HashMap<String, Object>();
			bindMap.put("REQUESTDETAILNAME", requestDetailName);
			List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
					.getSqlTemplate()
					.queryForList(sql, bindMap);
			List<MaterialPackingKey> materialPackingKeyList = new ArrayList<MaterialPackingKey>();

			for (int i = 0; i < sqlResult.size(); i++) {
						MaterialPackingKey keyInfo = new MaterialPackingKey();
						keyInfo.setMaterialPackingName(sqlResult.get(i).get("MATERIALPACKINGNAME").toString());
						keyInfo.setSiteName(sqlResult.get(i).get("SITENAME").toString());
						materialPackingKeyList.add(keyInfo);
						}
			SetEventInfo setEventInfo = new SetEventInfo();
			Map<String, Object> bindMap2 = new HashMap<String, Object>();
			bindMap2.put("stockState", "StockOut");
			bindMap2.put("packingState", "Completed");
			bindMap2.put("erpState", "SUCCESS");
			bindMap2.put("receiveActNo", receiveActNo);
			setEventInfo.setUserColumns(bindMap2);
				MaterialPackingServiceProxy.getMaterialPackingService().setEvent(materialPackingKeyList, eventInfo, setEventInfo);
				// SetEventInfo setEventInfo = new SetEventInfo();
				
			// MaterialPackingServiceProxy.getMaterialPackingService().makeScrapped(materialPackingKey,
			// eventInfo, makeScrappedInfo);
		} catch (IDMFrameDBErrorSignal ex) {
			log.error(ex, ex);
			throw ex;
		} catch (NotFoundSignal ex) {
			log.error(ex, ex);
			throw ex;
		}
	}

	/*
	 * Name : makePreScrapped Desc : This function is MaterialPreStockOut
	 * Author : boe cim dev. Date : 2019.03.02
	 */
	public void PreStockOut(EventInfo eventInfo, String siteName, String  materialPackingName, String locationName) throws Exception {
		try {
			String[] materialPackingNameList = materialPackingName.split("\\|");
			List<MaterialPackingKey> mpKeyList = new ArrayList<MaterialPackingKey>();
			for (int i = 0; i < materialPackingNameList.length; i++) {
				MaterialPackingKey mpk = new MaterialPackingKey();
				mpk.setSiteName(siteName);
				mpk.setMaterialPackingName(materialPackingNameList[i]);
				mpKeyList.add(mpk);
			}
			Map<String, Object> bindMap_ACT = new HashMap<String,Object>();
			bindMap_ACT.put("stockState", "PreStockOut");
			bindMap_ACT.put("locationName", locationName);
			SetEventInfo setEventInfo=new SetEventInfo();
			setEventInfo.setUserColumns(bindMap_ACT);
			MaterialPackingServiceProxy.getMaterialPackingService().setEvent(mpKeyList, eventInfo, setEventInfo);
		} catch (IDMFrameDBErrorSignal ex) {
			log.error(ex, ex);
			throw ex;
		} catch (NotFoundSignal ex) {
			log.error(ex, ex);
			throw ex;
		}
	}
	
	/*	
	 * Name : durableBinding Desc : This function is CarrierBinding
	 * Author : boe cim dev. Date : 2019.03.25
	 */
	public void durableBinding(EventInfo eventInfo, String siteName,String durableName,String assignedPackingQuantity, String shipRequestName,String materialPackingName)throws Exception {
		try{
			String[] materialPackingNameList = materialPackingName.split("\\|");
			Timestamp lastEventTime = new Timestamp(System.currentTimeMillis());
			
			MaterialPackingKey key = new MaterialPackingKey();
			key.setSiteName(siteName);
			key.setMaterialPackingName(materialPackingNameList[0]);
			MaterialPacking mp = MaterialPackingServiceProxy.getMaterialPackingService().selectByKey(key);
			
			String durableState = "USED";
			if(mp.getMaterialSpecName().startsWith("44-971")||mp.getMaterialSpecName().startsWith("44-977")){
				durableState = "IDLE";
			}
			
			String sql_updateDurable=" UPDATE DURABLE SET DURABLESTATE = :DURABLESTATE, ASSIGNEDPACKINGQUANTITY =:ASSIGNEDPACKINGQUANTITY , SHIPREQUESTNAME =:SHIPREQUESTNAME,"
					+"LASTEVENTNAME = :LASTEVENTNAME, LASTEVENTTIME=:LASTEVENTTIME, LASTEVENTUSER=:LASTEVENTUSER "
					+" WHERE SITENAME=:SITENAME AND DURABLENAME=:DURABLENAME";

			Map<String, Object> bindMap_ACT = new HashMap<String, Object>();
			bindMap_ACT.put("ASSIGNEDPACKINGQUANTITY", assignedPackingQuantity);
			bindMap_ACT.put("SHIPREQUESTNAME", shipRequestName);
			bindMap_ACT.put("LASTEVENTNAME",eventInfo.getEventName());
			bindMap_ACT.put("LASTEVENTTIME",lastEventTime);
			bindMap_ACT.put("LASTEVENTUSER",eventInfo.getEventUser());
			bindMap_ACT.put("SITENAME",siteName);
			bindMap_ACT.put("DURABLENAME",durableName);
			bindMap_ACT.put("DURABLESTATE", durableState);
			IDMFrameServiceProxy.getSqlTemplate().update(sql_updateDurable,bindMap_ACT);
			
			for(int i = 0 ; i < materialPackingNameList.length ; i++){
				List<MaterialPackingKey> mpKeyList = new ArrayList<MaterialPackingKey>();
				MaterialPackingKey mpk = new MaterialPackingKey();
				mpk.setSiteName(siteName);
				mpk.setMaterialPackingName(materialPackingNameList[i]);
				mpKeyList.add(mpk);
				
				Map<String, Object> bindMap = new HashMap<String,Object>();
				bindMap.put("durableName", durableName);
				SetEventInfo setEventInfo=new SetEventInfo();
				setEventInfo.setUserColumns(bindMap);
				MaterialPackingServiceProxy.getMaterialPackingService().setEvent(mpKeyList, eventInfo, setEventInfo);
				
			}
		}catch(IDMFrameDBErrorSignal ex){
			log.error(ex, ex);
			throw ex;
		}catch(NotFoundSignal ex){
			log.error(ex, ex);
			throw ex;
		}
	}
	
	/*	
	 * Name : durableBinding Desc : This function is CarrierBinding
	 * Author : boe cim dev. Date : 2019.03.25
	 */
	public void PDADurableBinding(EventInfo eventInfo, String siteName,String durableName, String shipRequestName,String materialPackingName)throws Exception {
		try{
			
			Timestamp lastEventTime = new Timestamp(System.currentTimeMillis());
			MaterialPackingKey mpk = new MaterialPackingKey();
			mpk.setSiteName(siteName);
			mpk.setMaterialPackingName(materialPackingName);
			
			MaterialPacking mp = new MaterialPacking();
			mp = MaterialPackingServiceProxy
					.getMaterialPackingService().selectByKey(
							mpk);
			String durableState = "USED";
			if(mp.getMaterialSpecName().startsWith("44-971")||mp.getMaterialSpecName().startsWith("44-977")){
				durableState = "IDLE";
			}
			
			String sql_updateDurable=" UPDATE DURABLE SET DURABLESTATE = :DURABLESTATE, ASSIGNEDPACKINGQUANTITY =ASSIGNEDPACKINGQUANTITY+1 , SHIPREQUESTNAME =:SHIPREQUESTNAME,"
					+"LASTEVENTNAME = :LASTEVENTNAME, LASTEVENTTIME=:LASTEVENTTIME, LASTEVENTUSER=:LASTEVENTUSER "
					+" WHERE SITENAME=:SITENAME AND DURABLENAME=:DURABLENAME";

			Map<String, Object> bindMap_ACT = new HashMap<String, Object>();
			bindMap_ACT.put("SHIPREQUESTNAME", shipRequestName);
			bindMap_ACT.put("LASTEVENTNAME",eventInfo.getEventName());
			bindMap_ACT.put("LASTEVENTTIME",lastEventTime);
			bindMap_ACT.put("LASTEVENTUSER",eventInfo.getEventUser());
			bindMap_ACT.put("SITENAME",siteName);
			bindMap_ACT.put("DURABLENAME",durableName);
			bindMap_ACT.put("DURABLESTATE", durableState);
			IDMFrameServiceProxy.getSqlTemplate().update(sql_updateDurable,bindMap_ACT);
						
			Map<String, Object> bindMap = new HashMap<String,Object>();
			bindMap.put("durableName", durableName);
			SetEventInfo setEventInfo=new SetEventInfo();
			setEventInfo.setUserColumns(bindMap);
			MaterialPackingServiceProxy.getMaterialPackingService().setEvent(mpk, eventInfo, setEventInfo);
		}catch(IDMFrameDBErrorSignal ex){
			log.error(ex, ex);
			throw ex;
		}catch(NotFoundSignal ex){
			log.error(ex, ex);
			throw ex;
		}
	}
	
	/*	
	 * Name : CanceldurableBinding Desc : This function is CarrierBinding
	 * Author : boe cim dev. Date : 2019.05.18
	 */
	public void cancelBinding(EventInfo eventInfo, String siteName,String durableName,String assignedPackingQuantity, String materialPackingName)throws Exception {
		try{
			Timestamp lastEventTime = new Timestamp(System.currentTimeMillis());
			List<MaterialPackingKey> mpKeyList = new ArrayList<MaterialPackingKey>();
			MaterialPackingKey mpk = new MaterialPackingKey();
			mpk.setSiteName(siteName);
			mpk.setMaterialPackingName(materialPackingName);
			mpKeyList.add(mpk);
			
			String durableState;
			String sql_updateDurable;
			int afterCancelQuantity = Integer.parseInt(assignedPackingQuantity) - 1;
			if(afterCancelQuantity > 0){
				durableState = "USED";
				sql_updateDurable=" UPDATE DURABLE SET DURABLESTATE =:DURABLESTATE, ASSIGNEDPACKINGQUANTITY =:ASSIGNEDPACKINGQUANTITY,"
						+"LASTEVENTNAME = :LASTEVENTNAME, LASTEVENTTIME=:LASTEVENTTIME, LASTEVENTUSER=:LASTEVENTUSER "
						+" WHERE SITENAME=:SITENAME AND DURABLENAME=:DURABLENAME";
			}else{
				durableState = "IDLE";
				sql_updateDurable=" UPDATE DURABLE SET DURABLESTATE =:DURABLESTATE, SHIPREQUESTNAME ='', ASSIGNEDPACKINGQUANTITY =:ASSIGNEDPACKINGQUANTITY,"
						+"LASTEVENTNAME = :LASTEVENTNAME, LASTEVENTTIME=:LASTEVENTTIME, LASTEVENTUSER=:LASTEVENTUSER "
						+" WHERE SITENAME=:SITENAME AND DURABLENAME=:DURABLENAME";
			}

			Map<String, Object> bindMap_ACT = new HashMap<String, Object>();
			bindMap_ACT.put("DURABLESTATE", durableState);
			bindMap_ACT.put("ASSIGNEDPACKINGQUANTITY", afterCancelQuantity);
			bindMap_ACT.put("LASTEVENTNAME",eventInfo.getEventName());
			bindMap_ACT.put("LASTEVENTTIME",lastEventTime);
			bindMap_ACT.put("LASTEVENTUSER",eventInfo.getEventUser());
			bindMap_ACT.put("SITENAME",siteName);
			bindMap_ACT.put("DURABLENAME",durableName);
			IDMFrameServiceProxy.getSqlTemplate()
			.update(sql_updateDurable,bindMap_ACT);
			
			
			Map<String, Object> bindMap = new HashMap<String,Object>();
			String durable = "";
			bindMap.put("durableName", durable);
			SetEventInfo setEventInfo=new SetEventInfo();
			setEventInfo.setUserColumns(bindMap);
			MaterialPackingServiceProxy.getMaterialPackingService().setEvent(mpKeyList, eventInfo, setEventInfo);
		}catch(IDMFrameDBErrorSignal ex){
			log.error(ex, ex);
			throw ex;
		}catch(NotFoundSignal ex){
			log.error(ex, ex);
			throw ex;
		}
	}
	
	public List<MaterialPackingKey>  makeScrapped(List<String> siteNameList,
			List<String> materialPackingNameList,
			List<String> materialSpecNameList, String requestDetailName,
			String erpEventTime, EventInfo eventInfo,String receiveActNo) throws Exception {
		if (materialPackingNameList.size() == 0) {
			throw new CustomException("PK-0001", "", "");
		}
		String sql = "select MATERIALSPECNAME,SUM(MATERIALQUANTITY) AS QUANTITY,ERPFACTORY,ERPLOCATION ,CHARGE "
				+ "from MATERIALPACKING bs "
				+ "where "
				+ "(BS.SITENAME,BS.MATERIALPACKINGNAME) in ( "
				+ "select regexp_substr(id ,  '[^|]+', 1, 1) AS c1,regexp_substr(id  , '[^|]+', 1, 2 ) AS c2 "
				+ "from (select regexp_substr(id, '[^,]+' ,1 ,rownum) id from (select  :REQUESTDETAILNAME id from dual) a "
				+ "connect by rownum- 1 <= length(regexp_replace(id, '[^,]+')) "
				+ ") ) "
				+ "GROUP BY MATERIALSPECNAME,ERPFACTORY,ERPLOCATION,CHARGE";
		try {
			CommonValidation cv = new CommonValidation();
			Map<String, Object> bindMap = new HashMap<String, Object>();
			bindMap.put("REQUESTDETAILNAME", requestDetailName);
			List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
					.getSqlTemplate()
					.queryForList(sql, bindMap);
			// Date erpdate = sdf.parse(erpEventTime);
			String erpEventTime1 = cv.getDate(erpEventTime) + " 00:00:00";
			List<MaterialPackingKey> materialPackingKeyList = new ArrayList<MaterialPackingKey>();
			// List<MaterialPackingKey> materialPackingKey = new
			// ArrayList<MaterialPackingKey>();
			for (int i = 0; i < sqlResult.size(); i++) {
				List<MaterialPacking> mpList = new ArrayList<MaterialPacking>();
				
				for (int j = 0; j < materialPackingNameList.size(); j++) {
					if (materialSpecNameList.get(j).equals(
							sqlResult.get(i).get("MATERIALSPECNAME"))) {
						MaterialPacking materialPacking = new MaterialPacking();
						MaterialPackingKey keyInfo = new MaterialPackingKey();
						keyInfo.setMaterialPackingName(materialPackingNameList
								.get(j));
						keyInfo.setSiteName(siteNameList.get(j));
						materialPacking = MaterialPackingServiceProxy
								.getMaterialPackingService().selectByKey(
										keyInfo);
						materialPacking.setUnDoDetailName(Integer
								.toString(i + 1));
						materialPacking.setPackingState("Scrapped");
						materialPacking.setReceiveActNo(receiveActNo);
						materialPacking.setLastEventName("MakeMaterialScraped");
						// materialPacking.setLastEventTimeKey(eventInfo.getEventTimeKey());
						materialPacking.setLastEventTime(eventInfo
								.getEventTime());
						materialPacking.setLastEventUser(eventInfo
								.getEventUser());
						materialPacking
								.setLastEventComment("MakeMaterialScraped");
						materialPacking.setErpEventTime(Timestamp
								.valueOf(erpEventTime1));
						materialPacking
								.setReasonCode(eventInfo.getReasonCode());
						materialPacking.setReasonCodeType(eventInfo
								.getReasonCodeType());
						// materialPackingInfo.setKey(keyInfo);
						mpList.add(materialPacking);
						materialPackingKeyList.add(keyInfo);
					}

				}
				MaterialPackingServiceProxy.getMaterialPackingService().update(
						mpList);
				// SetEventInfo setEventInfo = new SetEventInfo();
				
			}
			return materialPackingKeyList;
			// MaterialPackingServiceProxy.getMaterialPackingService().makeScrapped(materialPackingKey,
			// eventInfo, makeScrappedInfo);
		} catch (IDMFrameDBErrorSignal ex) {
			log.error(ex, ex);
			throw ex;
		} catch (NotFoundSignal ex) {
			log.error(ex, ex);
			throw ex;
		}
	}
	
	public List<MaterialPackingKey>  makeScrappedByReceiveactNo(String siteName,
			List<MaterialPacking> materialPackingList,
			String erpEventTime, EventInfo eventInfo,String receiveActNo ,String receiveRequestName) throws Exception {
		if (materialPackingList.size() == 0) {
			throw new CustomException("PK-0001", "", "");
		}
		String sql = "select MATERIALSPECNAME,SUM(MATERIALQUANTITY) AS QUANTITY,ERPFACTORY,ERPLOCATION,CHARGE "
				+ "from MATERIALPACKING bs "
				+ "where "
				+ " bs.receiveactno= :receiveactNo and sitename= :siteName and materialpackingtype='Box' "
				+ "GROUP BY MATERIALSPECNAME,ERPFACTORY,ERPLOCATION,CHARGE";
		try {
			CommonValidation cv = new CommonValidation();
			Map<String, Object> bindMap = new HashMap<String, Object>();
			bindMap.put("receiveactNo", receiveActNo);
			bindMap.put("siteName", siteName);
			List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
					.getSqlTemplate()
					.queryForList(sql, bindMap);
			// Date erpdate = sdf.parse(erpEventTime);
			String erpEventTime1 = cv.getDate(erpEventTime) + " 00:00:00";
			List<MaterialPackingKey> materialPackingKeyList = new ArrayList<MaterialPackingKey>();
			// List<MaterialPackingKey> materialPackingKey = new
			// ArrayList<MaterialPackingKey>();
			List<MaterialPacking> mpList = new ArrayList<MaterialPacking>();
			for (int i = 0; i < sqlResult.size(); i++) {
				for (int j = 0; j < materialPackingList.size(); j++) {
					if (materialPackingList.get(j).getMaterialSpecName().equals(
							sqlResult.get(i).get("MATERIALSPECNAME").toString())&&materialPackingList.get(j).getCharge().equals(sqlResult.get(i).get("CHARGE")==null?"":sqlResult.get(i).get("CHARGE").toString())) {
							MaterialPacking materialPacking = new MaterialPacking();
							MaterialPackingKey keyInfo = materialPackingList
									.get(j).getKey();
							materialPacking = MaterialPackingServiceProxy
									.getMaterialPackingService().selectByKey(
											keyInfo);
							materialPacking.setUnDoDetailName(Integer
									.toString(i + 1));
							materialPacking.setPackingState("Scrapped");
							materialPacking.setStockState("StockOut");
							materialPacking.setReceiveActNo(receiveActNo);
							materialPacking.setLastEventName("MakeMaterialScraped");
							// materialPacking.setLastEventTimeKey(eventInfo.getEventTimeKey());
							materialPacking.setLastEventTime(eventInfo
									.getEventTime());
							materialPacking.setLastEventUser(eventInfo
									.getEventUser());
							materialPacking
									.setLastEventComment("MakeMaterialScraped");
							materialPacking.setErpEventTime(Timestamp
									.valueOf(erpEventTime1));
							materialPacking
									.setReasonCode(eventInfo.getReasonCode());
							materialPacking.setReasonCodeType(eventInfo
									.getReasonCodeType());
							// materialPackingInfo.setKey(keyInfo);
							mpList.add(materialPacking);
							materialPackingKeyList.add(keyInfo);
							}
						}
	
					
				
			}
			if(mpList.size()>0)
			{
				MaterialPackingServiceProxy.getMaterialPackingService().update(
					mpList);
			}
			MaterialReceiveActKey receiveActKey=new MaterialReceiveActKey(siteName, receiveRequestName, receiveActNo);
			Map<String, Object> bindMap1 = new HashMap<String, Object>();
			bindMap1.put("receiveActState", "Completed");
			com.cim.idm.wmspackage.materialreceiverequestact.management.info.SetEventInfo setEventInfo = new com.cim.idm.wmspackage.materialreceiverequestact.management.info.SetEventInfo();
			setEventInfo.setUserColumns(bindMap1);
			MaterialReceiveRequestActServiceProxy.getReceiveRequestBatchService().setEvent(receiveActKey, eventInfo, setEventInfo);
			return materialPackingKeyList;
			// MaterialPackingServiceProxy.getMaterialPackingService().makeScrapped(materialPackingKey,
			// eventInfo, makeScrappedInfo);
		} catch (IDMFrameDBErrorSignal ex) {
			log.error(ex, ex);
			throw ex;
		} catch (NotFoundSignal ex) {
			log.error(ex, ex);
			throw ex;
		}
	}
	public void insertScrappedInfo(List<MaterialUnDoinfo> materialUnDoinfoList,
			EventInfo eventInfo,String receiveActNo) throws Exception {
		// List<MaterialUnDoinfo> materialUnDoinfoList=new
		// ERPInterfaceServiceImpl().erpInterface_WMS19(shipType,requestDetailName,eventInfo);

		if (materialUnDoinfoList.size() == 0) {
			throw new CustomException("PK-0001", "", "");
		}

		try {
			String sql_sel = "SELECT MATERIALPACKINGNAME,SITENAME FROM MATERIALPACKING  where UNDODETAILNAME=:seq AND RECEIVEACTNO = :receiveActNo ";
			// String
			// sql="update MATERIALPACKING set UNDODETAILNAME=:unDoDetailName,UNDOID=:unDoID where UNDODETAILNAME=:seq";
			String sql2 = insertUnDOMaterialPackingInfo_v3
					+ "select P.SITENAME,P.MATERIALPACKINGNAME,P.LASTEVENTTIMEKEY FROM MATERIALPACKING P WHERE P.UNDODETAILNAME=:seq AND P.RECEIVEACTNO = :receiveActNo)	";

			for (int i = 0; i < materialUnDoinfoList.size(); i++) {
				Map<String, Object> bindMap = new HashMap<String, Object>();
				Map<String, Object> bindMap1 = new HashMap<String, Object>();
				if(materialUnDoinfoList.get(i).getSeq().length()>15)
				{
					bindMap1.put("seq", materialUnDoinfoList.get(i).getSeq().substring(15));
				}
				else
				{
					bindMap1.put("seq", materialUnDoinfoList.get(i).getSeq());
				}
				//bindMap1.put("seq", materialUnDoinfoList.get(i).getSeq().substring(15));
				bindMap1.put("receiveActNo", materialUnDoinfoList.get(i).getReceiveActNo());
				List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
						.getSqlTemplate()
						.queryForList(sql_sel, bindMap1);
				List<MaterialPackingKey> materialPackingKeyList = new ArrayList<MaterialPackingKey>();
				for (int j = 0; j < sqlResult.size(); j++) {
					MaterialPackingKey keyInfo = new MaterialPackingKey();
					keyInfo.setMaterialPackingName(sqlResult.get(j)
							.get("MATERIALPACKINGNAME").toString());
					keyInfo.setSiteName(sqlResult.get(j).get("SITENAME")
							.toString());
					// materialPackingInfo.setKey(keyInfo);
					materialPackingKeyList.add(keyInfo);
				}
				SetEventInfo setEventInfo = new SetEventInfo();
				Map<String, Object> bindMap2 = new HashMap<String, Object>();
				bindMap2.put("unDoDetailName", materialUnDoinfoList.get(i)
						.getUnDoDetailName());
				bindMap2.put("unDoID", materialUnDoinfoList.get(i).getUnDoID());
				bindMap2.put("erpState", "SUCCESS");
				setEventInfo.setUserColumns(bindMap2);
				bindMap.put("unDoDetailName", materialUnDoinfoList.get(i)
						.getUnDoDetailName());
				bindMap.put("unDoID", materialUnDoinfoList.get(i).getUnDoID());
				if(materialUnDoinfoList.get(i).getSeq().length()>15)
				{
					bindMap.put("seq", materialUnDoinfoList.get(i).getSeq().substring(15));
				}
				else
				{
					bindMap.put("seq", materialUnDoinfoList.get(i).getSeq());
				}
				/*
				 * if((sqlResult.get(0).get("SITENAME").toString().equals("B5"))||(sqlResult.get
				 * (0).get("SITENAME").toString().equals("TM1"))) { bindMap.put("stockState",
				 * "StockOut"); }
				 */
				//bindMap.put("seq", materialUnDoinfoList.get(i).getSeq().substring(15));
				bindMap.put("receiveActNo", receiveActNo);
				bindMap.put("UNDOIDDATE", materialUnDoinfoList.get(i)
						.getUnDoIdDate());
				bindMap.put("LASTEVENTNAME", eventInfo.getEventName());
				bindMap.put("LASTEVENTCOMMENT", eventInfo.getEventComment());
				int result = IDMFrameServiceProxy.getSqlTemplate()
						.update(sql2, bindMap);
				MaterialPackingServiceProxy.getMaterialPackingService()
						.setEvent(materialPackingKeyList, eventInfo,
								setEventInfo);
			}
			// MaterialPackingServiceProxy.getMaterialPackingService().makeScrapped(materialPackingKey,
			// eventInfo, makeScrappedInfo);
		} catch (IDMFrameDBErrorSignal ex) {
			log.error(ex, ex);
			throw ex;
		} catch (NotFoundSignal ex) {
			log.error(ex, ex);
			throw ex;
		}
	}

	/*
	 * Name : makeUnScrapped Desc : This function is makeMaterialUnScrapped
	 * Author : boe cim dev. Date : 2016.01.27
	 */
	public void makeUnDo(EventInfo eventInfo,
			List<MaterialUnDoinfo> newUnDoList, String UnDoID,
			String erpEventTime, List<String> siteNameList,
			List<String> unDoDetailNameList, List<String> receiveRequestNameList) throws Exception {
		CommonValidation cv = new CommonValidation();
		if (unDoDetailNameList.size() == 0) {
			throw new CustomException("PK-0001", "", "");
		}
		try {
			String sql_selUndoBoxInfo = " SELECT SITENAME,MATERIALPACKINGNAME,RECEIVEACTNO "
					+ "FROM MATERIALPACKING "
					+ "WHERE (SITENAME,MATERIALPACKINGNAME) IN( "
					+ "SELECT SITENAME,DESTMATERIALPACKINGNAMENAME AS MATERIALPACKINGNAME  "
					+ "FROM BS_MATERIALPACKINGSPLITMERGE "
					+ "CONNECT BY  MATERIALPACKINGNAME=PRIOR DESTMATERIALPACKINGNAMENAME "
					+ "START WITH (SITENAME,MATERIALPACKINGNAME) IN( "
					+ "SELECT SITENAME,MATERIALPACKINGNAME "
					+ " FROM BS_MATERIALPACKINGUNDOINFO BS "
					+ " WHERE BS.UNDOID=:UNDOID AND "
					+ "BS.SITENAME=:sitename AND BS.UNDODETAILNAME=:undodetailname "
					+ " AND LASTEVENTNAME<>'MToM' )"
					+ " union "
					+ "SELECT SITENAME,MATERIALPACKINGNAME "
					+ "FROM BS_MATERIALPACKINGUNDOINFO BS "
					+ "WHERE BS.UNDOID=:UNDOID AND "
					+ "BS.SITENAME=:sitename AND BS.UNDODETAILNAME=:undodetailname "
					+ "AND LASTEVENTNAME<>'MToM' " + ")"
					+ "and PACKINGSTATE<>'Emptied'";

			HashMap<String, String> unDoDetailNameListMap = new HashMap<String, String>();
			for (int i = 0; i < newUnDoList.size(); i++) {
				unDoDetailNameListMap.put(Integer.toString(i + 1),
						unDoDetailNameList.get(i));

			}
			String receiveActNo="";
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Date erpdate = sdf.parse(cv.getDate(erpEventTime));
			for (int i = 0; i < newUnDoList.size(); i++) {
				List<MaterialPackingKey> materialPackingKeyList = new ArrayList<MaterialPackingKey>();
				Map<String, Object> bindMap_selUndoBoxInfo = new HashMap<String, Object>();
				bindMap_selUndoBoxInfo.put("sitename", siteNameList.get(i));
				bindMap_selUndoBoxInfo.put("UNDOID", UnDoID);
				bindMap_selUndoBoxInfo.put("undodetailname",
						unDoDetailNameListMap.get(newUnDoList.get(i).getSeq().substring(15)));
				// bindMap_UndoBoxInfo.put("REQUESTDETAILNAME",requestDetailName);
				List<Map<String, Object>> queryResult_BoxInfo = IDMFrameServiceProxy
						.getSqlTemplate()
						
						.queryForList(sql_selUndoBoxInfo,
								bindMap_selUndoBoxInfo);
				for (int j = 0; j < queryResult_BoxInfo.size(); j++) {
					MaterialPackingKey keyInfo = new MaterialPackingKey();
					keyInfo.setMaterialPackingName(queryResult_BoxInfo.get(j)
							.get("MATERIALPACKINGNAME").toString());
					keyInfo.setSiteName(queryResult_BoxInfo.get(j)
							.get("SITENAME").toString());
					// keyInfo=(materialPackingList.get(i).getKey());
					materialPackingKeyList.add(keyInfo);
					receiveActNo=queryResult_BoxInfo.get(j)
							.get("RECEIVEACTNO").toString();
				}
				SetEventInfo setEventInfo = new SetEventInfo();
				Map<String, Object> bindMap = new HashMap<String, Object>();
				bindMap.put("erpEventTime", erpdate);
				bindMap.put("packingState", "Released");
				bindMap.put("stockState", "Stocked");
				bindMap.put("erpState","SUCCESS");
				bindMap.put("shipRequestName", "");
				bindMap.put("shipRequestDetailName", "");
				bindMap.put("unDoID", newUnDoList.get(i).getUnDoID());
				bindMap.put("unDoDetailName", newUnDoList.get(i)
						.getUnDoDetailName());
				setEventInfo.setUserColumns(bindMap);
				MaterialPackingServiceProxy.getMaterialPackingService()
						.setEvent(materialPackingKeyList, eventInfo,
								setEventInfo);
			}
			if(!receiveActNo.equals("")){
			String sql_updateActNo="UPDATE MATERIALRECEIVEACT  SET RECEIVEACTSTATE = 'Created' WHERE SITENAME=:siteName AND RECEIVEACTNO=:receiveActNo";
			Map<String, Object> bindMap_ACT = new HashMap<String, Object>();
			bindMap_ACT.put("receiveActNo", receiveActNo);
			bindMap_ACT.put("siteName",siteNameList.get(0));
			IDMFrameServiceProxy.getSqlTemplate()
			.update(sql_updateActNo, bindMap_ACT);
			}
			
			if (receiveRequestNameList.size() != 0) {
				String sql_REC = "UPDATE MATERIALRECEIVEREQUESTDETAIL SET RECEIVEDQUANTITY='0' WHERE RECEIVEREQUESTNAME = :RECEIVEREQUESTNAME AND RETURNFLAG = 'X'";
				String receiveRequestName = receiveRequestNameList.get(0);
				Map<String,Object> bindMap_REC = new HashMap<String, Object>();
				bindMap_REC.put("RECEIVEREQUESTNAME",receiveRequestName);
				IDMFrameServiceProxy.getSqlTemplate().update(sql_REC, bindMap_REC);
			}
			
			String sql_UndoBoxInfo = " UPDATE BS_MATERIALPACKINGUNDOINFO A SET UNDOIDSTATE='N' WHERE A.UNDOID=:UNDOID AND MATERIALPACKINGNAME IN (SELECT MATERIALPACKINGNAME"
					+ " FROM BS_MATERIALPACKINGUNDOINFO BS"
					+ " WHERE BS.UNDOID=:UNDOID AND("
					+ " ("
					+ " BS.UNDODETAILNAME=:UNDODETAILNAME"
					+ " AND BS.SITENAME=:SITENAME"
					+ " )"
					+ " AND UNDOIDSTATE<>'N'" + " AND LASTEVENTNAME<>'MToM'))";
			String sql_insert = insertUnDOMaterialPackingInfo_v2
					+ " AND UNDODETAILNAME = :unDoDetailName ";
			for (int i = 0; i < unDoDetailNameList.size(); i++) {
				Map<String, Object> bindMap_UndoBoxInfo = new HashMap<String, Object>();
				Map<String, Object> bindMap_insert = new HashMap<String, Object>();
				bindMap_UndoBoxInfo.put("SITENAME", siteNameList.get(i));
				bindMap_UndoBoxInfo.put("UNDOID", UnDoID);
				bindMap_UndoBoxInfo.put("UNDODETAILNAME",
						unDoDetailNameList.get(i));
				bindMap_insert.put("unDoID", newUnDoList.get(i).getUnDoID());
				bindMap_insert.put("oldUndoid", UnDoID);
				bindMap_insert.put("UNDOIDDATE", newUnDoList.get(i)
						.getUnDoIdDate());
				bindMap_insert.put("unDoDetailName", newUnDoList.get(i)
						.getUnDoDetailName());
				IDMFrameServiceProxy.getSqlTemplate()
						.update(sql_UndoBoxInfo, bindMap_UndoBoxInfo);
				try {
					IDMFrameServiceProxy.getSqlTemplate()
							
							.update(sql_insert, bindMap_insert);
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
					throw e;
				}
			}

		} catch (IDMFrameDBErrorSignal ex) {
			log.error(ex, ex);
			throw ex;
		} catch (NotFoundSignal ex) {
			log.error(ex, ex);
			throw ex;
		}
	}

//	public void makeUnShip(EventInfo eventInfo,
//			List<MaterialUnDoinfo> newUnDoList, String UnDoID,
//			List<String> siteNameList, List<String> unDoDetailNameList)
//			throws Exception {
//		if (unDoDetailNameList.size() == 0) {
//			throw new CustomException("PK-0001", "", "");
//		}
//		try {
//			String sql_selUndoBoxInfo = " SELECT SITENAME,MATERIALPACKINGNAME "
//					+ "FROM MATERIALPACKING "
//					+ "WHERE (SITENAME,MATERIALPACKINGNAME) IN( "
//					+ "SELECT SITENAME,MATERIALPACKINGNAME  "
//					+ "FROM BS_MATERIALPACKINGSPLITMERGE "
//					+ "CONNECT BY  MATERIALPACKINGNAME=PRIOR DESTMATERIALPACKINGNAMENAME "
//					+ "START WITH (SITENAME,MATERIALPACKINGNAME) IN( "
//					+ "SELECT SITENAME,MATERIALPACKINGNAME "
//					+ " FROM BS_MATERIALPACKINGUNDOINFO BS "
//					+ " WHERE BS.UNDOID=:UNDOID AND "
//					+ "BS.SITENAME=:sitename AND BS.UNDODETAILNAME=:undodetailname "
//					+ " AND LASTEVENTNAME<>'MToM' )"
//					+ " union "
//					+ "SELECT SITENAME,MATERIALPACKINGNAME "
//					+ "FROM BS_MATERIALPACKINGUNDOINFO BS "
//					+ "WHERE BS.UNDOID=:UNDOID AND "
//					+ "BS.SITENAME=:sitename AND BS.UNDODETAILNAME=:undodetailname "
//					+ "AND LASTEVENTNAME<>'MToM' " + ")"
//					+ "and PACKINGSTATE<>'Emptied'";
//
//			HashMap<String, String> unDoDetailNameListMap = new HashMap<String, String>();
//			for (int i = 0; i < newUnDoList.size(); i++) {
//				unDoDetailNameListMap.put(Integer.toString(i + 1),
//						unDoDetailNameList.get(i));
//
//			}
//			// 转储类型原数据信息 added by wh
//			List<Map<String, Object>> oldInfoList = new ArrayList<Map<String, Object>>();
//
//			for (int i = 0; i < newUnDoList.size(); i++) {
//				List<MaterialPackingKey> materialPackingKeyList = new ArrayList<MaterialPackingKey>();
//				Map<String, Object> bindMap_selUndoBoxInfo = new HashMap<String, Object>();
//				bindMap_selUndoBoxInfo.put("sitename", siteNameList.get(i));
//				bindMap_selUndoBoxInfo.put("UNDOID", UnDoID);
//				bindMap_selUndoBoxInfo.put("undodetailname",
//						unDoDetailNameListMap.get(newUnDoList.get(i).getSeq()));
//				// bindMap_UndoBoxInfo.put("REQUESTDETAILNAME",requestDetailName);
//				List<Map<String, Object>> queryResult_BoxInfo = IDMFrameServiceProxy
//						.getSqlTemplate()
//						
//						.queryForList(sql_selUndoBoxInfo,
//								bindMap_selUndoBoxInfo);
//				for (int j = 0; j < queryResult_BoxInfo.size(); j++) {
//					MaterialPackingKey keyInfo = new MaterialPackingKey();
//					keyInfo.setMaterialPackingName(queryResult_BoxInfo.get(j)
//							.get("MATERIALPACKINGNAME").toString());
//					keyInfo.setSiteName(queryResult_BoxInfo.get(j)
//							.get("SITENAME").toString());
//					// keyInfo=(materialPackingList.get(i).getKey());
//					materialPackingKeyList.add(keyInfo);
//				}
//				// Add By WangHeng
//				// 转储出库时SITENAME改变，该SITENAME，UNDOID，UNDODETAILNAME下对应最多只有一条记录，所以用get（0）获取字段信息
//				String sqlPreUndoId = "SELECT PREUNDOID FROM BS_MATERIALPACKINGUNDOINFO  WHERE MATERIALPACKINGNAME=:MATERIALPACKINGNAME AND SITENAME=:SITENAME AND UNDOID=:UNDOID";
//				Map<String, Object> packBind = new HashMap<String, Object>();
//				packBind.put("MATERIALPACKINGNAME", queryResult_BoxInfo.get(0)
//						.get("MATERIALPACKINGNAME").toString());
//				packBind.put("SITENAME",
//						queryResult_BoxInfo.get(0).get("SITENAME").toString());
//				packBind.put("UNDOID", UnDoID);
//				List<Map<String, Object>> queryPreUndoId = IDMFrameServiceProxy
//						.getSqlTemplate()
//						.queryForList(sqlPreUndoId, packBind);
//				// 获取PRRUNDOID
//				String preUndo = queryPreUndoId.isEmpty() ? "" : queryPreUndoId
//						.get(0).get("PREUNDOID").toString();
//
//				// PROUNDOID不为空 ，获取sql语句中查询字段信息
//				if (preUndo != "") {
//					String sqlOldInfo = "SELECT SITENAME,ERPLOCATION,ERPFACTORY,REASONCODE,REASONCODETYPE FROM BS_MATERIALPACKINGUNDOINFO WHERE UNDOID=:UNDOID";
//					Map<String, Object> oldMap = new HashMap<String, Object>();					
//					oldMap.put("UNDOID", preUndo);
//					oldInfoList = IDMFrameServiceProxy.getSqlTemplate()
//							
//							.queryForList(sqlOldInfo, oldMap);
//				}
//				// Add By WangHeng
//
//				SetEventInfo setEventInfo = new SetEventInfo();
//				Map<String, Object> bindMap = new HashMap<String, Object>();
//				bindMap.put("stockState", "Stocked");
//				// 冲销的虚拟库位待指定
//				bindMap.put("locationName", "");
//				bindMap.put("unDoID", newUnDoList.get(0).getUnDoID());
//				bindMap.put("unDoDetailName", newUnDoList.get(i)
//						.getUnDoDetailName());
//				// Added By WangHeng
//				if (oldInfoList != null && oldInfoList.size() > 0) {
//					// 转储类型
//					if (eventInfo.getReasonCodeType() == "302") {
//						bindMap.put("siteName",
//								oldInfoList.get(0).get("SITENAME").toString());
//						bindMap.put("erpLocation",
//								oldInfoList.get(0).get("ERPLOCATION").toString());
//						bindMap.put("erpFactory",
//								oldInfoList.get(0).get("ERPFACTORY").toString());
//					}
//				}
//				// Added By WangHeng
//				setEventInfo.setUserColumns(bindMap);
//				MaterialPackingServiceProxy.getMaterialPackingService()
//						.setEvent(materialPackingKeyList, eventInfo,
//								setEventInfo);
//
//			}
//
//			String sql_UndoBoxInfo = " UPDATE BS_MATERIALPACKINGUNDOINFO A SET UNDOIDSTATE='N' WHERE A.UNDOID=:UNDOID AND MATERIALPACKINGNAME IN (SELECT MATERIALPACKINGNAME"
//					+ " FROM BS_MATERIALPACKINGUNDOINFO BS"
//					+ " WHERE BS.UNDOID=:UNDOID AND("
//					+ " ("
//					+ " BS.UNDODETAILNAME=:UNDODETAILNAME"
//					+ " AND BS.SITENAME=:SITENAME"
//					+ " )"
//					+ " AND UNDOIDSTATE<>'N'" + " AND LASTEVENTNAME<>'MToM'))";
//			String sql_insert = insertUnDOMaterialPackingInfo_v2
//					+ " AND UNDODETAILNAME = :unDoDetailName ";
//			for (int i = 0; i < unDoDetailNameList.size(); i++) {
//				Map<String, Object> bindMap_UndoBoxInfo = new HashMap<String, Object>();
//				Map<String, Object> bindMap_insert = new HashMap<String, Object>();
//				bindMap_UndoBoxInfo.put("SITENAME", siteNameList.get(i));
//				bindMap_UndoBoxInfo.put("UNDOID", UnDoID);
//				bindMap_UndoBoxInfo.put("UNDODETAILNAME",
//						unDoDetailNameList.get(i));
//				bindMap_insert.put("unDoID", newUnDoList.get(i).getUnDoID());
//				bindMap_insert.put("oldUndoid", UnDoID);
//				bindMap_insert.put("UNDOIDDATE", newUnDoList.get(i)
//						.getUnDoIdDate());
//				bindMap_insert.put("unDoDetailName", newUnDoList.get(i)
//						.getUnDoDetailName());
//				// Added By WangHeng
//				if (oldInfoList != null && oldInfoList.size() > 0) {
//					// 转储类型
//					if (eventInfo.getReasonCodeType() == "302") {
//						bindMap_insert.put("sitename",
//								oldInfoList.get(0).get("SITENAME").toString());
//						bindMap_insert.put("erpLocation", oldInfoList.get(0)
//								.get("ERPLOCATION").toString());
//						bindMap_insert.put("erpFactory", oldInfoList.get(0)
//								.get("ERPFACTORY").toString());
//					}
//				}
//				// Added By WangHeng
//				IDMFrameServiceProxy.getSqlTemplate()
//						.update(sql_UndoBoxInfo, bindMap_UndoBoxInfo);
//				IDMFrameServiceProxy.getSqlTemplate()
//						.update(sql_insert, bindMap_insert);
//			}
//
//		} catch (IDMFrameDBErrorSignal ex) {
//			log.error(ex, ex);
//			throw ex;
//		} catch (NotFoundSignal ex) {
//			log.error(ex, ex);
//			throw ex;
//		}
//	}
	public void cancleExportBoxOut(EventInfo eventInfo,List<String> materialPackingKeyList,String siteName)
	{
		List<MaterialPackingKey> mpKeyLsit=new ArrayList<MaterialPackingKey>();
		for(int i=0;i<materialPackingKeyList.size();i++)
		{
			MaterialPackingKey mpk=new MaterialPackingKey();
			mpk.setSiteName(siteName);
			mpk.setMaterialPackingName(materialPackingKeyList.get(i).toString());
			mpKeyLsit.add(mpk);
		}
		SetEventInfo setEventInfo=new SetEventInfo();
		Map<String,Object> updateMap=new HashMap<String, Object>();
		updateMap.put("stockState","Stocked");
		updateMap.put("receiveActNo","");
		updateMap.put("erpState","SUCCESS");
		//bindMap.put("shipRequestName", "");
		//bindMap.put("shipRequestDetailName", "");
		//冲销的虚拟库位待指定
		updateMap.put("locationName","");
//		updateMap.put("unDoID",newUnDoList.get(0).getUnDoID());
//		updateMap.put("unDoDetailName",newUnDoList.get(i).getUnDoDetailName());
		setEventInfo.setUserColumns(updateMap);
		MaterialPackingServiceProxy.getMaterialPackingService().setEvent(mpKeyLsit, eventInfo, setEventInfo);
	}
public void updateComplete(EventInfo eventInfo,String siteName,String invoiceNo,String shipRequestState,String Undoid){
		
		String lastEventTimeKey = TimeStampUtil.getCurrentEventTimeKey();
		Timestamp eventTime = TimeStampUtil.getCurrentTimestamp();
		
		MaterialShipRequestKey keyInfo=new MaterialShipRequestKey(siteName, invoiceNo);
		//MaterialShipRequest selectByKey = selectByKey(keyInfo);
		
		MaterialShipRequestSetEventInfo setEventInfo= new MaterialShipRequestSetEventInfo();
		
		Map<String, Object> bindMap = new HashMap<String, Object>();
		bindMap.put("shipRequestState", shipRequestState);
		setEventInfo.setUserColumns(bindMap);
		
		//selectByKey.setLastEventTime(eventTime);
		MaterialShipRequestServiceProxy.getMaterialShipRequestService().setEvent(keyInfo, eventInfo, setEventInfo);
}
	public void cancleStockOutState(EventInfo eventinfo,String Undoid,String siteName,List<String> unDoDetailNameList) throws Exception
	{
		try
		{
			for(int i=0; i<unDoDetailNameList.size();i++)
			{
			String selectBox = "Select materialpackingname from MATERIALPACKING where sitename =:SITENAME and undoid =:UNDOID and undodetailname=:UNDODETAILNAME";
			Map<String,Object> map=new HashMap<String, Object>();
			map.put("SITENAME", siteName);
			map.put("UNDOID", Undoid);
			map.put("UNDODETAILNAME", unDoDetailNameList.get(i));
			List<Map<String, Object>> result = IDMFrameServiceProxy.getSqlTemplate()
					.queryForList(selectBox, map);
			List<MaterialPackingKey> mpKeyLsit=new ArrayList<MaterialPackingKey>();
			if(result.size()>0)
			{
				for(Map<String, Object> pkName:result){
					MaterialPackingKey mk=new MaterialPackingKey();
					mk.setSiteName(siteName);
					mk.setMaterialPackingName(pkName.get("materialpackingname").toString());
					mpKeyLsit.add(mk);										
				}
				SetEventInfo seteventInfo=new SetEventInfo();
				Map<String,Object> updateMap=new HashMap<String, Object>();
				updateMap.put("stockState","Stocked");
				updateMap.put("receiveActNo","");
				updateMap.put("erpState","SUCCESS");
				//bindMap.put("shipRequestName", "");
				//bindMap.put("shipRequestDetailName", "");
				//冲销的虚拟库位待指定
				updateMap.put("locationName","");
//				updateMap.put("unDoID",newUnDoList.get(0).getUnDoID());
//				updateMap.put("unDoDetailName",newUnDoList.get(i).getUnDoDetailName());
				seteventInfo.setUserColumns(updateMap);
				MaterialPackingServiceProxy.getMaterialPackingService().setEvent(mpKeyLsit, eventinfo, seteventInfo);
				String updateBox="UPDATE BS_MATERIALPACKINGUNDOINFO SET UNDOIDSTATE='N' WHERE SITENAME=:SITENAME AND UNDOID=:UNDOID and undodetailname=:UNDODETAILNAME";
				Map<String,Object> bindMap=new HashMap<String, Object>();
				bindMap.put("SITENAME", siteName);
				bindMap.put("UNDOID", Undoid);
				bindMap.put("UNDODETAILNAME", unDoDetailNameList.get(i));
				IDMFrameServiceProxy.getSqlTemplate().update(updateBox, bindMap);
				
			}
			}
		}
		catch(IDMFrameDBErrorSignal ex){
			log.error(ex,ex);
			throw ex;
		}catch(NotFoundSignal ex){
			log.error(ex,ex);
			throw ex;
		}
	}
	public void makeUnShip( EventInfo eventInfo,List<MaterialUnDoinfo> newUnDoList,
			String UnDoID,List<String> siteNameList,List<String> unDoDetailNameList)
			throws Exception
			{	
				if(unDoDetailNameList.size()==0){
					throw new CustomException("PK-0001","","");
				}
				try {
				String sql_selUndoBoxInfo=" SELECT SITENAME,MATERIALPACKINGNAME "+
						"FROM MATERIALPACKING "+
						"WHERE (SITENAME,MATERIALPACKINGNAME) IN( "+
						"SELECT SITENAME,DESTMATERIALPACKINGNAMENAME AS MATERIALPACKINGNAME  "+
						"FROM BS_MATERIALPACKINGSPLITMERGE "+ 
						"CONNECT BY  MATERIALPACKINGNAME=PRIOR DESTMATERIALPACKINGNAMENAME "+
						"START WITH (SITENAME,MATERIALPACKINGNAME) IN( "+
						"SELECT SITENAME,MATERIALPACKINGNAME "+  
						" FROM BS_MATERIALPACKINGUNDOINFO BS "+
						" WHERE BS.UNDOID=:UNDOID AND "+
						"BS.SITENAME=:sitename AND BS.UNDODETAILNAME=:undodetailname "+
						" AND LASTEVENTNAME<>'MToM' )"+
						" union "+
						"SELECT SITENAME,MATERIALPACKINGNAME "+
						"FROM BS_MATERIALPACKINGUNDOINFO BS "+
						"WHERE BS.UNDOID=:UNDOID AND "+
						"BS.SITENAME=:sitename AND BS.UNDODETAILNAME=:undodetailname "+
						"AND LASTEVENTNAME<>'MToM' "+
						")"+
						"and PACKINGSTATE<>'Emptied'";

				HashMap<String, String> unDoDetailNameListMap=new HashMap<String, String>();
				for(int i=0;i<newUnDoList.size();i++)
				{
					unDoDetailNameListMap.put(Integer.toString(i+1), unDoDetailNameList.get(i));
			
				}
				for(int i=0;i<newUnDoList.size();i++)
				{
					List<MaterialPackingKey> materialPackingKeyList = new ArrayList<MaterialPackingKey>();
					Map<String, Object> bindMap_selUndoBoxInfo = new HashMap<String, Object>();
					bindMap_selUndoBoxInfo.put("sitename", siteNameList.get(i));
					bindMap_selUndoBoxInfo.put("UNDOID", UnDoID);
					bindMap_selUndoBoxInfo.put("undodetailname",unDoDetailNameListMap.get(newUnDoList.get(i).getSeq().substring(15)));
					//bindMap_UndoBoxInfo.put("REQUESTDETAILNAME",requestDetailName);
					List<Map<String, Object>> queryResult_BoxInfo = 
							IDMFrameServiceProxy.getSqlTemplate().queryForList(sql_selUndoBoxInfo, bindMap_selUndoBoxInfo);
					for(int j=0;j<queryResult_BoxInfo.size();j++)
					{
						MaterialPackingKey  keyInfo = new MaterialPackingKey();
						keyInfo.setMaterialPackingName(queryResult_BoxInfo.get(j).get("MATERIALPACKINGNAME").toString());
						keyInfo.setSiteName(queryResult_BoxInfo.get(j).get("SITENAME").toString());
						//keyInfo=(materialPackingList.get(i).getKey());
						materialPackingKeyList.add(keyInfo);
					}
					SetEventInfo setEventInfo = new SetEventInfo();
					Map<String, Object> bindMap = new HashMap<String, Object>();
					bindMap.put("stockState","Stocked");
					bindMap.put("receiveActNo","");
					bindMap.put("erpState","SUCCESS");
					//bindMap.put("shipRequestName", "");
					//bindMap.put("shipRequestDetailName", "");
					//冲销的虚拟库位待指定
					bindMap.put("locationName","");
					bindMap.put("unDoID",newUnDoList.get(0).getUnDoID());
					bindMap.put("unDoDetailName",newUnDoList.get(i).getUnDoDetailName());
					setEventInfo.setUserColumns(bindMap);
					MaterialPackingServiceProxy.getMaterialPackingService().setEvent(materialPackingKeyList, eventInfo, setEventInfo);
					
				}
				
				
				String sql_UndoBoxInfo=" UPDATE BS_MATERIALPACKINGUNDOINFO A SET UNDOIDSTATE='N' WHERE A.UNDOID=:UNDOID AND MATERIALPACKINGNAME IN (SELECT MATERIALPACKINGNAME"+
					    " FROM BS_MATERIALPACKINGUNDOINFO BS"+
					            " WHERE BS.UNDOID=:UNDOID AND("+
					            " ("+
					            " BS.UNDODETAILNAME=:UNDODETAILNAME"+
					            " AND BS.SITENAME=:SITENAME"+
					            " )"+
					            " AND UNDOIDSTATE<>'N'"+
					            " AND LASTEVENTNAME<>'MToM'))"
					            ;
			String sql_insert=insertUnDOMaterialPackingInfo_v2+ " AND UNDODETAILNAME = :unDoDetailName ";
				for(int i=0;i<unDoDetailNameList.size();i++){
					Map<String, Object> bindMap_UndoBoxInfo = new HashMap<String, Object>();
					Map<String, Object> bindMap_insert = new HashMap<String, Object>();
					bindMap_UndoBoxInfo.put("SITENAME", siteNameList.get(i));
					bindMap_UndoBoxInfo.put("UNDOID", UnDoID);
					bindMap_UndoBoxInfo.put("UNDODETAILNAME",unDoDetailNameList.get(i));
					bindMap_insert.put("unDoID", newUnDoList.get(i).getUnDoID());
					bindMap_insert.put("oldUndoid", UnDoID);
					bindMap_insert.put("UNDOIDDATE", newUnDoList.get(i).getUnDoIdDate());
					bindMap_insert.put("unDoDetailName", newUnDoList.get(i).getUnDoDetailName());
					IDMFrameServiceProxy.getSqlTemplate().update(sql_UndoBoxInfo, bindMap_UndoBoxInfo);
					IDMFrameServiceProxy.getSqlTemplate().update(sql_insert, bindMap_insert);
						}

				}catch(IDMFrameDBErrorSignal ex){
					log.error(ex,ex);
					throw ex;
				}catch(NotFoundSignal ex){
					log.error(ex,ex);
					throw ex;
				}
				}
	public void cancelStockOut(EventInfo eventinfo,String Undoid,String siteName,String shipRequestName,String receiveActNo) throws Exception
	{
		try
		{
			String selectBox = "Select materialpackingname,shiprequestname,shiprequestdetailname from MATERIALPACKING where sitename =:SITENAME and undoid =:UNDOID and receiveactno=:receiveActNo";
			Map<String,Object> map=new HashMap<String, Object>();
			map.put("SITENAME", siteName);
			map.put("UNDOID", Undoid);
			map.put("receiveActNo", receiveActNo);
			List<Map<String, Object>> result = IDMFrameServiceProxy.getSqlTemplate()
					.queryForList(selectBox, map);
			String selectShipRequest = "Select sum(materialquantity) as MATERIALQUANTITY,shiprequestname,shiprequestdetailname from MATERIALPACKING where sitename =:SITENAME and undoid =:UNDOID group by shiprequestname,shiprequestdetailname";
			Map<String,Object> mapShip=new HashMap<String, Object>();
			mapShip.put("SITENAME", siteName);
			mapShip.put("UNDOID", Undoid);
			mapShip.put("receiveActNo", receiveActNo);
			List<Map<String, Object>> Shipresult = IDMFrameServiceProxy.getSqlTemplate()
					.queryForList(selectShipRequest, mapShip);
			List<MaterialPackingKey> mpKeyLsit=new ArrayList<MaterialPackingKey>();
			if(result.size()>0)
			{
				for(Map<String, Object> pkName:result){
					MaterialPackingKey mk=new MaterialPackingKey();
					mk.setSiteName(siteName);
					mk.setMaterialPackingName(pkName.get("materialpackingname").toString());
					mpKeyLsit.add(mk);										
				}
				SetEventInfo seteventInfo=new SetEventInfo();
				Map<String,Object> updateMap=new HashMap<String, Object>();
				updateMap.put("stockState","Stocked");
				updateMap.put("receiveActNo","");
				updateMap.put("erpState","SUCCESS");
				updateMap.put("shipRequestName", "");
				updateMap.put("shipRequestDetailName", "");
				//冲销的虚拟库位待指定
				updateMap.put("locationName","");
//				updateMap.put("unDoID",newUnDoList.get(0).getUnDoID());
//				updateMap.put("unDoDetailName",newUnDoList.get(i).getUnDoDetailName());
				seteventInfo.setUserColumns(updateMap);
				MaterialPackingServiceProxy.getMaterialPackingService().setEvent(mpKeyLsit, eventinfo, seteventInfo);
				String updateBox="UPDATE BS_MATERIALPACKINGUNDOINFO SET UNDOIDSTATE='N' WHERE SITENAME=:SITENAME AND UNDOID=:UNDOID";
				Map<String,Object> bindMap=new HashMap<String, Object>();
				bindMap.put("SITENAME", siteName);
				bindMap.put("UNDOID", Undoid);
				IDMFrameServiceProxy.getSqlTemplate().update(updateBox, bindMap);
				
			}
			
			if(Shipresult.size()>0)
			{
				for(int i=0;i<Shipresult.size();i++){
					MaterialShipRequestDetailKey keyInfo = new MaterialShipRequestDetailKey(siteName, shipRequestName,Shipresult.get(i).get("SHIPREQUESTDETAILNAME").toString());
					MaterialShipRequestDetail selectByKey = MaterialShipRequestDetailServiceProxy.getMaterialShipRequestDetailService().selectByKey(keyInfo);
					MakeShipDetailDecreaseAssignedInfo makeShipDetailDecreaseAssignedInfo=new MakeShipDetailDecreaseAssignedInfo();
				    double qty = Double.parseDouble(Shipresult.get(i).get("MATERIALQUANTITY").toString());
						makeShipDetailDecreaseAssignedInfo.setAssignedQuantity(qty);
						MaterialShipRequestDetailServiceProxy.getMaterialShipRequestDetailService().decreaseAssignedQuantity(keyInfo, makeShipDetailDecreaseAssignedInfo);
				}
			}
		}
		catch(IDMFrameDBErrorSignal ex){
			log.error(ex,ex);
			throw ex;
		}catch(NotFoundSignal ex){
			log.error(ex,ex);
			throw ex;
		}
	}
	
	public List<MaterialPacking> GetTQMSUndoBoxList( EventInfo eventInfo,List<MaterialUnDoinfo> newUnDoList,
			String UnDoID,List<String> siteNameList,List<String> unDoDetailNameList,String receiveActNo)
			throws Exception
			{	
				if(unDoDetailNameList.size()==0){
					throw new CustomException("PK-0001","","");
				}
				try {
					SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					List<MaterialPacking> tqmsList=new ArrayList<MaterialPacking>();
					//List<MaterialPacking> materialPackingList = new ArrayList<MaterialPacking>();
				String sql_selOQABoxInfo=" SELECT * "+ 
						" FROM BS_MATERIALPACKINGUNDOINFO BS "+
						" WHERE (SITENAME, MATERIALPACKINGNAME) IN ( " +
						"SELECT SITENAME,MATERIALPACKINGNAME "+  
						" FROM BS_MATERIALPACKINGUNDOINFO BS "+
						" WHERE BS.UNDOID=:UNDOID AND "+
						" BS.SITENAME=:sitename AND BS.UNDODETAILNAME=:undodetailname "+
						 " ) "+
						 "and LASTEVENTNAME='NoValueOQAResult' ";
				String sql_selUndoBoxInfo=" SELECT MATERIALPACKINGNAME,SITENAME,CREATEUSER,RECEIVEACTNO,RECEIVEREQUESTNAME,RECEIVEREQUESTDETAILNAME,TO_CHAR(MAKEDATE,'yyyy-MM-dd HH:mm:ss') as MAKEDATE, "+
						"TO_CHAR(RECEIVETIME,'yyyy-MM-dd HH:mm:ss') as RECEIVETIME,SUPPLIERNAME, MATERIALQUANTITY,ERPLOCATION,ERPFACTORY,MATERIALSPECNAME "+
						"FROM MATERIALPACKING "+
						"WHERE (SITENAME,MATERIALPACKINGNAME) IN( "+
						"SELECT SITENAME,DESTMATERIALPACKINGNAMENAME AS MATERIALPACKINGNAME  "+
						"FROM BS_MATERIALPACKINGSPLITMERGE "+ 
						"CONNECT BY  MATERIALPACKINGNAME=PRIOR DESTMATERIALPACKINGNAMENAME "+
						"START WITH (SITENAME,MATERIALPACKINGNAME) IN( "+
						"SELECT SITENAME,MATERIALPACKINGNAME "+  
						" FROM BS_MATERIALPACKINGUNDOINFO BS "+
						" WHERE BS.UNDOID=:UNDOID AND "+
						"BS.SITENAME=:sitename AND BS.UNDODETAILNAME=:undodetailname "+
						" AND LASTEVENTNAME<>'MToM' )"+
						" union "+
						"SELECT SITENAME,MATERIALPACKINGNAME "+
						"FROM BS_MATERIALPACKINGUNDOINFO BS "+
						"WHERE BS.UNDOID=:UNDOID AND "+
						"BS.SITENAME=:sitename AND BS.UNDODETAILNAME=:undodetailname "+
						"AND LASTEVENTNAME<>'MToM' "+
						")"+
						"and PACKINGSTATE<>'Emptied' and packinggrade is null ";

				HashMap<String, String> unDoDetailNameListMap=new HashMap<String, String>();
				for(int i=0;i<newUnDoList.size();i++)
				{
					unDoDetailNameListMap.put(Integer.toString(i+1), unDoDetailNameList.get(i));
			
				}
				for(int i=0;i<newUnDoList.size();i++)
				{
					
					Map<String, Object> bindMap_selUndoBoxInfo = new HashMap<String, Object>();
					bindMap_selUndoBoxInfo.put("sitename", siteNameList.get(i));
					bindMap_selUndoBoxInfo.put("UNDOID", UnDoID);
					bindMap_selUndoBoxInfo.put("undodetailname",unDoDetailNameListMap.get(newUnDoList.get(i).getSeq().substring(15)));
					//bindMap_UndoBoxInfo.put("REQUESTDETAILNAME",requestDetailName);
					List<Map<String, Object>> queryResult_BoxInfo = 
							IDMFrameServiceProxy.getSqlTemplate().queryForList(sql_selUndoBoxInfo, bindMap_selUndoBoxInfo);
					List<Map<String, Object>> queryResult_OQABoxInfo = 
							IDMFrameServiceProxy.getSqlTemplate().queryForList(sql_selOQABoxInfo, bindMap_selUndoBoxInfo);
					if(queryResult_OQABoxInfo.size()<=0)
					{
						for(int j=0;j<queryResult_BoxInfo.size();j++)
						{
							MaterialPacking  materialPacking = new MaterialPacking();
							MaterialPackingKey  keyInfo = new MaterialPackingKey();
							keyInfo.setMaterialPackingName(queryResult_BoxInfo.get(j).get("MATERIALPACKINGNAME").toString());
							keyInfo.setSiteName(queryResult_BoxInfo.get(j).get("SITENAME").toString());
							materialPacking.setKey(keyInfo);
							materialPacking.setCreateUser(queryResult_BoxInfo.get(j).get("CREATEUSER").toString());
							materialPacking.setReceiveActNo(receiveActNo);
							materialPacking.setReceiveRequestName(queryResult_BoxInfo.get(j).get("RECEIVEREQUESTNAME").toString());
							materialPacking.setReceiveRequestDetailName(queryResult_BoxInfo.get(j).get("RECEIVEREQUESTDETAILNAME").toString());
							materialPacking.setMakeDate(Timestamp.valueOf(queryResult_BoxInfo.get(j).get("MAKEDATE").toString()));
							materialPacking.setReceiveTime(Timestamp.valueOf(queryResult_BoxInfo.get(j).get("RECEIVETIME").toString()));
							materialPacking.setSupplierName(queryResult_BoxInfo.get(j).get("SUPPLIERNAME").toString());
							materialPacking.setMaterialQuantity(Double.valueOf(queryResult_BoxInfo.get(j).get("MATERIALQUANTITY").toString()));
							materialPacking.setErpLocation(queryResult_BoxInfo.get(j).get("ERPLOCATION").toString());
							materialPacking.setErpFactory(queryResult_BoxInfo.get(j).get("ERPFACTORY").toString());
							materialPacking.setMaterialSpecName(queryResult_BoxInfo.get(j).get("MATERIALSPECNAME").toString());
							materialPacking.setRemark("INVALID");
							//keyInfo=(materialPackingList.get(i).getKey());
							tqmsList.add(materialPacking);
						}
					}
					
				}
				return tqmsList;

				}catch(IDMFrameDBErrorSignal ex){
					log.error(ex,ex);
					throw ex;
				}catch(NotFoundSignal ex){
					log.error(ex,ex);
					throw ex;
				}
				
				}
	

	
	public void makeUnShipToOEM( EventInfo eventInfo,List<MaterialUnDoinfo> newUnDoList,
			String UnDoID,List<String> siteNameList,List<String> unDoDetailNameList, List<String> shipRequestNameList)
			throws Exception
			{	
				if(unDoDetailNameList.size()==0){
					throw new CustomException("PK-0001","","");
				}
				try {
				String sql_selUndoBoxInfo=" SELECT SITENAME,MATERIALPACKINGNAME "+
						"FROM MATERIALPACKING "+
						"WHERE (SITENAME,MATERIALPACKINGNAME) IN( "+
						"SELECT SITENAME,DESTMATERIALPACKINGNAMENAME AS MATERIALPACKINGNAME  "+
						"FROM BS_MATERIALPACKINGSPLITMERGE "+ 
						"CONNECT BY  MATERIALPACKINGNAME=PRIOR DESTMATERIALPACKINGNAMENAME "+
						"START WITH (SITENAME,MATERIALPACKINGNAME) IN( "+
						"SELECT SITENAME,MATERIALPACKINGNAME "+  
						" FROM BS_MATERIALPACKINGUNDOINFO BS "+
						" WHERE BS.UNDOID=:UNDOID AND "+
						"BS.SITENAME=:sitename AND BS.UNDODETAILNAME=:undodetailname "+
						" AND LASTEVENTNAME<>'MToM' )"+
						" union "+
						"SELECT SITENAME,MATERIALPACKINGNAME "+
						"FROM BS_MATERIALPACKINGUNDOINFO BS "+
						"WHERE BS.UNDOID=:UNDOID AND "+
						"BS.SITENAME=:sitename AND BS.UNDODETAILNAME=:undodetailname "+
						"AND LASTEVENTNAME<>'MToM' "+
						")"+
						"and PACKINGSTATE<>'Emptied'";

				HashMap<String, String> unDoDetailNameListMap=new HashMap<String, String>();
				for(int i=0;i<newUnDoList.size();i++)
				{
					unDoDetailNameListMap.put(Integer.toString(i+1), unDoDetailNameList.get(i));
			
				}
				for(int i=0;i<newUnDoList.size();i++)
				{
					List<MaterialPackingKey> materialPackingKeyList = new ArrayList<MaterialPackingKey>();
					Map<String, Object> bindMap_selUndoBoxInfo = new HashMap<String, Object>();
					bindMap_selUndoBoxInfo.put("sitename", siteNameList.get(i));
					bindMap_selUndoBoxInfo.put("UNDOID", UnDoID);
					bindMap_selUndoBoxInfo.put("undodetailname",unDoDetailNameListMap.get(newUnDoList.get(i).getSeq().substring(15)));
					//bindMap_UndoBoxInfo.put("REQUESTDETAILNAME",requestDetailName);
					List<Map<String, Object>> queryResult_BoxInfo = 
							IDMFrameServiceProxy.getSqlTemplate().queryForList(sql_selUndoBoxInfo, bindMap_selUndoBoxInfo);
					for(int j=0;j<queryResult_BoxInfo.size();j++)
					{
						MaterialPackingKey  keyInfo = new MaterialPackingKey();
						keyInfo.setMaterialPackingName(queryResult_BoxInfo.get(j).get("MATERIALPACKINGNAME").toString());
						keyInfo.setSiteName(queryResult_BoxInfo.get(j).get("SITENAME").toString());
						//keyInfo=(materialPackingList.get(i).getKey());
						materialPackingKeyList.add(keyInfo);
					}
					SetEventInfo setEventInfo = new SetEventInfo();
					Map<String, Object> bindMap = new HashMap<String, Object>();
					bindMap.put("stockState","Stocked");
					bindMap.put("receiveActNo","");
					bindMap.put("erpState","SUCCESS");
					bindMap.put("shipRequestName", "");
					bindMap.put("shipRequestDetailName", "");
					//冲销的虚拟库位待指定
					bindMap.put("locationName","");
					bindMap.put("unDoID",newUnDoList.get(0).getUnDoID());
					bindMap.put("unDoDetailName",newUnDoList.get(i).getUnDoDetailName());
					setEventInfo.setUserColumns(bindMap);
					MaterialPackingServiceProxy.getMaterialPackingService().setEvent(materialPackingKeyList, eventInfo, setEventInfo);
					
				}

				if (shipRequestNameList.size() != 0) {
					String sql_OEM = "UPDATE MATERIALSHIPREQUESTTOOEM SET ASSIGNEDQUANTITY='0' WHERE RECEIVEREQUESTNAME = :RECEIVEREQUESTNAME";
					String receiveRequestName = shipRequestNameList.get(0);
					Map<String,Object> bindMap_OEM = new HashMap<String, Object>();
					bindMap_OEM.put("RECEIVEREQUESTNAME",receiveRequestName);
					IDMFrameServiceProxy.getSqlTemplate().update(sql_OEM, bindMap_OEM);
				}
				
				
				String sql_UndoBoxInfo=" UPDATE BS_MATERIALPACKINGUNDOINFO A SET UNDOIDSTATE='N' WHERE A.UNDOID=:UNDOID AND MATERIALPACKINGNAME IN (SELECT MATERIALPACKINGNAME"+
					    " FROM BS_MATERIALPACKINGUNDOINFO BS"+
					            " WHERE BS.UNDOID=:UNDOID AND("+
					            " ("+
					            " BS.UNDODETAILNAME=:UNDODETAILNAME"+
					            " AND BS.SITENAME=:SITENAME"+
					            " )"+
					            " AND UNDOIDSTATE<>'N'"+
					            " AND LASTEVENTNAME<>'MToM'))"
					            ;
			String sql_insert=insertUnDOMaterialPackingInfo_v2+ " AND UNDODETAILNAME = :unDoDetailName ";
				for(int i=0;i<unDoDetailNameList.size();i++){
					Map<String, Object> bindMap_UndoBoxInfo = new HashMap<String, Object>();
					Map<String, Object> bindMap_insert = new HashMap<String, Object>();
					bindMap_UndoBoxInfo.put("SITENAME", siteNameList.get(i));
					bindMap_UndoBoxInfo.put("UNDOID", UnDoID);
					bindMap_UndoBoxInfo.put("UNDODETAILNAME",unDoDetailNameList.get(i));
					bindMap_insert.put("unDoID", newUnDoList.get(i).getUnDoID());
					bindMap_insert.put("oldUndoid", UnDoID);
					bindMap_insert.put("UNDOIDDATE", newUnDoList.get(i).getUnDoIdDate());
					bindMap_insert.put("unDoDetailName", newUnDoList.get(i).getUnDoDetailName());
					IDMFrameServiceProxy.getSqlTemplate().update(sql_UndoBoxInfo, bindMap_UndoBoxInfo);
					IDMFrameServiceProxy.getSqlTemplate().update(sql_insert, bindMap_insert);
						}

				}catch(IDMFrameDBErrorSignal ex){
					log.error(ex,ex);
					throw ex;
				}catch(NotFoundSignal ex){
					log.error(ex,ex);
					throw ex;
				}
				}

	public void updateMaterialPackingShipRequest(EventInfo eventInfo,
			String siteName, List<Element> materialPackingNameList,
			String shipRequestName, String shipRequestDetailName, String flag,
			String receiveActNo) {
		try {
			List<MaterialPackingKey> packingList = new ArrayList<MaterialPackingKey>();
			for (Element materialPackingName : materialPackingNameList) {
				MaterialPackingKey keyInfo = new MaterialPackingKey();
				keyInfo.setSiteName(siteName);
				keyInfo.setMaterialPackingName(materialPackingName
						.getTextTrim());
				packingList.add(keyInfo);
			}
			MaterialPackingAssignShipRequestInfo assignShipRequestInfo = new MaterialPackingAssignShipRequestInfo();
			if ("Assign".equals(flag)) {
				assignShipRequestInfo.setShipRequestName(shipRequestName);
				assignShipRequestInfo
						.setShipRequestDetailName(shipRequestDetailName);
				Map<String, Object> bindMap = new HashMap<String, Object>();
				bindMap.put("receiveActNo", receiveActNo);
				assignShipRequestInfo.setUserColumns(bindMap);
			} else if ("Deassign".equals(flag)) {
				assignShipRequestInfo.setShipRequestName("");
				assignShipRequestInfo.setShipRequestDetailName("");
				Map<String, Object> bindMap = new HashMap<String, Object>();
				bindMap.put("receiveActNo", "");
				assignShipRequestInfo.setUserColumns(bindMap);
			}
			MaterialPackingServiceProxy.getMaterialPackingService()
					.assignShipRequest(packingList, eventInfo,
							assignShipRequestInfo);

		} catch (IDMFrameDBErrorSignal e) {
			e.printStackTrace();
		}
	}
	public void updateSuperMaterialPacking1(EventInfo eventInfo,
			String siteName, String materialPackingName,			
			String superMaterialPackingName) {
		try {
			
			MaterialPackingKey keyInfo = new MaterialPackingKey();
			keyInfo.setSiteName(siteName);
			keyInfo.setMaterialPackingName(materialPackingName);
			
				SetEventInfo setEventInfo = new SetEventInfo();
				Map<String, Object> bindMap = new HashMap<String, Object>();
				bindMap.put("superMaterialPackingName", superMaterialPackingName);
				
			 setEventInfo.setUserColumns(bindMap);
			MaterialPackingServiceProxy.getMaterialPackingService().setEvent(keyInfo, eventInfo, setEventInfo);
								
		} catch (IDMFrameDBErrorSignal e) {
			e.printStackTrace();
		}
	}
	public void updateSuperMaterialPacking(EventInfo eventInfo,
			String siteName, List<Element> materialPackingNameList,
			String shipRequestName, String shipRequestDetailName, String flag,
			String receiveActNo) {
		try {
			List<MaterialPackingKey> packingList = new ArrayList<MaterialPackingKey>();
			for (Element materialPackingName : materialPackingNameList) {
				MaterialPackingKey keyInfo = new MaterialPackingKey();
				keyInfo.setSiteName(siteName);
				keyInfo.setMaterialPackingName(materialPackingName
						.getTextTrim());
				packingList.add(keyInfo);
			}
			MaterialPackingAssignShipRequestInfo assignShipRequestInfo = new MaterialPackingAssignShipRequestInfo();
			if ("Assign".equals(flag)) {
				assignShipRequestInfo.setShipRequestName(shipRequestName);
				assignShipRequestInfo
						.setShipRequestDetailName(shipRequestDetailName);
				Map<String, Object> bindMap = new HashMap<String, Object>();
				bindMap.put("receiveActNo", receiveActNo);
				assignShipRequestInfo.setUserColumns(bindMap);
			} else if ("Deassign".equals(flag)) {
				assignShipRequestInfo.setShipRequestName("");
				assignShipRequestInfo.setShipRequestDetailName("");
				Map<String, Object> bindMap = new HashMap<String, Object>();
				bindMap.put("receiveActNo", "");
				assignShipRequestInfo.setUserColumns(bindMap);
			}
			MaterialPackingServiceProxy.getMaterialPackingService()
					.assignShipRequest(packingList, eventInfo,
							assignShipRequestInfo);

		} catch (IDMFrameDBErrorSignal e) {
			e.printStackTrace();
		}
	}
	public void preAssignShipRequestToBox(EventInfo eventInfo,
			String siteName, String materialPackingName,
			String shipRequestName, String shipRequestDetailName, String flag,
			String receiveActNo,List<MaterialPacking> palletList) throws Exception
			{
				try
				{
					List<MaterialPackingKey> keyList=new ArrayList<MaterialPackingKey>();
					MaterialPackingKey mpKey=new MaterialPackingKey();
					mpKey.setSiteName(siteName);
					mpKey.setMaterialPackingName(materialPackingName);
					Map<String,Object> map=new HashMap<String, Object>();
					map.put("receiveActNo", receiveActNo);
					if ("Assign".equals(flag)) 
					{
						map.put("shipRequestName", shipRequestName);
						map.put("shipRequestDetailName", shipRequestDetailName);
						if(palletList.size() <= 0)
							map.put("superMaterialPackingName", "");
					}else
					{
						map.put("shipRequestName", "");
						map.put("shipRequestDetailName", "");
					}
					SetEventInfo info=new SetEventInfo();
					info.setUserColumns(map);
					keyList.add(mpKey);
					if(palletList.size()>0)
					{
						for (MaterialPacking materialPacking : palletList) {
							keyList.add(materialPacking.getKey());
						}
					}						
					MaterialPackingServiceProxy.getMaterialPackingService().setEvent(keyList, eventInfo, info);					
					
				}
				catch(Exception e)
				{			
					throw e;
				}
			}
		public List<MaterialPacking> getBoxListByPallet(String siteName, String materialPackingName) throws Exception
		{
			try
			{
				List<MaterialPacking> mpList=new ArrayList<MaterialPacking>();
				MaterialPackingKey mpKey=new MaterialPackingKey();
				mpKey.setSiteName(siteName);
				mpKey.setMaterialPackingName(materialPackingName);
				MaterialPacking mp=MaterialPackingServiceProxy.getMaterialPackingService().selectByKey(mpKey);
				if(mp.getMaterialPackingType().equalsIgnoreCase("PALLET"))
				{
					String queryPallet="SELECT MATERIALPACKINGNAME FROM MATERIALPACKING WHERE SUPERMATERIALPACKINGNAME=:SUPERMATERIALPACKINGNAME";
					Map<String,Object> map=new HashMap<String, Object>();
					map.put("SUPERMATERIALPACKINGNAME", materialPackingName);
					List<Map<String,Object>> result=IDMFrameServiceProxy.getSqlTemplate().queryForList(queryPallet, map);
					if(result.size()>0)
					{ 
						MaterialPackingKey mpk=new MaterialPackingKey();
						mpk.setSiteName(siteName);
						//获取该pallet下所有box
						for(int m= 0;m<result.size();m++)
						{
							mpk.setMaterialPackingName(result.get(m).get("MATERIALPACKINGNAME").toString());
							MaterialPacking materialpacking=MaterialPackingServiceProxy.getMaterialPackingService().selectByKey(mpk);
							mpList.add(materialpacking);
						}
						//校验一拍下是否存在多个质检状态
						String oqaResult=mpList.get(0).getPackingGrade();
						for (MaterialPacking materialpacking : mpList) {
							if(materialpacking.getPackingGrade().equalsIgnoreCase(oqaResult))
								continue;
							else
								throw new CustomException("PALLET-002","","");
						}
					}																	
				}else
				{				
					//拣配Pallet中某一箱，更新Pallet总数
					if(!mp.getSuperMaterialPackingName().equalsIgnoreCase("") && !siteName.equals("B3"))
					{						
						mpKey.setMaterialPackingName(mp.getSuperMaterialPackingName());
						MaterialPacking superPacking=MaterialPackingServiceProxy.getMaterialPackingService().selectByKey(mpKey);
						superPacking.setMaterialQuantity(superPacking.getMaterialQuantity()-mp.getMaterialQuantity());
						MaterialPackingServiceProxy.getMaterialPackingService().update(superPacking);
						//将单独拣配的BOX的PalletID清空
						mp.setSuperMaterialPackingName("");
						MaterialPackingServiceProxy.getMaterialPackingService().update(mp);
					}
					
				}
				return mpList;
			}
			catch(Exception e)
			{
				e.printStackTrace();
				throw e;
			}
		}
	public void updateMaterialPackingPORturnt(EventInfo eventInfo,
			String siteName, String materialPackingName,
			String shipRequestName, String shipRequestDetailName, String flag,
			String receiveActNo) {
		try {
			List<MaterialPackingKey> packingList = new ArrayList<MaterialPackingKey>();
			
				MaterialPackingKey keyInfo = new MaterialPackingKey();
				keyInfo.setSiteName(siteName);
				keyInfo.setMaterialPackingName(materialPackingName);
				packingList.add(keyInfo);
			MaterialPackingAssignShipRequestInfo assignShipRequestInfo = new MaterialPackingAssignShipRequestInfo();
			if ("Assign".equals(flag)) {
				assignShipRequestInfo.setShipRequestName(shipRequestName);
				assignShipRequestInfo
						.setShipRequestDetailName(shipRequestDetailName);
				Map<String, Object> bindMap = new HashMap<String, Object>();
				bindMap.put("receiveActNo", receiveActNo);
				//bindMap.put("superMaterialPackingName", "");
				assignShipRequestInfo.setUserColumns(bindMap);
			} else if ("Deassign".equals(flag)) {
				assignShipRequestInfo.setShipRequestName("");
				assignShipRequestInfo.setShipRequestDetailName("");
				Map<String, Object> bindMap = new HashMap<String, Object>();
				bindMap.put("receiveActNo", "");
				assignShipRequestInfo.setUserColumns(bindMap);
			}
			MaterialPackingServiceProxy.getMaterialPackingService()
					.assignShipRequest(packingList, eventInfo,
							assignShipRequestInfo);

		} catch (IDMFrameDBErrorSignal e) {
			e.printStackTrace();
			throw e;
		}
	}

	public void updateMaterialPackingShipRequest(EventInfo eventInfo,
			String siteName, List<Element> materialPackingNameList,
			String shipRequestName, String shipRequestDetailName, String flag) {
		try {
			List<MaterialPackingKey> packingList = new ArrayList<MaterialPackingKey>();
			for (Element materialPackingName : materialPackingNameList) {
				MaterialPackingKey keyInfo = new MaterialPackingKey();
				keyInfo.setSiteName(siteName);
				keyInfo.setMaterialPackingName(materialPackingName
						.getTextTrim());
				packingList.add(keyInfo);
			}
			MaterialPackingAssignShipRequestInfo assignShipRequestInfo = new MaterialPackingAssignShipRequestInfo();
			if ("Assign".equals(flag)) {
				assignShipRequestInfo.setShipRequestName(shipRequestName);
				assignShipRequestInfo
						.setShipRequestDetailName(shipRequestDetailName);
				Map<String, Object> bindMap = new HashMap<String, Object>();
				assignShipRequestInfo.setUserColumns(bindMap);
			} else if ("Deassign".equals(flag)) {
				assignShipRequestInfo.setShipRequestName("");
				assignShipRequestInfo.setShipRequestDetailName("");
				Map<String, Object> bindMap = new HashMap<String, Object>();
				bindMap.put("receiveActno", "");
				assignShipRequestInfo.setUserColumns(bindMap);
			}
			MaterialPackingServiceProxy.getMaterialPackingService()
					.assignShipRequest(packingList, eventInfo,
							assignShipRequestInfo);

		} catch (IDMFrameDBErrorSignal e) {
			e.printStackTrace();
		}
	}

	// PDA reserve
	public void updateMaterialPackingShipRequest(EventInfo eventInfo,
			org.jdom.Document doc, String flag) throws Exception {
		try {

			List<String> srdList = new ArrayList<String>();

			List<String> boxList = new ArrayList<String>();

			Element root = doc.getDocument().getRootElement();

			Element element = root.getChild("Body"); // .getChild("MATERIALPACKING");

			String srName = "";
			String srdName = "";
			String boxName = "";

			for (Iterator<?> iterator = element.getChildren().iterator(); iterator
					.hasNext();) {

				Element mpE = (Element) iterator.next();

				if (mpE.getName().equals("MATERIALPACKING")) {
					srdName = mpE.getChild("SHIPREQUESTDETAILNAME").getText();

					boxName = mpE.getChild("MATERIALPACKINGNAME").getText();

					if (boxList.contains(boxName)) {
						throw new CustomException("BOX-0001", "", "");
					} else {
						boxList.add(boxName);
					}

					if(!srdList.contains(srdName))
					{
						srdList.add(srdName);
					}
				}
			}

			for (int i = 0; i < srdList.size(); i++) {
				List<MaterialPackingKey> packingList = new ArrayList<MaterialPackingKey>();
				for (Iterator<?> iterator = element.getChildren().iterator(); iterator
						.hasNext();) {

					Element mpE = (Element) iterator.next();

					if (mpE.getName().equals("MATERIALPACKING")) {
					if (mpE.getChild("SHIPREQUESTDETAILNAME").getText()
							.equals(srdList.get(i).toString())) {
						String siteName = mpE.getChild("SITENAME").getText();
						String mpName = mpE.getChild("MATERIALPACKINGNAME")
								.getText();
						srName = mpE.getChild("SHIPREQUESTNAME").getText();
							srdName = srdList.get(i);

						MaterialPackingKey keyInfo = new MaterialPackingKey();
						keyInfo.setSiteName(siteName);
						keyInfo.setMaterialPackingName(mpName);
						packingList.add(keyInfo);
						}
					}
				}
				MaterialPackingAssignShipRequestInfo assignShipRequestInfo = new MaterialPackingAssignShipRequestInfo();
				flag = "Assign";

				if ("Assign".equals(flag)) {
					assignShipRequestInfo.setShipRequestName(srName);
					assignShipRequestInfo.setShipRequestDetailName(srdName);
				} else if ("Deassign".equals(flag)) {
					assignShipRequestInfo.setShipRequestName("");
					assignShipRequestInfo.setShipRequestDetailName("");
				}
				MaterialPackingServiceProxy.getMaterialPackingService()
						.assignShipRequest(packingList, eventInfo,
								assignShipRequestInfo);

			}


		} catch (IDMFrameDBErrorSignal e) {
			e.printStackTrace();
		}
	}


	public void PDAChangeLocation(EventInfo eventInfo, String siteName,
			String materialPackingName, String locationName,
			String oriLocationName) throws Exception {
		try {
			MaterialPackingKey materialPackingKey = new MaterialPackingKey();

			MaterialPacking materialPakcing = new MaterialPacking();
			materialPakcing = null;
			SetEventInfo setEventInfo = new SetEventInfo();
			Map<String, Object> bindMap = new HashMap<String, Object>();

			materialPackingKey.setSiteName(siteName);
			materialPackingKey.setMaterialPackingName(materialPackingName);

			bindMap.put("locationName", locationName);

			setEventInfo.setUserColumns(bindMap);
			MaterialPackingServiceProxy.getMaterialPackingService().setEvent(
					materialPackingKey, eventInfo, setEventInfo);

			// Location State Change
			com.cim.idm.wmspackage.storage.management.info.SetEventInfo setEventInfoNotFull = new com.cim.idm.wmspackage.storage.management.info.SetEventInfo();
			StorageKey StorageKeyto = new StorageKey();

			StorageKeyto.setSiteName(siteName);
			StorageKeyto.setStorageName(locationName);

			Map<String, Object> bindMaptolocnotfull = new HashMap<String, Object>();

			bindMaptolocnotfull.put("useState", "NotFull");

			setEventInfoNotFull.setUserColumns(bindMaptolocnotfull);

			StorageServiceProxy.getStorageService().setEvent(StorageKeyto,
					eventInfo, setEventInfoNotFull);
			// query materialpacking for oriLocationName

			if (StringUtils.isNotEmpty(oriLocationName)) {
				String sql = "SELECT * FROM materialpacking WHERE locationName = :locationName AND STOCKSTATE='Stocked'";

				Map<String, Object> bindMaporiloc = new HashMap<String, Object>();
				bindMaporiloc.put("locationName", oriLocationName);

				List<Map<String, Object>> queryResult = IDMFrameServiceProxy
						.getSqlTemplate()
						.queryForList(sql, bindMaporiloc);
				// make oriLocationName Empty
				if (queryResult.size() == 0) {
					com.cim.idm.wmspackage.storage.management.info.SetEventInfo setEventInfoEmpty = new com.cim.idm.wmspackage.storage.management.info.SetEventInfo();
					StorageKey StorageKey = new StorageKey();

					StorageKey.setSiteName(siteName);
					StorageKey.setStorageName(oriLocationName);

					Map<String, Object> bindMaptolocempty = new HashMap<String, Object>();

					bindMaptolocempty.put("useState", "Empty");

					setEventInfoEmpty.setUserColumns(bindMaptolocempty);
					StorageServiceProxy.getStorageService().setEvent(
							StorageKey, eventInfo, setEventInfoEmpty);
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			throw ex;
		}
	}
	public void PDAChangeLocationByPallet(EventInfo eventInfo, String siteName,
			String SupermaterialPackingName, String locationName,
			String AreaName) throws Exception {
		try {			
			MaterialPackingKey materialPackingKey = new MaterialPackingKey();
			SetEventInfo setEventInfo = new SetEventInfo();
			String sql1 = "SELECT MATERIALPACKINGNAME FROM materialpacking WHERE SupermaterialPackingName = :SupermaterialPackingName ";
			Map<String, Object> bindMapvloc = new HashMap<String, Object>();
			bindMapvloc.put("SupermaterialPackingName", SupermaterialPackingName);						
			List<Map<String, Object>> queryResult1 = IDMFrameServiceProxy
					.getSqlTemplate()
					.queryForList(sql1, bindMapvloc);
			Map<String, Object> PalletMap = new HashMap<String, Object>();
			PalletMap.put("MATERIALPACKINGNAME", SupermaterialPackingName);
			queryResult1.add(PalletMap);
			for (int i = 0; i < queryResult1.size(); i++) {			
				materialPackingKey.setSiteName(siteName);
				materialPackingKey.setMaterialPackingName(queryResult1.get(i).get("MATERIALPACKINGNAME").toString());
				Map<String, Object> bindMap3 = new HashMap<String, Object>();
				bindMap3.put("LocationName", locationName);
				setEventInfo.setUserColumns(bindMap3);
				MaterialPackingServiceProxy.getMaterialPackingService().setEvent(materialPackingKey,
						eventInfo, setEventInfo);	
			}			
			
			// Location State Change
			com.cim.idm.wmspackage.storage.management.info.SetEventInfo setEventInfoNotFull = new com.cim.idm.wmspackage.storage.management.info.SetEventInfo();
			StorageKey StorageKeyto = new StorageKey();
			StorageKeyto.setSiteName(siteName);
			StorageKeyto.setStorageName(locationName);			
			Map<String, Object> bindMaptolocnotfull = new HashMap<String, Object>();
			bindMaptolocnotfull.put("useState", "Full");
			setEventInfoNotFull.setUserColumns(bindMaptolocnotfull);
			StorageServiceProxy.getStorageService().setEvent(StorageKeyto,
					eventInfo, setEventInfoNotFull);
			// query materialpacking for oriLocationName

			if (StringUtils.isNotEmpty(AreaName)) {
				String sql3 = "SELECT * FROM materialpacking WHERE locationName = :locationName  AND STOCKSTATE='Stocked' ";
				Map<String, Object> bindMaporiloc = new HashMap<String, Object>();
				bindMaporiloc.put("locationName", AreaName);			
				List<Map<String, Object>> queryResult = IDMFrameServiceProxy
						.getSqlTemplate()
						.queryForList(sql3, bindMaporiloc);
				// make oriLocationName Empty
				if (queryResult.size() == 0) {
					
					com.cim.idm.wmspackage.storage.management.info.SetEventInfo setEventInfoEmpty = new com.cim.idm.wmspackage.storage.management.info.SetEventInfo();
					StorageKey StorageKey = new StorageKey();
					StorageKey.setSiteName(siteName);
					StorageKey.setStorageName(AreaName);
					Map<String, Object> bindMaptolocempty = new HashMap<String, Object>();
					bindMaptolocempty.put("useState", "Empty");
					setEventInfoEmpty.setUserColumns(bindMaptolocempty);
					StorageServiceProxy.getStorageService().setEvent(
							StorageKey, eventInfo, setEventInfoEmpty);
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			throw ex;
		}
	}
	public void PDAChangeMaterialSpecName(EventInfo eventInfo, String siteName,
			String materialPackingName, String materialSpecName)
			throws Exception {
		try {
			MaterialPackingKey materialPackingKey = new MaterialPackingKey();

			MaterialPacking materialPakcing = new MaterialPacking();
			materialPakcing = null;
			SetEventInfo setEventInfo = new SetEventInfo();
			Map<String, Object> bindMap = new HashMap<String, Object>();

			materialPackingKey.setSiteName(siteName);
			materialPackingKey.setMaterialPackingName(materialPackingName);

			bindMap.put("materialSpecName", materialSpecName);

			setEventInfo.setUserColumns(bindMap);

			MaterialPackingServiceProxy.getMaterialPackingService().setEvent(
					materialPackingKey, eventInfo, setEventInfo);
		} catch (Exception ex) {
			ex.printStackTrace();
			throw ex;
		}
	}

	public void PDAHoldReleaseByBox(EventInfo eventInfo, org.jdom.Document doc,
			String holdState) throws Exception {
		Element root = doc.getDocument().getRootElement();
		Element materialPackingListElement = root.getChild("Body");

		try {

			SetEventInfo setEventInfo = new SetEventInfo();

			List<MaterialPackingKey> keyList = new ArrayList<MaterialPackingKey>();
			if (materialPackingListElement != null) {
				for (Iterator<?> iterator = materialPackingListElement
						.getChildren().iterator(); iterator.hasNext();) {
					Element panelE = (Element) iterator.next();
					MaterialPackingKey materialPackingKey = new MaterialPackingKey();
					materialPackingKey.setSiteName(panelE.getChild("SITENAME")
							.getText());
					materialPackingKey.setMaterialPackingName(panelE.getChild(
							"MATERIALPACKINGNAME").getText());

					keyList.add(materialPackingKey);

				}
			}
			Map<String, Object> bindMap = new HashMap<String, Object>();
			bindMap.put("holdState", holdState);

			setEventInfo.setUserColumns(bindMap);
			MaterialPackingServiceProxy.getMaterialPackingService().setEvent(
					keyList, eventInfo, setEventInfo);
			doc = PDASearchByBoxList(doc);
		} catch (IDMFrameDBErrorSignal ex) {
			ex.printStackTrace();
			throw ex;
		}
	}

	public void PDAScrapByBox(EventInfo eventInfo, org.jdom.Document doc,
			String packingState) throws Exception {
		Element root = doc.getDocument().getRootElement();
		Element materialPackingListElement = root.getChild("Body");

		try {

			SetEventInfo setEventInfo = new SetEventInfo();

			List<MaterialPackingKey> keyList = new ArrayList<MaterialPackingKey>();
			if (materialPackingListElement != null) {
				for (Iterator<?> iterator = materialPackingListElement
						.getChildren().iterator(); iterator.hasNext();) {
					Element panelE = (Element) iterator.next();
					MaterialPackingKey materialPackingKey = new MaterialPackingKey();
					materialPackingKey.setSiteName(panelE.getChild("SITENAME")
							.getText());
					materialPackingKey.setMaterialPackingName(panelE.getChild(
							"MATERIALPACKINGNAME").getText());

					keyList.add(materialPackingKey);

				}
			}
			Map<String, Object> bindMap = new HashMap<String, Object>();
			bindMap.put("packingState", packingState);

			setEventInfo.setUserColumns(bindMap);

			MaterialPackingServiceProxy.getMaterialPackingService().setEvent(
					keyList, eventInfo, setEventInfo);
			doc = PDASearchByBoxList(doc);
		} catch (IDMFrameDBErrorSignal ex) {
			ex.printStackTrace();
			throw ex;
		}
	}
	// add by zhurr
		public void makePreUnShip( EventInfo eventInfo,List<MaterialUnDoinfo> newUnDoList,
				String UnDoID,List<String> siteNameList,List<String> unDoDetailNameList)
				throws Exception
				{	
					if(unDoDetailNameList.size()==0){
						throw new CustomException("PK-0001","","");
					}
					try {
					String sql_selUndoBoxInfo=" SELECT SITENAME,MATERIALPACKINGNAME "+
							"FROM MATERIALPACKING "+
							"WHERE (SITENAME,MATERIALPACKINGNAME) IN( "+
							"SELECT SITENAME,DESTMATERIALPACKINGNAMENAME AS MATERIALPACKINGNAME  "+
							"FROM BS_MATERIALPACKINGSPLITMERGE "+ 
							"CONNECT BY  MATERIALPACKINGNAME=PRIOR DESTMATERIALPACKINGNAMENAME "+
							"START WITH (SITENAME,MATERIALPACKINGNAME) IN( "+
							"SELECT SITENAME,MATERIALPACKINGNAME "+  
							" FROM BS_MATERIALPACKINGUNDOINFO BS "+
							" WHERE BS.UNDOID=:UNDOID AND "+
							"BS.SITENAME=:sitename AND BS.UNDODETAILNAME=:undodetailname "+
							" AND LASTEVENTNAME<>'MToM' )"+
							" union "+
							"SELECT SITENAME,MATERIALPACKINGNAME "+
							"FROM BS_MATERIALPACKINGUNDOINFO BS "+
							"WHERE BS.UNDOID=:UNDOID AND "+
							"BS.SITENAME=:sitename AND BS.UNDODETAILNAME=:undodetailname "+
							"AND LASTEVENTNAME<>'MToM' "+
							")"+
							"and PACKINGSTATE<>'Emptied'";

					/*HashMap<String, String> unDoDetailNameListMap=new HashMap<String, String>();
					for(int i=0;i<newUnDoList.size();i++)
					{
						unDoDetailNameListMap.put(Integer.toString(i+1), unDoDetailNameList.get(i));
				
					}*/
					for(int i=0;i<newUnDoList.size();i++)
					{
						List<MaterialPackingKey> materialPackingKeyList = new ArrayList<MaterialPackingKey>();
						Map<String, Object> bindMap_selUndoBoxInfo = new HashMap<String, Object>();
						bindMap_selUndoBoxInfo.put("sitename", siteNameList.get(i));
						bindMap_selUndoBoxInfo.put("UNDOID", UnDoID);
						bindMap_selUndoBoxInfo.put("undodetailname",unDoDetailNameList.get(i));
						//bindMap_selUndoBoxInfo.put("undodetailname",newUnDoList.get(i).getSeq().substring(15,newUnDoList.get(i).getSeq().length()));
						//bindMap_UndoBoxInfo.put("REQUESTDETAILNAME",requestDetailName);
						List<Map<String, Object>> queryResult_BoxInfo = 
								IDMFrameServiceProxy.getSqlTemplate().queryForList(sql_selUndoBoxInfo, bindMap_selUndoBoxInfo);
						for(int j=0;j<queryResult_BoxInfo.size();j++)
						{
							MaterialPackingKey  keyInfo = new MaterialPackingKey();
							keyInfo.setMaterialPackingName(queryResult_BoxInfo.get(j).get("MATERIALPACKINGNAME").toString());
							keyInfo.setSiteName(queryResult_BoxInfo.get(j).get("SITENAME").toString());
							//keyInfo=(materialPackingList.get(i).getKey());
							materialPackingKeyList.add(keyInfo);
						}
						SetEventInfo setEventInfo = new SetEventInfo();
						Map<String, Object> bindMap = new HashMap<String, Object>();
						bindMap.put("stockState","Stocked");
						bindMap.put("receiveActNo","");
						bindMap.put("erpState","SUCCESS");
						bindMap.put("shipRequestName", "");
						bindMap.put("shipRequestDetailName", "");
						//冲销的虚拟库位待指定
						bindMap.put("locationName","");
						bindMap.put("unDoID",newUnDoList.get(0).getUnDoID());
						bindMap.put("unDoDetailName",newUnDoList.get(i).getUnDoDetailName());
						setEventInfo.setUserColumns(bindMap);
						MaterialPackingServiceProxy.getMaterialPackingService().setEvent(materialPackingKeyList, eventInfo, setEventInfo);
						
					}
					
					
					String sql_UndoBoxInfo=" UPDATE BS_MATERIALPACKINGUNDOINFO A SET UNDOIDSTATE='N' WHERE A.UNDOID=:UNDOID AND MATERIALPACKINGNAME IN (SELECT MATERIALPACKINGNAME"+
						    " FROM BS_MATERIALPACKINGUNDOINFO BS"+
						            " WHERE BS.UNDOID=:UNDOID AND("+
						            " ("+
						            " BS.UNDODETAILNAME=:UNDODETAILNAME"+
						            " AND BS.SITENAME=:SITENAME"+
						            " )"+
						            " AND UNDOIDSTATE<>'N'"+
						            " AND LASTEVENTNAME<>'MToM'))"
						            ;
				String sql_insert=insertUnDOMaterialPackingInfo_v2+ " AND UNDODETAILNAME = :unDoDetailName ";
					for(int i=0;i<unDoDetailNameList.size();i++){
						Map<String, Object> bindMap_UndoBoxInfo = new HashMap<String, Object>();
						Map<String, Object> bindMap_insert = new HashMap<String, Object>();
						bindMap_UndoBoxInfo.put("SITENAME", siteNameList.get(i));
						bindMap_UndoBoxInfo.put("UNDOID", UnDoID);
						bindMap_UndoBoxInfo.put("UNDODETAILNAME",unDoDetailNameList.get(i));
						bindMap_insert.put("unDoID", newUnDoList.get(i).getUnDoID());
						bindMap_insert.put("oldUndoid", UnDoID);
						bindMap_insert.put("UNDOIDDATE", newUnDoList.get(i).getUnDoIdDate());
						bindMap_insert.put("unDoDetailName", newUnDoList.get(i).getUnDoDetailName());
						IDMFrameServiceProxy.getSqlTemplate().update(sql_UndoBoxInfo, bindMap_UndoBoxInfo);
						IDMFrameServiceProxy.getSqlTemplate().update(sql_insert, bindMap_insert);
							}

					}catch(IDMFrameDBErrorSignal ex){
						log.error(ex,ex);
						throw ex;
					}catch(NotFoundSignal ex){
						log.error(ex,ex);
						throw ex;
					}
					}
		//add by zhurr
		public void makeUnBind(String UnDoID,List<String> unDoDetailNameList,String siteName) throws Exception
		{
			if(unDoDetailNameList.size()==0){
				throw new CustomException("PK-0001","","");
			}
			try
			{
				for(int i=0;i<unDoDetailNameList.size();i++)
				{
					String sql ="SELECT DISTINCT SHIPREQUESTNAME,SHIPREQUESTDETAILNAME FROM BS_MATERIALPACKINGUNDOINFO WHERE SITENAME=:SITENAME AND UNDOID=:UNDOID AND UNDODETAILNAME =:UNDODETAILNAME";
					HashMap<String, Object> bindMap=new HashMap<String, Object>();
					bindMap.put("SITENAME", siteName);
					bindMap.put("UNDOID", UnDoID);
					bindMap.put("UNDODETAILNAME", unDoDetailNameList.get(i).toString());
					List<Map<String,Object>> shipList=IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, bindMap);
					if(shipList!=null&&shipList.size()>0)
					{
						String updateSsl="UPDATE MATERIALSHIPREQUESTDETAIL SET ASSIGNEDQUANTITY=0 WHERE SHIPREQUESTNAME=:SHIPREQUESTNAME AND SHIPREQUESTDETAILNAME=:SHIPREQUESTDETAILNAME AND SITENAME=:SITENAME";
						HashMap<String, Object> updateMap=new HashMap<String, Object>();
						updateMap.put("SITENAME", siteName);
						updateMap.put("SHIPREQUESTNAME", shipList.get(0).get("SHIPREQUESTNAME").toString());
						updateMap.put("SHIPREQUESTDETAILNAME", shipList.get(0).get("SHIPREQUESTDETAILNAME").toString());
						IDMFrameServiceProxy.getSqlTemplate().update(updateSsl, updateMap);
					}
				}
			}catch(IDMFrameDBErrorSignal ex){
				log.error(ex,ex);
				throw ex;
			}catch(NotFoundSignal ex){
				log.error(ex,ex);
				throw ex;
			}
		}
	public void PDAPreScrapByBox(EventInfo eventInfo, org.jdom.Document doc,
			String erpFactory) throws Exception {
		Element root = doc.getDocument().getRootElement();
		// Element bodyElement = root.getChild("Body");
		Element materialPackingListElement = root.getChild("Body");

		try {

			SetEventInfo setEventInfo = new SetEventInfo();

			List<MaterialPackingKey> keyList = new ArrayList<MaterialPackingKey>();
			if (materialPackingListElement != null) {
				for (Iterator<?> iterator = materialPackingListElement
						.getChildren().iterator(); iterator.hasNext();) {
					Element panelE = (Element) iterator.next();
					MaterialPackingKey materialPackingKey = new MaterialPackingKey();
					materialPackingKey.setSiteName(panelE.getChild("SITENAME")
							.getText());
					materialPackingKey.setMaterialPackingName(panelE.getChild(
							"MATERIALPACKINGNAME").getText());

					keyList.add(materialPackingKey);

				}
			}
			Map<String, Object> bindMap = new HashMap<String, Object>();
			bindMap.put("erpFactory", erpFactory);

			setEventInfo.setUserColumns(bindMap);

			MaterialPackingServiceProxy.getMaterialPackingService().setEvent(
					keyList, eventInfo, setEventInfo);
			doc = PDASearchByBoxList(doc);
		} catch (IDMFrameDBErrorSignal ex) {
			ex.printStackTrace();
			throw ex;
		}
	}

	public Document PDASearchByBoxList(Document doc) throws Exception {
		Element root = doc.getDocument().getRootElement();
		Element materialPackingListElement = root.getChild("Body");
		try {

			List<MaterialPackingKey> keyList = new ArrayList<MaterialPackingKey>();
			if (materialPackingListElement != null) {
				for (Iterator<?> iterator = materialPackingListElement
						.getChildren().iterator(); iterator.hasNext();) {
					Element panelE = (Element) iterator.next();
					MaterialPackingKey materialPackingKey = new MaterialPackingKey();
					materialPackingKey.setSiteName(panelE.getChild("SITENAME")
							.getText());
					materialPackingKey.setMaterialPackingName(panelE.getChild(
							"MATERIALPACKINGNAME").getText());
					keyList.add(materialPackingKey);
				}

			}

			List<MaterialPacking> boxList = new MaterialPackingServiceUtil()
					.getMaterialPackingListByKeyList(keyList);

			doc = new MaterialPackingServiceUtil()
					.writeDocWithMaterialPackingList(doc, boxList);

			return doc;
		} catch (IDMFrameDBErrorSignal ex) {
			ex.printStackTrace();
			throw ex;
		}
	}
    
	public Document OICSearchBoxByCondition(Document doc) throws Exception {
		Element root = doc.getDocument().getRootElement();
		Element body = root.getChild("Body");
		String conditionName = "";
		String condition = "";
		String siteName = "";
		try {
			conditionName = body.getChildText("AREANAME");
			condition = body.getChildText("ETCSTATE");
			siteName = body.getChildText("SITENAME");
			List<MaterialPacking> boxList = new MaterialPackingServiceUtil()
					.getMaterialPackingListByCondition(siteName, conditionName,
							condition);

			doc = new MaterialPackingServiceUtil()
					.writeDocWithMaterialPackingList(doc, boxList);

			return doc;
		} catch (IDMFrameDBErrorSignal ex) {
			ex.printStackTrace();
			throw ex;
		}
	}
		
	public void PDABoxMerge(EventInfo eventInfo, String siteName,
			String materialPackingName, String fBoxName, String sBoxName,
			String quantity) {
		try {
			MaterialPackingKey materialPackingKey = new MaterialPackingKey();

			// SetEventInfo setEventInfo = new SetEventInfo();

			Map<String, Object> bindMap = new HashMap<String, Object>();

			MaterialPacking fmp = new MaterialPacking();
			MaterialPacking smp = new MaterialPacking();

			materialPackingKey.setMaterialPackingName(fBoxName);
			materialPackingKey.setSiteName(siteName);
			fmp = MaterialPackingServiceProxy.getMaterialPackingService()
					.selectByKey(materialPackingKey);

			materialPackingKey.setMaterialPackingName(sBoxName);
			materialPackingKey.setSiteName(siteName);
			smp = MaterialPackingServiceProxy.getMaterialPackingService()
					.selectByKey(materialPackingKey);

			// // CreateInfo materialPacking = new CreateInfo();
			// bindMap.put("materialQuantity", quantity);
			//
			// setEventInfo.setUserColumns(bindMap);
			//
			// MaterialPackingServiceProxy.getMaterialPackingService().setEvent(
			// materialPackingKey, eventInfo, setEventInfo);

			CreateInfo createInfo = new CreateInfo();
			createInfo.setSiteName(siteName);
			createInfo.setMaterialPackingName(materialPackingName);// 新生成的box id
			createInfo.setMaterialPackingType(fmp.getMaterialPackingType());
			createInfo.setContentMaterialType(fmp.getContentMaterialType());

			// bindMap.put("siteName", siteName);
			// bindMap.put("materialPackingName", materialPackingName);
			// bindMap.put("MaterialPackingType", materialPackingType);
			// bindMap.put("ContentMaterialType", contentMaterialType);
			bindMap.put("MaterialType", fmp.getMaterialType());
			bindMap.put("MaterialSpecName", fmp.getMaterialSpecName());
			bindMap.put("SuperMaterialPackingName",
					fmp.getSuperMaterialPackingName());
			bindMap.put("PackingGrade", fmp.getPackingGrade());
			bindMap.put("SubPackingQuantity", fmp.getSubPackingQuantity());
			bindMap.put("MaterialCreateQuantity",
					fmp.getMaterialCreateQuantity());
			bindMap.put("MaterialQuantity", quantity);// 数量
			bindMap.put("PackingState", fmp.getPackingState());
			bindMap.put("OldPackingState", fmp.getOldStockState());
			bindMap.put("stockState", fmp.getStockState());
			bindMap.put("OldStockState", fmp.getOldStockState());
			bindMap.put("HoldState", fmp.getHoldState());
			bindMap.put("AreaName", fmp.getAreaName());
			bindMap.put("LocationName", fmp.getLocationName());
			bindMap.put("DurableName", fmp.getDurableName());
			bindMap.put("MaterialProcessGroupName",
					fmp.getMaterialProcessGroupName());
			// bindMap.put("LastEventName", "SplitCreatBox");
			bindMap.put("LastEventTimeKey",
					TimeStampUtil.getCurrentEventTimeKey());
			// bindMap.put("LastEventTime",
			// ConvertUtil.convertToTimeStamp(lastEventTime));
			bindMap.put("LastEventTime", fmp.getLastEventTime());
			// bindMap.put("LastEventUser",
			// materialPackingData.getLastEventUser());
			// bindMap.put("LastEventComment",
			// materialPackingData.getLastEventComment());
			// bindMap.put("CreateTime",
			// ConvertUtil.convertToTimeStamp(createTime));
			bindMap.put("CreateTime", fmp.getCreateTime());
			bindMap.put("CreateUser", fmp.getCreateUser());
			bindMap.put("ReceiveRequestName", fmp.getReceiveRequestName());
			bindMap.put("ReceiveRequestDetailName",
					fmp.getReceiveRequestDetailName());
			// bindMap.put("MakeDate",
			// ConvertUtil.convertToTimeStamp(makeDate));
			bindMap.put("MakeDate", fmp.getMakeDate());
			bindMap.put("ReceiveActNo", fmp.getReceiveActNo());
			// bindMap.put("ReceiveTime",
			// ConvertUtil.convertToTimeStamp(receiveTime));
			bindMap.put("ReceiveTime", fmp.getReceiveTime());
			bindMap.put("ReceiveUser", fmp.getReceiveUser());
			bindMap.put("ShipRequestName", fmp.getShipRequestName());
			bindMap.put("ShipRequestDetailName", fmp.getShipRequestDetailName());
			// bindMap.put("ShipTime",
			// ConvertUtil.convertToTimeStamp(shipTime));
			bindMap.put("ShipTime", fmp.getShipTime());
			bindMap.put("ShipUser", fmp.getShipUser());
			bindMap.put("ReasonCodeType", fmp.getReasonCodeType());
			bindMap.put("ReasonCode", fmp.getReasonCode());
			bindMap.put("ErpLocation", fmp.getErpLocation());
			bindMap.put("EtcState", fmp.getEtcState());
			bindMap.put("Charge", fmp.getCharge());
			bindMap.put("SupplierName", fmp.getSupplierName());
			bindMap.put("ErpFactory", fmp.getErpFactory());
			bindMap.put("StockInType", fmp.getStockInType());
			createInfo.setUserColumns(bindMap);
			MaterialPackingServiceProxy.getMaterialPackingService().create(
					eventInfo, createInfo);

			String strCondition = "INSERT INTO  BS_MATERIALPACKINGSPLITMERGE (SITENAME,MATERIALPACKINGNAME,DESTMATERIALPACKINGNAMENAME,"
					+ "ACTIONTIMEKEY,ACTIONTYPE,PACKINGGRADE,ACTIONTIME,ACTIONUSER,MATERIALQUANTITY,DESTMATERIALQUANTITY)"
					+ "VALUES (?,?,?,?,?,?,?,?,?,?)";

			Object[] bind = new Object[] { siteName, fBoxName,
					materialPackingName,
					TimeStampUtil.getCurrentEventTimeKey().toString(), "Merge",
					fmp.getPackingGrade(), TimeStampUtil.getCurrentTimestamp(),
					eventInfo.getEventUser(), fmp.getMaterialQuantity(),
					Double.parseDouble(quantity) };
			IDMFrameServiceProxy.getSqlTemplate().update(strCondition, bind);

			bind = new Object[] { siteName, sBoxName, materialPackingName,
					TimeStampUtil.getCurrentEventTimeKey().toString(), "Merge",
					smp.getPackingGrade(), TimeStampUtil.getCurrentTimestamp(),
					eventInfo.getEventUser(), smp.getMaterialQuantity(),
					Double.parseDouble(quantity) };

			IDMFrameServiceProxy.getSqlTemplate().update(strCondition, bind);

			try {

				SetEventInfo setEventInfo = new SetEventInfo();

				MaterialPackingKey MaterialPackingKey = new MaterialPackingKey();

				MaterialPackingKey.setSiteName(siteName);
				MaterialPackingKey.setMaterialPackingName(fBoxName);

				Map<String, Object> bindMapf = new HashMap<String, Object>();

				bindMapf.put("PackingState", "Emptied");
				bindMapf.put("MaterialQuantity", Double.parseDouble("0"));

				setEventInfo.setUserColumns(bindMapf);

				MaterialPackingServiceProxy.getMaterialPackingService()
						.setEvent(MaterialPackingKey, eventInfo, setEventInfo);

			} catch (IDMFrameDBErrorSignal e) {
				e.printStackTrace();
			}

			try {

				SetEventInfo setEventInfo = new SetEventInfo();

				MaterialPackingKey MaterialPackingKey = new MaterialPackingKey();

				MaterialPackingKey.setSiteName(siteName);
				MaterialPackingKey.setMaterialPackingName(sBoxName);

				Map<String, Object> bindMaps = new HashMap<String, Object>();

				bindMaps.put("PackingState", "Emptied");
				bindMaps.put("MaterialQuantity", Double.parseDouble("0"));

				setEventInfo.setUserColumns(bindMaps);

				MaterialPackingServiceProxy.getMaterialPackingService()
						.setEvent(MaterialPackingKey, eventInfo, setEventInfo);

			} catch (IDMFrameDBErrorSignal e) {
				e.printStackTrace();
			}

		} catch (IDMFrameDBErrorSignal e) {
			e.printStackTrace();
		}
	}

	public void PDAPalletMerge(EventInfo eventInfo, String siteName,
			String SuperMaterialPackingName, String fBoxName, String sBoxName,
			String quantity) {
		try {
			MaterialPackingKey materialPackingKey = new MaterialPackingKey();
			// SetEventInfo setEventInfo = new SetEventInfo();

			Map<String, Object> bindMap = new HashMap<String, Object>();

			MaterialPacking fmp = new MaterialPacking();
			MaterialPacking smp = new MaterialPacking();

			materialPackingKey.setMaterialPackingName(fBoxName);
			materialPackingKey.setSiteName(siteName);
			fmp = MaterialPackingServiceProxy.getMaterialPackingService()
					.selectByKey(materialPackingKey);

			materialPackingKey.setMaterialPackingName(sBoxName);
			materialPackingKey.setSiteName(siteName);
			smp = MaterialPackingServiceProxy.getMaterialPackingService()
					.selectByKey(materialPackingKey);
			fmp.setMaterialQuantity(fmp.getMaterialQuantity()+smp.getMaterialQuantity());
			fmp.setSuperMaterialPackingName(SuperMaterialPackingName);
			MaterialPackingServiceProxy.getMaterialPackingService().update(fmp);
			String condition= "where supermaterialpackingname = ? ";
			Object[] bind={sBoxName};
			List<MaterialPacking> fList= MaterialPackingServiceProxy.getMaterialPackingService().select(condition, bind);
			for (MaterialPacking materialPacking : fList) {
				materialPacking.setSuperMaterialPackingName(sBoxName); //更新第二个托里的box托号
			}
			MaterialPackingServiceProxy.getMaterialPackingService().update(fList);	
			/*
			String strCondition = "INSERT INTO  BS_MATERIALPACKINGSPLITMERGE (SITENAME,MATERIALPACKINGNAME,DESTMATERIALPACKINGNAMENAME,"
					+ "ACTIONTIMEKEY,ACTIONTYPE,PACKINGGRADE,ACTIONTIME,ACTIONUSER,MATERIALQUANTITY,DESTMATERIALQUANTITY)"
					+ "VALUES (?,?,?,?,?,?,?,?,?,?)";
             */
			String strCondition = "INSERT INTO  BS_MATERIALPACKINGSPLITMERGE (SITENAME,MATERIALPACKINGNAME"
					+ "MATERIALQUANTITY)"
					+ "VALUES (?,?,?)";
			Object[] bind1 = new Object[] { siteName, fBoxName,
					SuperMaterialPackingName,
					TimeStampUtil.getCurrentEventTimeKey().toString(), "Merge",
					fmp.getPackingGrade(), TimeStampUtil.getCurrentTimestamp(),
					eventInfo.getEventUser(), fmp.getMaterialQuantity(),
					Double.parseDouble(quantity) };
			IDMFrameServiceProxy.getSqlTemplate().update(strCondition, bind);

			bind = new Object[] { siteName, sBoxName, SuperMaterialPackingName,
					TimeStampUtil.getCurrentEventTimeKey().toString(), "Merge",
					smp.getPackingGrade(), TimeStampUtil.getCurrentTimestamp(),
					eventInfo.getEventUser(), smp.getMaterialQuantity(),
					Double.parseDouble(quantity) };

			IDMFrameServiceProxy.getSqlTemplate().update(strCondition, bind1);

			try {

				SetEventInfo setEventInfo = new SetEventInfo();

				MaterialPackingKey MaterialPackingKey = new MaterialPackingKey();

				MaterialPackingKey.setSiteName(siteName);
				MaterialPackingKey.setMaterialPackingName(fBoxName);

				Map<String, Object> bindMapf = new HashMap<String, Object>();

				bindMapf.put("PackingState", "Emptied");
				bindMapf.put("MaterialQuantity", Double.parseDouble("0"));
				setEventInfo.setUserColumns(bindMapf);
				MaterialPackingServiceProxy.getMaterialPackingService()
						.setEvent(MaterialPackingKey, eventInfo, setEventInfo);
			} catch (IDMFrameDBErrorSignal e) {
				e.printStackTrace();
			}

			try {

				SetEventInfo setEventInfo = new SetEventInfo();
				MaterialPackingKey MaterialPackingKey = new MaterialPackingKey();
				MaterialPackingKey.setSiteName(siteName);
				MaterialPackingKey.setMaterialPackingName(sBoxName);

				Map<String, Object> bindMaps = new HashMap<String, Object>();
				bindMaps.put("PackingState", "Emptied");
				bindMaps.put("MaterialQuantity", Double.parseDouble("0"));
				setEventInfo.setUserColumns(bindMaps);

				MaterialPackingServiceProxy.getMaterialPackingService()
						.setEvent(MaterialPackingKey, eventInfo, setEventInfo);

			} catch (IDMFrameDBErrorSignal e) {
				e.printStackTrace();
			}

		} catch (IDMFrameDBErrorSignal e) {
			e.printStackTrace();
		}
	}
	public void PDAEtcOut(EventInfo eventInfo, List<String> siteNameList,
			List<String> materialPackingNameList,
			List<String> packingStateList, List<String> confirmUsrList,
			List<String> locationNameList, List<String> materialSpecNameList,
			List<String> materialQuantityList) {
		try {
			MaterialPackingKey materialPackingKey = new MaterialPackingKey();
			SetEventInfo setEventInfo = new SetEventInfo();
			Map<String, Object> bindMap = new HashMap<String, Object>();
			String siteName = siteNameList.get(0).toString();
			String packingState = packingStateList.get(0).toString();
			String confirmUser = confirmUsrList.get(0).toString();
			//String locationName = locationNameList.get(0).toString();
			String materialSpecName = materialSpecNameList.get(0).toString();
			// String locationName = locationNameList.get(0).toString();
			for (int i = 0; i < materialPackingNameList.size(); i++) {
				materialPackingKey.setSiteName(siteName);
				materialPackingKey.setMaterialPackingName(materialPackingNameList.get(i));
				MaterialPacking materialPacking=new MaterialPacking();
				materialPacking=MaterialPackingServiceProxy.getMaterialPackingService().selectByKey(materialPackingKey);
				if(materialPacking.getEtcState().equals("") ||materialPacking.getEtcState().equals("EtcIn"))
				{
						bindMap.put("EtcState", packingState);
						setEventInfo.setUserColumns(bindMap);
						MaterialPackingServiceProxy.getMaterialPackingService()
								.setEvent(materialPackingKey, eventInfo, setEventInfo);			   
		                
						String strCondition = "INSERT INTO  MATERIALPACKINGETC(SITENAME,MATERIALPACKINGNAME,TIMEKEY,MATERIALSPECNAME,"
								+ "ETCSTATE,LOCATIONNAME,ETCINQTY,ETCOUTQTY,ETCINTIME,ETCOUTTIME,ETCINUSER,ETCOUTUSER,CONFIRMINUSER,CONFIRMOUTUSER)"
								+ "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
						//String strCondition1 ="UPDATE MATERIALPACKING SET ETCSTATE = ? WHERE SITENAME = ? AND MATERIALPACKINGNAME =? AND （ETCSTATE IS NULL OR ETCSTATE!='EtcOut'） ";			
						String locationName = materialPacking.getLocationName();
						//if (locationNameList.size() > 0)
						//{
							//locationName = locationNameList.get(i);
						    Object[] bind = new Object[] 
								{ 
						    	siteName,materialPacking.getKey().getMaterialPackingName(),
								TimeStampUtil.getCurrentEventTimeKey().toString(),
								materialPacking.getMaterialSpecName(), packingState,locationName, null,
								Double.parseDouble(materialQuantityList.get(i)), null,
								TimeStampUtil.getCurrentTimestamp(), null,
								eventInfo.getEventUser(), null, confirmUser 
						        };
						IDMFrameServiceProxy.getSqlTemplate().update(strCondition, bind);
                       }
				  }
			  // }			
		} catch (IDMFrameDBErrorSignal e) {
			e.printStackTrace();
		}
	}

	public void PDAEtcIn(EventInfo eventInfo, List<String> siteNameList,
			List<String> materialPackingNameList,
			//String materialPackingName,
			List<String> packingStateList, List<String> confirmUsrList,
			List<String>  materialQuantityList)
	{
		try {
			MaterialPackingKey materialPackingKey = new MaterialPackingKey();
			SetEventInfo setEventInfo = new SetEventInfo();
			Map<String, Object> bindMap = new HashMap<String, Object>();
			String siteName = siteNameList.get(0).toString();
			String packingState = packingStateList.get(0).toString();
			String confirmUser = confirmUsrList.get(0).toString();
			for (int i = 0; i < materialPackingNameList.size(); i++){			
				materialPackingKey.setSiteName(siteName);
				materialPackingKey.setMaterialPackingName(materialPackingNameList.get(i));
				MaterialPacking materialPacking=new MaterialPacking();
				materialPacking=MaterialPackingServiceProxy.getMaterialPackingService().selectByKey(materialPackingKey);
				if(materialPacking.getEtcState().equals("EtcOut")){
				bindMap.put("EtcState", packingState);
				setEventInfo.setUserColumns(bindMap);
				MaterialPackingServiceProxy.getMaterialPackingService()
						.setEvent(materialPackingKey, eventInfo, setEventInfo);
				String strCondition = 
				"UPDATE MATERIALPACKINGETC SET ETCSTATE = ?,ETCINQTY=?,ETCINTIME =?,ETCINUSER = ?,CONFIRMINUSER = ? WHERE SITENAME = ? AND MATERIALPACKINGNAME =? AND ETCSTATE = 'EtcOut' ";
				Object[] bind = new Object[] { packingState,
						Double.parseDouble(materialQuantityList.get(i)),
						TimeStampUtil.getCurrentTimestamp(),
						eventInfo.getEventUser(), confirmUser, siteName,
						//materialPackingName.get(i) };
						materialPackingNameList.get(i) };
				IDMFrameServiceProxy.getSqlTemplate()
						.update(strCondition, bind);
			}
		}
	}
		 catch (IDMFrameDBErrorSignal e) {
			e.printStackTrace();
		}
	}

	public void reserveInvoice(String boxName, String materialshiprequest,
			String materialshiprequestdetail, String eventName, String eventUser) {

		String lastEventTimeKey = TimeStampUtil.getCurrentEventTimeKey();
		String sql = "CALL RESERVE_INVOICE(?,?,?,?,?,?)";
		JdbcTemplate jdbcTemplate = IDMFrameServiceProxy.getSqlTemplate()
				.getJdbcTemplate();
		jdbcTemplate.update(sql, new Object[] { boxName, materialshiprequest,
				materialshiprequestdetail, eventName, eventUser,
				lastEventTimeKey });
	}
	//增加发料领用人receiptor字段 added by wh 18.10.22
	public void updateMaterialPackingStockOut(EventInfo eventInfo,
			String siteName, List<String> materialPackingKeyList,
			String stockState, String erpEventTime, String eventUser,
			String eventComment, String receiveActNo, String messageId) throws Exception {
		try {
			String lastEventTimeKey = TimeStampUtil.getCurrentEventTimeKey();
			List<MaterialPackingKey> packingKeyList = new ArrayList<MaterialPackingKey>();
			Timestamp lastEventTime = new Timestamp(System.currentTimeMillis());
			SetEventInfo setEventInfo = new SetEventInfo();

			Map<String, Object> bindMap = new HashMap<String, Object>();
			CommonValidation cv = new CommonValidation();
			SimpleDateFormat wad = new SimpleDateFormat("yyyy-MM-dd");
			// Date erpTime= wad.parse(erpEventTime);
			erpEventTime = cv.getDate(erpEventTime) + " 00:00:00";
			Date date = new Date();
			date = wad.parse(cv.getDate(erpEventTime));

			bindMap.put("stockState", stockState);
			bindMap.put("erpEventTime", date);
			bindMap.put("shipTime", lastEventTime);
			bindMap.put("receiveActNo", receiveActNo);
			bindMap.put("locationName", "");
			bindMap.put("oldStockState", "Stocked");
			// bindMap.setLocationName("");

			setEventInfo.setUserColumns(bindMap);

			for (int i = 0; i < materialPackingKeyList.size(); i++) {

				MaterialPackingKey keyInfo = new MaterialPackingKey();
				keyInfo.setSiteName(siteName);
				keyInfo.setMaterialPackingName((String) materialPackingKeyList
						.get(i));
				MaterialPacking dataInfo = selectByKey(keyInfo);
//                if(eventInfo.getEventName().equalsIgnoreCase("CompleteNPShipRequest"))
//                {
//				  dataInfo.setStockState(stockState);
//                }
				dataInfo.setShipTime(lastEventTime);
				dataInfo.setReceiveActNo(receiveActNo);
				dataInfo.setLocationName("");
				dataInfo.setErpEventTime(Timestamp.valueOf(erpEventTime));
				dataInfo.setLastEventName(eventInfo.getEventName());
				dataInfo.setLastEventComment(eventInfo.getEventComment());
				dataInfo.setLastEventTimeKey(lastEventTimeKey);
				dataInfo.setLastEventUser(eventInfo.getEventUser());
				dataInfo.setLastEventTime(eventInfo.getEventTime());
				dataInfo.setReasonCodeType(eventInfo.getReasonCodeType());
				dataInfo.setReasonCode(eventInfo.getReasonCode());
		        //dataInfo.setReceiptor(receiptor);
				MaterialPackingServiceProxy.getMaterialPackingService().update(
						dataInfo);

				// packingKeyList.add(keyInfo);

			}
			// 20160525，马兴华注释，保证出库只留一条历史记录，才用上面的Update方法
			// MaterialPackingServiceProxy.getMaterialPackingService().setEvent(packingKeyList,
			// eventInfo, setEventInfo);
		} catch (IDMFrameDBErrorSignal e) {
			e.printStackTrace();
		}
	}
	
	public void updateMaterialPackingStockOutForOME(EventInfo eventInfo, String siteName, List<String> materialPackingKeyList,
			String stockState, String erpEventTime, String eventUser, String eventComment, String receiveActNo,
			String messageId) throws Exception {
		try {
			String lastEventTimeKey = TimeStampUtil.getCurrentEventTimeKey();
			List<MaterialPackingKey> packingKeyList = new ArrayList<MaterialPackingKey>();
			Timestamp lastEventTime = new Timestamp(System.currentTimeMillis());
			SetEventInfo setEventInfo = new SetEventInfo();

			Map<String, Object> bindMap = new HashMap<String, Object>();
			CommonValidation cv = new CommonValidation();
			SimpleDateFormat wad = new SimpleDateFormat("yyyy-MM-dd");
			// Date erpTime= wad.parse(erpEventTime);
			erpEventTime = cv.getDate(erpEventTime) + " 00:00:00";
			Date date = new Date();
			date = wad.parse(cv.getDate(erpEventTime));
			
			bindMap.put("stockState", stockState);
			bindMap.put("erpEventTime", date);
			bindMap.put("shipTime", lastEventTime);
			bindMap.put("receiveActNo", receiveActNo);
			// bindMap.put("locationName", "");
			bindMap.put("oldStockState", "Stocked");
			// bindMap.setLocationName("");

			setEventInfo.setUserColumns(bindMap);
			for (int i = 0; i < materialPackingKeyList.size(); i++) {

				MaterialPackingKey keyInfo = new MaterialPackingKey();
				keyInfo.setSiteName(siteName);
				keyInfo.setMaterialPackingName((String) materialPackingKeyList.get(i));
				MaterialPacking dataInfo = selectByKey(keyInfo);
				
//                if(eventInfo.getEventName().equalsIgnoreCase("CompleteNPShipRequest"))
//                {
//				  dataInfo.setStockState(stockState);
//                }
				// shiprequesttype 411 412  not update stockstate
				dataInfo.setShipTime(lastEventTime);
				dataInfo.setReceiveActNo(receiveActNo);
				dataInfo.setOldStockState("Stocked");
				dataInfo.setShipTime(lastEventTime);
				dataInfo.setReceiveActNo(receiveActNo);
				// dataInfo.setLocationName("");
				dataInfo.setErpEventTime(Timestamp.valueOf(erpEventTime));
				dataInfo.setLastEventName(eventInfo.getEventName());
				dataInfo.setLastEventComment(eventInfo.getEventComment());
				dataInfo.setLastEventTimeKey(lastEventTimeKey);
				dataInfo.setLastEventUser(eventInfo.getEventUser());
				dataInfo.setLastEventTime(eventInfo.getEventTime());
				dataInfo.setReasonCodeType(eventInfo.getReasonCodeType());
				dataInfo.setReasonCode(eventInfo.getReasonCode());
				// dataInfo.setReceiptor(receiptor);
				MaterialPackingServiceProxy.getMaterialPackingService().update(dataInfo);

				// packingKeyList.add(keyInfo);

			}
			// 20160525，马兴华注释，保证出库只留一条历史记录，才用上面的Update方法
			// MaterialPackingServiceProxy.getMaterialPackingService().setEvent(packingKeyList,
			// eventInfo, setEventInfo);
			// SaveUnDoInfo(receiveActNo,"",messageId);
		} catch (IDMFrameDBErrorSignal e) {
			e.printStackTrace();
		}
	}
	
	public void updateMaterialPackingStockOutForStockOut(EventInfo eventInfo,
			String siteName, List<String> materialPackingKeyList,
			String stockState, String erpEventTime, String eventUser,
			String eventComment, String receiveActNo) throws Exception {
		try {
			String lastEventTimeKey = TimeStampUtil.getCurrentEventTimeKey();
			// List<MaterialPacking> packingList = new
			// ArrayList<MaterialPacking>();
			List<MaterialPackingKey> packingKeyList = new ArrayList<MaterialPackingKey>();
			Timestamp lastEventTime = new Timestamp(System.currentTimeMillis());

			// for(int i=0;i<materialPackingNameList.size();i++)
			// {
			// MaterialPackingKey keyInfo = new MaterialPackingKey();
			// keyInfo.setSiteName(siteName);
			// (String)materialPackingNameList.get(i);
			// // if(i==0)
			// // {
			// // keyInfo.setMaterialPackingName("B33333333333");
			// // }
			// // else
			// // {
			// // keyInfo.setMaterialPackingName("B33333333334");
			// // }
			// MaterialPacking dataInfo = selectByKey(keyInfo);
			// dataInfo.setStockState(stockState);
			// //dataInfo.setShipTime(lastEventTime);
			// dataInfo.setLastEventTime(lastEventTime);
			// dataInfo.setLastEventUser(eventUser);
			// dataInfo.setLastEventTimeKey(lastEventTimeKey);
			// dataInfo.setLastEventComment(eventComment);
			// packingList.add(dataInfo);
			//
			// }

			SetEventInfo setEventInfo = new SetEventInfo();

			Map<String, Object> bindMap = new HashMap<String, Object>();
			CommonValidation cv = new CommonValidation();
			SimpleDateFormat wad = new SimpleDateFormat("yyyy-MM-dd");
			// Date erpTime= wad.parse(erpEventTime);
			erpEventTime = cv.getDate(erpEventTime) + " 00:00:00";
			Date date = new Date();
			date = wad.parse(cv.getDate(erpEventTime));

			bindMap.put("stockState", stockState);
			bindMap.put("erpEventTime", date);
			bindMap.put("shipTime", lastEventTime);
			bindMap.put("receiveActNo", receiveActNo);
			bindMap.put("locationName", "");
			bindMap.put("oldStockState", "Stocked");
			// bindMap.setLocationName("");

			setEventInfo.setUserColumns(bindMap);

			for (int i = 0; i < materialPackingKeyList.size(); i++) {

				MaterialPackingKey keyInfo = new MaterialPackingKey();
				keyInfo.setSiteName(siteName);
				keyInfo.setMaterialPackingName((String) materialPackingKeyList
						.get(i));
				MaterialPacking dataInfo = selectByKey(keyInfo);
//                if(eventInfo.getEventName().equalsIgnoreCase("CompleteNPShipRequest"))
//                {
//				  dataInfo.setStockState(stockState);
//                }
				dataInfo.setShipTime(lastEventTime);
				dataInfo.setReceiveActNo(receiveActNo);
				dataInfo.setLocationName("");
				dataInfo.setErpEventTime(Timestamp.valueOf(erpEventTime));
				dataInfo.setLastEventName(eventInfo.getEventName());
				dataInfo.setLastEventComment(eventInfo.getEventComment());
				dataInfo.setLastEventTimeKey(lastEventTimeKey);
				dataInfo.setLastEventUser(eventInfo.getEventUser());
				dataInfo.setLastEventTime(eventInfo.getEventTime());
				dataInfo.setReasonCodeType(eventInfo.getReasonCodeType());
				dataInfo.setReasonCode(eventInfo.getReasonCode());
				MaterialPackingServiceProxy.getMaterialPackingService().update(
						dataInfo);

				// packingKeyList.add(keyInfo);

			}
			// 20160525，马兴华注释，保证出库只留一条历史记录，才用上面的Update方法
			// MaterialPackingServiceProxy.getMaterialPackingService().setEvent(packingKeyList,
			// eventInfo, setEventInfo);
		} catch (IDMFrameDBErrorSignal e) {
			e.printStackTrace();
		}
	}

	public void MaterialPackingStockOut_05SEQ(EventInfo eventInfo,
			List<String> materialPackingKeyList, String siteName,
			String invoiceNo) throws Exception {
		try {

			String sql = "SELECT T.MATERIALPACKINGNAME ,S.SEQ FROM  MATERIALPACKING T   JOIN "
					+ "(SELECT A.SHIPREQUESTNAME,B.SHIPREQUESTDETAILNAME, "
					+ "B.MATERIALSPECNAME,A.SHIPPLANDATE, "
					+ "B.ASSIGNEDQUANTITY,B.CHARGE,C.MATERIALUNIT, ROWNUM AS SEQ "
					+ "FROM  MATERIALSHIPREQUEST A,MATERIALSHIPREQUESTDETAIL B,MATERIALSPEC C "
					+ "WHERE A.SHIPREQUESTNAME=B.SHIPREQUESTNAME AND B.MATERIALSPECNAME=C.MATERIALSPECNAME and C.sitename=a.sitename AND A.SHIPREQUESTNAME=:invoiceNo) S "
					+ "ON(T.SHIPREQUESTNAME=S.SHIPREQUESTNAME AND T.SHIPREQUESTDETAILNAME=S.SHIPREQUESTDETAILNAME ) WHERE  T.stockstate='Stocked' and T.MATERIALPACKINGTYPE='Box'";
			Map<String, Object> bindMap1 = new HashMap<String, Object>();
			bindMap1.put("invoiceNo", invoiceNo);
			List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
					.getSqlTemplate()
					.queryForList(sql, bindMap1);
			List<MaterialPackingKey> packingKeyList = new ArrayList<MaterialPackingKey>();

			String unDoID = generateVirtualUndoName(siteName);

			for (int i = 0; i < materialPackingKeyList.size(); i++) {

				MaterialPackingKey keyInfo = new MaterialPackingKey();
				keyInfo.setSiteName(siteName);
				keyInfo.setMaterialPackingName(sqlResult.get(i)
						.get("MATERIALPACKINGNAME").toString());
				MaterialPacking dataInfo = selectByKey(keyInfo);
				dataInfo.setUnDoDetailName(sqlResult.get(i).get("SEQ")
						.toString());
				dataInfo.setUnDoID(unDoID);
				packingKeyList.add(keyInfo);
				MaterialPackingServiceProxy.getMaterialPackingService().update(
						dataInfo);

				String sql1 = "INSERT INTO BS_MATERIALPACKINGUNDOINFO (unDoID,siteName,materialPackingName,materialPackingType,contentMaterialType,materialType,materialSpecName"
						+ ",superMaterialPackingName,packingGrade,subPackingQuantity,materialCreateQuantity,materialQuantity,packingState"
						+ ",oldPackingState,stockState,oldStockState,holdState,areaName,locationName,durableName,materialProcessGroupName"
						+ ",createTime,createUser,receiveRequestName,receiveRequestDetailName,makeDate,receiveActNo,receiveTime"
						+ ",receiveUser,shipRequestName,shipRequestDetailName,shipTime,shipUser,reasonCodeType,reasonCode,oqaResult,"
						+ "oqaResultState,erpLocation,erpFactory,etcState,stockInType,charge,supplierName,unDoDetailName"
						+ ",erpEventTime,LASTEVENTNAME, LASTEVENTTIMEKEY, LASTEVENTTIME, LASTEVENTUSER,LASTEVENTCOMMENT,NPFLAG) values (:unDoID,:siteName,:materialPackingName,:materialPackingType,:contentMaterialType,:materialType,"
						+ ":materialSpecName,:superMaterialPackingName,:packingGrade,:subPackingQuantity,:materialCreateQuantity,:materialQuantity,"
						+ ":packingState,:oldPackingState,:stockState,:oldStockState,:holdState,:areaName,:locationName,:durableName,:materialProcessGroupName,"
						+ ":createTime,:createUser,:receiveRequestName,:receiveRequestDetailName,:makeDate,:receiveActNo,:receiveTime,:receiveUser,"
						+ ":shipRequestName,:shipRequestDetailName,:shipTime,:shipUser,:reasonCodeType,:reasonCode,:oqaResult,:oqaResultState,:erpLocation,"
						+ ":erpFactory,:etcState,:stockInType,:charge,:supplierName,:unDoDetailName,:erpEventTime,:LASTEVENTNAME,:LASTEVENTTIMEKEY,:LASTEVENTTIME,:LASTEVENTUSER,:LASTEVENTCOMMENT,:NPFLAG)";

				Map<String, Object> bindMap = new HashMap<String, Object>();
				bindMap.put("unDoID", unDoID);
				bindMap.put("siteName", siteName);
				bindMap.put("materialPackingName",
						sqlResult.get(i).get("MATERIALPACKINGNAME").toString());
				bindMap.put("materialPackingType",
						dataInfo.getMaterialPackingType());
				bindMap.put("contentMaterialType",
						dataInfo.getContentMaterialType());
				bindMap.put("materialType", dataInfo.getMaterialType());
				bindMap.put("materialSpecName", dataInfo.getMaterialSpecName());
				bindMap.put("superMaterialPackingName",
						dataInfo.getSuperMaterialPackingName());
				bindMap.put("packingGrade", dataInfo.getPackingGrade());
				bindMap.put("subPackingQuantity",
						dataInfo.getSubPackingQuantity());
				bindMap.put("materialCreateQuantity",
						dataInfo.getMaterialCreateQuantity());
				bindMap.put("materialQuantity", dataInfo.getMaterialQuantity());
				bindMap.put("packingState", dataInfo.getPackingState());
				bindMap.put("oldPackingState", dataInfo.getOldPackingState());
				bindMap.put("stockState", dataInfo.getStockState());
				bindMap.put("oldStockState", dataInfo.getOldStockState());
				bindMap.put("holdState", dataInfo.getHoldState());
				bindMap.put("areaName", dataInfo.getAreaName());
				bindMap.put("locationName", dataInfo.getLocationName());
				bindMap.put("durableName", dataInfo.getDurableName());
				bindMap.put("materialProcessGroupName",
						dataInfo.getMaterialProcessGroupName());
				bindMap.put("createTime", dataInfo.getCreateTime());
				bindMap.put("createUser", dataInfo.getCreateUser());
				bindMap.put("receiveRequestName",
						dataInfo.getReceiveRequestName());
				bindMap.put("receiveRequestDetailName",
						dataInfo.getReceiveRequestDetailName());
				bindMap.put("makeDate", dataInfo.getMakeDate());
				bindMap.put("receiveActNo", dataInfo.getReceiveActNo());
				bindMap.put("receiveTime", dataInfo.getReceiveTime());
				bindMap.put("receiveUser", dataInfo.getReceiveUser());
				bindMap.put("shipRequestName", dataInfo.getShipRequestName());
				bindMap.put("shipRequestDetailName",
						dataInfo.getShipRequestDetailName());
				bindMap.put("shipTime", dataInfo.getShipTime());
				bindMap.put("shipUser", dataInfo.getShipUser());
				bindMap.put("reasonCodeType", dataInfo.getReasonCodeType());
				bindMap.put("reasonCode", dataInfo.getReasonCode());
				bindMap.put("oqaResult", dataInfo.getOqaResult());
				bindMap.put("oqaResultState", dataInfo.getOqaResultState());
				bindMap.put("erpLocation", dataInfo.getErpLocation());
				bindMap.put("erpFactory", dataInfo.getErpFactory());
				bindMap.put("etcState", dataInfo.getEtcState());
				bindMap.put("stockInType", dataInfo.getStockInType());
				bindMap.put("charge", dataInfo.getCharge());
				bindMap.put("supplierName", dataInfo.getSupplierName());
				// bindMap.put("preUnDoId", dataInfo.getPreUnDoId());
				bindMap.put("unDoDetailName", dataInfo.getUnDoDetailName());
				// bindMap.put("unDoIdDate", dataInfo.getUnDoIdDate());
				bindMap.put("erpEventTime", dataInfo.getErpEventTime());
				bindMap.put("LASTEVENTNAME", eventInfo.getEventName());
				bindMap.put("LASTEVENTTIMEKEY", eventInfo.getEventTimeKey());
				bindMap.put("LASTEVENTTIME", eventInfo.getEventTime());
				bindMap.put("LASTEVENTUSER", eventInfo.getEventUser());
				bindMap.put("LASTEVENTCOMMENT", eventInfo.getEventComment());
				// NPFLAG
				bindMap.put("NPFLAG", dataInfo.getNpFlag());
				IDMFrameServiceProxy.getSqlTemplate()
						.update(sql1, bindMap);

			}
			// MaterialPackingServiceProxy.getMaterialPackingService().setEvent(packingKeyList,
			// eventInfo, setEventInfo);
		} catch (IDMFrameDBErrorSignal e) {
			e.printStackTrace();
		}
	}

	public void NPMaterialPackingStockOut_05SEQ(EventInfo eventInfo,
			List<String> materialPackingKeyList, String siteName,
			String invoiceNo,String reasonCode,String reasonCodeType) throws Exception {
		try {

			String sql = "SELECT T.MATERIALPACKINGNAME ,S.SEQ FROM  MATERIALPACKING T  WHERE T.STOCKSTATE='StockOut' JOIN "
					+ "(SELECT A.SHIPREQUESTNAME,B.SHIPREQUESTDETAILNAME, "
					+ "B.MATERIALSPECNAME,A.SHIPPLANDATE, "
					+ "B.ASSIGNEDQUANTITY,B.CHARGE,C.MATERIALUNIT, ROWNUM AS SEQ "
					+ "FROM  MATERIALSHIPREQUEST A,MATERIALSHIPREQUESTDETAIL B,MATERIALSPEC C "
					+ "WHERE A.SHIPREQUESTNAME=B.SHIPREQUESTNAME AND B.MATERIALSPECNAME=C.MATERIALSPECNAME AND C.SITENAME=:siteName  AND A.SHIPREQUESTNAME=:invoiceNo) S "
					+ "ON((T.SHIPREQUESTNAME=S.SHIPREQUESTNAME AND T.SHIPREQUESTDETAILNAME=S.SHIPREQUESTDETAILNAME AND T.CHARGE=S.CHARGE) OR (T.SHIPREQUESTNAME=S.SHIPREQUESTNAME AND T.SHIPREQUESTDETAILNAME=S.SHIPREQUESTDETAILNAME AND T.CHARGE IS NULL AND S.CHARGE IS NULL)) ";
			Map<String, Object> bindMap1 = new HashMap<String, Object>();
			bindMap1.put("invoiceNo", invoiceNo);
			bindMap1.put("siteName", siteName);
			List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
					.getSqlTemplate()
					.queryForList(sql, bindMap1);
			List<MaterialPackingKey> packingKeyList = new ArrayList<MaterialPackingKey>();
			String unDoID = generateVirtualUndoName(siteName);

			Date date = new Date();
			SimpleDateFormat df = new SimpleDateFormat("yyyy");
			String receiveyear = df.format(date);
			for (int i = 0; i < materialPackingKeyList.size(); i++) {

				MaterialPackingKey keyInfo = new MaterialPackingKey();
				keyInfo.setSiteName(siteName);
				keyInfo.setMaterialPackingName(sqlResult.get(i)
						.get("MATERIALPACKINGNAME").toString());
				MaterialPacking dataInfo = selectByKey(keyInfo);
				dataInfo.setUnDoDetailName("V-"
						+ sqlResult.get(i).get("SEQ").toString());
				dataInfo.setUnDoID(unDoID);
				packingKeyList.add(keyInfo);
				MaterialPackingServiceProxy.getMaterialPackingService().update(
						dataInfo);

				String sql1 = "INSERT INTO BS_MATERIALPACKINGUNDOINFO (unDoID,siteName,materialPackingName,materialPackingType,contentMaterialType,materialType,materialSpecName"
						+ ",superMaterialPackingName,packingGrade,subPackingQuantity,materialCreateQuantity,materialQuantity,packingState"
						+ ",oldPackingState,stockState,oldStockState,holdState,areaName,locationName,durableName,materialProcessGroupName"
						+ ",createTime,createUser,receiveRequestName,receiveRequestDetailName,makeDate,receiveActNo,receiveTime"
						+ ",receiveUser,shipRequestName,shipRequestDetailName,shipTime,shipUser,reasonCodeType,reasonCode,oqaResult,"
						+ "oqaResultState,erpLocation,erpFactory,etcState,stockInType,charge,supplierName,unDoDetailName"
						+ ",erpEventTime,LASTEVENTNAME, LASTEVENTTIMEKEY, LASTEVENTTIME, LASTEVENTUSER,LASTEVENTCOMMENT,NPFLAG,UNDOIDDATE,UNDOIDSTATE) values (:unDoID,:siteName,:materialPackingName,:materialPackingType,:contentMaterialType,:materialType,"
						+ ":materialSpecName,:superMaterialPackingName,:packingGrade,:subPackingQuantity,:materialCreateQuantity,:materialQuantity,"
						+ ":packingState,:oldPackingState,:stockState,:oldStockState,:holdState,:areaName,:locationName,:durableName,:materialProcessGroupName,"
						+ ":createTime,:createUser,:receiveRequestName,:receiveRequestDetailName,:makeDate,:receiveActNo,:receiveTime,:receiveUser,"
						+ ":shipRequestName,:shipRequestDetailName,:shipTime,:shipUser,:reasonCodeType,:reasonCode,:oqaResult,:oqaResultState,:erpLocation,"
						+ ":erpFactory,:etcState,:stockInType,:charge,:supplierName,:unDoDetailName,:erpEventTime,:LASTEVENTNAME,:LASTEVENTTIMEKEY,:LASTEVENTTIME,:LASTEVENTUSER,:LASTEVENTCOMMENT,:NPFLAG,:UNDOIDDATE,:UNDOIDSTATE)";

				Map<String, Object> bindMap = new HashMap<String, Object>();
				bindMap.put("unDoID", unDoID);
				bindMap.put("siteName", siteName);
				bindMap.put("materialPackingName",
						sqlResult.get(i).get("MATERIALPACKINGNAME").toString());
				bindMap.put("materialPackingType",
						dataInfo.getMaterialPackingType());
				bindMap.put("contentMaterialType",
						dataInfo.getContentMaterialType());
				bindMap.put("materialType", dataInfo.getMaterialType());
				bindMap.put("materialSpecName", dataInfo.getMaterialSpecName());
				bindMap.put("superMaterialPackingName",
						dataInfo.getSuperMaterialPackingName());
				bindMap.put("packingGrade", dataInfo.getPackingGrade());
				bindMap.put("subPackingQuantity",
						dataInfo.getSubPackingQuantity());
				bindMap.put("materialCreateQuantity",
						dataInfo.getMaterialCreateQuantity());
				bindMap.put("materialQuantity", dataInfo.getMaterialQuantity());
				bindMap.put("packingState", dataInfo.getPackingState());
				bindMap.put("oldPackingState", dataInfo.getOldPackingState());
				bindMap.put("stockState", dataInfo.getStockState());
				bindMap.put("oldStockState", dataInfo.getOldStockState());
				bindMap.put("holdState", dataInfo.getHoldState());
				bindMap.put("areaName", dataInfo.getAreaName());
				bindMap.put("locationName", dataInfo.getLocationName());
				bindMap.put("durableName", dataInfo.getDurableName());
				bindMap.put("materialProcessGroupName",
						dataInfo.getMaterialProcessGroupName());
				bindMap.put("createTime", dataInfo.getCreateTime());
				bindMap.put("createUser", dataInfo.getCreateUser());
				bindMap.put("receiveRequestName",
						dataInfo.getReceiveRequestName());
				bindMap.put("receiveRequestDetailName",
						dataInfo.getReceiveRequestDetailName());
				bindMap.put("makeDate", dataInfo.getMakeDate());
				bindMap.put("receiveActNo", dataInfo.getReceiveActNo());
				bindMap.put("receiveTime", dataInfo.getReceiveTime());
				bindMap.put("receiveUser", dataInfo.getReceiveUser());
				bindMap.put("shipRequestName", dataInfo.getShipRequestName());
				bindMap.put("shipRequestDetailName",
						dataInfo.getShipRequestDetailName());
				bindMap.put("shipTime", dataInfo.getShipTime());
				bindMap.put("shipUser", dataInfo.getShipUser());
				bindMap.put("reasonCodeType", reasonCodeType);
				bindMap.put("reasonCode", reasonCode);
				bindMap.put("oqaResult", dataInfo.getOqaResult());
				bindMap.put("oqaResultState", dataInfo.getOqaResultState());
				bindMap.put("erpLocation", dataInfo.getErpLocation());
				bindMap.put("erpFactory", dataInfo.getErpFactory());
				bindMap.put("etcState", dataInfo.getEtcState());
				bindMap.put("stockInType", dataInfo.getStockInType());
				bindMap.put("charge", dataInfo.getCharge());
				bindMap.put("supplierName", dataInfo.getSupplierName());
				// bindMap.put("preUnDoId", dataInfo.getPreUnDoId());
				bindMap.put("unDoDetailName", dataInfo.getUnDoDetailName());
				// bindMap.put("unDoIdDate", dataInfo.getUnDoIdDate());
				bindMap.put("erpEventTime", dataInfo.getErpEventTime());
				bindMap.put("LASTEVENTNAME", eventInfo.getEventName());
				bindMap.put("LASTEVENTTIMEKEY", eventInfo.getEventTimeKey());
				bindMap.put("LASTEVENTTIME", eventInfo.getEventTime());
				bindMap.put("LASTEVENTUSER", eventInfo.getEventUser());
				bindMap.put("LASTEVENTCOMMENT", eventInfo.getEventComment());
				// NPFLAG
				bindMap.put("NPFLAG", dataInfo.getNpFlag());
				bindMap.put("UNDOIDDATE", receiveyear);
				bindMap.put("UNDOIDSTATE", "Created");
				IDMFrameServiceProxy.getSqlTemplate()
						.update(sql1, bindMap);

			}
			// MaterialPackingServiceProxy.getMaterialPackingService().setEvent(packingKeyList,
			// eventInfo, setEventInfo);
		} catch (IDMFrameDBErrorSignal e) {
			e.printStackTrace();
		}
	}
	
	public void MaterialPackingStockOut_15SEQ(
			List<String> materialPackingKeyList, String siteName,
			String invoiceNo) throws Exception {
		try {

			String sql = "SELECT T.MATERIALPACKINGNAME, S.SEQ FROM MATERIALPACKING T, "
					+ "(SELECT  SHIPREQUESTNAME,SHIPREQUESTDETAILNAME, CHARGE,rownum AS SEQ "
					+ "FROM  (SELECT  A.ERPFACTORYNAME,A.SHIPREQUESTNAME ,A.SHIPREQUESTTYPE AS BWART, "
					+ "A.WORKORDERID AS AUFNR,B.SHIPREQUESTDETAILNAME, B.MATERIALSPECNAME AS MATNR, "
					+ "SUM(C.MATERIALQUANTITY) AS MENGE,A.SHIPPLANDATE AS BDTER, "
					+ "B.ERPLOCATION,A.ERPRECEIVEFACTORY AS UMWRK,A.ERPRECEIVELOCATION AS UMLGO,C.CHARGE "
					+ "FROM   MATERIALSHIPREQUEST A,MATERIALSHIPREQUESTDETAIL B,MATERIALPACKING C "
					+ "WHERE  A.SHIPREQUESTNAME = B.SHIPREQUESTNAME AND A.SHIPREQUESTNAME = C.SHIPREQUESTNAME "
					+ "AND B.SHIPREQUESTDETAILNAME = C.SHIPREQUESTDETAILNAME AND A.SHIPREQUESTNAME = :invoiceNo and C.stockstate='Stocked' and C.MATERIALPACKINGTYPE='Box' "
					+ "GROUP BY   A.ERPFACTORYNAME,A.SHIPREQUESTNAME,A.SHIPREQUESTTYPE,A.WORKORDERID, "
					+ "B.SHIPREQUESTDETAILNAME,B.MATERIALSPECNAME,B.REQUESTQUANTITY,A.SHIPPLANDATE,B.ERPLOCATION, "
					+ "A.ERPRECEIVEFACTORY,A.ERPRECEIVELOCATION,C.CHARGE)) S "
					+ "WHERE T.SHIPREQUESTNAME=S.SHIPREQUESTNAME AND T.SHIPREQUESTDETAILNAME=S.SHIPREQUESTDETAILNAME AND T.stockstate='Stocked' "
					+ "AND (nvl (T.CHARGE, 'X')= nvl (S.CHARGE, 'X') ) ";
			Map<String, Object> bindMap1 = new HashMap<String, Object>();
			bindMap1.put("invoiceNo", invoiceNo);
			List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
					.getSqlTemplate()
					.queryForList(sql, bindMap1);
			List<MaterialPackingKey> packingKeyList = new ArrayList<MaterialPackingKey>();
			for (int i = 0; i < materialPackingKeyList.size(); i++) {

				MaterialPackingKey keyInfo = new MaterialPackingKey();
				keyInfo.setSiteName(siteName);
				keyInfo.setMaterialPackingName(sqlResult.get(i)
						.get("MATERIALPACKINGNAME").toString());
				MaterialPacking dataInfo = selectByKey(keyInfo);
				dataInfo.setUnDoDetailName(sqlResult.get(i).get("SEQ")
						.toString());
				packingKeyList.add(keyInfo);
				MaterialPackingServiceProxy.getMaterialPackingService().update(
						dataInfo);
			}
			// MaterialPackingServiceProxy.getMaterialPackingService().setEvent(packingKeyList,
			// eventInfo, setEventInfo);
		} catch (IDMFrameDBErrorSignal e) {
			e.printStackTrace();
		}
	}

	public void NPMaterialPackingStockOut_15SEQ(EventInfo eventInfo,
			List<String> materialPackingKeyList, String siteName,
			String invoiceNo,String reasonCode,String reasonCodeType) throws Exception {
		try {

			String sql = "SELECT T.MATERIALPACKINGNAME, S.SEQ FROM MATERIALPACKING T, "
					+ "(SELECT  SHIPREQUESTNAME,SHIPREQUESTDETAILNAME, CHARGE,rownum AS SEQ "
					+ "FROM  (SELECT  A.ERPFACTORYNAME,A.SHIPREQUESTNAME ,A.SHIPREQUESTTYPE AS BWART, "
					+ "A.WORKORDERID AS AUFNR,B.SHIPREQUESTDETAILNAME, B.MATERIALSPECNAME AS MATNR, "
					+ "SUM(C.MATERIALQUANTITY) AS MENGE,A.SHIPPLANDATE AS BDTER, "
					+ "B.ERPLOCATION,A.ERPRECEIVEFACTORY AS UMWRK,A.ERPRECEIVELOCATION AS UMLGO,C.CHARGE "
					+ "FROM   MATERIALSHIPREQUEST A,MATERIALSHIPREQUESTDETAIL B,MATERIALPACKING C "
					+ "WHERE  A.SHIPREQUESTNAME = B.SHIPREQUESTNAME AND A.SHIPREQUESTNAME = C.SHIPREQUESTNAME "
					+ "AND B.SHIPREQUESTDETAILNAME = C.SHIPREQUESTDETAILNAME AND A.SHIPREQUESTNAME = :invoiceNo and C.STOCKSTATE='Stocked' "
					+ "GROUP BY   A.ERPFACTORYNAME,A.SHIPREQUESTNAME,A.SHIPREQUESTTYPE,A.WORKORDERID, "
					+ "B.SHIPREQUESTDETAILNAME,B.MATERIALSPECNAME,B.REQUESTQUANTITY,A.SHIPPLANDATE,B.ERPLOCATION, "
					+ "A.ERPRECEIVEFACTORY,A.ERPRECEIVELOCATION,C.CHARGE)) S "
					+ "WHERE T.SHIPREQUESTNAME=S.SHIPREQUESTNAME AND T.SHIPREQUESTDETAILNAME=S.SHIPREQUESTDETAILNAME and T.STOCKSTATE='Stocked'"
					+ "AND (T.CHARGE=S.CHARGE OR  S.CHARGE IS NULL) ";
			Map<String, Object> bindMap1 = new HashMap<String, Object>();
			bindMap1.put("invoiceNo", invoiceNo);
			List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
					.getSqlTemplate()
					.queryForList(sql, bindMap1);

			List<MaterialPackingKey> packingKeyList = new ArrayList<MaterialPackingKey>();

			String unDoID = generateVirtualUndoName(siteName);
			Date date = new Date();
			SimpleDateFormat df = new SimpleDateFormat("yyyy");
			String receiveyear = df.format(date);

			for (int i = 0; i < materialPackingKeyList.size(); i++) {

				MaterialPackingKey keyInfo = new MaterialPackingKey();
				keyInfo.setSiteName(siteName);
				keyInfo.setMaterialPackingName(sqlResult.get(i)
						.get("MATERIALPACKINGNAME").toString());
				MaterialPacking dataInfo = selectByKey(keyInfo);
				dataInfo.setUnDoDetailName("V-"
						+ sqlResult.get(i).get("SEQ").toString());
				dataInfo.setUnDoID(unDoID);
				dataInfo.setStockState("StockOut");
				packingKeyList.add(keyInfo);

				String sql1 = "INSERT INTO BS_MATERIALPACKINGUNDOINFO (unDoID,siteName,materialPackingName,materialPackingType,contentMaterialType,materialType,materialSpecName"
						+ ",superMaterialPackingName,packingGrade,subPackingQuantity,materialCreateQuantity,materialQuantity,packingState"
						+ ",oldPackingState,stockState,oldStockState,holdState,areaName,locationName,durableName,materialProcessGroupName"
						+ ",createTime,createUser,receiveRequestName,receiveRequestDetailName,makeDate,receiveActNo,receiveTime"
						+ ",receiveUser,shipRequestName,shipRequestDetailName,shipTime,shipUser,reasonCodeType,reasonCode,oqaResult,"
						+ "oqaResultState,erpLocation,erpFactory,etcState,stockInType,charge,supplierName,unDoDetailName"
						+ ",erpEventTime,LASTEVENTNAME, LASTEVENTTIMEKEY, LASTEVENTTIME, LASTEVENTUSER,LASTEVENTCOMMENT,NPFLAG,UNDOIDDATE,UNDOIDSTATE) values (:unDoID,:siteName,:materialPackingName,:materialPackingType,:contentMaterialType,:materialType,"
						+ ":materialSpecName,:superMaterialPackingName,:packingGrade,:subPackingQuantity,:materialCreateQuantity,:materialQuantity,"
						+ ":packingState,:oldPackingState,:stockState,:oldStockState,:holdState,:areaName,:locationName,:durableName,:materialProcessGroupName,"
						+ ":createTime,:createUser,:receiveRequestName,:receiveRequestDetailName,:makeDate,:receiveActNo,:receiveTime,:receiveUser,"
						+ ":shipRequestName,:shipRequestDetailName,:shipTime,:shipUser,:reasonCodeType,:reasonCode,:oqaResult,:oqaResultState,:erpLocation,"
						+ ":erpFactory,:etcState,:stockInType,:charge,:supplierName,:unDoDetailName,:erpEventTime,:LASTEVENTNAME,:LASTEVENTTIMEKEY,:LASTEVENTTIME,:LASTEVENTUSER,:LASTEVENTCOMMENT,:NPFLAG,:UNDOIDDATE,:UNDOIDSTATE)";

				Map<String, Object> bindMap = new HashMap<String, Object>();
				bindMap.put("unDoID", unDoID);
				bindMap.put("siteName", siteName);
				bindMap.put("materialPackingName",
						sqlResult.get(i).get("MATERIALPACKINGNAME").toString());
				bindMap.put("materialPackingType",
						dataInfo.getMaterialPackingType());
				bindMap.put("contentMaterialType",
						dataInfo.getContentMaterialType());
				bindMap.put("materialType", dataInfo.getMaterialType());
				bindMap.put("materialSpecName", dataInfo.getMaterialSpecName());
				bindMap.put("superMaterialPackingName",
						dataInfo.getSuperMaterialPackingName());
				bindMap.put("packingGrade", dataInfo.getPackingGrade());
				bindMap.put("subPackingQuantity",
						dataInfo.getSubPackingQuantity());
				bindMap.put("materialCreateQuantity",
						dataInfo.getMaterialCreateQuantity());
				bindMap.put("materialQuantity", dataInfo.getMaterialQuantity());
				bindMap.put("packingState", dataInfo.getPackingState());
				bindMap.put("oldPackingState", dataInfo.getOldPackingState());
				bindMap.put("stockState", dataInfo.getStockState());
				bindMap.put("oldStockState", dataInfo.getOldStockState());
				bindMap.put("holdState", dataInfo.getHoldState());
				bindMap.put("areaName", dataInfo.getAreaName());
				bindMap.put("locationName", dataInfo.getLocationName());
				bindMap.put("durableName", dataInfo.getDurableName());
				bindMap.put("materialProcessGroupName",
						dataInfo.getMaterialProcessGroupName());
				bindMap.put("createTime", dataInfo.getCreateTime());
				bindMap.put("createUser", dataInfo.getCreateUser());
				bindMap.put("receiveRequestName",
						dataInfo.getReceiveRequestName());
				bindMap.put("receiveRequestDetailName",
						dataInfo.getReceiveRequestDetailName());
				bindMap.put("makeDate", dataInfo.getMakeDate());
				bindMap.put("receiveActNo", dataInfo.getReceiveActNo());
				bindMap.put("receiveTime", dataInfo.getReceiveTime());
				bindMap.put("receiveUser", dataInfo.getReceiveUser());
				bindMap.put("shipRequestName", dataInfo.getShipRequestName());
				bindMap.put("shipRequestDetailName",
						dataInfo.getShipRequestDetailName());
				bindMap.put("shipTime", dataInfo.getShipTime());
				bindMap.put("shipUser", dataInfo.getShipUser());
				bindMap.put("reasonCodeType", reasonCodeType);
				bindMap.put("reasonCode", reasonCode);
				bindMap.put("oqaResult", dataInfo.getOqaResult());
				bindMap.put("oqaResultState", dataInfo.getOqaResultState());
				bindMap.put("erpLocation", dataInfo.getErpLocation());
				bindMap.put("erpFactory", dataInfo.getErpFactory());
				bindMap.put("etcState", dataInfo.getEtcState());
				bindMap.put("stockInType", dataInfo.getStockInType());
				bindMap.put("charge", dataInfo.getCharge());
				bindMap.put("supplierName", dataInfo.getSupplierName());
				// bindMap.put("preUnDoId", dataInfo.getPreUnDoId());
				bindMap.put("unDoDetailName", dataInfo.getUnDoDetailName());
				// bindMap.put("unDoIdDate", dataInfo.getUnDoIdDate());
				bindMap.put("erpEventTime", dataInfo.getErpEventTime());
				bindMap.put("LASTEVENTNAME", eventInfo.getEventName());
				bindMap.put("LASTEVENTTIMEKEY", eventInfo.getEventTimeKey());
				bindMap.put("LASTEVENTTIME", eventInfo.getEventTime());
				bindMap.put("LASTEVENTUSER", eventInfo.getEventUser());
				bindMap.put("LASTEVENTCOMMENT", eventInfo.getEventComment());
				// NPFLAG
				bindMap.put("NPFLAG", dataInfo.getNpFlag());
				bindMap.put("UNDOIDDATE", receiveyear);
				bindMap.put("UNDOIDSTATE", "Created");

				IDMFrameServiceProxy.getSqlTemplate()
						.update(sql1, bindMap);

				MaterialPackingServiceProxy.getMaterialPackingService().update(
						dataInfo);
			}
			// MaterialPackingServiceProxy.getMaterialPackingService().setEvent(packingKeyList,
			// eventInfo, setEventInfo);

		} catch (IDMFrameDBErrorSignal e) {
			e.printStackTrace();
		}
	}

	public void MaterialPackingStockOut_02SEQ(
			List<String> materialPackingKeyList, String siteName,
			String invoiceNo) throws Exception {
		try {
			String sql="SELECT   T.MATERIALPACKINGNAME, S.SEQ FROM   MATERIALPACKING T, "
                    +"(SELECT   SHIPREQUESTNAME,WORKORDERID,MATERIALSPECNAME,SHIPREQUESTDETAILNAME, "
                    +"CHARGE,ERPLOCATION,ROWNUM AS SEQ FROM (  "
                    +"SELECT A.SHIPREQUESTNAME, B.ERPFACTORYNAME,B.SHIPREQUESTDETAILNAME , A.WORKORDERID, "
                    +"B.MATERIALSPECNAME, SUM(C.MATERIALQUANTITY) AS BDMNG,C.CHARGE, B.ERPLOCATION,A.ERPFACTORYNAME AS WERKA "
                    +"FROM MATERIALSHIPREQUEST A,MATERIALSHIPREQUESTDETAIL B,MATERIALPACKING C "
                    +"WHERE A.SHIPREQUESTNAME=B.SHIPREQUESTNAME AND  A.SHIPREQUESTNAME=:invoiceNo AND A.SHIPREQUESTNAME=C.SHIPREQUESTNAME and C.stockstate='Stocked' and C.MATERIALPACKINGTYPE='Box'"
                    +"AND B.SHIPREQUESTDETAILNAME=C.SHIPREQUESTDETAILNAME GROUP BY   A.SHIPREQUESTNAME,B.ERPFACTORYNAME, B.MATERIALSPECNAME "
                    +",B.SHIPREQUESTDETAILNAME, C.CHARGE,B.ERPLOCATION,A.WORKORDERID,A.ERPFACTORYNAME)) S "
                    +"WHERE T.SHIPREQUESTNAME=S.SHIPREQUESTNAME "
                    +"AND T.SHIPREQUESTDETAILNAME= S.SHIPREQUESTDETAILNAME and T.stockstate='Stocked' "
                    +"AND (T.CHARGE = S.CHARGE OR nvl (T.CHARGE,'TEST') =nvl(S.CHARGE,'TEST'))  " ;
		Map<String, Object> bindMap1 = new HashMap<String, Object>();
			bindMap1.put("invoiceNo", invoiceNo);
			List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
					.getSqlTemplate()
					.queryForList(sql, bindMap1);
			List<MaterialPackingKey> packingKeyList = new ArrayList<MaterialPackingKey>();
			for (int i = 0; i < materialPackingKeyList.size(); i++) {

				MaterialPackingKey keyInfo = new MaterialPackingKey();
				keyInfo.setSiteName(siteName);
				keyInfo.setMaterialPackingName(sqlResult.get(i)
						.get("MATERIALPACKINGNAME").toString());
				MaterialPacking dataInfo = selectByKey(keyInfo);
				dataInfo.setUnDoDetailName(sqlResult.get(i).get("SEQ")
						.toString());
				packingKeyList.add(keyInfo);
				MaterialPackingServiceProxy.getMaterialPackingService().update(
						dataInfo);
			}
			// MaterialPackingServiceProxy.getMaterialPackingService().setEvent(packingKeyList,
			// eventInfo, setEventInfo);
		} catch (IDMFrameDBErrorSignal e) {
			e.printStackTrace();
		}
	}

	public String UndoIDtoShipRequestName(String UndoID) {
		List<Map<String, Object>> sqlResult = new ArrayList<Map<String, Object>>();
		try {

			String sql = "select * from BS_MATERIALPACKINGUNDOINFO A where A.UndoID = :undoId";
			Map<String, Object> bindMap = new HashMap<String, Object>();
			bindMap.put("undoId", UndoID);

			sqlResult = IDMFrameServiceProxy.getSqlTemplate()
					.queryForList(sql, bindMap);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return sqlResult.get(0).get("SHIPREQUESTNAME").toString();
	}

	public String ShipRequestNametoDetailType(String shipRequestName) {
		List<Map<String, Object>> sqlResult = new ArrayList<Map<String, Object>>();
		try {

			String sql = "select * from MATERIALSHIPREQUEST A where A.SHIPREQUESTNAME = :shipRequestName";
			Map<String, Object> bindMap = new HashMap<String, Object>();
			bindMap.put("shipRequestName", shipRequestName);

			sqlResult = IDMFrameServiceProxy.getSqlTemplate()
					.queryForList(sql, bindMap);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return sqlResult.get(0).get("SHIPREQUESTDETAILTYPE").toString();
	}

	public String UndoIDtoDeliveryType(String UndoID) {
		List<Map<String, Object>> sqlResult = new ArrayList<Map<String, Object>>();
		List<Map<String, Object>> sqlResult1 = new ArrayList<Map<String, Object>>();
		try {

			String sql = "select * from BS_MATERIALPACKINGUNDOINFO A where A.UndoID = :undoId";
			String sql1 = "select * from MATERIALSHIPREQUEST A where A.SHIPREQUESTNAME = :shipRequestName";
			Map<String, Object> bindMap = new HashMap<String, Object>();
			bindMap.put("undoId", UndoID);

			sqlResult = IDMFrameServiceProxy.getSqlTemplate()
					.queryForList(sql, bindMap);

			bindMap.put("shipRequestName",
					sqlResult.get(0).get("SHIPREQUESTNAME").toString());
			sqlResult1 = IDMFrameServiceProxy.getSqlTemplate()
					.queryForList(sql1, bindMap);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return sqlResult1.get(0).get("DELIVERYTYPE").toString();
	}

	public String UndoIDtoReceiveActNo(String UndoID) {
		List<Map<String, Object>> sqlResult = new ArrayList<Map<String, Object>>();
		try {

			String sql = "select * from BS_MATERIALPACKINGUNDOINFO A where A.UndoID = :undoId";
			Map<String, Object> bindMap = new HashMap<String, Object>();
			bindMap.put("undoId", UndoID);

			sqlResult = IDMFrameServiceProxy.getSqlTemplate()
					.queryForList(sql, bindMap);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return sqlResult.get(0).get("RECEIVEACTNO").toString();
	}

	public void UndoStateChange(List<MaterialUnDoinfo> UnDoList, String UndoID,
			String SiteName, EventInfo eventInfo,String shipRequestDetailName) {

		List<MaterialUnDoinfo> undolist = new MaterialPackingStockInUtil()
				.GetNoPOStockOutUnDoInfoList(UndoID);
		HashMap<String, String> unDoDetailNameListMap = new HashMap<String, String>();
		for (int i = 0; i < UnDoList.size(); i++) {
			unDoDetailNameListMap.put(undolist.get(i).getUnDoDetailName()
					.substring(2), UnDoList.get(i).getUnDoDetailName());

		}
		if (undolist.size() == UnDoList.size()) {
			// 存储新的物料凭证
			for (int i = 0; i < UnDoList.size(); i++) {
				List<MaterialPackingKey> materialPackingKeyList = new ArrayList<MaterialPackingKey>();
				List<SetEventInfo> setlist = new ArrayList<SetEventInfo>();
				MaterialUnDoinfo undoselect = undolist.get(i);
				MaterialUnDoinfo undoerp = UnDoList.get(i);
				List<MaterialUnDoinfo> undoselectbyundodetail = new MaterialPackingStockInUtil()
						.GetNoPOUnDoInfoList(undoselect.getUnDoID(),
								undoselect.getUnDoDetailName());
				for (MaterialUnDoinfo undo : undoselectbyundodetail) {
					MaterialPackingKey keyInfo = new MaterialPackingKey();
					keyInfo.setMaterialPackingName(undo
							.getMaterialPackingName());
					keyInfo.setSiteName(undo.getSiteName());
					materialPackingKeyList.add(keyInfo);
					SetEventInfo setEventInfo = new SetEventInfo();
					Map<String, Object> bindmpMap = new HashMap<String, Object>();
					bindmpMap.put("erpState","SUCCESS");
					bindmpMap.put("unDoID", undoerp.getUnDoID());
					bindmpMap.put("npFlag", "N");
					bindmpMap.put(
							"unDoDetailName",
							unDoDetailNameListMap.get(undolist.get(i)
									.getUnDoDetailName().substring(2)));
//					if (undoselect.getMaterialProcessGroupName().contains(
//							"OQA-")) {
//						bindmpMap.put("materialProcessGroupName",
//								undoerp.getOqaname());
//					}
					setEventInfo.setUserColumns(bindmpMap);
					setlist.add(setEventInfo);
				}
				eventInfo.setEventName("CompleteShipRequest");
				eventInfo.setEventComment("NoPOStockOutForAccount");
				MaterialPackingServiceProxy.getMaterialPackingService()
						.setEvent(materialPackingKeyList, eventInfo, setlist);
				
			}
			String sql_UndoBoxInfo = "UPDATE BS_MATERIALPACKINGUNDOINFO SET UNDOIDSTATE='N' "
					+ "WHERE UNDOID=:UNDOID AND SITENAME=:SITENAME and SHIPREQUESTDETAILNAME=:shipRequestDetailName AND UNDOIDSTATE<>'N' AND LASTEVENTNAME<>'MToM'";

			Map<String, Object> bindMap_UndoBoxInfo = new HashMap<String, Object>();
			bindMap_UndoBoxInfo.put("SITENAME", SiteName);
			bindMap_UndoBoxInfo.put("UNDOID", UndoID);
			bindMap_UndoBoxInfo.put("shipRequestDetailName", shipRequestDetailName);
			IDMFrameServiceProxy.getSqlTemplate()
					.update(sql_UndoBoxInfo, bindMap_UndoBoxInfo);
			// 存储新的物料凭证

			try{new MaterialPackingStockInImpl().SaveOQAUnDoInfo(UnDoList.get(0)
					.getUnDoIdDate(), UnDoList.get(0).getUnDoID());}
			catch (Exception e)
			{e.printStackTrace();}
		}
	}

	public void NPMaterialPackingStockOut_02SEQ(EventInfo eventInfo,
			List<String> materialPackingKeyList, String siteName,
			String invoiceNo,String reasonCode,String reasonCodeType) throws Exception {
		try {

			String sql = "SELECT   T.MATERIALPACKINGNAME, S.SEQ FROM   MATERIALPACKING T, "
					+ "(SELECT   SHIPREQUESTNAME,WORKORDERID,MATERIALSPECNAME,SHIPREQUESTDETAILNAME, "
					+ "CHARGE,ERPLOCATION,ROWNUM AS SEQ FROM   (  SELECT   A.SHIPREQUESTNAME, "
					+ "B.ERPFACTORYNAME,A.WORKORDERID,B.SHIPREQUESTDETAILNAME,B.MATERIALSPECNAME, "
					// +"SUM(C.MATERIALQUANTITY) AS BDMNG,"
					+ " B.CHARGE,B.ERPLOCATION FROM   MATERIALSHIPREQUEST A, "
					+ "MATERIALSHIPREQUESTDETAIL B WHERE   A.SHIPREQUESTNAME = B.SHIPREQUESTNAME "
					+ "AND A.SHIPREQUESTNAME = :invoiceNo GROUP BY   A.SHIPREQUESTNAME, "
					+ "B.ERPFACTORYNAME,B.MATERIALSPECNAME,B.SHIPREQUESTDETAILNAME,B.CHARGE,B.ERPLOCATION, "
					+ "A.WORKORDERID)) S WHERE T.SHIPREQUESTNAME=S.SHIPREQUESTNAME and T.STOCKSTATE='Stocked'  "
					+ "AND T.SHIPREQUESTDETAILNAME= S.SHIPREQUESTDETAILNAME ";
			Map<String, Object> bindMap1 = new HashMap<String, Object>();
			bindMap1.put("invoiceNo", invoiceNo);
			List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
					.getSqlTemplate()
					.queryForList(sql, bindMap1);
			List<MaterialPackingKey> packingKeyList = new ArrayList<MaterialPackingKey>();

			String unDoID = generateVirtualUndoName(siteName);

			Date date = new Date();
			SimpleDateFormat df = new SimpleDateFormat("yyyy");
			String receiveyear = df.format(date);

			for (int i = 0; i < materialPackingKeyList.size(); i++) {

				MaterialPackingKey keyInfo = new MaterialPackingKey();
				keyInfo.setSiteName(siteName);
				keyInfo.setMaterialPackingName(sqlResult.get(i)
						.get("MATERIALPACKINGNAME").toString());
				MaterialPacking dataInfo = selectByKey(keyInfo);
				dataInfo.setUnDoDetailName("V-"
						+ sqlResult.get(i).get("SEQ").toString());
				dataInfo.setUnDoID(unDoID);
				dataInfo.setStockState("StockOut");
				packingKeyList.add(keyInfo);
				MaterialPackingServiceProxy.getMaterialPackingService().update(
						dataInfo);

				String sql1 = "INSERT INTO BS_MATERIALPACKINGUNDOINFO (unDoID,siteName,materialPackingName,materialPackingType,contentMaterialType,materialType,materialSpecName"
						+ ",superMaterialPackingName,packingGrade,subPackingQuantity,materialCreateQuantity,materialQuantity,packingState"
						+ ",oldPackingState,stockState,oldStockState,holdState,areaName,locationName,durableName,materialProcessGroupName"
						+ ",createTime,createUser,receiveRequestName,receiveRequestDetailName,makeDate,receiveActNo,receiveTime"
						+ ",receiveUser,shipRequestName,shipRequestDetailName,shipTime,shipUser,reasonCodeType,reasonCode,oqaResult,"
						+ "oqaResultState,erpLocation,erpFactory,etcState,stockInType,charge,supplierName,unDoDetailName"
						+ ",erpEventTime,LASTEVENTNAME, LASTEVENTTIMEKEY, LASTEVENTTIME, LASTEVENTUSER,LASTEVENTCOMMENT,NPFLAG,UNDOIDDATE,UNDOIDSTATE) values (:unDoID,:siteName,:materialPackingName,:materialPackingType,:contentMaterialType,:materialType,"
						+ ":materialSpecName,:superMaterialPackingName,:packingGrade,:subPackingQuantity,:materialCreateQuantity,:materialQuantity,"
						+ ":packingState,:oldPackingState,:stockState,:oldStockState,:holdState,:areaName,:locationName,:durableName,:materialProcessGroupName,"
						+ ":createTime,:createUser,:receiveRequestName,:receiveRequestDetailName,:makeDate,:receiveActNo,:receiveTime,:receiveUser,"
						+ ":shipRequestName,:shipRequestDetailName,:shipTime,:shipUser,:reasonCodeType,:reasonCode,:oqaResult,:oqaResultState,:erpLocation,"
						+ ":erpFactory,:etcState,:stockInType,:charge,:supplierName,:unDoDetailName,:erpEventTime,:LASTEVENTNAME,:LASTEVENTTIMEKEY,:LASTEVENTTIME,:LASTEVENTUSER,:LASTEVENTCOMMENT,:NPFLAG,:UNDOIDDATE,:UNDOIDSTATE)";

				Map<String, Object> bindMap = new HashMap<String, Object>();
				bindMap.put("unDoID", unDoID);
				bindMap.put("siteName", siteName);
				bindMap.put("materialPackingName",
						sqlResult.get(i).get("MATERIALPACKINGNAME").toString());
				bindMap.put("materialPackingType",
						dataInfo.getMaterialPackingType());
				bindMap.put("contentMaterialType",
						dataInfo.getContentMaterialType());
				bindMap.put("materialType", dataInfo.getMaterialType());
				bindMap.put("materialSpecName", dataInfo.getMaterialSpecName());
				bindMap.put("superMaterialPackingName",
						dataInfo.getSuperMaterialPackingName());
				bindMap.put("packingGrade", dataInfo.getPackingGrade());
				bindMap.put("subPackingQuantity",
						dataInfo.getSubPackingQuantity());
				bindMap.put("materialCreateQuantity",
						dataInfo.getMaterialCreateQuantity());
				bindMap.put("materialQuantity", dataInfo.getMaterialQuantity());
				bindMap.put("packingState", dataInfo.getPackingState());
				bindMap.put("oldPackingState", dataInfo.getOldPackingState());
				bindMap.put("stockState", dataInfo.getStockState());
				bindMap.put("oldStockState", dataInfo.getOldStockState());
				bindMap.put("holdState", dataInfo.getHoldState());
				bindMap.put("areaName", dataInfo.getAreaName());
				bindMap.put("locationName", dataInfo.getLocationName());
				bindMap.put("durableName", dataInfo.getDurableName());
				bindMap.put("materialProcessGroupName",
						dataInfo.getMaterialProcessGroupName());
				bindMap.put("createTime", dataInfo.getCreateTime());
				bindMap.put("createUser", dataInfo.getCreateUser());
				bindMap.put("receiveRequestName",
						dataInfo.getReceiveRequestName());
				bindMap.put("receiveRequestDetailName",
						dataInfo.getReceiveRequestDetailName());
				bindMap.put("makeDate", dataInfo.getMakeDate());
				bindMap.put("receiveActNo", dataInfo.getReceiveActNo());
				bindMap.put("receiveTime", dataInfo.getReceiveTime());
				bindMap.put("receiveUser", dataInfo.getReceiveUser());
				bindMap.put("shipRequestName", dataInfo.getShipRequestName());
				bindMap.put("shipRequestDetailName",
						dataInfo.getShipRequestDetailName());
				bindMap.put("shipTime", dataInfo.getShipTime());
				bindMap.put("shipUser", dataInfo.getShipUser());
				bindMap.put("reasonCodeType", reasonCodeType);
				bindMap.put("reasonCode", reasonCode);
				bindMap.put("oqaResult", dataInfo.getOqaResult());
				bindMap.put("oqaResultState", dataInfo.getOqaResultState());
				bindMap.put("erpLocation", dataInfo.getErpLocation());
				bindMap.put("erpFactory", dataInfo.getErpFactory());
				bindMap.put("etcState", dataInfo.getEtcState());
				bindMap.put("stockInType", dataInfo.getStockInType());
				bindMap.put("charge", dataInfo.getCharge());
				bindMap.put("supplierName", dataInfo.getSupplierName());
				// bindMap.put("preUnDoId", dataInfo.getPreUnDoId());
				bindMap.put("unDoDetailName", dataInfo.getUnDoDetailName());
				// bindMap.put("unDoIdDate", dataInfo.getUnDoIdDate());
				bindMap.put("erpEventTime", dataInfo.getErpEventTime());
				bindMap.put("LASTEVENTNAME", eventInfo.getEventName());
				bindMap.put("LASTEVENTTIMEKEY", eventInfo.getEventTimeKey());
				bindMap.put("LASTEVENTTIME", eventInfo.getEventTime());
				bindMap.put("LASTEVENTUSER", eventInfo.getEventUser());
				bindMap.put("LASTEVENTCOMMENT", eventInfo.getEventComment());
				// NPFLAG
				bindMap.put("NPFLAG", dataInfo.getNpFlag());
				bindMap.put("UNDOIDDATE", receiveyear);
				bindMap.put("UNDOIDSTATE", "Created");
				IDMFrameServiceProxy.getSqlTemplate()
						.update(sql1, bindMap);

			}
			// MaterialPackingServiceProxy.getMaterialPackingService().setEvent(packingKeyList,
			// eventInfo, setEventInfo);
		} catch (IDMFrameDBErrorSignal e) {
			e.printStackTrace();
		}
	}

	public void MaterialPackingStockOut_17SEQ(
			List<String> materialPackingKeyList, String siteName,
			String receiveActNo, String receiveRequestName, EventInfo eventInfo)
			throws Exception {
		try {

			/*
			 * String sql=
			 * "SELECT T.MATERIALPACKINGNAME,S.SEQ FROM MATERIALPACKING T, " +
			 * "(SELECT RECEIVEREQUESTNAME,RECEIVEREQUESTDETAILNAME,CHARGE,SUBMATERIALSPECNAME,ROWNUM AS SEQ "
			 * +
			 * "FROM (SELECT DISTINCT  B.RECEIVEREQUESTDETAILTYPE ,B.RECEIVEREQUESTNAME, "
			 * +
			 * "B.PLANDATE,A.RECEIVEREQUESTDETAILNAME,B.ERPFACTORY,A.SUBMATERIALSPECNAME, "
			 * +"SUM(C.MATERIALQUANTITY) AS MENGE,C.CHARGE ,C.ERPLOCATION " +
			 * "FROM   MATERIALSHIPREQUESTTOOEM A, MATERIALRECEIVEREQUESTDETAIL B,MATERIALPACKING C "
			 * +
			 * "WHERE   A.RECEIVEREQUESTNAME = B.RECEIVEREQUESTNAME AND A.RECEIVEREQUESTNAME=C.SHIPREQUESTNAME "
			 * +"AND A.SUBMATERIALSPECNAME=C.MATERIALSPECNAME " +
			 * "AND A.RECEIVEREQUESTDETAILNAME=C.SHIPREQUESTDETAILNAME AND C.STOCKSTATE='Stocked' AND A.RECEIVEREQUESTNAME =:invoiceNo "
			 * +
			 * "GROUP BY B.RECEIVEREQUESTDETAILTYPE,B.RECEIVEREQUESTNAME,B.PLANDATE,A.RECEIVEREQUESTDETAILNAME, "
			 * +"C.ERPLOCATION,A.SUBMATERIALSPECNAME,C.CHARGE,B.ERPFACTORY)) S "
			 * +
			 * "where T.SHIPREQUESTNAME=S.RECEIVEREQUESTNAME and T.SHIPREQUESTDETAILNAME =S.RECEIVEREQUESTDETAILNAME "
			 * +
			 * "and (T.CHARGE=S.CHARGE or S.CHARGE is  null) and T.MATERIALSPECNAME=S.SUBMATERIALSPECNAME "
			 * ;
			 */
//			String sql = "SELECT  MATERIALPACKINGNAME,S.SEQ FROM MATERIALPACKING T,"
//					+ "(SELECT A.MATERIALSPECNAME, MATERIALQUANTITY,A.CHARGE,A.ERPLOCATION,A.ERPFACTORY,A.SHIPREQUESTNAME,A.SHIPREQUESTDETAILNAME,A.RECEIVEACTNO, ROWNUM AS SEQ "
//					+ "FROM (SELECT B.MATERIALSPECNAME, SUM(MATERIALQUANTITY)AS MATERIALQUANTITY,B.CHARGE,B.ERPLOCATION,B.ERPFACTORY,B.SHIPREQUESTNAME, "
//					+ "B.SHIPREQUESTDETAILNAME,B.RECEIVEACTNO FROM MATERIALPACKING B WHERE RECEIVEACTNO = :receiveActNo "
//					+ "GROUP BY B.MATERIALSPECNAME,B.CHARGE,B.ERPLOCATION,B.ERPFACTORY,B.SHIPREQUESTNAME,B.SHIPREQUESTDETAILNAME,B.RECEIVEACTNO) A)S "
//					+ "WHERE T.MATERIALSPECNAME=S.MATERIALSPECNAME AND ((S.CHARGE IS null and t.charge is null)or T.CHARGE=S.CHARGE ) AND T.ERPLOCATION=S.ERPLOCATION "
//					+ "AND T.ERPFACTORY=S.ERPFACTORY AND T.SHIPREQUESTNAME=S.SHIPREQUESTNAME AND T.SHIPREQUESTDETAILNAME=S.SHIPREQUESTDETAILNAME AND T.RECEIVEACTNO=S.RECEIVEACTNO ";
			String sql = "SELECT B.MATERIALSPECNAME, SUM(MATERIALQUANTITY) AS MENGE,B.CHARGE,B.ERPLOCATION,B.ERPFACTORY,B.SHIPREQUESTNAME,B.SHIPREQUESTDETAILNAME "
					+ "FROM MATERIALPACKING B WHERE RECEIVEACTNO = :receiveActNo and stockstate='Stocked' and MATERIALPACKINGTYPE='Box' "
					+ "GROUP BY B.MATERIALSPECNAME,B.CHARGE,B.ERPLOCATION,B.ERPFACTORY,B.SHIPREQUESTNAME,B.SHIPREQUESTDETAILNAME";
			Map<String, Object> bindMap1 = new HashMap<String, Object>();
			bindMap1.put("receiveActNo", receiveActNo);
			List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
					.getSqlTemplate()
					.queryForList(sql, bindMap1);
			List<MaterialPackingKey> packingKeyList = new ArrayList<MaterialPackingKey>();
			for(int j=0;j<sqlResult.size();j++){
				for (int i = 0; i < materialPackingKeyList.size(); i++) {
					MaterialPackingKey keyInfo = new MaterialPackingKey();
					keyInfo.setSiteName(siteName);
					keyInfo.setMaterialPackingName(materialPackingKeyList.get(i));
					MaterialPacking dataInfo = selectByKey(keyInfo);
					if(dataInfo.getCharge()==null||dataInfo.getCharge().equals(""))
					{
					if(dataInfo.getMaterialSpecName().equals(sqlResult.get(j).get("MATERIALSPECNAME").toString())&&
							dataInfo.getErpLocation().equals(sqlResult.get(j).get("ERPLOCATION").toString())&&
							dataInfo.getErpFactory().equals(sqlResult.get(j).get("ERPFACTORY").toString())&&
							dataInfo.getShipRequestName().equals(sqlResult.get(j).get("SHIPREQUESTNAME").toString())&&
							dataInfo.getShipRequestDetailName().equals(sqlResult.get(j).get("SHIPREQUESTDETAILNAME").toString())&&
							sqlResult.get(j).get("CHARGE")==null)
					{
						dataInfo.setUnDoDetailName(Integer.toString(j+1));
						packingKeyList.add(keyInfo);
						MaterialPackingServiceProxy.getMaterialPackingService().update(
								dataInfo);
					}
					}
					else{
						if(dataInfo.getMaterialSpecName().equals(sqlResult.get(j).get("MATERIALSPECNAME").toString())&&
								dataInfo.getErpLocation().equals(sqlResult.get(j).get("ERPLOCATION").toString())&&
								dataInfo.getErpFactory().equals(sqlResult.get(j).get("ERPFACTORY").toString())&&
								dataInfo.getShipRequestName().equals(sqlResult.get(j).get("SHIPREQUESTNAME").toString())&&
								dataInfo.getShipRequestDetailName().equals(sqlResult.get(j).get("SHIPREQUESTDETAILNAME").toString())&&
								dataInfo.getCharge().equals(sqlResult.get(j).get("CHARGE")==null?"":sqlResult.get(j).get("CHARGE").toString()))
						{
							dataInfo.setUnDoDetailName(Integer.toString(j+1));
							packingKeyList.add(keyInfo);
							MaterialPackingServiceProxy.getMaterialPackingService().update(
									dataInfo);
						}
					}
						
				}
				
			}
			
			MaterialReceiveActKey mrk = new MaterialReceiveActKey();
			mrk.setSiteName(siteName);
			mrk.setReceiveactNO(receiveActNo);
			mrk.setReceiveRequestName(receiveRequestName);
			com.cim.idm.wmspackage.materialreceiverequestact.management.info.SetEventInfo setevent = new com.cim.idm.wmspackage.materialreceiverequestact.management.info.SetEventInfo();
			Map<String, Object> bindMap2 = new HashMap<String, Object>();
			bindMap2.put("receiveActState", "StockOut");
			setevent.setUserColumns(bindMap2);
			MaterialReceiveRequestActServiceProxy
					.getReceiveRequestBatchService().setEvent(mrk, eventInfo,
							setevent);
			// MaterialPackingServiceProxy.getMaterialPackingService().setEvent(packingKeyList,
			// eventInfo, setEventInfo);
		} catch (IDMFrameDBErrorSignal e) {
			e.printStackTrace();
		}
	}
	
	public void MaterialPackingWOStockOut_17SEQ(
			List<String> materialPackingKeyList, String siteName,
			String receiveActNo, String receiveRequestName, EventInfo eventInfo)
			throws Exception {
		try {

			String sql =" SELECT A.SHIPREQUESTNAME, B.ERPFACTORYNAME,B.SHIPREQUESTDETAILNAME , A.WORKORDERID,A.SHIPREQUESTDETAILTYPE,  "
                    +"B.MATERIALSPECNAME, SUM(C.MATERIALQUANTITY) AS BDMNG,C.CHARGE, B.ERPLOCATION,A.ERPFACTORYNAME AS WERKA "
                    +"FROM MATERIALSHIPREQUEST A,MATERIALSHIPREQUESTDETAIL B,MATERIALPACKING C "
                    +"WHERE A.SHIPREQUESTNAME=B.SHIPREQUESTNAME AND  A.SHIPREQUESTNAME=:invoiceNo AND C.RECEIVEACTNO = :receiveActNo  AND A.SHIPREQUESTNAME=C.SHIPREQUESTNAME and C.stockstate='Stocked' "
                    +"AND B.SHIPREQUESTDETAILNAME=C.SHIPREQUESTDETAILNAME GROUP BY   A.SHIPREQUESTNAME,B.ERPFACTORYNAME, B.MATERIALSPECNAME " 
                    +",B.SHIPREQUESTDETAILNAME,A.SHIPREQUESTDETAILTYPE, C.CHARGE,B.ERPLOCATION,A.WORKORDERID,A.ERPFACTORYNAME ";
			
			Map<String, Object> bindMap1 = new HashMap<String, Object>();
			bindMap1.put("receiveActNo", receiveActNo);
			bindMap1.put("invoiceNo", receiveRequestName);
			List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
					.getSqlTemplate()
					.queryForList(sql, bindMap1);
			List<MaterialPackingKey> packingKeyList = new ArrayList<MaterialPackingKey>();
			for(int j=0;j<sqlResult.size();j++){
				for (int i = 0; i < materialPackingKeyList.size(); i++) {
					MaterialPackingKey keyInfo = new MaterialPackingKey();
					keyInfo.setSiteName(siteName);
					keyInfo.setMaterialPackingName(materialPackingKeyList.get(i));
					MaterialPacking dataInfo = selectByKey(keyInfo);
					if(dataInfo.getCharge()==null||dataInfo.getCharge().equals(""))
					{
					if(dataInfo.getMaterialSpecName().equals(sqlResult.get(j).get("MATERIALSPECNAME").toString())&&
							dataInfo.getErpLocation().equals(sqlResult.get(j).get("ERPLOCATION").toString())&&
							dataInfo.getErpFactory().equals(sqlResult.get(j).get("ERPFACTORYNAME").toString())&&
							dataInfo.getShipRequestName().equals(sqlResult.get(j).get("SHIPREQUESTNAME").toString())&&
							dataInfo.getShipRequestDetailName().equals(sqlResult.get(j).get("SHIPREQUESTDETAILNAME").toString())&&
							sqlResult.get(j).get("CHARGE")==null)
					{
						dataInfo.setUnDoDetailName(Integer.toString(j+1));
						packingKeyList.add(keyInfo);
						MaterialPackingServiceProxy.getMaterialPackingService().update(
								dataInfo);
					}
					}
					else{
						if(dataInfo.getMaterialSpecName().equals(sqlResult.get(j).get("MATERIALSPECNAME").toString())&&
								dataInfo.getErpLocation().equals(sqlResult.get(j).get("ERPLOCATION").toString())&&
								dataInfo.getErpFactory().equals(sqlResult.get(j).get("ERPFACTORYNAME").toString())&&
								dataInfo.getShipRequestName().equals(sqlResult.get(j).get("SHIPREQUESTNAME").toString())&&
								dataInfo.getShipRequestDetailName().equals(sqlResult.get(j).get("SHIPREQUESTDETAILNAME").toString())&&
								dataInfo.getCharge().equals(sqlResult.get(j).get("CHARGE")==null?"":sqlResult.get(j).get("CHARGE").toString()))
						{
							dataInfo.setUnDoDetailName(Integer.toString(j+1));
							packingKeyList.add(keyInfo);
							MaterialPackingServiceProxy.getMaterialPackingService().update(
									dataInfo);
						}
					}
						
				}
				
			}
			
			MaterialReceiveActKey mrk = new MaterialReceiveActKey();
			mrk.setSiteName(siteName);
			mrk.setReceiveactNO(receiveActNo);
			mrk.setReceiveRequestName(receiveRequestName);
			com.cim.idm.wmspackage.materialreceiverequestact.management.info.SetEventInfo setevent = new com.cim.idm.wmspackage.materialreceiverequestact.management.info.SetEventInfo();
			Map<String, Object> bindMap2 = new HashMap<String, Object>();
			bindMap2.put("receiveActState", "StockOut");
			setevent.setUserColumns(bindMap2);
			MaterialReceiveRequestActServiceProxy
					.getReceiveRequestBatchService().setEvent(mrk, eventInfo,
							setevent);
			// MaterialPackingServiceProxy.getMaterialPackingService().setEvent(packingKeyList,
			// eventInfo, setEventInfo);
		} catch (IDMFrameDBErrorSignal e) {
			e.printStackTrace();
		}
	}
	
	public void PreScrapSEQ(
			List<String> materialPackingKeyList, String siteName,
			String receiveActNo, String receiveRequestName, EventInfo eventInfo,String erpLocation,String factoryName)
			throws Exception {
		try {

			String sql = "SELECT B.MATERIALSPECNAME, SUM(MATERIALQUANTITY) AS QUANTITY,B.CHARGE,B.ERPLOCATION,B.ERPFACTORY,B.SHIPREQUESTNAME,B.SHIPREQUESTDETAILNAME,B.PACKINGGRADE "
					+ "FROM MATERIALPACKING B WHERE RECEIVEACTNO = :receiveActNo "
					+ "GROUP BY B.MATERIALSPECNAME,B.CHARGE,B.ERPLOCATION,B.ERPFACTORY,B.SHIPREQUESTNAME,B.SHIPREQUESTDETAILNAME,B.PACKINGGRADE";
			String sql_box="SELECT a.sitename,a.materialpackingname ,A.MATERIALSPECNAME, MATERIALQUANTITY,A.CHARGE,A.ERPLOCATION,A.ERPFACTORY,A.SHIPREQUESTNAME,A.SHIPREQUESTDETAILNAME,A.PACKINGGRADE,A.RECEIVEACTNO "
					+" from materialpacking a "
					+" where RECEIVEACTNO = :receiveActNo ";
			Map<String, Object> bindMap1 = new HashMap<String, Object>();
			bindMap1.put("receiveActNo", receiveActNo);
			List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
					.getSqlTemplate()
					.queryForList(sql, bindMap1);
			List<Map<String, Object>> sqlResult_box = IDMFrameServiceProxy
					.getSqlTemplate()
					.queryForList(sql_box, bindMap1);
			EventInfo eventInfoForStockOut=new EventInfo();
			eventInfoForStockOut=eventInfo;
			eventInfoForStockOut.setReasonCode("0001");
			eventInfoForStockOut.setReasonCodeType("valueStockOut");
			CommonValidation cv = new CommonValidation();
			String erpEventTime1 = cv.getDate("") + " 00:00:00";
			List<MaterialPacking> mpList = new ArrayList<MaterialPacking>();
			String CHARGE="";
			String charge="";
			for (int i = 0; i < materialPackingKeyList.size(); i++) {
				CHARGE = sqlResult_box.get(i).get("CHARGE")==null?"":sqlResult_box.get(i).get("CHARGE").toString();
				
				for(int j=0;j<sqlResult.size();j++){
					charge = sqlResult.get(j).get("CHARGE")==null?"":sqlResult.get(j).get("CHARGE").toString();
					if(charge.equals(CHARGE)
							&&sqlResult_box.get(i).get("MATERIALSPECNAME").toString().equals(sqlResult.get(j).get("MATERIALSPECNAME").toString())
							&&sqlResult_box.get(i).get("ERPLOCATION").toString().equals(sqlResult.get(j).get("ERPLOCATION").toString())
							&&sqlResult_box.get(i).get("ERPFACTORY").toString().equals(sqlResult.get(j).get("ERPFACTORY").toString()))
							//&&sqlResult_box.get(i).get("PACKINGGRADE").toString().equals(sqlResult.get(j).get("PACKINGGRADE").toString()))//未质检物料进行财务报废 add by mxh
					{
						MaterialPackingKey keyInfo = new MaterialPackingKey();
						keyInfo.setSiteName(siteName);
						keyInfo.setMaterialPackingName(sqlResult_box.get(i)
								.get("MATERIALPACKINGNAME").toString());
						SetEventInfo setEventInfo = new SetEventInfo();
						eventInfoForStockOut.setEventName("ScrapOut");
						Map<String, Object> bindMap= new HashMap<String, Object>();
						//bindMap.put("shipRequestName",receiveRequestName);
						bindMap.put("stockState","StockOut");
						setEventInfo.setUserColumns(bindMap);
						MaterialPackingServiceProxy.getMaterialPackingService().setEvent(keyInfo, eventInfoForStockOut, setEventInfo);
						MaterialPacking materialPacking = selectByKey(keyInfo);
						materialPacking.setUnDoDetailName(Integer.toString(j+1));
						//materialPacking.setPackingState("Completed");
						if (sqlResult.get(j).get("ERPLOCATION").toString().substring(3, 4)
								.equals("N")) {
							erpLocation = erpLocation.substring(0, 3) + "N";

						} else {
							erpLocation = erpLocation.substring(0, 3) + "B";

						}
						if(factoryName.equals("2000")||factoryName.equals("2001"))
						{
							String CHARG = "";
							if(factoryName.equals("2000"))
							{
								CHARG="KSBMD001";
								
							}
							if(factoryName.equals("2001"))
							{
								CHARG="BSBMD001";
								
							}
							materialPacking.setCharge(CHARG);
							
						}
						//add by wt 20180703 B11099工厂启用批次管理，批次值为B1和F  start
						if(factoryName.equals("1000")||factoryName.equals("1099"))
						{
							String CHARG = "";
							
							if ("150N".equals(erpLocation.toString()) || "150B".equals(erpLocation.toString())) {
								CHARG="B1";
							} 
							else if ("190N".equals(erpLocation.toString()) || "190B".equals(erpLocation.toString())) {
								CHARG="F";
							}
							else {
								CHARG="";
							}
							materialPacking.setCharge(CHARG);
						}

						materialPacking.setStockState("Stocked");
						materialPacking.setErpFactory(factoryName);
						materialPacking.setErpLocation(erpLocation);
						materialPacking.setPackingGrade("OK");
						materialPacking.setOqaResult("OK");
						materialPacking
								.setLastEventName("MakeMaterialPreScraped");
						materialPacking
								.setLastEventComment("MakeMaterialPreScraped");
						//materialPacking.setReceiveActNo(receiveActNo);
						materialPacking.setShipRequestName("");
						materialPacking.setShipRequestDetailName("");
						materialPacking.setReceiveRequestName(receiveRequestName);
						materialPacking.setReceiveRequestDetailName(sqlResult_box.get(i)
								.get("SHIPREQUESTDETAILNAME").toString());
						materialPacking.setLastEventTime(eventInfo
								.getEventTime());
						materialPacking.setLastEventUser(eventInfo
								.getEventUser());
						materialPacking.setErpEventTime(Timestamp
								.valueOf(erpEventTime1));
						materialPacking
								.setReasonCode(eventInfo.getReasonCode());
						
						materialPacking.setReasonCodeType("511");
						if(siteName.equals("BMDT"))
						{
							materialPacking.setReasonCodeType("Z51");
						}
						mpList.add(materialPacking);
						//dataInfo.setStockState("StockOut");
					}
				}
			
			}
			MaterialPackingServiceProxy.getMaterialPackingService().update(
					mpList);
			MaterialReceiveActKey mrk = new MaterialReceiveActKey();
			mrk.setSiteName(siteName);
			mrk.setReceiveactNO(receiveActNo);
			mrk.setReceiveRequestName(receiveRequestName);
			com.cim.idm.wmspackage.materialreceiverequestact.management.info.SetEventInfo setevent = new com.cim.idm.wmspackage.materialreceiverequestact.management.info.SetEventInfo();
			Map<String, Object> bindMap2 = new HashMap<String, Object>();
			bindMap2.put("receiveActState", "StockOut");
			setevent.setUserColumns(bindMap2);
			MaterialReceiveRequestActServiceProxy
					.getReceiveRequestBatchService().setEvent(mrk, eventInfo,
							setevent);
			MaterialShipRequestKey materialShipRequestKey = new MaterialShipRequestKey();
			materialShipRequestKey.setShipRequestName(receiveRequestName);
			materialShipRequestKey.setSiteName(siteName);
			eventInfo.setEventName("MakeMaterialPreScraped");
			eventInfo.setReasonCode("0001");
			eventInfo.setReasonCodeType("511");
			if(siteName.equals("BMDT"))
			{
				eventInfo.setReasonCodeType("Z51");
			}
			//取消修改凭证状态，处理一个凭证对应过个报废库位问题  add by mxh for B1
//			MaterialShipRequestMakeCompletedInfo makeCompletedInfo = new MaterialShipRequestMakeCompletedInfo();
//			MaterialShipRequestServiceProxy.getMaterialShipRequestService()
//					.makeCompleted(materialShipRequestKey, eventInfo,
//							makeCompletedInfo);
			// MaterialPackingServiceProxy.getMaterialPackingService().setEvent(packingKeyList,
			// eventInfo, setEventInfo);
		} catch (IDMFrameDBErrorSignal e) {
			e.printStackTrace();
		}
	}
	public void poReturnSEQ(
			List<String> materialPackingKeyList, String siteName,
			String receiveActNo, String receiveRequestName, EventInfo eventInfo)
			throws Exception {
		try {

			String sql = "SELECT B.MATERIALSPECNAME, SUM(MATERIALQUANTITY) AS QUANTITY,B.CHARGE,B.ERPLOCATION,B.ERPFACTORY,B.SHIPREQUESTNAME,B.SHIPREQUESTDETAILNAME,B.PACKINGGRADE "
					+ "FROM MATERIALPACKING B WHERE RECEIVEACTNO = :receiveActNo "
					+ "GROUP BY B.MATERIALSPECNAME,B.CHARGE,B.ERPLOCATION,B.ERPFACTORY,B.SHIPREQUESTNAME,B.SHIPREQUESTDETAILNAME,B.PACKINGGRADE";
			String sql_box="SELECT a.sitename,a.materialpackingname ,A.MATERIALSPECNAME, MATERIALQUANTITY,A.CHARGE,A.ERPLOCATION,A.ERPFACTORY,A.SHIPREQUESTNAME,A.SHIPREQUESTDETAILNAME,A.PACKINGGRADE,A.RECEIVEACTNO "
					+" from materialpacking a "
					+" where RECEIVEACTNO = :receiveActNo ";
			Map<String, Object> bindMap1 = new HashMap<String, Object>();
			bindMap1.put("receiveActNo", receiveActNo);
			List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
					.getSqlTemplate()
					.queryForList(sql, bindMap1);
			List<Map<String, Object>> sqlResult_box = IDMFrameServiceProxy
					.getSqlTemplate()
					.queryForList(sql_box, bindMap1);
			List<MaterialPackingKey> packingKeyList = new ArrayList<MaterialPackingKey>();
			String CHARGE="";
			String charge="";
			for (int i = 0; i < materialPackingKeyList.size(); i++) {
				CHARGE = sqlResult_box.get(i).get("CHARGE")==null?"":sqlResult_box.get(i).get("CHARGE").toString();
				
				for(int j=0;j<sqlResult.size();j++){
					charge = sqlResult.get(j).get("CHARGE")==null?"":sqlResult.get(j).get("CHARGE").toString();
					if(charge.equals(CHARGE)
							&&sqlResult_box.get(i).get("MATERIALSPECNAME").toString().equals(sqlResult.get(j).get("MATERIALSPECNAME").toString())
							&&sqlResult_box.get(i).get("ERPLOCATION").toString().equals(sqlResult.get(j).get("ERPLOCATION").toString())
							&&sqlResult_box.get(i).get("ERPFACTORY").toString().equals(sqlResult.get(j).get("ERPFACTORY").toString())
							&&sqlResult_box.get(i).get("PACKINGGRADE").toString().equals(sqlResult.get(j).get("PACKINGGRADE").toString()))
					{
						MaterialPackingKey keyInfo = new MaterialPackingKey();
						keyInfo.setSiteName(siteName);
						keyInfo.setMaterialPackingName(sqlResult_box.get(i)
								.get("MATERIALPACKINGNAME").toString());
						MaterialPacking dataInfo = selectByKey(keyInfo);
						dataInfo.setUnDoDetailName(Integer.toString(j+1));
						dataInfo.setPackingState("Completed");
						//增加UNDOINFO表中移动类型
						dataInfo.setReasonCodeType(eventInfo.getReasonCodeType());
						dataInfo.setReasonCode(eventInfo.getReasonCode());
						//dataInfo.setShipRequestName(receiveRequestName);
						//dataInfo.setStockState("StockOut");
						packingKeyList.add(keyInfo);
						MaterialPackingServiceProxy.getMaterialPackingService().update(
								dataInfo);
					}
				}
			
			}
			MaterialReceiveActKey mrk = new MaterialReceiveActKey();
			mrk.setSiteName(siteName);
			mrk.setReceiveactNO(receiveActNo);
			mrk.setReceiveRequestName(receiveRequestName);
			com.cim.idm.wmspackage.materialreceiverequestact.management.info.SetEventInfo setevent = new com.cim.idm.wmspackage.materialreceiverequestact.management.info.SetEventInfo();
			Map<String, Object> bindMap2 = new HashMap<String, Object>();
			bindMap2.put("receiveActState", "StockOut");
			setevent.setUserColumns(bindMap2);
			MaterialReceiveRequestActServiceProxy
					.getReceiveRequestBatchService().setEvent(mrk, eventInfo,
							setevent);
			// MaterialPackingServiceProxy.getMaterialPackingService().setEvent(packingKeyList,
			// eventInfo, setEventInfo);
		} catch (IDMFrameDBErrorSignal e) {
			e.printStackTrace();
		}
	}
	
	public void updateMessageID(List<MaterialPackingKey> mpklist,String messageid,EventInfo eventinfo)
	{
			String eventComment=eventinfo.getEventComment();
			String eventName =eventinfo.getEventName();
			SetEventInfo setevent = new SetEventInfo();
			Map<String, Object> bindMap = new HashMap<String, Object>();			
			bindMap.put(MaterialPacking.Field.messageID,messageid);
			bindMap.put("erpState","ERPSUCCESS");
			setevent.setUserColumns(bindMap);
			eventinfo.setEventComment("SaveMessageID");
			eventinfo.setEventName("SaveMessageID");
			MaterialPackingServiceProxy.getMaterialPackingService()
			.setEvent(mpklist, eventinfo, setevent);
			eventinfo.setEventName(eventName);
			eventinfo.setEventComment(eventComment);
		
	}
	
	public void updateMessageID(List<String> materialPackingNameList,List<String> siteNameList,String messageid,EventInfo eventinfo)
	{
		List<MaterialPackingKey> materialPackingKeyList =new ArrayList<MaterialPackingKey>();
		String eventComment=eventinfo.getEventComment();
		String eventName =eventinfo.getEventName();
		for(int i=0;i<materialPackingNameList.size();i++ )
		{
			MaterialPackingKey materialPackingKey = new MaterialPackingKey();
			materialPackingKey.setMaterialPackingName(materialPackingNameList.get(i));
			materialPackingKey.setSiteName(siteNameList.get(i));
			materialPackingKeyList.add(materialPackingKey);
		}
			SetEventInfo setevent = new SetEventInfo();
			Map<String, Object> bindMap = new HashMap<String, Object>();			
			bindMap.put(MaterialPacking.Field.messageID,messageid);
			bindMap.put("erpState","ERPSUCCESS");
			setevent.setUserColumns(bindMap);
			eventinfo.setEventComment("SaveMessageID");
			eventinfo.setEventName("SaveMessageID");
			MaterialPackingServiceProxy.getMaterialPackingService()
			.setEvent(materialPackingKeyList, eventinfo, setevent);
			eventinfo.setEventName(eventName);
			eventinfo.setEventComment(eventComment);
		
	}
	
	public void updateMessageID(List<String> materialPackingNameList,String siteName,String messageid,EventInfo eventinfo)
	{
		List<MaterialPackingKey> materialPackingKeyList =new ArrayList<MaterialPackingKey>();
		String eventComment=eventinfo.getEventComment();
		String eventName =eventinfo.getEventName();
		for(int i=0;i<materialPackingNameList.size();i++ )
		{
			MaterialPackingKey materialPackingKey = new MaterialPackingKey();
			materialPackingKey.setMaterialPackingName(materialPackingNameList.get(i));
			materialPackingKey.setSiteName(siteName);
			materialPackingKeyList.add(materialPackingKey);
		}
			SetEventInfo setevent = new SetEventInfo();
			Map<String, Object> bindMap = new HashMap<String, Object>();			
			bindMap.put(MaterialPacking.Field.messageID,messageid);
			bindMap.put("erpState","ERPSUCCESS");
			setevent.setUserColumns(bindMap);
			eventinfo.setEventComment("SaveMessageID");
			eventinfo.setEventName("SaveMessageID");
			MaterialPackingServiceProxy.getMaterialPackingService()
			.setEvent(materialPackingKeyList, eventinfo, setevent);
			eventinfo.setEventName(eventName);
			eventinfo.setEventComment(eventComment);
		
	}
	
	
	
	
	public void updateEventName(List<String> materialPackingNameList,String siteName,String messageid,EventInfo eventinfo)
	{
		List<MaterialPackingKey> materialPackingKeyList =new ArrayList<MaterialPackingKey>();
		String eventComment=eventinfo.getEventComment();
		String eventName =eventinfo.getEventName();
		for(int i=0;i<materialPackingNameList.size();i++ )
		{
			MaterialPackingKey materialPackingKey = new MaterialPackingKey();
			materialPackingKey.setMaterialPackingName(materialPackingNameList.get(i));
			materialPackingKey.setSiteName(siteName);
			materialPackingKeyList.add(materialPackingKey);
		}
			SetEventInfo setevent = new SetEventInfo();
			Map<String, Object> bindMap = new HashMap<String, Object>();			
			bindMap.put(MaterialPacking.Field.messageID,messageid);
			bindMap.put("erpState","SUCCESS");
			bindMap.put("stockState","StockOut");
			setevent.setUserColumns(bindMap);
			//eventinfo.setEventComment("SaveMessageID");
			//eventinfo.setEventName("SaveMessageID");
			MaterialPackingServiceProxy.getMaterialPackingService()
			.setEvent(materialPackingKeyList, eventinfo, setevent);
//			eventinfo.setEventName(eventName);
//			eventinfo.setEventComment(eventComment);
		
	}
	/*
	 * 
	 * Author : zj Date : 2016.03.16
	 */
	public void BMDTChangeERPLocation(EventInfo eventInfo, String siteName,
			List<String> materialPackingNameList, List<String> ChargeList,
			String requestDetailName, String erpReceiveLocation,
			String erpEventTime, String eventUser, String eventComment,String toERPFactory) {
		try {

			String sql1 = "select SUM(MATERIALQUANTITY) AS QUANTITY,DECODE (CHARGE,'','-', CHARGE) AS CHARGE "
					+ "from MATERIALPACKING bs "
					+ "where "
					+ "(BS.SITENAME,BS.MATERIALPACKINGNAME) in ( "
					+ "select regexp_substr(id ,  '[^|]+', 1, 1) AS c1,regexp_substr(id  , '[^|]+', 1, 2 ) AS c2 "
					+ "from (select regexp_substr(id, '[^,]+' ,1 ,rownum) id from (select  :REQUESTDETAILNAME id from dual) a "
					+ "connect by rownum- 1 <= length(regexp_replace(id, '[^,]+')) "
					+ ") ) " + "GROUP BY CHARGE";

			Map<String, Object> bindMap1 = new HashMap<String, Object>();
			bindMap1.put("REQUESTDETAILNAME", requestDetailName);
			List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
					.getSqlTemplate()
					.queryForList(sql1, bindMap1);
			CommonValidation cv = new CommonValidation();
			String lastEventTimeKey = TimeStampUtil.getCurrentEventTimeKey();
			// List<MaterialPacking> packingList = new
			// ArrayList<MaterialPacking>();
			List<MaterialPackingKey> packingKeyList = new ArrayList<MaterialPackingKey>();
			Timestamp lastEventTime = new Timestamp(System.currentTimeMillis());
			String erpEventTime1 = "";
			try {
				erpEventTime1 = cv.getDate(erpEventTime) + " 00:00:00";
			} catch (ParseException e) {
				e.printStackTrace();
			}

			SetEventInfo setEventInfo = new SetEventInfo();

			Map<String, Object> bindMap = new HashMap<String, Object>();

			bindMap.put("erpLocation", erpReceiveLocation);
			

			for (int i = 0; i < sqlResult.size(); i++) {
				List<MaterialPacking> mpList = new ArrayList<MaterialPacking>();
				List<MaterialPackingKey> materialPackingKey = new ArrayList<MaterialPackingKey>();
				for (int j = 0; j < materialPackingNameList.size(); j++) {
					if (ChargeList.get(j)
							.equals(sqlResult.get(i).get("CHARGE"))) {
						MaterialPacking materialPacking = new MaterialPacking();
						MaterialPackingKey keyInfo = new MaterialPackingKey();
						keyInfo.setMaterialPackingName(materialPackingNameList
								.get(j));
						keyInfo.setSiteName(siteName);
						materialPacking = MaterialPackingServiceProxy
								.getMaterialPackingService().selectByKey(
										keyInfo);
						materialPacking.setUnDoDetailName(Integer
								.toString(i + 1));
						materialPacking.setErpLocation(erpReceiveLocation);
						materialPacking.setErpFactory(toERPFactory);
						materialPacking.setLastEventUser(eventUser);
						materialPacking.setLastEventName(eventComment);
						materialPacking.setErpEventTime(Timestamp
								.valueOf(erpEventTime1));
						materialPacking.setLocationName("");
						materialPacking.setReceiveActNo("ChangeERPLocation");
						mpList.add(materialPacking);
						MaterialPackingServiceProxy.getMaterialPackingService()
								.update(mpList);
					}

				}
			}
			MaterialPackingServiceProxy.getMaterialPackingService().setEvent(
					packingKeyList, eventInfo, setEventInfo);
		} catch (IDMFrameDBErrorSignal e) {
			e.printStackTrace();
		}
	}
	
	public void ChangeERPLocation(EventInfo eventInfo, String siteName,
			List<String> materialPackingNameList, List<String> ChargeList,
			String requestDetailName, String erpReceiveLocation,
			String erpEventTime, String eventUser, String eventComment) {
		try {
			System.out.println("ChangeERPLocation begin*******************************************");
			String sql1 = "select SUM(MATERIALQUANTITY) AS QUANTITY,DECODE (CHARGE,'','-', CHARGE) AS CHARGE "
					+ "from MATERIALPACKING bs "
					+ "where "
					+ "(BS.SITENAME,BS.MATERIALPACKINGNAME) in ( "
					+ "select regexp_substr(id ,  '[^|]+', 1, 1) AS c1,regexp_substr(id  , '[^|]+', 1, 2 ) AS c2 "
					+ "from (select regexp_substr(id, '[^,]+' ,1 ,rownum) id from (select  :REQUESTDETAILNAME id from dual) a "
					+ "connect by rownum- 1 <= length(regexp_replace(id, '[^,]+')) "
					+ ") ) " + "GROUP BY CHARGE";

			Map<String, Object> bindMap1 = new HashMap<String, Object>();
			bindMap1.put("REQUESTDETAILNAME", requestDetailName);
			List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
					.getSqlTemplate()
					.queryForList(sql1, bindMap1);
			CommonValidation cv = new CommonValidation();
			String lastEventTimeKey = TimeStampUtil.getCurrentEventTimeKey();
			// List<MaterialPacking> packingList = new
			// ArrayList<MaterialPacking>();
			List<MaterialPackingKey> packingKeyList = new ArrayList<MaterialPackingKey>();
			Timestamp lastEventTime = new Timestamp(System.currentTimeMillis());
			String erpEventTime1 = "";
			try {
				erpEventTime1 = cv.getDate(erpEventTime) + " 00:00:00";
			} catch (ParseException e) {
				e.printStackTrace();
			}

			SetEventInfo setEventInfo = new SetEventInfo();

			Map<String, Object> bindMap = new HashMap<String, Object>();

			bindMap.put("erpLocation", erpReceiveLocation);

			for (int i = 0; i < sqlResult.size(); i++) {
				List<MaterialPacking> mpList = new ArrayList<MaterialPacking>();
				List<MaterialPackingKey> materialPackingKey = new ArrayList<MaterialPackingKey>();
				for (int j = 0; j < materialPackingNameList.size(); j++) {
					if (ChargeList.get(j)
							.equals(sqlResult.get(i).get("CHARGE"))) {
						MaterialPacking materialPacking = new MaterialPacking();
						MaterialPackingKey keyInfo = new MaterialPackingKey();
						keyInfo.setMaterialPackingName(materialPackingNameList
								.get(j));
						keyInfo.setSiteName(siteName);
						materialPacking = MaterialPackingServiceProxy
								.getMaterialPackingService().selectByKey(
										keyInfo);
						materialPacking.setUnDoDetailName(Integer
								.toString(i + 1));
						materialPacking.setErpLocation(erpReceiveLocation);
						materialPacking.setLastEventUser(eventUser);
						materialPacking.setLastEventName(eventComment);
						materialPacking.setErpEventTime(Timestamp
								.valueOf(erpEventTime1));
						materialPacking.setReceiveActNo("ChangeERPLocation");
						materialPacking.setLocationName("");
						//materialPacking.setReceiptor(receiptor);
						// materialPackingInfo.setKey(keyInfo);
						mpList.add(materialPacking);
						MaterialPackingServiceProxy.getMaterialPackingService()
								.update(mpList);
					}

				}

				// for(Element materialPackingName : materialPackingKeyList){
				//
				// MaterialPackingKey keyInfo = new MaterialPackingKey();
				// keyInfo.setSiteName(siteName);
				//
				// String bs = materialPackingName.getTextTrim();
				// keyInfo.setMaterialPackingName(bs);
				// MaterialPacking dataInfo = selectByKey(keyInfo);
				// dataInfo.setShipTime(lastEventTime);
				// dataInfo.setErpLocation(erpReceiveLocation);
				// dataInfo.setLastEventTime(lastEventTime);
				// dataInfo.setLastEventUser(eventUser);
				// dataInfo.setLastEventTimeKey(lastEventTimeKey);
				// dataInfo.setLastEventComment(eventComment);
				// packingKeyList.add(keyInfo);
				// MaterialPackingServiceProxy.getMaterialPackingService().update(dataInfo);
				// }
			}
			System.out.println("*******************************************");
			MaterialPackingServiceProxy.getMaterialPackingService().setEvent(
					packingKeyList, eventInfo, setEventInfo);
			System.out.println("ChangeERPLocation end*******************************************");
		} catch (IDMFrameDBErrorSignal e) {
			e.printStackTrace();
		}
	}

	// public void modify(EventInfo eventInfo, String siteName, String
	// MaterialPackingName,String MaterialSpecName)

	/*
	 * Name : modify Desc : modify Author : wzj Date : 2016.01.20
	 */

	public void MultiChangeERPLocation(EventInfo eventInfo, String siteName,
			List<String> materialPackingNameList, List<String> ChargeList,
			String requestDetailName, String erpReceiveLocation,
			String erpEventTime, String eventUser, String eventComment,String toERPFactory) {
		try {

			String sql1 = "select SUM(MATERIALQUANTITY) AS QUANTITY,DECODE (CHARGE,'','-', CHARGE) AS CHARGE "
					+ "from MATERIALPACKING bs "
					+ "where "
					+ "(BS.SITENAME,BS.MATERIALPACKINGNAME) in ( "
					+ "select regexp_substr(id ,  '[^|]+', 1, 1) AS c1,regexp_substr(id  , '[^|]+', 1, 2 ) AS c2 "
					+ "from (select regexp_substr(id, '[^,]+' ,1 ,rownum) id from (select  :REQUESTDETAILNAME id from dual) a "
					+ "connect by rownum- 1 <= length(regexp_replace(id, '[^,]+')) "
					+ ") ) " + "GROUP BY CHARGE";

			Map<String, Object> bindMap1 = new HashMap<String, Object>();
			bindMap1.put("REQUESTDETAILNAME", requestDetailName);
			List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
					.getSqlTemplate()
					.queryForList(sql1, bindMap1);
			CommonValidation cv = new CommonValidation();
			String lastEventTimeKey = TimeStampUtil.getCurrentEventTimeKey();
			// List<MaterialPacking> packingList = new
			// ArrayList<MaterialPacking>();
			List<MaterialPackingKey> packingKeyList = new ArrayList<MaterialPackingKey>();
			Timestamp lastEventTime = new Timestamp(System.currentTimeMillis());
			String erpEventTime1 = "";
			try {
				erpEventTime1 = cv.getDate(erpEventTime) + " 00:00:00";
			} catch (ParseException e) {
				e.printStackTrace();
			}

			SetEventInfo setEventInfo = new SetEventInfo();

			Map<String, Object> bindMap = new HashMap<String, Object>();

			bindMap.put("erpLocation", erpReceiveLocation);
			

			for (int i = 0; i < sqlResult.size(); i++) {
				List<MaterialPacking> mpList = new ArrayList<MaterialPacking>();
				List<MaterialPackingKey> materialPackingKey = new ArrayList<MaterialPackingKey>();
				for (int j = 0; j < materialPackingNameList.size(); j++) {
					if (ChargeList.get(j)
							.equals(sqlResult.get(i).get("CHARGE"))) {
						MaterialPacking materialPacking = new MaterialPacking();
						MaterialPackingKey keyInfo = new MaterialPackingKey();
						keyInfo.setMaterialPackingName(materialPackingNameList
								.get(j));
						keyInfo.setSiteName(siteName);
						materialPacking = MaterialPackingServiceProxy
								.getMaterialPackingService().selectByKey(
										keyInfo);
						materialPacking.setUnDoDetailName(Integer
								.toString(i + 1));
						materialPacking.setErpLocation(erpReceiveLocation);
						materialPacking.setErpFactory(toERPFactory);
						materialPacking.setLastEventUser(eventUser);
						materialPacking.setLastEventName(eventComment);
						materialPacking.setErpEventTime(Timestamp
								.valueOf(erpEventTime1));
						materialPacking.setLocationName("");
						materialPacking.setReceiveActNo("ChangeERPLocation");
						mpList.add(materialPacking);
						MaterialPackingServiceProxy.getMaterialPackingService()
								.update(mpList);
					}

				}
			}
			MaterialPackingServiceProxy.getMaterialPackingService().setEvent(
					packingKeyList, eventInfo, setEventInfo);
		} catch (IDMFrameDBErrorSignal e) {
			e.printStackTrace();
		}
	}

	public void modify(EventInfo eventInfo, String siteName,
			String materialPackingName, String materialSpecName)

	{
		try {

			SetEventInfo setEventInfo = new SetEventInfo();

			MaterialPackingKey MaterialPackingKey = new MaterialPackingKey();

			MaterialPackingKey.setSiteName(siteName);
			MaterialPackingKey.setMaterialPackingName(materialPackingName);

			Map<String, Object> bindMap = new HashMap<String, Object>();

			bindMap.put("MaterialSpecName", materialSpecName);

			setEventInfo.setUserColumns(bindMap);

			MaterialPackingServiceProxy.getMaterialPackingService().setEvent(
					MaterialPackingKey, eventInfo, setEventInfo);

		} catch (IDMFrameDBErrorSignal e) {
			e.printStackTrace();
		}
	}

	/*
	 * Name : modify Desc : modify Author : wzj Date : 2016.01.20
	 */

	public void ModifyMaterialPackingState(EventInfo eventInfo,
			String siteName, String materialPackingName, String packingState) {
		try {

			SetEventInfo setEventInfo = new SetEventInfo();

			MaterialPackingKey MaterialPackingKey = new MaterialPackingKey();

			MaterialPackingKey.setSiteName(siteName);
			MaterialPackingKey.setMaterialPackingName(materialPackingName);

			Map<String, Object> bindMap = new HashMap<String, Object>();

			bindMap.put("packingState", packingState);
			bindMap.put("MaterialQuantity", Double.parseDouble("0"));
			bindMap.put("locationName", "");//从原库位解除
			setEventInfo.setUserColumns(bindMap);

			MaterialPackingServiceProxy.getMaterialPackingService().setEvent(
					MaterialPackingKey, eventInfo, setEventInfo);

		} catch (IDMFrameDBErrorSignal e) {
			e.printStackTrace();
		}
	}
	public void ModifyMaterialPackingOldStockState(EventInfo eventInfo,
			String siteName, List<String> materialPackingNameList, List<String> oldStockStateList){
	  try {

			SetEventInfo setEventInfo = new SetEventInfo();
			Map<String, Object> bindMap = new HashMap<String, Object>();
			for(int i=0;i<materialPackingNameList.size();i++)
			{

				MaterialPackingKey oldStockStateKey = new MaterialPackingKey();
				oldStockStateKey.setSiteName(siteName);
				oldStockStateKey.setMaterialPackingName(materialPackingNameList.get(i));

				bindMap.put("oldStockState", "Completed");

				setEventInfo.setUserColumns(bindMap);

				MaterialPackingServiceProxy.getMaterialPackingService().setEvent(
						oldStockStateKey, eventInfo, setEventInfo);
			}
		} catch (IDMFrameDBErrorSignal e) {
			e.printStackTrace();
			throw e;
		}
	}

	/*
	 * Name : modify Desc : modify Author : baoyue Date : 2016.10.11
	 */

	public void RMAModifyMaterialPackingState(EventInfo eventInfo,
			List<String> siteNameList, List<String> materialPackingNameList,
			List<MaterialUnDoinfo> newUnDoList, List<String> chargeList,
			List<String> materialSpeNameList, List<String> erpLocationList,
			String erpEventTime, String requestDetailName, String receiveActNo)
			throws Exception {
		try {

			String sql_1="SELECT B.MATERIALSPECNAME, SUM(MATERIALQUANTITY) AS QUANTITY,B.CHARGE,B.ERPLOCATION,B.ERPFACTORY,B.SHIPREQUESTNAME,B.SHIPREQUESTDETAILNAME,B.PACKINGGRADE "
					+ "FROM MATERIALPACKING B WHERE RECEIVEACTNO = :receiveActNo "
					+ "GROUP BY B.MATERIALSPECNAME,B.CHARGE,B.ERPLOCATION,B.ERPFACTORY,B.SHIPREQUESTNAME,B.SHIPREQUESTDETAILNAME,B.PACKINGGRADE";
			CommonValidation cv = new CommonValidation();
			Map<String, Object> bindMap1 = new HashMap<String, Object>();
			bindMap1.put("receiveActNo", receiveActNo);
			List<Map<String, Object>> sqlResult2 = IDMFrameServiceProxy
					.getSqlTemplate()
					.queryForList(sql_1, bindMap1);
			SetEventInfo setEventInfo = new SetEventInfo();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			String erpEventTime1 = cv.getDate(erpEventTime) + " 00:00:00";
			// String sql1 =
			// "SELECT CHARGE FROM MATERIALRECEIVEREQUESTDETAIL A WHERE A.RECEIVEREQUESTDETAILNAME= :receiveRequestDetailName AND A.RECEIVEREQUESTNAME= :receiveRequestName ";
			for (int i = 0; i < sqlResult2.size(); i++) {
				String charge = sqlResult2.get(i).get("CHARGE") == null ? "-"
						: sqlResult2.get(i).get("CHARGE").toString();
				List<MaterialPacking> mpList = new ArrayList<MaterialPacking>();
				for (int j = 0; j < materialPackingNameList.size(); j++) {
					if (materialSpeNameList.get(j).equals(
							sqlResult2.get(i).get("MATERIALSPECNAME")
									.toString())
							&& erpLocationList.get(j).equals(
									sqlResult2.get(j).get("ERPLOCATION")
											.toString())
							&& chargeList.get(i).equals(charge)) {
						MaterialPacking materialPacking = new MaterialPacking();
						MaterialPackingKey materialPackingKey = new MaterialPackingKey();
						materialPackingKey
								.setMaterialPackingName(materialPackingNameList
										.get(i));
						materialPackingKey.setSiteName(siteNameList.get(i));
						materialPacking = MaterialPackingServiceProxy
								.getMaterialPackingService().selectByKey(
										materialPackingKey);
						materialPacking.setUnDoDetailName(Integer
								.toString(i + 1));
						materialPacking.setReceiveActNo(receiveActNo);
						materialPacking.setPackingState("Completed");
						materialPacking.setStockState("StockOut");
						materialPacking
								.setLastEventName("RMAModifyMaterialPackingState");
						materialPacking
								.setLastEventComment("RMAModifyMaterialPackingState");
						// materialPacking.setLastEventTimeKey(eventInfo.getEventTimeKey());
						materialPacking.setLastEventTime(eventInfo
								.getEventTime());
						materialPacking.setLastEventUser(eventInfo
								.getEventUser());
						materialPacking
								.setReasonCode(eventInfo.getReasonCode());
						materialPacking.setReasonCodeType(eventInfo
								.getReasonCodeType());
						materialPacking.setErpEventTime(Timestamp
								.valueOf(erpEventTime1));
						mpList.add(materialPacking);
					}
				}

				MaterialPackingServiceProxy.getMaterialPackingService().update(
						mpList);
			}
			String sql = " SELECT MATERIALPACKINGNAME,SITENAME FROM MATERIALPACKING WHERE UNDODETAILNAME = :seq AND RECEIVEACTNO = :receiveActNo ";
			String sql2 = insertUnDOMaterialPackingInfo_v1
					+ "select P.SITENAME,P.MATERIALPACKINGNAME,P.LASTEVENTTIMEKEY FROM MATERIALPACKING P WHERE P.UNDODETAILNAME=:seq AND P.RECEIVEACTNO = :receiveActNo)	";
			for (int i = 0; i < newUnDoList.size(); i++) {
				List<MaterialPackingKey> materialPackingKeyList = new ArrayList<MaterialPackingKey>();
				Map<String, Object> bindMap_selUndoBoxInfo = new HashMap<String, Object>();
				bindMap_selUndoBoxInfo.put("seq", newUnDoList.get(i).getSeq());
				bindMap_selUndoBoxInfo.put("receiveActNo", receiveActNo);
				List<Map<String, Object>> queryResult_BoxInfo = IDMFrameServiceProxy
						.getSqlTemplate()
						.queryForList(sql, bindMap_selUndoBoxInfo);
				for (int j = 0; j < queryResult_BoxInfo.size(); j++) {
					MaterialPackingKey materialPackingKey = new MaterialPackingKey();
					materialPackingKey
							.setMaterialPackingName(queryResult_BoxInfo.get(j)
									.get("MATERIALPACKINGNAME").toString());
					materialPackingKey.setSiteName(queryResult_BoxInfo.get(j)
							.get("SITENAME").toString());
					materialPackingKeyList.add(materialPackingKey);
				}
				Map<String, Object> bindMap = new HashMap<String, Object>();
				Map<String, Object> bindMap2 = new HashMap<String, Object>();
				bindMap.put("unDoDetailName", newUnDoList.get(i)
						.getUnDoDetailName());
				bindMap.put("unDoID", newUnDoList.get(i).getUnDoID());
				bindMap.put("erpState", "SUCCESS");
				// bindMap.put("UNDOIDDATE",
				// newUnDoList.get(i).getUnDoIdDate());
				setEventInfo.setUserColumns(bindMap);
				eventInfo.setEventComment("RMAModifyMaterialPackingState");
				eventInfo.setEventName("RMAModifyMaterialPackingState");
				bindMap2.put("unDoDetailName", newUnDoList.get(i)
						.getUnDoDetailName());
				bindMap2.put("unDoID", newUnDoList.get(i).getUnDoID());
				bindMap2.put("seq", newUnDoList.get(i).getSeq());
				bindMap2.put("UNDOIDDATE", newUnDoList.get(i).getUnDoIdDate());
				bindMap2.put("receiveActNo", receiveActNo);
				// IDMFrameServiceProxy.getSqlTemplate().update(sql2,
				// bindMap1);
				IDMFrameServiceProxy.getSqlTemplate()
						.update(sql2, bindMap2);
				MaterialPackingServiceProxy.getMaterialPackingService()
						.setEvent(materialPackingKeyList, eventInfo,
								setEventInfo);
			}
		} catch (Exception e) {
			throw e;
		}
	}
	public void PoReduce(EventInfo eventInfo,String poName,String siteName,
			List<String> poDetailNameList,
			List<String> poDetailQuantity) throws Exception {
		try {
			
			for(int i=0;i<poDetailNameList.size();i++)
			{
				 MakeDetailDecreaseReceivedInfo makeDetailDecreaseReceivedInfo =new MakeDetailDecreaseReceivedInfo();
				 MaterialReceiveRequestDetailKey materialReceiveRequestDetailKey =new MaterialReceiveRequestDetailKey();
				 materialReceiveRequestDetailKey.setReceiveRequestName(poName);
				 materialReceiveRequestDetailKey.setSiteName(siteName);
				 materialReceiveRequestDetailKey.setReceiveRequestDetailName(poDetailNameList.get(i));
				 
				 makeDetailDecreaseReceivedInfo.setDecreaseQuantity(Double.parseDouble(poDetailQuantity.get(i)));
				 
				 ReceiveRequestDetailServiceProxy.getReceiveRequestDetailService().decreaseReceivedQuantity(materialReceiveRequestDetailKey, eventInfo, makeDetailDecreaseReceivedInfo);
			}
			
		} catch (Exception e) {
			throw e;
		}
	}

	public void poReturn(EventInfo eventInfo, List<String> siteNameList,
			List<String> materialPackingNameList,
			List<MaterialUnDoinfo> newUnDoList,
			List<String> materialSpeNameList, List<String> erpLocationList,
			List<String> erpFactoryList, List<String> poDetailErpLocationList,
			List<String> poDetailErpFactoryList,
			List<String> poDetailMaterialSpeNameList,
			List<String> unDoIdDetailName, String unDoId, String erpEventTime,
			List<String> unDoIdDetailChargeList, List<String> chargeList,
			String receiveActNo) throws Exception {
		try {
			CommonValidation cv = new CommonValidation();
			SetEventInfo setEventInfo = new SetEventInfo();
			String erpEventTime1 = cv.getDate(erpEventTime) + " 00:00:00";
			// String sql1 =
			// "SELECT CHARGE FROM MATERIALRECEIVEREQUESTDETAIL A WHERE A.RECEIVEREQUESTDETAILNAME= :receiveRequestDetailName AND A.RECEIVEREQUESTNAME= :receiveRequestName ";
			for (int j = 0; j < unDoIdDetailName.size(); j++) {
				List<MaterialPacking> mpList = new ArrayList<MaterialPacking>();
				for (int i = 0; i < materialPackingNameList.size(); i++) {
					if (materialSpeNameList.get(i).equals(
							poDetailMaterialSpeNameList.get(j))
							&& erpLocationList.get(i).equals(
									poDetailErpLocationList.get(j))
							&& erpFactoryList.get(i).equals(
									poDetailErpFactoryList.get(j))
							&& chargeList.get(i).equals(
									unDoIdDetailChargeList.get(j))) {
						MaterialPacking materialPacking = new MaterialPacking();
						MaterialPackingKey materialPackingKey = new MaterialPackingKey();
						materialPackingKey
								.setMaterialPackingName(materialPackingNameList
										.get(i));
						materialPackingKey.setSiteName(siteNameList.get(i));
						materialPacking = MaterialPackingServiceProxy
								.getMaterialPackingService().selectByKey(
										materialPackingKey);
						materialPacking.setUnDoDetailName(Integer
								.toString(j + 1));
						materialPacking.setPackingState("Completed");
						materialPacking.setStockState("StockOut");
						materialPacking.setReceiveActNo(receiveActNo);
						materialPacking.setLastEventName("PoReturn");
						materialPacking.setLastEventComment(eventInfo.getEventComment());
						// materialPacking.setLastEventTimeKey(eventInfo.getEventTimeKey());
						materialPacking.setLastEventTime(eventInfo
								.getEventTime());
						materialPacking.setLastEventUser(eventInfo
								.getEventUser());
						materialPacking
								.setReasonCode(eventInfo.getReasonCode());
						materialPacking.setReasonCodeType(eventInfo
								.getReasonCodeType());
						materialPacking.setErpEventTime(Timestamp
								.valueOf(erpEventTime1));
						mpList.add(materialPacking);
					}
				}
				MaterialPackingServiceProxy.getMaterialPackingService().update(
						mpList);
			}
			String sql = " SELECT MATERIALPACKINGNAME,SITENAME FROM MATERIALPACKING WHERE UNDODETAILNAME = :seq and RECEIVEACTNO = :receiveActNo ";
			String sql2 = insertUnDOMaterialPackingInfo_v1
					+ "select P.SITENAME,P.MATERIALPACKINGNAME,P.LASTEVENTTIMEKEY FROM MATERIALPACKING P WHERE P.UNDODETAILNAME=:seq and P.RECEIVEACTNO = :receiveActNo)	";
			for (int i = 0; i < newUnDoList.size(); i++) {
				List<MaterialPackingKey> materialPackingKeyList = new ArrayList<MaterialPackingKey>();
				Map<String, Object> bindMap_selUndoBoxInfo = new HashMap<String, Object>();
				bindMap_selUndoBoxInfo.put("seq", newUnDoList.get(i).getSeq().substring(15));
				bindMap_selUndoBoxInfo.put("receiveActNo", receiveActNo);
				List<Map<String, Object>> queryResult_BoxInfo = IDMFrameServiceProxy
						.getSqlTemplate()
						.queryForList(sql, bindMap_selUndoBoxInfo);
				for (int j = 0; j < queryResult_BoxInfo.size(); j++) {
					MaterialPackingKey materialPackingKey = new MaterialPackingKey();
					materialPackingKey
							.setMaterialPackingName(queryResult_BoxInfo.get(j)
									.get("MATERIALPACKINGNAME").toString());
					materialPackingKey.setSiteName(queryResult_BoxInfo.get(j)
							.get("SITENAME").toString());
					materialPackingKeyList.add(materialPackingKey);
				}
				Map<String, Object> bindMap = new HashMap<String, Object>();
				Map<String, Object> bindMap2 = new HashMap<String, Object>();
				bindMap.put("unDoDetailName", newUnDoList.get(i)
						.getUnDoDetailName());
				bindMap.put("unDoID", newUnDoList.get(i).getUnDoID());
				bindMap.put("erpState", "SUCCESS");
				// bindMap.put("UNDOIDDATE",
				// newUnDoList.get(i).getUnDoIdDate());
				setEventInfo.setUserColumns(bindMap);
				//eventInfo.setEventComment("PoReturn");
				eventInfo.setEventName("PoReturn");
				bindMap2.put("unDoDetailName", newUnDoList.get(i)
						.getUnDoDetailName());
				bindMap2.put("unDoID", newUnDoList.get(i).getUnDoID());
				bindMap2.put("seq", newUnDoList.get(i).getSeq().substring(15));
				bindMap2.put("UNDOIDDATE", newUnDoList.get(i).getUnDoIdDate());
				bindMap2.put("receiveActNo", receiveActNo);
				// IDMFrameServiceProxy.getSqlTemplate().update(sql2,
				// bindMap1);
				IDMFrameServiceProxy.getSqlTemplate()
						.update(sql2, bindMap2);
				MaterialPackingServiceProxy.getMaterialPackingService()
						.setEvent(materialPackingKeyList, eventInfo,
								setEventInfo);
			}
		} catch (Exception e) {
			throw e;
		}
	}
	
	
	
	public void asignActNo(EventInfo eventInfo, List<String> siteNameList,
			List<String> materialPackingNameList,String receiveActNo)throws Exception {
		try {
			List<MaterialPacking> mpList = new ArrayList<MaterialPacking>();
			for (int i = 0; i < materialPackingNameList.size(); i++) {
				MaterialPacking materialPacking = new MaterialPacking();
				MaterialPackingKey materialPackingKey = new MaterialPackingKey();
				materialPackingKey
						.setMaterialPackingName(materialPackingNameList
								.get(i));
				materialPackingKey.setSiteName(siteNameList.get(i));
				materialPacking = MaterialPackingServiceProxy
						.getMaterialPackingService().selectByKey(
								materialPackingKey);
				materialPacking.setReceiveActNo(receiveActNo);
				mpList.add(materialPacking);
			}
			MaterialPackingServiceProxy.getMaterialPackingService().update(
					mpList);
		}catch(Exception e) {
			throw e;
		}
	}

	public void OEMReturn(EventInfo eventInfo, List<String> siteNameList,
			List<String> materialPackingNameList,
			List<MaterialUnDoinfo> newUnDoList,
			List<String> materialSpeNameList, List<String> erpLocationList,
			List<String> materialDetailErpLocationList,
			List<String> materialDetailMaterialSpeNameList,
			String erpEventTime, String receiveActNo) throws Exception {
		try {
			CommonValidation cv = new CommonValidation();
			SetEventInfo setEventInfo = new SetEventInfo();
			String erpEventTime1 = cv.getDate(erpEventTime) + " 00:00:00";

			for (int j = 0; j < materialDetailMaterialSpeNameList.size(); j++) {
				List<MaterialPacking> mpList = new ArrayList<MaterialPacking>();
				for (int i = 0; i < materialPackingNameList.size(); i++) {
					if (materialSpeNameList.get(i).equals(
							materialDetailMaterialSpeNameList.get(j))
							&& erpLocationList.get(i).equals(
									materialDetailErpLocationList.get(j))) {
						MaterialPacking materialPacking = new MaterialPacking();
						MaterialPackingKey materialPackingKey = new MaterialPackingKey();
						materialPackingKey
								.setMaterialPackingName(materialPackingNameList
										.get(i));
						materialPackingKey.setSiteName(siteNameList.get(i));
						materialPacking = MaterialPackingServiceProxy
								.getMaterialPackingService().selectByKey(
										materialPackingKey);
						materialPacking.setUnDoDetailName(Integer
								.toString(j + 1));
						materialPacking.setPackingState("Completed");
						materialPacking.setStockState("StockOut");
						materialPacking.setReceiveActNo(receiveActNo);
						materialPacking.setLastEventName("OEMReturn");
						materialPacking.setLastEventComment("OEMReturn");
						// materialPacking.setLastEventTimeKey(eventInfo.getEventTimeKey());
						materialPacking.setLastEventTime(eventInfo
								.getEventTime());
						materialPacking.setLastEventUser(eventInfo
								.getEventUser());
						materialPacking.setErpEventTime(Timestamp
								.valueOf(erpEventTime1));
						materialPacking
								.setReasonCode(eventInfo.getReasonCode());
						materialPacking.setReasonCodeType(eventInfo
								.getReasonCodeType());
						mpList.add(materialPacking);
					}
				}

				MaterialPackingServiceProxy.getMaterialPackingService().update(
						mpList);
			}
			String sql = " SELECT MATERIALPACKINGNAME,SITENAME FROM MATERIALPACKING WHERE UNDODETAILNAME = :seq and RECEIVEACTNO = :receiveActNo ";
			String sql2 = insertUnDOMaterialPackingInfo_v1
					+ "select P.SITENAME,P.MATERIALPACKINGNAME,P.LASTEVENTTIMEKEY FROM MATERIALPACKING P WHERE P.UNDODETAILNAME=:seq and P.RECEIVEACTNO = :receiveActNo)	";
			for (int i = 0; i < newUnDoList.size(); i++) {
				List<MaterialPackingKey> materialPackingKeyList = new ArrayList<MaterialPackingKey>();
				Map<String, Object> bindMap_selUndoBoxInfo = new HashMap<String, Object>();
				bindMap_selUndoBoxInfo.put("seq", newUnDoList.get(i).getSeq().substring(15));
				bindMap_selUndoBoxInfo.put("receiveActNo", receiveActNo);
				List<Map<String, Object>> queryResult_BoxInfo = IDMFrameServiceProxy
						.getSqlTemplate()
						.queryForList(sql, bindMap_selUndoBoxInfo);
				for (int j = 0; j < queryResult_BoxInfo.size(); j++) {
					MaterialPackingKey materialPackingKey = new MaterialPackingKey();
					materialPackingKey
							.setMaterialPackingName(queryResult_BoxInfo.get(j)
									.get("MATERIALPACKINGNAME").toString());
					materialPackingKey.setSiteName(queryResult_BoxInfo.get(j)
							.get("SITENAME").toString());
					materialPackingKeyList.add(materialPackingKey);
				}
				Map<String, Object> bindMap = new HashMap<String, Object>();
				Map<String, Object> bindMap2 = new HashMap<String, Object>();
				bindMap.put("unDoDetailName", newUnDoList.get(i)
						.getUnDoDetailName());
				bindMap.put("unDoID", newUnDoList.get(i).getUnDoID());
				bindMap.put("erpState", "SUCCESS");
				// bindMap.put("UNDOIDDATE",
				// newUnDoList.get(i).getUnDoIdDate());
				setEventInfo.setUserColumns(bindMap);
				eventInfo.setEventComment("OEMReturn");
				eventInfo.setEventName("OEMReturn");
				bindMap2.put("unDoDetailName", newUnDoList.get(i)
						.getUnDoDetailName());
				bindMap2.put("unDoID", newUnDoList.get(i).getUnDoID());
				bindMap2.put("seq", newUnDoList.get(i).getSeq().substring(15));
				bindMap2.put("UNDOIDDATE", newUnDoList.get(i).getUnDoIdDate());
				bindMap2.put("receiveActNo", receiveActNo);
				// IDMFrameServiceProxy.getSqlTemplate().update(sql2,
				// bindMap1);
				IDMFrameServiceProxy.getSqlTemplate()
						.update(sql2, bindMap2);
				MaterialPackingServiceProxy.getMaterialPackingService()
						.setEvent(materialPackingKeyList, eventInfo,
								setEventInfo);
			}
		} catch (Exception e) {
			throw e;
		}
	}

	/*
	 * Name : EtcOutMaterialPacking Desc : EtcOutMaterialPacking Author : wzj
	 * Date : 2016.02.02
	 */

	public void EtcOutMaterialPacking(EventInfo eventInfo, String eventUser,
			String siteName, String materialPackingName, String etcState,
			String materialQuantity, String locationName,
			String materialSpecName, String confirmOutUser) {
		try {

			SetEventInfo setEventInfo = new SetEventInfo();

			MaterialPackingKey MaterialPackingKey = new MaterialPackingKey();

			MaterialPackingKey.setSiteName(siteName);
			MaterialPackingKey.setMaterialPackingName(materialPackingName);

			Map<String, Object> bindMap = new HashMap<String, Object>();

			bindMap.put("EtcState", etcState);
			bindMap.put("ETCOUTQuantity", materialQuantity);
			setEventInfo.setUserColumns(bindMap);

			MaterialPackingServiceProxy.getMaterialPackingService().setEvent(
					MaterialPackingKey, eventInfo, setEventInfo);

			String strCondition = "INSERT INTO  MATERIALPACKINGETC(SITENAME,MATERIALPACKINGNAME,TIMEKEY,MATERIALSPECNAME,"
					+ "ETCSTATE,LOCATIONNAME,ETCINQTY,ETCOUTQTY,ETCINTIME,ETCOUTTIME,ETCINUSER,ETCOUTUSER,CONFIRMINUSER,CONFIRMOUTUSER)"
					+ "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
			Object[] bind = new Object[] { siteName, materialPackingName,
					TimeStampUtil.getCurrentEventTimeKey().toString(),
					materialSpecName, etcState, locationName, null,
					Double.parseDouble(materialQuantity), null,
					TimeStampUtil.getCurrentTimestamp(), null, eventUser, null,
					confirmOutUser };

			IDMFrameServiceProxy.getSqlTemplate().update(strCondition, bind);

		} catch (IDMFrameDBErrorSignal e) {
			e.printStackTrace();
		}
	}
	
	public void EtcOut(EventInfo eventInfo, String eventUser,
			String siteName, String materialPackingName, String etcState,
			String materialQuantity, String locationName,
			String materialSpecName, String confirmOutUser,String Quantity) {
		try {

			SetEventInfo setEventInfo = new SetEventInfo();

			MaterialPackingKey MaterialPackingKey = new MaterialPackingKey();

			MaterialPackingKey.setSiteName(siteName);
			MaterialPackingKey.setMaterialPackingName(materialPackingName);

			Map<String, Object> bindMap = new HashMap<String, Object>();

			bindMap.put("EtcState", etcState);
			bindMap.put("ETCOUTQuantity", Quantity);
			setEventInfo.setUserColumns(bindMap);
			if(siteName.equals("B5"))
			{
			MaterialPacking mp=MaterialPackingServiceProxy.getMaterialPackingService().selectByKey(MaterialPackingKey);
			eventInfo.setReasonCode(mp.getReasonCode());
			eventInfo.setReasonCodeType(mp.getReasonCodeType());
			}
			MaterialPackingServiceProxy.getMaterialPackingService().setEvent(
					MaterialPackingKey, eventInfo, setEventInfo);

			String strCondition = "INSERT INTO  MATERIALPACKINGETC(SITENAME,MATERIALPACKINGNAME,TIMEKEY,MATERIALSPECNAME,"
					+ "ETCSTATE,LOCATIONNAME,ETCINQTY,ETCOUTQTY,ETCINTIME,ETCOUTTIME,ETCINUSER,ETCOUTUSER,CONFIRMINUSER,CONFIRMOUTUSER)"
					+ "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
			Object[] bind = new Object[] { siteName, materialPackingName,
					TimeStampUtil.getCurrentEventTimeKey().toString(),
					materialSpecName, etcState, locationName, 0,
					Double.parseDouble(materialQuantity), null,
					TimeStampUtil.getCurrentTimestamp(), null, eventUser, null,
					null };

			IDMFrameServiceProxy.getSqlTemplate().update(strCondition, bind);

		} catch (IDMFrameDBErrorSignal e) {
			e.printStackTrace();
		}
	}

	
	public void EtcConfirm(EventInfo eventInfo, String eventUser,String siteName,  String etcState,String materialSpecName) {
		try {
			
			String sql_confirmOut="update MATERIALPACKINGETC c set CONFIRMOUTUSER=:eventUser where C.materialpackingname in(  SELECT B.MATERIALPACKINGNAME FROM MATERIALPACKING A,MATERIALPACKINGETC B   "
									+"WHERE A.SITENAME=:SITENAME AND (:MATERIALSPECNAME IS NULL OR A.MATERIALSPECNAME=:MATERIALSPECNAME) AND A.ETCSTATE='EtcOut'  " 
									+"AND A.STOCKSTATE='Stocked' AND A.MATERIALPACKINGNAME=B.MATERIALPACKINGNAME AND A.SITENAME=B.SITENAME AND B.CONFIRMOUTUSER IS NULL) AND C.ETCSTATE='EtcOut'";
			String sql_confirmIn="update MATERIALPACKINGETC c set CONFIRMINUSER=:eventUser where C.materialpackingname in(  SELECT B.MATERIALPACKINGNAME FROM MATERIALPACKING A,MATERIALPACKINGETC B   "
					+"WHERE A.SITENAME=:SITENAME AND (:MATERIALSPECNAME IS NULL OR A.MATERIALSPECNAME=:MATERIALSPECNAME) AND B.ETCINQTY>0  " 
					+"AND A.STOCKSTATE='Stocked' AND A.MATERIALPACKINGNAME=B.MATERIALPACKINGNAME AND A.SITENAME=B.SITENAME AND B.CONFIRMINUSER IS NULL) ";

			Map<String, Object> bindMap = new HashMap<String, Object>();

			bindMap.put("eventUser", eventInfo.getEventUser());
			bindMap.put("SITENAME", siteName);
			bindMap.put("MATERIALSPECNAME", materialSpecName);
			if(etcState.equals("EtcOut"))
			{
				IDMFrameServiceProxy.getSqlTemplate().update(sql_confirmOut, bindMap);
			}
			else
			{
				IDMFrameServiceProxy.getSqlTemplate().update(sql_confirmIn, bindMap);
			}

		} catch (IDMFrameDBErrorSignal e) {
			e.printStackTrace();
		}
	}
	/*
	 * Name : EtcOutMaterialPacking Desc : EtcOutMaterialPacking Author : wzj
	 * Date : 2016.02.02
	 */
	public void EtcOutConfirm(EventInfo eventInfo, String eventUser,String siteName,  String etcState,String ETCOUTUser) {
		try {
			
			String sql_confirmOut="update MATERIALPACKINGETC c set CONFIRMOUTUSER=:eventUser where C.materialpackingname in(  SELECT B.MATERIALPACKINGNAME FROM MATERIALPACKING A,MATERIALPACKINGETC B   "
									+"WHERE A.SITENAME=:SITENAME  AND A.ETCSTATE='EtcOut'  " 
									+"AND A.STOCKSTATE='Stocked' AND A.MATERIALPACKINGNAME=B.MATERIALPACKINGNAME AND A.SITENAME=B.SITENAME AND B.CONFIRMOUTUSER IS NULL AND B.ETCOUTUSER=:MATERIALSPECNAME) AND C.ETCSTATE='EtcOut'";
			String sql_confirmIn="update MATERIALPACKINGETC c set CONFIRMINUSER=:eventUser where C.materialpackingname in(  SELECT B.MATERIALPACKINGNAME FROM MATERIALPACKING A,MATERIALPACKINGETC B   "
					+"WHERE A.SITENAME=:SITENAME AND (:MATERIALSPECNAME IS NULL OR A.MATERIALSPECNAME=:MATERIALSPECNAME) AND B.ETCINQTY>0  " 
					+"AND A.STOCKSTATE='Stocked' AND A.MATERIALPACKINGNAME=B.MATERIALPACKINGNAME AND A.SITENAME=B.SITENAME AND B.CONFIRMINUSER IS NULL) ";

			Map<String, Object> bindMap = new HashMap<String, Object>();

			bindMap.put("eventUser", eventInfo.getEventUser());
			bindMap.put("SITENAME", siteName);
			bindMap.put("MATERIALSPECNAME", ETCOUTUser);
			if(etcState.equals("EtcOut"))
			{
				IDMFrameServiceProxy.getSqlTemplate().update(sql_confirmOut, bindMap);
			}
			else
			{
				IDMFrameServiceProxy.getSqlTemplate().update(sql_confirmIn, bindMap);
			}

		} catch (IDMFrameDBErrorSignal e) {
			e.printStackTrace();
		}
	}
	
	/*PC端抽检借出
	 * */
	public void EtcOutConfirmPC(EventInfo eventInfo, String eventUser,String siteName,  String etcState,String ETCOUTUser,String materialSpecName) {
		try {
			
			String sql_confirmOut="update MATERIALPACKINGETC c set CONFIRMOUTUSER=:eventUser where C.materialpackingname in(  SELECT B.MATERIALPACKINGNAME FROM MATERIALPACKING A,MATERIALPACKINGETC B   "
									+"WHERE A.SITENAME=:SITENAME  AND A.ETCSTATE='EtcOut'  " 
									+"AND A.STOCKSTATE='Stocked' AND A.MATERIALPACKINGNAME=B.MATERIALPACKINGNAME AND A.SITENAME=B.SITENAME AND B.CONFIRMOUTUSER IS NULL AND B.ETCOUTUSER=:ETCOUTUSER AND B.MATERIALSPECNAME=:MATERIALSPECNAME) AND C.ETCSTATE='EtcOut'";
			String sql_confirmIn="update MATERIALPACKINGETC c set CONFIRMINUSER=:eventUser where C.materialpackingname in(  SELECT B.MATERIALPACKINGNAME FROM MATERIALPACKING A,MATERIALPACKINGETC B   "
					+"WHERE A.SITENAME=:SITENAME AND (:MATERIALSPECNAME IS NULL OR A.MATERIALSPECNAME=:MATERIALSPECNAME) AND B.ETCINQTY>0  " 
					+"AND A.STOCKSTATE='Stocked' AND A.MATERIALPACKINGNAME=B.MATERIALPACKINGNAME AND A.SITENAME=B.SITENAME AND B.CONFIRMINUSER IS NULL) ";

			Map<String, Object> bindMap = new HashMap<String, Object>();

			bindMap.put("eventUser", eventInfo.getEventUser());
			bindMap.put("SITENAME", siteName);
			bindMap.put("ETCOUTUSER", ETCOUTUser);
			bindMap.put("MATERIALSPECNAME", materialSpecName);
			if(etcState.equals("EtcOut"))
			{
				IDMFrameServiceProxy.getSqlTemplate().update(sql_confirmOut, bindMap);
			}
			else
			{
				IDMFrameServiceProxy.getSqlTemplate().update(sql_confirmIn, bindMap);
			}

		} catch (IDMFrameDBErrorSignal e) {
			e.printStackTrace();
		}
	}
	
	public void EtcInMaterialPacking(EventInfo eventInfo, String eventUser,
			String siteName, String materialPackingName, String etcState,
			String materialQuantity, String confirmInUser) {
		try {

			SetEventInfo setEventInfo = new SetEventInfo();

			MaterialPackingKey MaterialPackingKey = new MaterialPackingKey();

			MaterialPackingKey.setSiteName(siteName);
			MaterialPackingKey.setMaterialPackingName(materialPackingName);

			Map<String, Object> bindMap = new HashMap<String, Object>();

			bindMap.put("EtcState", etcState);
			bindMap.put("ETCOUTQuantity", 0);
			setEventInfo.setUserColumns(bindMap);

			MaterialPackingServiceProxy.getMaterialPackingService().setEvent(
					MaterialPackingKey, eventInfo, setEventInfo);

			String strCondition = "UPDATE MATERIALPACKINGETC SET ETCSTATE = ?,ETCINQTY=ETCINQTY+?,ETCINTIME =?,ETCINUSER = ?,CONFIRMINUSER = ? WHERE SITENAME = ? AND MATERIALPACKINGNAME =? AND ETCSTATE = 'EtcOut' ";
			Object[] bind = new Object[] { etcState,
					Double.parseDouble(materialQuantity),
					TimeStampUtil.getCurrentTimestamp(), eventUser,
					confirmInUser, siteName, materialPackingName };

			// String strCondition =
			// "INSERT INTO  MATERIALPACKINGETC(SITENAME,MATERIALPACKINGNAME,TIMEKEY,MATERIALSPECNAME,"
			// +
			// "ETCSTATE,LOCATIONNAME,ETCINQTY,ETCOUTQTY,ETCINTIME,ETCOUTTIME,ETCINUSER,ETCOUTUSER,CONFIRMINUSER,CONFIRMOUTUSER)"
			// +
			// "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
			// Object[] bind= new
			// Object[]{siteName,materialPackingName,TimeStampUtil.getCurrentEventTimeKey().toString(),materialSpecName,etcState,locationName,null,Double.parseDouble(materialQuantity),null,TimeStampUtil.getCurrentTimestamp(),null,eventUser,null,null};

			IDMFrameServiceProxy.getSqlTemplate().update(strCondition, bind);

		} catch (IDMFrameDBErrorSignal e) {
			e.printStackTrace();
		}
	}
	public void EtcIn(EventInfo eventInfo, String eventUser,
			String siteName, String materialPackingName, String etcState,
			String materialQuantity, String confirmInUser,String Quantity) {
		try {

			SetEventInfo setEventInfo = new SetEventInfo();

			MaterialPackingKey MaterialPackingKey = new MaterialPackingKey();

			MaterialPackingKey.setSiteName(siteName);
			MaterialPackingKey.setMaterialPackingName(materialPackingName);

			Map<String, Object> bindMap = new HashMap<String, Object>();

			bindMap.put("EtcState", etcState);
			bindMap.put("ETCOUTQuantity", Quantity);
			setEventInfo.setUserColumns(bindMap);
			if(siteName.equals("B5"))
			{
			MaterialPacking mp=MaterialPackingServiceProxy.getMaterialPackingService().selectByKey(MaterialPackingKey);
			eventInfo.setReasonCode(mp.getReasonCode());
			eventInfo.setReasonCodeType(mp.getReasonCodeType());
			}
			MaterialPackingServiceProxy.getMaterialPackingService().setEvent(
					MaterialPackingKey, eventInfo, setEventInfo);

			String strCondition = "UPDATE MATERIALPACKINGETC SET ETCSTATE = ?,ETCINQTY=ETCINQTY+?,ETCINTIME =?,ETCINUSER = ?,CONFIRMINUSER = ? WHERE SITENAME = ? AND MATERIALPACKINGNAME =? AND ETCSTATE = 'EtcOut' ";
			Object[] bind = new Object[] { etcState,
					Double.parseDouble(materialQuantity),
					TimeStampUtil.getCurrentTimestamp(), eventUser,
					confirmInUser, siteName, materialPackingName };

			// String strCondition =
			// "INSERT INTO  MATERIALPACKINGETC(SITENAME,MATERIALPACKINGNAME,TIMEKEY,MATERIALSPECNAME,"
			// +
			// "ETCSTATE,LOCATIONNAME,ETCINQTY,ETCOUTQTY,ETCINTIME,ETCOUTTIME,ETCINUSER,ETCOUTUSER,CONFIRMINUSER,CONFIRMOUTUSER)"
			// +
			// "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
			// Object[] bind= new
			// Object[]{siteName,materialPackingName,TimeStampUtil.getCurrentEventTimeKey().toString(),materialSpecName,etcState,locationName,null,Double.parseDouble(materialQuantity),null,TimeStampUtil.getCurrentTimestamp(),null,eventUser,null,null};

			IDMFrameServiceProxy.getSqlTemplate().update(strCondition, bind);

		} catch (IDMFrameDBErrorSignal e) {
			e.printStackTrace();
		}
	}
	/*
	 * Name : ModifyLocation Desc : ModifyLocation Author : wzj Date :
	 * 2016.02.02
	 */

	public void ModifyLocation(EventInfo eventInfo, String siteName,
			String materialPackingName, String toLocationName,
			String oriLocationName) {
		try {

			SetEventInfo setEventInfo = new SetEventInfo();

			MaterialPackingKey MaterialPackingKey = new MaterialPackingKey();

			MaterialPackingKey.setSiteName(siteName);
			MaterialPackingKey.setMaterialPackingName(materialPackingName);

			Map<String, Object> bindMap = new HashMap<String, Object>();

			bindMap.put("LocationName", toLocationName);

			setEventInfo.setUserColumns(bindMap);

			MaterialPackingServiceProxy.getMaterialPackingService().setEvent(
					MaterialPackingKey, eventInfo, setEventInfo);
			// make toLocationName notfull
			MakeNotFullInfo makeNotFullInfo = new MakeNotFullInfo();
			StorageKey StorageKeyto = new StorageKey();

			StorageKeyto.setSiteName(siteName);
			StorageKeyto.setStorageName(toLocationName);

			Map<String, Object> bindMaptolocnotfull = new HashMap<String, Object>();
			
			bindMaptolocnotfull.put("useState", "NotFull");
			
			makeNotFullInfo.setUserColumns(bindMaptolocnotfull);

			StorageServiceProxy.getStorageService().makeNotFull(StorageKeyto,
					eventInfo, makeNotFullInfo);
			
			
			if (oriLocationName != null && oriLocationName != "") {
				
				// query materialpacking for oriLocationName
				String sql = "SELECT * FROM materialpacking WHERE locationName = :locationName  AND STOCKSTATE='Stocked' ";
				Map<String, Object> bindMaporiloc = new HashMap<String, Object>();
				bindMaporiloc.put("locationName", oriLocationName);
				
				List<Map<String, Object>> queryResult = IDMFrameServiceProxy
						.getSqlTemplate()
						.queryForList(sql, bindMaporiloc);
				// make oriLocationName Empty
				if (queryResult.size() == 0) {
					MakeEmptyInfo makeEmptyInfo = new MakeEmptyInfo();
					StorageKey StorageKey = new StorageKey();

					StorageKey.setSiteName(siteName);
					StorageKey.setStorageName(oriLocationName);

					// Map<String, Object> bindMaporilocempty = new
					// HashMap<String, Object>();
					//
					// bindMaporilocempty.put("useState", "Empty");
					//
					// makeEmptyInfo.setUserColumns(bindMaporilocempty);

					StorageServiceProxy.getStorageService().makeEmpty(
							StorageKey, eventInfo, makeEmptyInfo);
				}
			}

		} catch (IDMFrameDBErrorSignal e) {
			e.printStackTrace();
		}
	}



	


	/*
	 * Name : hold Desc : hold Author : wzj Date : 2016.01.28
	 */
	public void hold(EventInfo eventInfo, String siteName,
			String materialPackingName, String holdState, String reasonCode,String reasonCodeType) {
		try {

			SetEventInfo setEventInfo = new SetEventInfo();

			MaterialPackingKey MaterialPackingKey = new MaterialPackingKey();

			MaterialPackingKey.setSiteName(siteName);
			MaterialPackingKey.setMaterialPackingName(materialPackingName);

			Map<String, Object> bindMap = new HashMap<String, Object>();

			bindMap.put("HoldState", holdState);
			eventInfo.setReasonCode(reasonCode);
			eventInfo.setReasonCodeType(reasonCodeType);
			//bindMap.put("ReasonCode", reasonCode);
			//bindMap.put("ResonCodeType", resonCodeType);

			setEventInfo.setUserColumns(bindMap);

			MaterialPackingServiceProxy.getMaterialPackingService().setEvent(
					MaterialPackingKey, eventInfo, setEventInfo);

		} catch (IDMFrameDBErrorSignal e) {
			e.printStackTrace();
		}
	}

	/*
	 * Name : release Desc : release Author : wzj Date : 2016.01.29
	 */
	public void release(EventInfo eventInfo, String siteName,
			String materialPackingName, String holdState, String reasonCode) {
		try {
			if(siteName.equals("B17")){
				String sql = "SELECT MATERIALPACKINGNAME FROM MATERIALPACKING WHERE "
						+ " SITENAME=:SITENAME "
						+ " AND  MATERIALPACKINGNAME LIKE :MATERIALPACKINGNAME "
						+ " AND STOCKSTATE='Stocked' "
						+ " AND PACKINGSTATE='Released' "
						+ " AND MATERIALQUANTITY>0 ";
				Map<String, Object> bindMapRelease = new HashMap<String, Object>();
				bindMapRelease.put("SITENAME", siteName);
				bindMapRelease.put("MATERIALPACKINGNAME", materialPackingName.substring(0, materialPackingName.length()-4)+"%");
				List<Map<String, Object>> sqlResult
				= IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, bindMapRelease);
				if(sqlResult.size()>0){
					for(int i=0;i<sqlResult.size();i++){
						SetEventInfo setEventInfo = new SetEventInfo();
						materialPackingName=sqlResult.get(i).get("MATERIALPACKINGNAME").toString();
						MaterialPackingKey MaterialPackingKey = new MaterialPackingKey();
						MaterialPackingKey.setSiteName(siteName);
						MaterialPackingKey.setMaterialPackingName(materialPackingName);

						Map<String, Object> bindMap = new HashMap<String, Object>();

						bindMap.put("HoldState", holdState);
						bindMap.put("ReasonCode", reasonCode);

						setEventInfo.setUserColumns(bindMap);

						MaterialPackingServiceProxy.getMaterialPackingService().setEvent(
								MaterialPackingKey, eventInfo, setEventInfo);
					}
				}
				
			}
			else{
				SetEventInfo setEventInfo = new SetEventInfo();

				MaterialPackingKey MaterialPackingKey = new MaterialPackingKey();

				MaterialPackingKey.setSiteName(siteName);
				MaterialPackingKey.setMaterialPackingName(materialPackingName);

				Map<String, Object> bindMap = new HashMap<String, Object>();

				bindMap.put("HoldState", holdState);
				bindMap.put("ReasonCode", reasonCode);

				setEventInfo.setUserColumns(bindMap);

				MaterialPackingServiceProxy.getMaterialPackingService().setEvent(
						MaterialPackingKey, eventInfo, setEventInfo);
			}
			

		} catch (IDMFrameDBErrorSignal e) {
			e.printStackTrace();
		}
	}

	/*
	 * Name : MergeBox Desc : MergeBox Author : wzj Date : 2016.02.25
	 */

	public void SplitMaterialPacking(EventInfo eventInfo, String eventUser,
			String siteName, String sourceMaterialPackingName,
			String sourceMaterialPackingQuantity, String materialPackingName,
			String materialQuantity)

	{
		try {

			MaterialPackingKey materialPackingKey = new MaterialPackingKey();
			materialPackingKey
					.setMaterialPackingName(sourceMaterialPackingName);
			materialPackingKey.setSiteName(siteName);
			// 找出原BOX信息
			MaterialPacking materialPackingData = MaterialPackingServiceProxy
					.getMaterialPackingService()
					.selectByKey(materialPackingKey);

			CreateInfo createInfo = new CreateInfo();

			createInfo.setSiteName(siteName);
			createInfo.setMaterialPackingName(materialPackingName);
			createInfo.setMaterialPackingType(materialPackingData
					.getMaterialPackingType());
			createInfo.setContentMaterialType(materialPackingData
					.getContentMaterialType());

			Map<String, Object> bindMap = new HashMap<String, Object>();

			bindMap.put("MaterialType", materialPackingData.getMaterialType());
			bindMap.put("MaterialSpecName",
					materialPackingData.getMaterialSpecName());
			bindMap.put("SuperMaterialPackingName",
					materialPackingData.getSuperMaterialPackingName());
			bindMap.put("PackingGrade", materialPackingData.getPackingGrade());
			bindMap.put("SubPackingQuantity",
					materialPackingData.getSubPackingQuantity());
			bindMap.put("MaterialCreateQuantity",
					materialPackingData.getMaterialCreateQuantity());
			bindMap.put("MaterialQuantity", materialQuantity);// 数量
			bindMap.put("PackingState", materialPackingData.getPackingState());
			bindMap.put("OldPackingState",
					materialPackingData.getOldStockState());
			bindMap.put("stockState", materialPackingData.getStockState());
			bindMap.put("OldStockState", materialPackingData.getOldStockState());
			//B9&B17对于pcb拆分，拆分后hold，手动解除
			if((siteName.equals("B9")||siteName.equals("B17"))&&materialPackingData.getMaterialSpecName().startsWith("44-977")){
				bindMap.put("HoldState", "Y");
			}else{
				bindMap.put("HoldState", materialPackingData.getHoldState());
			}
			bindMap.put("AreaName", materialPackingData.getAreaName());
			bindMap.put("LocationName", materialPackingData.getLocationName());
			bindMap.put("DurableName", materialPackingData.getDurableName());
			bindMap.put("MaterialProcessGroupName",
					materialPackingData.getMaterialProcessGroupName());
			// bindMap.put("LastEventName", "SplitCreatBox");
			// bindMap.put("LastEventTimeKey",
			// TimeStampUtil.getCurrentEventTimeKey());
			// bindMap.put("LastEventTime",
			// ConvertUtil.convertToTimeStamp(lastEventTime));
			// bindMap.put("LastEventTime",
			// materialPackingData.getLastEventTime());
			// bindMap.put("LastEventUser",
			// materialPackingData.getLastEventUser());
			// bindMap.put("LastEventComment",
			// materialPackingData.getLastEventComment());
			// bindMap.put("CreateTime",
			// ConvertUtil.convertToTimeStamp(createTime));
			bindMap.put("CreateTime", materialPackingData.getCreateTime());
			bindMap.put("CreateUser", materialPackingData.getCreateUser());
			bindMap.put("ReceiveRequestName",
					materialPackingData.getReceiveRequestName());
			bindMap.put("ReceiveRequestDetailName",
					materialPackingData.getReceiveRequestDetailName());
			// bindMap.put("MakeDate",
			// ConvertUtil.convertToTimeStamp(makeDate));
			bindMap.put("MakeDate", materialPackingData.getMakeDate());
			bindMap.put("expiringDate", materialPackingData.getExpiringDate());
			bindMap.put("ReceiveActNo", materialPackingData.getReceiveActNo());
			// bindMap.put("ReceiveTime",
			// ConvertUtil.convertToTimeStamp(receiveTime));
			bindMap.put("ReceiveTime", materialPackingData.getReceiveTime());
			bindMap.put("ReceiveUser", materialPackingData.getReceiveUser());
			bindMap.put("ShipRequestName",
					materialPackingData.getShipRequestName());
			bindMap.put("ShipRequestDetailName",
					materialPackingData.getShipRequestDetailName());
			// bindMap.put("ShipTime",
			// ConvertUtil.convertToTimeStamp(shipTime));
			bindMap.put("ShipTime", materialPackingData.getShipTime());
			bindMap.put("ShipUser", materialPackingData.getShipUser());
			bindMap.put("ReasonCodeType",
					materialPackingData.getReasonCodeType());
			bindMap.put("ReasonCode", materialPackingData.getReasonCode());
			bindMap.put("ErpLocation", materialPackingData.getErpLocation());
			bindMap.put("EtcState", materialPackingData.getEtcState());
			bindMap.put("ErpFactory", materialPackingData.getErpFactory());
			bindMap.put("StockInType", materialPackingData.getStockInType());
			// add item
			bindMap.put("oqaResult", materialPackingData.getOqaResult());
			bindMap.put("oqaResultState",
					materialPackingData.getOqaResultState());
			bindMap.put("charge", materialPackingData.getCharge());
			bindMap.put("supplierName", materialPackingData.getSupplierName());
			bindMap.put("unDoID", materialPackingData.getUnDoID());
			bindMap.put("unDoDetailName",
					materialPackingData.getUnDoDetailName());
			bindMap.put("erpEventTime", materialPackingData.getErpEventTime());
			bindMap.put("npFlag", materialPackingData.getNpFlag());
			createInfo.setUserColumns(bindMap);

			MaterialPackingServiceProxy.getMaterialPackingService().create(
					eventInfo, createInfo);

			String strCondition = "INSERT INTO  BS_MATERIALPACKINGSPLITMERGE(SITENAME,MATERIALPACKINGNAME,DESTMATERIALPACKINGNAMENAME,"
					+ "ACTIONTIMEKEY,ACTIONTYPE,PACKINGGRADE,ACTIONTIME,ACTIONUSER,MATERIALQUANTITY,DESTMATERIALQUANTITY)"
					+ "VALUES (?,?,?,?,?,?,?,?,?,?)";
			Object[] bind = new Object[] { siteName, sourceMaterialPackingName,
					materialPackingName,
					TimeStampUtil.getCurrentEventTimeKey().toString(), "Split",
					materialPackingData.getPackingGrade(),
					TimeStampUtil.getCurrentTimestamp(), eventUser,
					Double.parseDouble(sourceMaterialPackingQuantity),
					Double.parseDouble(materialQuantity) };

			IDMFrameServiceProxy.getSqlTemplate().update(strCondition, bind);		

		} catch (IDMFrameDBErrorSignal e) {
			e.printStackTrace();
		}

	}

	/*
	 * Name : MergeMaterialPacking Desc : MergeMaterialPacking Author : wzj Date
	 * : 2016.03.09
	 */

	public void MergeMaterialPacking(EventInfo eventInfo, String eventUser,
			String siteName, String materialPackingNamef,
			String materialQuantityf, String materialPackingNames,
			String materialQuantitys, String materialPackingName,
			String materialQuantity) {
		try {

			MaterialPackingKey materialPackingKey = new MaterialPackingKey();
			materialPackingKey.setMaterialPackingName(materialPackingNamef);
			materialPackingKey.setSiteName(siteName);
			// 找出原BOX信息
			MaterialPacking materialPackingData = MaterialPackingServiceProxy
					.getMaterialPackingService()
					.selectByKey(materialPackingKey);

			CreateInfo createInfo = new CreateInfo();

			createInfo.setSiteName(siteName);
			createInfo.setMaterialPackingName(materialPackingName);
			createInfo.setMaterialPackingType(materialPackingData
					.getMaterialPackingType());
			createInfo.setContentMaterialType(materialPackingData
					.getContentMaterialType());

			Map<String, Object> bindMap = new HashMap<String, Object>();

			bindMap.put("MaterialType", materialPackingData.getMaterialType());
			bindMap.put("MaterialSpecName",
					materialPackingData.getMaterialSpecName());
			bindMap.put("SuperMaterialPackingName",
					materialPackingData.getSuperMaterialPackingName());
			bindMap.put("PackingGrade", materialPackingData.getPackingGrade());
			bindMap.put("SubPackingQuantity",
					materialPackingData.getSubPackingQuantity());
			bindMap.put("MaterialCreateQuantity",
					materialPackingData.getMaterialCreateQuantity());
			bindMap.put("MaterialQuantity", materialQuantity);// 数量
			bindMap.put("PackingState", materialPackingData.getPackingState());
			bindMap.put("OldPackingState",
					materialPackingData.getOldStockState());
			bindMap.put("stockState", materialPackingData.getStockState());
			bindMap.put("OldStockState", materialPackingData.getOldStockState());
			bindMap.put("HoldState", materialPackingData.getHoldState());
			bindMap.put("AreaName", materialPackingData.getAreaName());
			bindMap.put("LocationName", materialPackingData.getLocationName());
			bindMap.put("DurableName", materialPackingData.getDurableName());
			bindMap.put("MaterialProcessGroupName",
					materialPackingData.getMaterialProcessGroupName());
			// bindMap.put("LastEventName", "SplitCreatBox");
			// bindMap.put("LastEventTimeKey",
			// TimeStampUtil.getCurrentEventTimeKey());
			// bindMap.put("LastEventTime",
			// ConvertUtil.convertToTimeStamp(lastEventTime));
			// bindMap.put("LastEventTime",
			// materialPackingData.getLastEventTime());
			// bindMap.put("LastEventUser",
			// materialPackingData.getLastEventUser());
			// bindMap.put("LastEventComment",
			// materialPackingData.getLastEventComment());
			// bindMap.put("CreateTime",
			// ConvertUtil.convertToTimeStamp(createTime));
			bindMap.put("CreateTime", materialPackingData.getCreateTime());
			bindMap.put("CreateUser", materialPackingData.getCreateUser());
			bindMap.put("ReceiveRequestName",
					materialPackingData.getReceiveRequestName());
			bindMap.put("ReceiveRequestDetailName",
					materialPackingData.getReceiveRequestDetailName());
			// bindMap.put("MakeDate",
			// ConvertUtil.convertToTimeStamp(makeDate));
			bindMap.put("MakeDate", materialPackingData.getMakeDate());
			bindMap.put("ReceiveActNo", materialPackingData.getReceiveActNo());
			// bindMap.put("ReceiveTime",
			// ConvertUtil.convertToTimeStamp(receiveTime));
			bindMap.put("ReceiveTime", materialPackingData.getReceiveTime());
			bindMap.put("ReceiveUser", materialPackingData.getReceiveUser());
			bindMap.put("ShipRequestName",
					materialPackingData.getShipRequestName());
			bindMap.put("ShipRequestDetailName",
					materialPackingData.getShipRequestDetailName());
			// bindMap.put("ShipTime",
			// ConvertUtil.convertToTimeStamp(shipTime));
			bindMap.put("ShipTime", materialPackingData.getShipTime());
			bindMap.put("ShipUser", materialPackingData.getShipUser());
			bindMap.put("ReasonCodeType",
					materialPackingData.getReasonCodeType());
			bindMap.put("ReasonCode", materialPackingData.getReasonCode());
			bindMap.put("ErpLocation", materialPackingData.getErpLocation());
			bindMap.put("EtcState", materialPackingData.getEtcState());
			bindMap.put("ErpFactory", materialPackingData.getErpFactory());
			bindMap.put("StockInType", materialPackingData.getStockInType());
			// add item
			bindMap.put("oqaResult", materialPackingData.getOqaResult());
			bindMap.put("oqaResultState",
					materialPackingData.getOqaResultState());
			bindMap.put("charge", materialPackingData.getCharge());
			bindMap.put("supplierName", materialPackingData.getSupplierName());
			bindMap.put("unDoID", materialPackingData.getUnDoID());
			bindMap.put("unDoDetailName",
					materialPackingData.getUnDoDetailName());
			bindMap.put("erpEventTime", materialPackingData.getErpEventTime());

			createInfo.setUserColumns(bindMap);

			MaterialPackingServiceProxy.getMaterialPackingService().create(
					eventInfo, createInfo);

			String strConditionF = "INSERT INTO  BS_MATERIALPACKINGSPLITMERGE(SITENAME,MATERIALPACKINGNAME,DESTMATERIALPACKINGNAMENAME,"
					+ "ACTIONTIMEKEY,ACTIONTYPE,PACKINGGRADE,ACTIONTIME,ACTIONUSER,MATERIALQUANTITY,DESTMATERIALQUANTITY)"
					+ "VALUES (?,?,?,?,?,?,?,?,?,?)";
			Object[] bindf = new Object[] { siteName, materialPackingNamef,
					materialPackingName,
					TimeStampUtil.getCurrentEventTimeKey().toString(), "Merge",
					materialPackingData.getPackingGrade(),
					TimeStampUtil.getCurrentTimestamp(), eventUser,
					Double.parseDouble(materialQuantityf),
					Double.parseDouble(materialQuantity) };

			IDMFrameServiceProxy.getSqlTemplate().update(strConditionF, bindf);

			String strConditionS = "INSERT INTO  BS_MATERIALPACKINGSPLITMERGE(SITENAME,MATERIALPACKINGNAME,DESTMATERIALPACKINGNAMENAME,"
					+ "ACTIONTIMEKEY,ACTIONTYPE,PACKINGGRADE,ACTIONTIME,ACTIONUSER,MATERIALQUANTITY,DESTMATERIALQUANTITY)"
					+ "VALUES (?,?,?,?,?,?,?,?,?,?)";
			Object[] binds = new Object[] { siteName, materialPackingNames,
					materialPackingName,
					TimeStampUtil.getCurrentEventTimeKey().toString(), "Merge",
					materialPackingData.getPackingGrade(),
					TimeStampUtil.getCurrentTimestamp(), eventUser,
					Double.parseDouble(materialQuantitys),
					Double.parseDouble(materialQuantity) };

			IDMFrameServiceProxy.getSqlTemplate().update(strConditionS, binds);

			try {

				SetEventInfo setEventInfo = new SetEventInfo();

				MaterialPackingKey MaterialPackingKey = new MaterialPackingKey();

				MaterialPackingKey.setSiteName(siteName);
				MaterialPackingKey.setMaterialPackingName(materialPackingNamef);

				Map<String, Object> bindMapf = new HashMap<String, Object>();

				bindMapf.put("PackingState", "Emptied");
				bindMapf.put("MaterialQuantity", Double.parseDouble("0"));

				setEventInfo.setUserColumns(bindMapf);

				MaterialPackingServiceProxy.getMaterialPackingService()
						.setEvent(MaterialPackingKey, eventInfo, setEventInfo);

			} catch (IDMFrameDBErrorSignal e) {
				e.printStackTrace();
			}

			try {

				SetEventInfo setEventInfo = new SetEventInfo();

				MaterialPackingKey MaterialPackingKey = new MaterialPackingKey();

				MaterialPackingKey.setSiteName(siteName);
				MaterialPackingKey.setMaterialPackingName(materialPackingNames);

				Map<String, Object> bindMaps = new HashMap<String, Object>();

				bindMaps.put("PackingState", "Emptied");
				bindMaps.put("MaterialQuantity", Double.parseDouble("0"));

				setEventInfo.setUserColumns(bindMaps);

				MaterialPackingServiceProxy.getMaterialPackingService()
						.setEvent(MaterialPackingKey, eventInfo, setEventInfo);

			} catch (IDMFrameDBErrorSignal e) {
				e.printStackTrace();
			}

		} catch (IDMFrameDBErrorSignal e) {
			e.printStackTrace();
		}

	}

	public void holdBatch(List<MaterialPackingKey> keyList,
			EventInfo eventInfo, List<SetEventInfo> setEventInfoList) {
		MaterialPackingServiceProxy.getMaterialPackingService().setEvent(
				keyList, eventInfo, setEventInfoList);
	}

	/*
	 * Name : Packing Desc : Packing Author : boe cim dev. Date : 2016.01.27
	 */

	public static String Packing_old(EventInfo eventInfo, String siteName,
			String areaName, String receiveQty, String boxQuantity,
			String EveryBoxQuantity, String boxFlag, String receiveRequestName,
			String receiveRequestDetailName, String materialSpecName,
			String receiveActNo, String makeDate, String shipRequestName,
			String shipRequestDetailName, String reasonCodeType,
			String reasonCode, String erpLocation, String erpFactory,
			String charge, String supplierName, String NPFlag,String expirationDay) throws Exception {
		
		// PO前缀36的寄售到货，添加标识specFlag，寄售到货：K，其它：N
		String poPrefix = receiveRequestName.equals("") ? shipRequestDetailName.substring(0,2) : receiveRequestName.substring(0, 2);
		String specialFlag = poPrefix.equals("36") ? "K" : "N";

		String receiveActNo1 = receiveActNo.substring(5);
		String lastEventTimeKey = "";
		List<CreateInfo> listMaterialPacking = new ArrayList<CreateInfo>();
		SimpleDateFormat sDateFormat=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		List<String> boxId;
		double EveryBoxQuantity1 = 0;
		
		try {
			if (boxFlag.equals("Y")) {
				double tempV = Math.round((Double.valueOf(receiveQty) - (Double
						.valueOf(boxQuantity) - 1)
						* Double.valueOf(EveryBoxQuantity)) * 100);
				// Double v=(Double) (tempV/100.00);
				EveryBoxQuantity1 = (double) (tempV / 100.00);
				// Double num=(Double)(Math.round(totalPrice*100)/100)
			}

			boxId = MaterialPackingServiceImpl.generateBoxID("BOXID", siteName,
					boxQuantity, makeDate);
			// MaterialPackingServiceImpl.generateBoxName("", "", siteName,
			// receiveActNo, "", "");
			MaterialSpec materialSpec = new MaterialSpec();
			MaterialSpecKey materialSpecKey = new MaterialSpecKey();
			materialSpecKey.setMaterialSpecName(materialSpecName);
			materialSpecKey.setSiteName(siteName);

			materialSpec = MaterialServiceProxy.getMaterialSpecService()
					.selectByKey(materialSpecKey);

			// try{
			// materialSpec=MaterialServiceProxy.getMaterialSpecService().selectByKey(materialSpecKey);
			// }
			// catch(NotFoundSignal e)
			// {
			// e.s
			// }
			Map<String, Object> box_quantity = new HashMap<String, Object>();
			int i = 0;			
			for (; i < boxId.size(); i++) {
				CreateInfo materialPacking = new CreateInfo();
				materialPacking.setMaterialPackingName(boxId.get(i));
				materialPacking.setSiteName(siteName);
				materialPacking.setContentMaterialType("");
				materialPacking.setMaterialPackingType("Box");

				Map<String, Object> bindMap = new HashMap<String, Object>();
				bindMap.put("materialQuantity", EveryBoxQuantity);
				bindMap.put("materialCreateQuantity", EveryBoxQuantity);
				bindMap.put("packingState", "Created");// 标记Box是刚创建的

				// bindMap.put("materialPackingType","Pallet");
				// bindMap.put("contentMaterialType", "MaterialPacking");
				bindMap.put("materialType", materialSpec.getMaterialType());
				bindMap.put("materialSpecName", materialSpecName);
				bindMap.put("stockState", "");
				bindMap.put("holdState", "N");
				bindMap.put("areaName", areaName);
				bindMap.put("createUser", eventInfo.getEventUser());
				bindMap.put("createTime", eventInfo.getEventTime());				
				receiveRequestName = receiveRequestName.equals("") ? shipRequestName
						: receiveRequestName;
				receiveRequestDetailName = receiveRequestDetailName.equals("") ? shipRequestDetailName
						: receiveRequestDetailName;

				bindMap.put("receiveRequestName", receiveRequestName);
				bindMap.put("receiveRequestDetailName",
						receiveRequestDetailName);
				// bindMap.put("receiveRequestName", shipRequestName);
				// bindMap.put("receiveRequestDetailName",
				// shipRequestDetailName);
				if(expirationDay==null||expirationDay.equals(""))
				{
					if(materialSpec.getExpirationDay()>0)
					{
						Date endTime=sDateFormat.parse(makeDate);
						Calendar rightNow = Calendar.getInstance();  
						rightNow.setTime(endTime);  
						if(siteName.equals("TM1"))
						{
							rightNow.add(Calendar.MONTH, materialSpec.getExpirationDay()); 
							rightNow.set(Calendar.DAY_OF_MONTH,rightNow.get(Calendar.DAY_OF_MONTH)-1);
						}
						else{
						rightNow.add(Calendar.MONTH, materialSpec.getExpirationDay());  
						}
						Date dt1 = rightNow.getTime();  
						expirationDay = sDateFormat.format(dt1);  
					}
					else 
					{
						Date endTime=sDateFormat.parse(makeDate);
						Calendar rightNow = Calendar.getInstance();  
					    rightNow.setTime(endTime);  
					    rightNow.add(Calendar.MONTH, 48);  
					    Date dt1 = rightNow.getTime();  
					    expirationDay = "2099-12-31 00:00:00";  

						//endTime.add(Calendar.MONTH, materialSpec.getExpirationDay()); 
						//endTime = (endTime).(materialSpec.getExpirationDay());
					}
					//endTime.add(Calendar.MONTH, materialSpec.getExpirationDay()); 
					//endTime = (endTime).(materialSpec.getExpirationDay());
				}
				
				
                //this.txtEndTime.Text = dt.ToString("yyyy年MM月dd日", System.Globalization.DateTimeFormatInfo.InvariantInfo);
				bindMap.put("makeDate", makeDate);
				bindMap.put("expiringDate", expirationDay.substring(0,expirationDay.indexOf(" "))+" 00:00:00");
				bindMap.put("receiveActNo", receiveActNo);
				bindMap.put("reasonCodeType", reasonCodeType);
				bindMap.put("reasonCode", reasonCode);
				bindMap.put("erpLocation", erpLocation);
				bindMap.put("erpFactory", erpFactory);
				bindMap.put("stockInType", "");
				bindMap.put("charge", charge);
				bindMap.put("supplierName", supplierName);
				bindMap.put("npFlag", NPFlag);
				// 寄售到货
				bindMap.put("specialFlag", specialFlag);
				materialPacking.setUserColumns(bindMap);

				listMaterialPacking.add(materialPacking);
				
			}

			if (EveryBoxQuantity1 > 0) {
				CreateInfo materialPacking = new CreateInfo();
				Map<String, Object> bindMap = new HashMap<String, Object>();
				bindMap.put("materialQuantity", EveryBoxQuantity1);
				bindMap.put("materialCreateQuantity", EveryBoxQuantity1);
				bindMap.put("packingState", "Created");// 标记Box是刚创建的

				materialPacking = listMaterialPacking.get(boxId.size() - 1);
				materialPacking.setUserColumns(bindMap);

				listMaterialPacking.remove(boxId.size() - 1);
				listMaterialPacking.add(materialPacking);
			}

			MaterialPackingServiceProxy.getMaterialPackingService().create(
					eventInfo, listMaterialPacking);

			lastEventTimeKey = eventInfo.getEventTimeKey();

		} catch (CustomException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return lastEventTimeKey;
	}


	/**
	 * 创建标签，SDK
	 * @param eventInfo
	 * @param siteName
	 * @param areaName
	 * @param receiveQty
	 * @param boxQuantity
	 * @param EveryBoxQuantity
	 * @param boxFlag
	 * @param receiveRequestName
	 * @param receiveRequestDetailName
	 * @param materialSpecName
	 * @param receiveActNo
	 * @param makeDate
	 * @param shipRequestName
	 * @param shipRequestDetailName
	 * @param reasonCodeType
	 * @param reasonCode
	 * @param erpLocation
	 * @param erpFactory
	 * @param charge
	 * @param supplierName
	 * @param NPFlag
	 * @param expirationDay
	 * @param supplierCharge
	 * @param sdkid
	 * @param locationName
	 * @param phase
	 * @param specName
	 * @param materialUnit
	 * @param IS_BATCH
	 * @param IQCFLAG
	 * @param funit
	 * @param fqty
	 * @param remark
	 * @param truegg
	 * @param SALESPERSON
	 * @param CAREER_ASSISTANCE
	 * @param BUSINESS_UNIT
	 * @return
	 * @throws Exception
	 */
	public static String Packing(EventInfo eventInfo, String siteName,
								 String areaName, String receiveQty, String boxQuantity,
								 String EveryBoxQuantity, String boxFlag, String receiveRequestName,
								 String receiveRequestDetailName, String materialSpecName,
								 String receiveActNo, String makeDate, String shipRequestName,
								 String shipRequestDetailName, String reasonCodeType,
								 String reasonCode, String erpLocation, String erpFactory,
								 String charge, String supplierName, String NPFlag,String expirationDay,String supplierCharge,String sdkid,
								 String locationName,String phase,String specName,String materialUnit,
								 String IS_BATCH,String IQCFLAG,String funit,String fqty,String remark,String truegg,
								 String SALESPERSON, String CAREER_ASSISTANCE, String BUSINESS_UNIT) throws Exception {

		String lastEventTimeKey = "";
		List<CreateInfo> listMaterialPacking = new ArrayList<CreateInfo>();
		SimpleDateFormat sDateFormat=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		List<String> boxId;
		BigDecimal EveryBoxQuantity1 = new BigDecimal(0);
		BigDecimal everyQty = new BigDecimal(receiveQty);
		BigDecimal sumQty = BigDecimal.ZERO;
		try {
			if (boxFlag.equals("Y")) {

				BigDecimal tempV = (new BigDecimal(receiveQty).subtract((new BigDecimal(boxQuantity).subtract(new BigDecimal(1))).multiply(new BigDecimal(EveryBoxQuantity))).multiply(new BigDecimal(100)));
				// float v=(float) (tempV/100.00);
				EveryBoxQuantity1 = (BigDecimal) (tempV.divide(new BigDecimal(100.00)));
				// float num=(float)(Math.round(totalPrice*100)/100)
			}
			String is_oven = "N";
			MaterialSpec materialSpec = new MaterialSpec();
			MaterialSpecKey materialSpecKey = new MaterialSpecKey();
			materialSpecKey.setMaterialSpecName(materialSpecName);
			materialSpecKey.setSiteName(siteName);

			materialSpec = MaterialServiceProxy.getMaterialSpecService()
					.selectByKey(materialSpecKey);
			String maturationflag = materialSpec.getMATURATIONFLAG();//熟化标识
			String is_CON_TEMP = materialSpec.getIS_CON_TEMP();//恒温恒湿
			//判断仓库是否启用了货位，但货位为空
			String sql = "SELECT be.USE_LOCATION,be.CONST_TEMP,be.IS_OVEN FROM BS_ERPLOCATION be WHERE be.ERPLOCATIONNAME = :ERPLOCATION";
			Map<String, Object> hashMap = new HashMap<String,Object> ();
			hashMap.put("ERPLOCATION", erpLocation);
			hashMap.put("LOCATIONNAME", locationName);
			List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, hashMap);
			if (queryForList == null || queryForList.size() < 1) {
				throw new RuntimeException("仓库不存在");
			} else {
				String string = queryForList.get(0).get("USE_LOCATION") == null ? "" : queryForList.get(0).get("USE_LOCATION").toString();//启用货位
				String const_temp = queryForList.get(0).get("CONST_TEMP") == null ? "" : queryForList.get(0).get("CONST_TEMP").toString(); //恒温标识
				is_oven = queryForList.get(0).get("IS_OVEN") == null ? "" : queryForList.get(0).get("IS_OVEN").toString(); //熟化标识
//				if ("Y".equals(string) && ("".equals(locationName) || locationName == null ))  {
//					throw new RuntimeException("仓库启用了货位，但货位为空");
//				}
//				if ("N".equals(string) && (!"".equals(locationName)) )  {
//					throw new RuntimeException("仓库未启用货位，货位为空");
//				}
				if (!"".equals(locationName)) {
					String sql2 = "SELECT * FROM STORAGESPEC S WHERE S.STORAGENAME = :LOCATIONNAME AND S.ERPLOCATION = :ERPLOCATION ";
					List<Map<String, Object>> queryForList2 = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql2, hashMap);
					if (queryForList2 == null || queryForList2.size() < 1) {
						throw new RuntimeException("仓库与货位对应关系不正确");
					}
				}
				String ckhw = "Y".equals(const_temp) ? "恒温恒湿" : "非恒温恒湿";
				String wlhw = "Y".equals(is_CON_TEMP) ? "恒温恒湿" : "非恒温恒湿";


				String cksh = "Y".equals(is_oven) ? "熟化" : "非熟化";
				String wlsh = "Y".equals(maturationflag) ? "熟化" : "非熟化";
//				if (!const_temp.equals(is_CON_TEMP)) {
//					throw new RuntimeException("仓库" + ckhw + "; 物料" + wlhw);
//				}



			}


			String materialType = materialSpec.getMaterialType();
			if (materialType !=  null && (materialType.startsWith("103")  || materialType.startsWith("106")  || materialType.startsWith("260"))) {
				materialType = "JS";
			} else {
				materialType = "WL";
			}
			boxId = MaterialPackingServiceImpl.generateBoxID("LabelId", siteName,
					boxQuantity, makeDate,materialType,erpFactory);
			Map<String, Object> box_quantity = new HashMap<String, Object>();
			int i = 0;
			for (; i < boxId.size(); i++) {
				CreateInfo materialPacking = new CreateInfo();
				if (i == boxId.size() - 1) {
					BigDecimal bigReceiveQty = new BigDecimal(receiveQty);
					BigDecimal bigEveryBoxQuantity = new BigDecimal(EveryBoxQuantity);
					BigDecimal bigBoxIdSizeMinusOne = new BigDecimal(boxId.size() - 1);
					BigDecimal result = bigReceiveQty.subtract(bigEveryBoxQuantity.multiply(bigBoxIdSizeMinusOne));
					EveryBoxQuantity =result.toString();
				}
				//470110856|1|C|75mm*1000m|SHBP01JT1202305240009|20230524|11|75
				String newBoxId = materialSpecName + "|1|" + phase + "|" + specName + "|" + boxId.get(i) + "|"
						+ makeDate.replace("-", "").substring(0, 8) + "|" + materialUnit + "|" + EveryBoxQuantity;
				materialPacking.setMaterialPackingName(newBoxId);
				materialPacking.setSiteName(siteName);
				materialPacking.setContentMaterialType("");
				materialPacking.setMaterialPackingType("Box");

				Map<String, Object> bindMap = new HashMap<String, Object>();
				bindMap.put("materialQuantity", EveryBoxQuantity);
				bindMap.put("materialCreateQuantity", EveryBoxQuantity);
				bindMap.put("packingState", "Created");// 标记Box是刚创建的
				bindMap.put("materialType", materialSpec.getMaterialType());
				bindMap.put("materialSpecName", materialSpecName);
				bindMap.put("stockState", "Created");
				bindMap.put("holdState", "N");
				bindMap.put("areaName", areaName);
				bindMap.put("createUser", eventInfo.getEventUser());
				bindMap.put("createTime", eventInfo.getEventTime());
				receiveRequestName = receiveRequestName.equals("") ? shipRequestName
						: receiveRequestName;
				receiveRequestDetailName = receiveRequestDetailName.equals("") ? shipRequestDetailName
						: receiveRequestDetailName;
				bindMap.put("ReceiveTime", eventInfo.getEventTime());
				bindMap.put("ReceiveUser", eventInfo.getEventUser());
				bindMap.put("receiveRequestName", receiveRequestName);
				bindMap.put("receiveRequestDetailName",
						receiveRequestDetailName);
				bindMap.put("receiveRequestDetailName",
						receiveRequestDetailName);
				bindMap.put("SDK_ID", sdkid);
//				String SALESPERSON, String CAREER_ASSISTANCE, String BUSINESS_UNIT
				bindMap.put("funit", funit);
				bindMap.put("FQTY", fqty);
				bindMap.put("truegg", truegg);
				bindMap.put("remark", remark);

				bindMap.put("SALESPERSON", SALESPERSON);
				bindMap.put("CAREER_ASSISTANCE", CAREER_ASSISTANCE);
				bindMap.put("BUSINESS_UNIT", BUSINESS_UNIT);
				if("Y".equals(is_oven)) {
					bindMap.put("MATURATIONINTIME", eventInfo.getEventTime());
				}
				// bindMap.put("receiveRequestName", shipRequestName);
				// bindMap.put("receiveRequestDetailName",
				// shipRequestDetailName);
				if(expirationDay==null||expirationDay.equals(""))
				{
					if(materialSpec.getExpirationDay()>0)
					{
						Date endTime=sDateFormat.parse(makeDate);
						Calendar rightNow = Calendar.getInstance();
						rightNow.setTime(endTime);
						if(siteName.equals("TM1"))
						{
							rightNow.add(Calendar.MONTH, materialSpec.getExpirationDay());
							rightNow.set(Calendar.DAY_OF_MONTH,rightNow.get(Calendar.DAY_OF_MONTH)-1);
						}
						else{
							rightNow.add(Calendar.DATE, materialSpec.getExpirationDay());
						}
						Date dt1 = rightNow.getTime();
						expirationDay = sDateFormat.format(dt1);
					}
					else
					{
						Date endTime=sDateFormat.parse(makeDate);
						Calendar rightNow = Calendar.getInstance();
						rightNow.setTime(endTime);
						rightNow.add(Calendar.MONTH, 48);
						Date dt1 = rightNow.getTime();
						expirationDay = "2099-12-31 00:00:00";

						//endTime.add(Calendar.MONTH, materialSpec.getExpirationDay());
						//endTime = (endTime).(materialSpec.getExpirationDay());
					}
					//endTime.add(Calendar.MONTH, materialSpec.getExpirationDay());
					//endTime = (endTime).(materialSpec.getExpirationDay());
				}


				//this.txtEndTime.Text = dt.ToString("yyyy年MM月dd日", System.Globalization.DateTimeFormatInfo.InvariantInfo);
				bindMap.put("makeDate", makeDate);
				bindMap.put("expiringDate", expirationDay.substring(0,expirationDay.indexOf(" "))+" 00:00:00");
				bindMap.put("receiveActNo", receiveActNo);
				bindMap.put("reasonCodeType", reasonCodeType);
				bindMap.put("reasonCode", reasonCode);
				bindMap.put("erpLocation", erpLocation);
				bindMap.put("erpFactory", erpFactory);
				bindMap.put("stockInType", "");
				bindMap.put("unit", materialUnit);
				if ("是".equals(IS_BATCH)) {
					bindMap.put("charge", boxId.get(i));
				}
				if ("否".equals(IQCFLAG)) {
					bindMap.put("oqaResultState",GenericServiceProxy.getConstantMap().OQA_State_End);
					bindMap.put("oqaResult","OK");
					bindMap.put("packingGrade", "OK");
				} else {
					bindMap.put("oqaResultState",GenericServiceProxy.getConstantMap().OQA_State_Pre);
				}

				bindMap.put("PHASE", phase);
				//bindMap.put("supplierCharge", supplierCharge);
				bindMap.put("supplierName", supplierName);
				bindMap.put("npFlag", NPFlag);
				bindMap.put("locationName", locationName );
				materialPacking.setUserColumns(bindMap);
				listMaterialPacking.add(materialPacking);

				box_quantity.put(boxId.get(i), EveryBoxQuantity);  // 防大数据float精度丢失

//				/** 计算最后一箱的数量 */
//				BigDecimal nextQty = new BigDecimal(EveryBoxQuantity);
//				sumQty = sumQty.add(nextQty);
//				if(nextQty.compareTo(everyQty.subtract(sumQty)) > 0) {
//					EveryBoxQuantity = everyQty.subtract(sumQty).toString();
//				}

			}

			if (EveryBoxQuantity1.compareTo(new BigDecimal(0)) > 0) {
				CreateInfo materialPacking = new CreateInfo();
				Map<String, Object> bindMap = new HashMap<String, Object>();
				bindMap.put("materialQuantity", EveryBoxQuantity1);
				bindMap.put("materialCreateQuantity", EveryBoxQuantity1);
				bindMap.put("packingState", "Created");// 标记Box是刚创建的
				bindMap.put("fqty", fqty);
				materialPacking = listMaterialPacking.get(boxId.size() - 1);
				materialPacking.setUserColumns(bindMap);

				listMaterialPacking.remove(boxId.size() - 1);
				listMaterialPacking.add(materialPacking);
			}

			MaterialPackingServiceProxy.getMaterialPackingService().create(
					eventInfo, listMaterialPacking);

//			因为float精度问题，再更新一次
			try {
//				for(CreateInfo creatInfo : listMaterialPacking) {
//					String updateSql= " UPDATE MATERIALPACKING SET MATERIALCREATEQUANTITY = :QTY,MATERIALQUANTITY = :QTY"
//							+ " WHERE MATERIALPACKINGNAME = :MATERIALPACKINGNAME AND SITENAME = :SITENAME";
//					Map<String, Object> updateMap = new HashMap<String, Object>();
//					updateMap.put("QTY", box_quantity.get(creatInfo.getMaterialPackingName()));
//					updateMap.put("MATERIALPACKINGNAME", creatInfo.getMaterialPackingName());
//					updateMap.put("SITENAME", siteName);
//					IDMFrameServiceProxy.getSqlTemplate().update(updateSql, updateMap);
//				}
			} catch (IDMFrameDBErrorSignal e) {
//				e.printStackTrace();
				log.info("创建BOX，更新大数据时失败 ==========> ");
			}

			lastEventTimeKey = eventInfo.getEventTimeKey();

		} catch (CustomException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();

		}
		return lastEventTimeKey;
	}
	// FORGERP
	public static String Packing(EventInfo eventInfo, String siteName, String areaName, String receiveQty,
			String boxQuantity, String EveryBoxQuantity, String boxFlag, String receiveRequestName,
			String receiveRequestDetailName, String materialSpecName, String receiveActNo, String makeDate,
			String shipRequestName, String shipRequestDetailName, String reasonCodeType, String reasonCode,
			String erpLocation, String erpFactory, String charge, String supplierName, String NPFlag,
			String expirationDay, String supplierCharge, String boeSuppplierNo,String psPosid,String sobkz,String knttp,String bwtar,String kostl) throws Exception {
		
		if (sobkz == null || sobkz == "") {
			if (knttp != null || knttp != "") {
				sobkz = knttp;
			}
		}
		
		String receiveActNo1 = receiveActNo.substring(5);
		String lastEventTimeKey = "";
		List<CreateInfo> listMaterialPacking = new ArrayList<CreateInfo>();
		SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		List<String> boxId;
		String sql = "SELECT DISTINCT RECEIVEREQUESTDETAILTYPE FROM MATERIALRECEIVEREQUESTDETAIL "
				+ "WHERE SITENAME = :siteName and RECEIVEREQUESTNAME = :receiveRequestName";

		Map<String, String> bindMap1 = new HashMap<String, String>();
		bindMap1.put("siteName", siteName);
		bindMap1.put("receiveRequestName", receiveRequestName);
		
		List<Map<String, Object>> queryResult = IDMFrameServiceProxy
				.getSqlTemplate()
				.queryForList(sql, bindMap1);
		if (queryResult.size()>0) {
			
		if (queryResult.get(0).get("RECEIVEREQUESTDETAILTYPE").toString().equals("2"))
		{
			sobkz = "K";
		}
		else if (queryResult.get(0).get("RECEIVEREQUESTDETAILTYPE").toString().equals("3"))
		{
			sobkz = "L";
		}
		
		}

		double EveryBoxQuantity1 = 0;
		try {
			if (boxFlag.equals("Y")) {
				double tempV = Math.round(
						(Double.valueOf(receiveQty) - (Double.valueOf(boxQuantity) - 1) * Double.valueOf(EveryBoxQuantity))
								* 100);
				// Double v=(Double) (tempV/100.00);
				EveryBoxQuantity1 = (double) (tempV / 100.00);
				// Double num=(Double)(Math.round(totalPrice*100)/100)
			}

			boxId = MaterialPackingServiceImpl.generateBoxID("BOXID", siteName, boxQuantity, makeDate);
			// MaterialPackingServiceImpl.generateBoxName("", "", siteName,
			// receiveActNo, "", "");
			MaterialSpec materialSpec = new MaterialSpec();
			MaterialSpecKey materialSpecKey = new MaterialSpecKey();
			materialSpecKey.setMaterialSpecName(materialSpecName);
			materialSpecKey.setSiteName(siteName);

			materialSpec = MaterialServiceProxy.getMaterialSpecService().selectByKey(materialSpecKey);

			// try{
			// materialSpec=MaterialSpecServiceProxy.getMaterialSpecService().selectByKey(materialSpecKey);
			// }
			// catch(NotFoundSignal e)
			// {
			// e.s
			// }
			int i = 0;
			for (; i < boxId.size(); i++) {
				CreateInfo materialPacking = new CreateInfo();
				materialPacking.setMaterialPackingName(boxId.get(i));
				materialPacking.setSiteName(siteName);
				materialPacking.setContentMaterialType("");
				materialPacking.setMaterialPackingType("Box");

				Map<String, Object> bindMap = new HashMap<String, Object>();
				bindMap.put("materialQuantity", EveryBoxQuantity);
				bindMap.put("materialCreateQuantity", EveryBoxQuantity);
				bindMap.put("packingState", "Created");// 标记Box是刚创建的

				// bindMap.put("materialPackingType","Pallet");
				// bindMap.put("contentMaterialType", "MaterialPacking");
				bindMap.put("materialType", materialSpec.getMaterialType());
				bindMap.put("materialSpecName", materialSpecName);
				bindMap.put("stockState", "");
				bindMap.put("holdState", "N");
				bindMap.put("areaName", areaName);
				bindMap.put("createUser", eventInfo.getEventUser());
				bindMap.put("createTime", eventInfo.getEventTime());
				bindMap.put("boeSupplierNo", boeSuppplierNo);
				receiveRequestName = receiveRequestName.equals("") ? shipRequestName : receiveRequestName;
				receiveRequestDetailName = receiveRequestDetailName.equals("") ? shipRequestDetailName
						: receiveRequestDetailName;
				// add by lixinghui 20221222 退库预留入库工厂库位处理
//				if (!"".equals(shipRequestName) && !"".equals(shipRequestDetailName)) {
//					MaterialShipRequestKey mpk = new MaterialShipRequestKey(siteName, shipRequestName);
//					MaterialShipRequest mp = MaterialShipRequestServiceProxy.getMaterialShipRequestService()
//							.selectByKey(mpk);
//					erpFactory = mp.getErpReceiveFactory();
//					erpLocation = mp.getErpReceiveLocation();
//				}

				bindMap.put("receiveRequestName", receiveRequestName);
				bindMap.put("receiveRequestDetailName", receiveRequestDetailName);
				bindMap.put("receiveRequestDetailName", receiveRequestDetailName);
				// bindMap.put("receiveRequestName", shipRequestName);
				// bindMap.put("receiveRequestDetailName",
				// shipRequestDetailName);
				if (expirationDay == null || expirationDay.equals("")) {
					if (materialSpec.getExpirationDay() > 0) {
						Date endTime = sDateFormat.parse(makeDate);
						Calendar rightNow = Calendar.getInstance();
						rightNow.setTime(endTime);
						if (siteName.equals("TM1")) {
							rightNow.add(Calendar.MONTH, materialSpec.getExpirationDay());
							rightNow.set(Calendar.DAY_OF_MONTH, rightNow.get(Calendar.DAY_OF_MONTH) - 1);
						} else {
							rightNow.add(Calendar.MONTH, materialSpec.getExpirationDay());
						}
						Date dt1 = rightNow.getTime();
						expirationDay = sDateFormat.format(dt1);
					} else {
						Date endTime = sDateFormat.parse(makeDate);
						Calendar rightNow = Calendar.getInstance();
						rightNow.setTime(endTime);
						rightNow.add(Calendar.MONTH, 48);
						Date dt1 = rightNow.getTime();
						expirationDay = "2099-12-31 00:00:00";

						// endTime.add(Calendar.MONTH, materialSpec.getExpirationDay());
						// endTime = (endTime).(materialSpec.getExpirationDay());
					}
					// endTime.add(Calendar.MONTH, materialSpec.getExpirationDay());
					// endTime = (endTime).(materialSpec.getExpirationDay());
				}

				// this.txtEndTime.Text = dt.ToString("yyyy年MM月dd日",
				// System.Globalization.DateTimeFormatInfo.InvariantInfo);
				bindMap.put("makeDate", makeDate);
				bindMap.put("expiringDate", expirationDay.substring(0, expirationDay.indexOf(" ")) + " 00:00:00");
				bindMap.put("receiveActNo", receiveActNo);
				bindMap.put("ps_Posid", psPosid);
				bindMap.put("sobkz", sobkz);
				bindMap.put("kostl", kostl);
				bindMap.put("wbs_o", psPosid);
				bindMap.put("wbs_n", psPosid);
				bindMap.put("reasonCodeType", reasonCodeType);
				bindMap.put("reasonCode", reasonCode);
				bindMap.put("erpLocation", erpLocation);
				bindMap.put("erpFactory", erpFactory);
				bindMap.put("stockInType", "");
				bindMap.put("charge", charge);
				bindMap.put("bwtar", bwtar);
				bindMap.put("supplierCharge", supplierCharge);
				bindMap.put("supplierName", supplierName);
				bindMap.put("npFlag", NPFlag);
				if (siteName.equals("B9")) {
					bindMap.put("locationName", "9-C1-02-C");
				}

				materialPacking.setUserColumns(bindMap);

				listMaterialPacking.add(materialPacking);
			}

			if (EveryBoxQuantity1 > 0) {
				CreateInfo materialPacking = new CreateInfo();
				Map<String, Object> bindMap = new HashMap<String, Object>();
				bindMap.put("materialQuantity", EveryBoxQuantity1);
				bindMap.put("materialCreateQuantity", EveryBoxQuantity1);
				bindMap.put("packingState", "Created");// 标记Box是刚创建的

				materialPacking = listMaterialPacking.get(boxId.size() - 1);
				materialPacking.setUserColumns(bindMap);

				listMaterialPacking.remove(boxId.size() - 1);
				listMaterialPacking.add(materialPacking);
			}

			MaterialPackingServiceProxy.getMaterialPackingService().create(eventInfo, listMaterialPacking);

			lastEventTimeKey = eventInfo.getEventTimeKey();

		} catch (CustomException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return lastEventTimeKey;
	}

	//BMDT创建Box
	public static String BMDTPacking(EventInfo eventInfo, String siteName,
			String areaName, String receiveQty, String boxQuantity,
			String EveryBoxQuantity, String boxFlag, String receiveRequestName,
			String receiveRequestDetailName, String materialSpecName,
			String receiveActNo, String makeDate, String shipRequestName,
			String shipRequestDetailName, String reasonCodeType,
			String reasonCode, String erpLocation, String erpFactory,
			String charge, String supplierName, String NPFlag,String improvmentFlag,
			String erpreceivelocation,String acttype,String palletID) throws Exception {

		String receiveActNo1 = receiveActNo.substring(5);
		String lastEventTimeKey = "";
		List<CreateInfo> listMaterialPacking = new ArrayList<CreateInfo>();

		List<String> boxId;
		double EveryBoxQuantity1 = 0;
		try {
			if (boxFlag.equals("Y")) {
				double tempV = Math.round((Double.valueOf(receiveQty) - (Double
						.valueOf(boxQuantity) - 1)
						* Double.valueOf(EveryBoxQuantity)) * 100);
				// Double v=(Double) (tempV/100.00);
				EveryBoxQuantity1 = (double) (tempV / 100.00);
				// Double num=(Double)(Math.round(totalPrice*100)/100)
			}

			boxId = MaterialPackingServiceImpl.generateBoxID("BOXID", siteName,
					boxQuantity, makeDate);
			// MaterialPackingServiceImpl.generateBoxName("", "", siteName,
			// receiveActNo, "", "");
			MaterialSpec materialSpec = new MaterialSpec();
			MaterialSpecKey materialSpecKey = new MaterialSpecKey();
			materialSpecKey.setMaterialSpecName(materialSpecName);
			materialSpecKey.setSiteName(siteName);

			materialSpec = MaterialServiceProxy.getMaterialSpecService()
					.selectByKey(materialSpecKey);			
			int i = 0;			
			for (; i < boxId.size(); i++) {
				CreateInfo materialPacking = new CreateInfo();
				materialPacking.setMaterialPackingName(boxId.get(i));
				materialPacking.setSiteName(siteName);
				materialPacking.setContentMaterialType("MaterialPacking");
				materialPacking.setMaterialPackingType("Box");

				Map<String, Object> bindMap = new HashMap<String, Object>();
				bindMap.put("materialQuantity", EveryBoxQuantity);
				bindMap.put("materialCreateQuantity", EveryBoxQuantity);
				bindMap.put("packingState", "Created");// 标记Box是刚创建的

				bindMap.put("materialType", materialSpec.getMaterialType());
				bindMap.put("materialSpecName", materialSpecName);
				bindMap.put("stockState", "");
				bindMap.put("holdState", "N");
				bindMap.put("areaName", areaName);
				bindMap.put("createUser", eventInfo.getEventUser());
				bindMap.put("createTime", eventInfo.getEventTime());				
				receiveRequestName = receiveRequestName.equals("") ? shipRequestName
						: receiveRequestName;
				receiveRequestDetailName = receiveRequestDetailName.equals("") ? shipRequestDetailName
						: receiveRequestDetailName;

				bindMap.put("receiveRequestName", receiveRequestName);
				bindMap.put("receiveRequestDetailName",
						receiveRequestDetailName);
				//绑定库位和palletid
				bindMap.put("superMaterialPackingName", palletID);

				bindMap.put("makeDate", makeDate);
				bindMap.put("receiveActNo", receiveActNo);
				bindMap.put("reasonCodeType", reasonCodeType);
				bindMap.put("reasonCode", reasonCode);
				if(acttype.equals("MES"))
				{
					bindMap.put("erpLocation", erpreceivelocation);
				}
				else{
					bindMap.put("erpLocation", erpLocation);
				}
				
				bindMap.put("erpFactory", erpFactory);
				bindMap.put("stockInType", "");
				bindMap.put("charge", charge);
				bindMap.put("supplierName", supplierName);
				bindMap.put("npFlag", NPFlag);
				bindMap.put("improvmentFlag", improvmentFlag);

				materialPacking.setUserColumns(bindMap);

				listMaterialPacking.add(materialPacking);

			}

			if (EveryBoxQuantity1 > 0) {
				CreateInfo materialPacking = new CreateInfo();
				Map<String, Object> bindMap = new HashMap<String, Object>();
				bindMap.put("materialQuantity", EveryBoxQuantity1);
				bindMap.put("materialCreateQuantity", EveryBoxQuantity1);
				bindMap.put("packingState", "Created");// 标记Box是刚创建的

				materialPacking = listMaterialPacking.get(boxId.size() - 1);
				materialPacking.setUserColumns(bindMap);

				listMaterialPacking.remove(boxId.size() - 1);
				listMaterialPacking.add(materialPacking);
			}

			MaterialPackingServiceProxy.getMaterialPackingService().create(
					eventInfo, listMaterialPacking);

			lastEventTimeKey = eventInfo.getEventTimeKey();

		} catch (CustomException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return lastEventTimeKey;
	}
	
	

	/*
	 * Name : GenerateMaterialPackingName Desc : This function is
	 * GenerateMaterialPackingName Author : boe cim dev. Date : 2016.01.27
	 */
	
	public static String GenerateBoxList(String siteName,String boxQuantity, String makeDate) throws Exception {

		List<String> boxId;
		boxId = MaterialPackingServiceImpl.generateBoxID("BOXID", siteName,
				boxQuantity, makeDate);
		
		return boxId.get(0);
	}

	public static List<String> generateBoxID(String ruleName, String siteName,
											 String BoxQty, String makeDate,String type,String erpFactory) throws CustomException {
		String newMakeDate = makeDate.replace("-", "");
		//String simpleNewMakeDate = newMakeDate.substring(6, 8);
		String year = newMakeDate.substring(0, 4);
		String month = newMakeDate.substring(4, 6);
		String formattedMonth = String.format("%02d", Integer.parseInt(month));
		String day = newMakeDate.substring(6, 8);
		String formattedDay = String.format("%02d", Integer.parseInt(day));
		List<String> args = new ArrayList<String>();
		// 获取系统当前时间
		// java.util.Calendar c=java.util.Calendar.getInstance();


		if ("1030".equals(erpFactory)) {
			args.add("TC");
		} else {
			args.add("SH");
		}
		args.add(type);
		args.add("00");
		args.add("000");
		args.add(year);
		args.add(formattedMonth);
		args.add(formattedDay);

		//args.add(simpleNewMakeDate);

		List<String> preboxName;
		preboxName = NameServiceProxy.getNameRuleDefService().generateName(ruleName, args, Integer.valueOf(BoxQty));

		//List<String> args1 = new ArrayList<String>();
		// 获取系统当前时间
		// java.util.Calendar c=java.util.Calendar.getInstance();

//		args1.add(preboxName.get(0).toString());
//		boxName = NameServiceProxy.getNameRuleDefService().generateName(
//				"BOXIDNEW", args1, Integer.valueOf(BoxQty));
		return preboxName;

	}

	public static List<String> generateBoxID(String ruleName, String siteName,
			String BoxQty, String makeDate) throws CustomException {
		String newMakeDate = makeDate.replace("-", "");
		String simpleNewMakeDate = newMakeDate.substring(2, 8);

		List<String> args = new ArrayList<String>();
		// 获取系统当前时间
		// java.util.Calendar c=java.util.Calendar.getInstance();

		args.add("B");

		if (siteName.equals("B5")) {
			args.add("B5");
		} else if (siteName.equals("TM1")) {
			args.add("T1");
		}else if (siteName.equals("B10")) {
			args.add("BA");
		}else if (siteName.equals("BMDT")) {
			args.add("BM");
		}else if (siteName.equals("B11")) {
			args.add("BB");
		}else if (siteName.equals("B17")) {
			args.add("BN");
		}else if (siteName.equals("BMOT")) {
			args.add("BO");
		}else if (siteName.equals("BBF1")) {
			args.add("F1");
		} else if ("B12".equals(siteName)) {
			args.add("BC");
		}else if (siteName.equals("B20")) {
			args.add("BJ");
		}
		else{
			args.add(siteName);
		}

		args.add(simpleNewMakeDate);

		List<String> boxName;
		List<String> preboxName;
		preboxName = NameServiceProxy.getNameRuleDefService().generateName(
				"PREBOXID", args, 1);

		List<String> args1 = new ArrayList<String>();
		// 获取系统当前时间
		// java.util.Calendar c=java.util.Calendar.getInstance();

		args1.add(preboxName.get(0).toString());
		boxName = NameServiceProxy.getNameRuleDefService().generateName(
				"BOXIDNEW", args1, Integer.valueOf(BoxQty));
		try {
			return boxName;
		} catch (Throwable e) {
			args = new ArrayList<String>();
			args.add("B");

			if (siteName.equals("B5")) {
				args.add("B5");
			} else if (siteName.equals("TM1")) {
				args.add("T1");
			}else if (siteName.equals("B10")) {
				args.add("BA");
			}else if (siteName.equals("BMDT")) {
				args.add("BM");
			}else if (siteName.equals("B11")) {
				args.add("BB");
			}else if (siteName.equals("B17")) {
				args.add("BN");
			}else if (siteName.equals("BMOT")) {
				args.add("BO");
			}else if (siteName.equals("BBF1")) {
				args.add("F1");
			}else if ("B12".equals(siteName)) {
				args.add("BC");
			}else if (siteName.equals("B20")) {
				args.add("BJ");
			}
			else{
				args.add(siteName);
			}
			args.add(simpleNewMakeDate);
			return NameServiceProxy.getNameRuleDefService().generateName(
					"BOXIDNEW", args, 1);
		}
	}

	/*
	 * Name : Packing Desc : Packing Author : boe cim dev. Date : 2016.01.27
	 */

	public static void ModifyErpLocationByLable(EventInfo eventInfo, String siteName,
			String areaName, String receiveRequestName,
			String receiveRequestDetailName, String materialSpecName,
			String shipRequestName, String shipRequestDetailName,
			String erpLocation, String erpFactory,String acttype) throws Exception {
		try {
			if (!receiveRequestName.equals("")&& !receiveRequestDetailName.equals("")) {
				if(acttype.equals("BMDTOEM")||acttype.equals("ERPReserve")){
						if(receiveRequestName.substring(0, 1).equals("3")){
                    	MaterialReceiveRequestDetail materialShipRequestDetail = new MaterialReceiveRequestDetail();
    					MaterialReceiveRequestDetailKey materialShipRequestDetailKey = new MaterialReceiveRequestDetailKey();	
    					materialShipRequestDetailKey.setReceiveRequestName(receiveRequestName);
    					materialShipRequestDetailKey.setSiteName(siteName);
    					materialShipRequestDetailKey.setReceiveRequestDetailName(receiveRequestDetailName);
                    	materialShipRequestDetail = ReceiveRequestDetailServiceProxy.getReceiveRequestDetailService().selectByKey(materialShipRequestDetailKey);
                    	if (materialShipRequestDetail != null&& !materialShipRequestDetail.getErpLocation().equals(erpLocation)) {
    						com.cim.idm.wmspackage.receiverequestdetail.management.info.SetEventInfo setEventInfo = new com.cim.idm.wmspackage.receiverequestdetail.management.info.SetEventInfo();
    						Map<String, Object> bindMap = new HashMap<String, Object>();
    						bindMap.put("erpLocation", erpLocation);
    						bindMap.put("erpFactory",erpFactory);
    						setEventInfo.setUserColumns(bindMap);
    						ReceiveRequestDetailServiceProxy.getReceiveRequestDetailService().setEvent(materialShipRequestDetailKey, eventInfo,setEventInfo);
    					}
                    }else {
                    	MaterialShipRequestDetail materialShipRequestDetail = new MaterialShipRequestDetail();
        				MaterialShipRequestDetailKey materialShipRequestDetailKey = new MaterialShipRequestDetailKey();
        				materialShipRequestDetailKey
        						.setShipRequestName(receiveRequestName);
        				materialShipRequestDetailKey.setSiteName(siteName);
        				materialShipRequestDetailKey
        						.setShipRequestDetailName(receiveRequestDetailName);

                    	materialShipRequestDetail = MaterialShipRequestDetailServiceProxy
        						.getMaterialShipRequestDetailService().selectByKey(materialShipRequestDetailKey);
                    	if (materialShipRequestDetail != null
        						&& !materialShipRequestDetail.getErpLocation().equals(
        								erpLocation)) {
        					com.cim.idm.wmspackage.materialshiprequestdetail.management.info.NonPrimaryKeyValueInfo nonPrimaryKeyValueInfo = new com.cim.idm.wmspackage.materialshiprequestdetail.management.info.NonPrimaryKeyValueInfo();
        					Map<String, Object> bindMap = new HashMap<String, Object>();
        					bindMap.put("erpLocation", erpLocation);
        					nonPrimaryKeyValueInfo.setUserColumns(bindMap);
        					MaterialShipRequestDetailServiceProxy
        							.getMaterialShipRequestDetailService().setEvent(
        									materialShipRequestDetailKey,
        									nonPrimaryKeyValueInfo);
        				}
                    }													
				}else{
					MaterialReceiveRequestDetail materialReceiveRequestDetail = new MaterialReceiveRequestDetail();
					MaterialReceiveRequestDetailKey materialReceiveRequestDetailKey = new MaterialReceiveRequestDetailKey();
					materialReceiveRequestDetailKey
							.setReceiveRequestName(receiveRequestName);
					materialReceiveRequestDetailKey.setSiteName(siteName);
					materialReceiveRequestDetailKey
							.setReceiveRequestDetailName(receiveRequestDetailName);

					materialReceiveRequestDetail = ReceiveRequestDetailServiceProxy.getReceiveRequestDetailService().selectByKey(materialReceiveRequestDetailKey);
					if (materialReceiveRequestDetail != null&& !materialReceiveRequestDetail.getErpLocation().equals(erpLocation)) {
						com.cim.idm.wmspackage.receiverequestdetail.management.info.SetEventInfo setEventInfo = new com.cim.idm.wmspackage.receiverequestdetail.management.info.SetEventInfo();
						Map<String, Object> bindMap = new HashMap<String, Object>();
						bindMap.put("erpLocation", erpLocation);
						setEventInfo.setUserColumns(bindMap);
						ReceiveRequestDetailServiceProxy.getReceiveRequestDetailService().setEvent(materialReceiveRequestDetailKey, eventInfo,setEventInfo);
					}
				}
				
			} else if (!shipRequestName.equals("")
					&& !shipRequestDetailName.equals("")) {
				MaterialShipRequestDetail materialShipRequestDetail = new MaterialShipRequestDetail();
				MaterialShipRequestDetailKey materialShipRequestDetailKey = new MaterialShipRequestDetailKey();
				materialShipRequestDetailKey
						.setShipRequestName(shipRequestName);
				materialShipRequestDetailKey.setSiteName(siteName);
				materialShipRequestDetailKey
						.setShipRequestDetailName(shipRequestDetailName);

				materialShipRequestDetail = MaterialShipRequestDetailServiceProxy
						.getMaterialShipRequestDetailService().selectByKey(
								materialShipRequestDetailKey);
				if (materialShipRequestDetail != null
						&& !materialShipRequestDetail.getErpLocation().equals(
								erpLocation)) {
					com.cim.idm.wmspackage.materialshiprequestdetail.management.info.NonPrimaryKeyValueInfo nonPrimaryKeyValueInfo = new com.cim.idm.wmspackage.materialshiprequestdetail.management.info.NonPrimaryKeyValueInfo();

					Map<String, Object> bindMap = new HashMap<String, Object>();
					bindMap.put("erpLocation", erpLocation);
					nonPrimaryKeyValueInfo.setUserColumns(bindMap);
					MaterialShipRequestDetailServiceProxy
							.getMaterialShipRequestDetailService().setEvent(
									materialShipRequestDetailKey,
									nonPrimaryKeyValueInfo);
				}
			}

		} catch (IDMFrameDBErrorSignal e) {
			e.printStackTrace();
		}

	}

	
	public static void ModifyErpLocation(EventInfo eventInfo, String siteName,
			String areaName, String receiveRequestName,
			String receiveRequestDetailName, String materialSpecName,
			String shipRequestName, String shipRequestDetailName,
			String erpLocation, String erpFactory) throws Exception {
		try {
			
			if (!receiveRequestName.equals("")
					&& !receiveRequestDetailName.equals("")) {
				
					MaterialReceiveRequestDetail materialReceiveRequestDetail = new MaterialReceiveRequestDetail();
					MaterialReceiveRequestDetailKey materialReceiveRequestDetailKey = new MaterialReceiveRequestDetailKey();
					materialReceiveRequestDetailKey
							.setReceiveRequestName(receiveRequestName);
					materialReceiveRequestDetailKey.setSiteName(siteName);
					materialReceiveRequestDetailKey
							.setReceiveRequestDetailName(receiveRequestDetailName);

					materialReceiveRequestDetail = ReceiveRequestDetailServiceProxy
							.getReceiveRequestDetailService().selectByKey(
									materialReceiveRequestDetailKey);
					if (materialReceiveRequestDetail != null
							&& !materialReceiveRequestDetail.getErpLocation()
									.equals(erpLocation)) {
						com.cim.idm.wmspackage.receiverequestdetail.management.info.SetEventInfo setEventInfo = new com.cim.idm.wmspackage.receiverequestdetail.management.info.SetEventInfo();
						Map<String, Object> bindMap = new HashMap<String, Object>();
						bindMap.put("erpLocation", erpLocation);
						setEventInfo.setUserColumns(bindMap);
						ReceiveRequestDetailServiceProxy
								.getReceiveRequestDetailService().setEvent(
										materialReceiveRequestDetailKey, eventInfo,
										setEventInfo);
					
				}
				
			} else if (!shipRequestName.equals("")
					&& !shipRequestDetailName.equals("")) {
				MaterialShipRequestDetail materialShipRequestDetail = new MaterialShipRequestDetail();
				MaterialShipRequestDetailKey materialShipRequestDetailKey = new MaterialShipRequestDetailKey();
				materialShipRequestDetailKey
						.setShipRequestName(shipRequestName);
				materialShipRequestDetailKey.setSiteName(siteName);
				materialShipRequestDetailKey
						.setShipRequestDetailName(shipRequestDetailName);

				materialShipRequestDetail = MaterialShipRequestDetailServiceProxy
						.getMaterialShipRequestDetailService().selectByKey(
								materialShipRequestDetailKey);
				if (materialShipRequestDetail != null
						&& !materialShipRequestDetail.getErpLocation().equals(
								erpLocation)) {
					com.cim.idm.wmspackage.materialshiprequestdetail.management.info.NonPrimaryKeyValueInfo nonPrimaryKeyValueInfo = new com.cim.idm.wmspackage.materialshiprequestdetail.management.info.NonPrimaryKeyValueInfo();

					Map<String, Object> bindMap = new HashMap<String, Object>();
					bindMap.put("erpLocation", erpLocation);
					nonPrimaryKeyValueInfo.setUserColumns(bindMap);
					MaterialShipRequestDetailServiceProxy
							.getMaterialShipRequestDetailService().setEvent(
									materialShipRequestDetailKey,
									nonPrimaryKeyValueInfo);
				}
			}

		} catch (IDMFrameDBErrorSignal e) {
			e.printStackTrace();
		}

	}
	public static void changeErpLocation(EventInfo eventInfo, String siteName,String receiveRequestName,
			String receiveRequestDetailName,String erpLocation,List<MaterialPackingKey> materialPackingKeyList) throws Exception {
		try {
				
					MaterialReceiveRequestDetail materialReceiveRequestDetail = new MaterialReceiveRequestDetail();
					MaterialReceiveRequestDetailKey materialReceiveRequestDetailKey = new MaterialReceiveRequestDetailKey();
					materialReceiveRequestDetailKey
							.setReceiveRequestName(receiveRequestName);
					materialReceiveRequestDetailKey.setSiteName(siteName);
					materialReceiveRequestDetailKey
							.setReceiveRequestDetailName(receiveRequestDetailName);
					Map<String, Object> bindMap = new HashMap<String, Object>();
					bindMap.put("erpLocation", erpLocation);
					materialReceiveRequestDetail = ReceiveRequestDetailServiceProxy
							.getReceiveRequestDetailService().selectByKey(
									materialReceiveRequestDetailKey);
					if (materialReceiveRequestDetail != null
							&& !materialReceiveRequestDetail.getErpLocation()
									.equals(erpLocation)) {
						com.cim.idm.wmspackage.receiverequestdetail.management.info.SetEventInfo setEventInfo = new com.cim.idm.wmspackage.receiverequestdetail.management.info.SetEventInfo();
						setEventInfo.setUserColumns(bindMap);
						ReceiveRequestDetailServiceProxy.getReceiveRequestDetailService().setEvent(materialReceiveRequestDetailKey, eventInfo,setEventInfo);
					}
						SetEventInfo SetEventInfo = new SetEventInfo();
						SetEventInfo.setUserColumns(bindMap);
						MaterialPackingServiceProxy.getMaterialPackingService().setEvent(materialPackingKeyList, eventInfo, SetEventInfo);
				
				

		} catch (IDMFrameDBErrorSignal e) {
			e.printStackTrace();
			throw e;
		}

	}
	
	public void PDABoxSplit(EventInfo eventInfo, String siteName,
			String origalmaterialPackingName, String materialPackingName,
			String materialquantity, String ActionUser) {
		try {
			MaterialPackingKey materialPackingKey = new MaterialPackingKey();
			materialPackingKey
					.setMaterialPackingName(origalmaterialPackingName);
			materialPackingKey.setSiteName(siteName);
			// 找出原BOX信息
			MaterialPacking materialPackingData = MaterialPackingServiceProxy
					.getMaterialPackingService()
					.selectByKey(materialPackingKey);
			CreateInfo createInfo = new CreateInfo();
			createInfo.setSiteName(siteName);
			createInfo.setMaterialPackingName(materialPackingName);// 新生成的box id
			createInfo.setMaterialPackingType(materialPackingData
					.getMaterialPackingType());
			createInfo.setContentMaterialType(materialPackingData
					.getContentMaterialType());

			Map<String, Object> bindMap = new HashMap<String, Object>();

			// bindMap.put("siteName", siteName);
			// bindMap.put("materialPackingName", materialPackingName);
			// bindMap.put("MaterialPackingType", materialPackingType);
			// bindMap.put("ContentMaterialType", contentMaterialType);
			bindMap.put("MaterialType", materialPackingData.getMaterialType());
			bindMap.put("MaterialSpecName",
					materialPackingData.getMaterialSpecName());
			bindMap.put("SuperMaterialPackingName",
					materialPackingData.getSuperMaterialPackingName());
			bindMap.put("PackingGrade", materialPackingData.getPackingGrade());
			bindMap.put("SubPackingQuantity",
					materialPackingData.getSubPackingQuantity());
			bindMap.put("MaterialCreateQuantity",
					materialPackingData.getMaterialCreateQuantity());
			bindMap.put("MaterialQuantity", Double.parseDouble(materialquantity));// 数量
			bindMap.put("PackingState",materialPackingData.getPackingState() );
			bindMap.put("OldPackingState",
					materialPackingData.getOldStockState());
			bindMap.put("stockState", materialPackingData.getStockState());
			bindMap.put("OldStockState", materialPackingData.getOldStockState());
			//B9对于pcb拆分，拆分后hold，手动解除
			if(siteName.equals("B9")&&materialPackingData.getMaterialSpecName().startsWith("44-977")){
				bindMap.put("HoldState", "Y");
			}else{
			bindMap.put("HoldState", materialPackingData.getHoldState());
			}
			bindMap.put("AreaName", materialPackingData.getAreaName());
			bindMap.put("LocationName", materialPackingData.getLocationName());
			bindMap.put("DurableName", materialPackingData.getDurableName());
			bindMap.put("MaterialProcessGroupName",
					materialPackingData.getMaterialProcessGroupName());
			// bindMap.put("LastEventName", "SplitCreatBox");
			bindMap.put("LastEventTimeKey",
					TimeStampUtil.getCurrentEventTimeKey());
			// bindMap.put("LastEventTime",
			// ConvertUtil.convertToTimeStamp(lastEventTime));
			bindMap.put("LastEventTime", eventInfo.getEventTime());
			// bindMap.put("LastEventUser",
			// materialPackingData.getLastEventUser());
			// bindMap.put("LastEventComment",
			// materialPackingData.getLastEventComment());
			// bindMap.put("CreateTime",
			// ConvertUtil.convertToTimeStamp(createTime));
			bindMap.put("CreateTime", materialPackingData.getCreateTime());
			bindMap.put("CreateUser", materialPackingData.getCreateUser());
			bindMap.put("ReceiveRequestName",
					materialPackingData.getReceiveRequestName());
			bindMap.put("ReceiveRequestDetailName",
					materialPackingData.getReceiveRequestDetailName());
			// bindMap.put("MakeDate",
			// ConvertUtil.convertToTimeStamp(makeDate));
			bindMap.put("MakeDate", materialPackingData.getMakeDate());
			bindMap.put("expiringDate", materialPackingData.getExpiringDate());
			bindMap.put("ReceiveActNo", materialPackingData.getReceiveActNo());
			// bindMap.put("ReceiveTime",
			// ConvertUtil.convertToTimeStamp(receiveTime));
			bindMap.put("ReceiveTime", materialPackingData.getReceiveTime());
			bindMap.put("ReceiveUser", materialPackingData.getReceiveUser());
			bindMap.put("ShipRequestName",
					materialPackingData.getShipRequestName());
			bindMap.put("ShipRequestDetailName",
					materialPackingData.getShipRequestDetailName());
			// bindMap.put("ShipTime",
			// ConvertUtil.convertToTimeStamp(shipTime));
			bindMap.put("ShipTime", materialPackingData.getShipTime());
			bindMap.put("ShipUser", materialPackingData.getShipUser());
			bindMap.put("ReasonCodeType",
					materialPackingData.getReasonCodeType());
			bindMap.put("ReasonCode", materialPackingData.getReasonCode());
			bindMap.put("ErpLocation", materialPackingData.getErpLocation());
			bindMap.put("EtcState", materialPackingData.getEtcState());
			bindMap.put("ErpFactory", materialPackingData.getErpFactory());
			bindMap.put("StockInType", materialPackingData.getStockInType());
			// add item
			bindMap.put("oqaResult", materialPackingData.getOqaResult());
			bindMap.put("oqaResultState",
					materialPackingData.getOqaResultState());
			bindMap.put("charge", materialPackingData.getCharge());
			bindMap.put("supplierName", materialPackingData.getSupplierName());
			bindMap.put("unDoID", materialPackingData.getUnDoID());
			bindMap.put("unDoDetailName",
					materialPackingData.getUnDoDetailName());
			bindMap.put("erpEventTime", materialPackingData.getErpEventTime());
			createInfo.setUserColumns(bindMap);
			MaterialPackingServiceProxy.getMaterialPackingService().create(
					eventInfo, createInfo);
			// 写SplitMergeTable
			/*
			 * String strCondition =
			 * "INSERT INTO  BS_MATERIALPACKINGSPLITMERGE " +
			 * "(SITENAME,MATERIALPACKINGNAME,DESTMATERIALPACKINGNAMENAME,ACTIONTIMEKEY,ACTIONTYPE,PACKINGGRADE,ACTIONTIME,ACTIONUSER,MATERIALQUANTITY,DESTMATERIALQUANTITY)"
			 * + "VALUES "+ "('"+siteName+"','"+materialPackingName+"','"+
			 * origalmaterialPackingName
			 * +"','"+TimeStampUtil.getCurrentEventTimeKey()+
			 * ",'Split'"+"','"+TimeStampUtil
			 * .getCurrentEventTimeKey()+"','"+ActionUser
			 * +"','"+materialquantity+
			 * "','"+materialPackingData.getMaterialQuantity()+"');";
			 */

			String strCondition = "INSERT INTO  BS_MATERIALPACKINGSPLITMERGE (SITENAME,MATERIALPACKINGNAME,DESTMATERIALPACKINGNAMENAME,"
					+ "ACTIONTIMEKEY,ACTIONTYPE,PACKINGGRADE,ACTIONTIME,ACTIONUSER,MATERIALQUANTITY,DESTMATERIALQUANTITY)"
					+ "VALUES (?,?,?,?,?,?,?,?,?,?)";

			/*
			 * Map<String, Object> bindMapSql = new HashMap<String, Object>();
			 * bindMapSql.put("SITENAME", siteName);
			 * bindMapSql.put("MATERIALPACKINGNAME", materialPackingName);
			 * bindMapSql.put("DESTMATERIALPACKINGNAMENAME",
			 * origalmaterialPackingName); bindMapSql.put("ACTIONTIMEKEY",
			 * TimeStampUtil.getCurrentEventTimeKey().toString());
			 * bindMapSql.put("ACTIONTYPE", "Split");
			 * bindMapSql.put("PACKINGGRADE",
			 * materialPackingData.getPackingGrade());
			 * bindMapSql.put("ACTIONTIME",
			 * TimeStampUtil.getCurrentTimestamp());
			 * bindMapSql.put("ACTIONUSER", ActionUser);
			 * bindMapSql.put("MATERIALQUANTITY",
			 * Double.parseDouble(materialquantity));
			 * bindMapSql.put("DESTMATERIALQUANTITY",
			 * materialPackingData.getMaterialQuantity());
			 */

			// Object[] bind= new
			// Object[]{siteName,materialPackingName,origalmaterialPackingName,TimeStampUtil.getCurrentEventTimeKey().toString(),"Split",
			// materialPackingData.getPackingGrade(),TimeStampUtil.getCurrentTimestamp(),ActionUser,Double.parseDouble(materialquantity),materialPackingData.getMaterialQuantity()};
			Object[] bind = new Object[] { siteName, origalmaterialPackingName,
					materialPackingName,
					TimeStampUtil.getCurrentEventTimeKey().toString(), "Split",
					materialPackingData.getPackingGrade(),
					TimeStampUtil.getCurrentTimestamp(), ActionUser,
					materialPackingData.getMaterialQuantity(),
					Double.parseDouble(materialquantity) };
			IDMFrameServiceProxy.getSqlTemplate().update(strCondition, bind);
		} catch (IDMFrameDBErrorSignal e) {
			e.printStackTrace();
		}
	}
	
	//拆pallet
	public void PDAPalletSplitByPallet(EventInfo eventInfo, String siteName,
			String origalmaterialPackingName, String materialPackingName,
			String materialquantity, String ActionUser) {
		try {
			MaterialPackingKey materialPackingKey = new MaterialPackingKey();
			materialPackingKey
					.setMaterialPackingName(origalmaterialPackingName);
			materialPackingKey.setSiteName(siteName);
			// 找出原BOX信息
			MaterialPacking materialPackingData = MaterialPackingServiceProxy
					.getMaterialPackingService()
					.selectByKey(materialPackingKey);
			CreateInfo createInfo = new CreateInfo();
			createInfo.setSiteName(siteName);
			createInfo.setMaterialPackingName(materialPackingName);// 新生成的box id
			createInfo.setMaterialPackingType(materialPackingData
					.getMaterialPackingType());
			createInfo.setContentMaterialType(materialPackingData
					.getContentMaterialType());

			Map<String, Object> bindMap = new HashMap<String, Object>();

			// bindMap.put("siteName", siteName);
			// bindMap.put("materialPackingName", materialPackingName);
			// bindMap.put("MaterialPackingType", materialPackingType);
			// bindMap.put("ContentMaterialType", contentMaterialType);
			bindMap.put("MaterialType", materialPackingData.getMaterialType());
			bindMap.put("MaterialSpecName",
					materialPackingData.getMaterialSpecName());
			bindMap.put("SuperMaterialPackingName",
					materialPackingData.getSuperMaterialPackingName());
			bindMap.put("PackingGrade", materialPackingData.getPackingGrade());
			bindMap.put("SubPackingQuantity",
					materialPackingData.getSubPackingQuantity());
			bindMap.put("MaterialCreateQuantity",
					materialPackingData.getMaterialCreateQuantity());
			bindMap.put("MaterialQuantity", Double.parseDouble(materialquantity));// 数量
			bindMap.put("PackingState",materialPackingData.getPackingState() );
			bindMap.put("OldPackingState",
					materialPackingData.getOldStockState());
			bindMap.put("stockState", materialPackingData.getStockState());
			bindMap.put("OldStockState", materialPackingData.getOldStockState());
			bindMap.put("HoldState", materialPackingData.getHoldState());
			bindMap.put("AreaName", materialPackingData.getAreaName());
			bindMap.put("LocationName", materialPackingData.getLocationName());
			bindMap.put("DurableName", materialPackingData.getDurableName());
			bindMap.put("MaterialProcessGroupName",
					materialPackingData.getMaterialProcessGroupName());
			// bindMap.put("LastEventName", "SplitCreatBox");
			bindMap.put("LastEventTimeKey",
					TimeStampUtil.getCurrentEventTimeKey());
			// bindMap.put("LastEventTime",
			// ConvertUtil.convertToTimeStamp(lastEventTime));
			bindMap.put("LastEventTime", materialPackingData.getLastEventTime());
			// bindMap.put("LastEventUser",
			// materialPackingData.getLastEventUser());
			// bindMap.put("LastEventComment",
			// materialPackingData.getLastEventComment());
			// bindMap.put("CreateTime",
			// ConvertUtil.convertToTimeStamp(createTime));
			bindMap.put("CreateTime", materialPackingData.getCreateTime());
			bindMap.put("CreateUser", materialPackingData.getCreateUser());
			bindMap.put("ReceiveRequestName",
					materialPackingData.getReceiveRequestName());
			bindMap.put("ReceiveRequestDetailName",
					materialPackingData.getReceiveRequestDetailName());
			// bindMap.put("MakeDate",
			// ConvertUtil.convertToTimeStamp(makeDate));
			bindMap.put("MakeDate", materialPackingData.getMakeDate());
			bindMap.put("ReceiveActNo", materialPackingData.getReceiveActNo());
			// bindMap.put("ReceiveTime",
			// ConvertUtil.convertToTimeStamp(receiveTime));
			bindMap.put("ReceiveTime", materialPackingData.getReceiveTime());
			bindMap.put("ReceiveUser", materialPackingData.getReceiveUser());
			bindMap.put("ShipRequestName",
					materialPackingData.getShipRequestName());
			bindMap.put("ShipRequestDetailName",
					materialPackingData.getShipRequestDetailName());
			// bindMap.put("ShipTime",
			// ConvertUtil.convertToTimeStamp(shipTime));
			bindMap.put("ShipTime", materialPackingData.getShipTime());
			bindMap.put("ShipUser", materialPackingData.getShipUser());
			bindMap.put("ReasonCodeType",
					materialPackingData.getReasonCodeType());
			bindMap.put("ReasonCode", materialPackingData.getReasonCode());
			bindMap.put("ErpLocation", materialPackingData.getErpLocation());
			bindMap.put("EtcState", materialPackingData.getEtcState());
			bindMap.put("ErpFactory", materialPackingData.getErpFactory());
			bindMap.put("StockInType", materialPackingData.getStockInType());
			// add item
			bindMap.put("oqaResult", materialPackingData.getOqaResult());
			bindMap.put("oqaResultState",
					materialPackingData.getOqaResultState());
			bindMap.put("charge", materialPackingData.getCharge());
			bindMap.put("supplierName", materialPackingData.getSupplierName());
			bindMap.put("unDoID", materialPackingData.getUnDoID());
			bindMap.put("unDoDetailName",
					materialPackingData.getUnDoDetailName());
			bindMap.put("erpEventTime", materialPackingData.getErpEventTime());
			createInfo.setUserColumns(bindMap);
			MaterialPackingServiceProxy.getMaterialPackingService().create(
					eventInfo, createInfo);
			// 写SplitMergeTable
			/*
			 * String strCondition =
			 * "INSERT INTO  BS_MATERIALPACKINGSPLITMERGE " +
			 * "(SITENAME,MATERIALPACKINGNAME,DESTMATERIALPACKINGNAMENAME,ACTIONTIMEKEY,ACTIONTYPE,PACKINGGRADE,ACTIONTIME,ACTIONUSER,MATERIALQUANTITY,DESTMATERIALQUANTITY)"
			 * + "VALUES "+ "('"+siteName+"','"+materialPackingName+"','"+
			 * origalmaterialPackingName
			 * +"','"+TimeStampUtil.getCurrentEventTimeKey()+
			 * ",'Split'"+"','"+TimeStampUtil
			 * .getCurrentEventTimeKey()+"','"+ActionUser
			 * +"','"+materialquantity+
			 * "','"+materialPackingData.getMaterialQuantity()+"');";
			 */

			String strCondition = "INSERT INTO  BS_MATERIALPACKINGSPLITMERGE (SITENAME,MATERIALPACKINGNAME,DESTMATERIALPACKINGNAMENAME,"
					+ "ACTIONTIMEKEY,ACTIONTYPE,PACKINGGRADE,ACTIONTIME,ACTIONUSER,MATERIALQUANTITY,DESTMATERIALQUANTITY)"
					+ "VALUES (?,?,?,?,?,?,?,?,?,?)";

			/*
			 * Map<String, Object> bindMapSql = new HashMap<String, Object>();
			 * bindMapSql.put("SITENAME", siteName);
			 * bindMapSql.put("MATERIALPACKINGNAME", materialPackingName);
			 * bindMapSql.put("DESTMATERIALPACKINGNAMENAME",
			 * origalmaterialPackingName); bindMapSql.put("ACTIONTIMEKEY",
			 * TimeStampUtil.getCurrentEventTimeKey().toString());
			 * bindMapSql.put("ACTIONTYPE", "Split");
			 * bindMapSql.put("PACKINGGRADE",
			 * materialPackingData.getPackingGrade());
			 * bindMapSql.put("ACTIONTIME",
			 * TimeStampUtil.getCurrentTimestamp());
			 * bindMapSql.put("ACTIONUSER", ActionUser);
			 * bindMapSql.put("MATERIALQUANTITY",
			 * Double.parseDouble(materialquantity));
			 * bindMapSql.put("DESTMATERIALQUANTITY",
			 * materialPackingData.getMaterialQuantity());
			 */

			// Object[] bind= new
			// Object[]{siteName,materialPackingName,origalmaterialPackingName,TimeStampUtil.getCurrentEventTimeKey().toString(),"Split",
			// materialPackingData.getPackingGrade(),TimeStampUtil.getCurrentTimestamp(),ActionUser,Double.parseDouble(materialquantity),materialPackingData.getMaterialQuantity()};
			Object[] bind = new Object[] { siteName, origalmaterialPackingName,
					materialPackingName,
					TimeStampUtil.getCurrentEventTimeKey().toString(), "Split",
					materialPackingData.getPackingGrade(),
					TimeStampUtil.getCurrentTimestamp(), ActionUser,
					materialPackingData.getMaterialQuantity(),
					Double.parseDouble(materialquantity) };
			IDMFrameServiceProxy.getSqlTemplate().update(strCondition, bind);
		} catch (IDMFrameDBErrorSignal e) {
			e.printStackTrace();
		}
	}
	
	public void PDAPalletSplit(EventInfo eventInfo, String siteName,
			String origalmaterialPackingName, String materialPackingName,
			String materialquantity, String ActionUser) {
		try {
			MaterialPackingKey materialPackingKey = new MaterialPackingKey();
			materialPackingKey
					.setMaterialPackingName(origalmaterialPackingName);
			materialPackingKey.setSiteName(siteName);
			// 找出原BOX信息
			MaterialPacking materialPackingData = MaterialPackingServiceProxy
					.getMaterialPackingService()
					.selectByKey(materialPackingKey);
			CreateInfo createInfo = new CreateInfo();
			createInfo.setSiteName(siteName);
			createInfo.setMaterialPackingName(materialPackingName);// 新生成的Pallet id
			createInfo.setMaterialPackingType(materialPackingData
					.getMaterialPackingType());
			createInfo.setContentMaterialType(materialPackingData
					.getContentMaterialType());

			Map<String, Object> bindMap = new HashMap<String, Object>();

			// bindMap.put("siteName", siteName);
			// bindMap.put("materialPackingName", materialPackingName);
			// bindMap.put("MaterialPackingType", materialPackingType);
			// bindMap.put("ContentMaterialType", contentMaterialType);
			bindMap.put("MaterialType", materialPackingData.getMaterialType());
			bindMap.put("MaterialSpecName",
					materialPackingData.getMaterialSpecName());
			bindMap.put("SuperMaterialPackingName",
					materialPackingName);
			bindMap.put("PackingGrade", materialPackingData.getPackingGrade());
			bindMap.put("SubPackingQuantity",
					materialPackingData.getSubPackingQuantity());
			bindMap.put("MaterialCreateQuantity",
					materialPackingData.getMaterialCreateQuantity());
			bindMap.put("MaterialQuantity", Double.parseDouble(materialquantity));// 数量
			bindMap.put("PackingState",materialPackingData.getPackingState() );
			bindMap.put("OldPackingState",
					materialPackingData.getOldStockState());
			bindMap.put("stockState", materialPackingData.getStockState());
			bindMap.put("OldStockState", materialPackingData.getOldStockState());
			bindMap.put("HoldState", materialPackingData.getHoldState());
			bindMap.put("AreaName", materialPackingData.getAreaName());
			bindMap.put("LocationName", materialPackingData.getLocationName());
			bindMap.put("DurableName", materialPackingData.getDurableName());
			bindMap.put("MaterialProcessGroupName",
					materialPackingData.getMaterialProcessGroupName());
			// bindMap.put("LastEventName", "SplitCreatBox");
			bindMap.put("LastEventTimeKey",
					TimeStampUtil.getCurrentEventTimeKey());
			// bindMap.put("LastEventTime",
			// ConvertUtil.convertToTimeStamp(lastEventTime));
			bindMap.put("LastEventTime", materialPackingData.getLastEventTime());
			// bindMap.put("LastEventUser",
			// materialPackingData.getLastEventUser());
			// bindMap.put("LastEventComment",
			// materialPackingData.getLastEventComment());
			// bindMap.put("CreateTime",
			// ConvertUtil.convertToTimeStamp(createTime));
			bindMap.put("CreateTime", materialPackingData.getCreateTime());
			bindMap.put("CreateUser", materialPackingData.getCreateUser());
			bindMap.put("ReceiveRequestName",
					materialPackingData.getReceiveRequestName());
			bindMap.put("ReceiveRequestDetailName",
					materialPackingData.getReceiveRequestDetailName());
			// bindMap.put("MakeDate",
			// ConvertUtil.convertToTimeStamp(makeDate));
			bindMap.put("MakeDate", materialPackingData.getMakeDate());
			bindMap.put("ReceiveActNo", materialPackingData.getReceiveActNo());
			// bindMap.put("ReceiveTime",
			// ConvertUtil.convertToTimeStamp(receiveTime));
			bindMap.put("ReceiveTime", materialPackingData.getReceiveTime());
			bindMap.put("ReceiveUser", materialPackingData.getReceiveUser());
			bindMap.put("ShipRequestName",
					materialPackingData.getShipRequestName());
			bindMap.put("ShipRequestDetailName",
					materialPackingData.getShipRequestDetailName());
			// bindMap.put("ShipTime",
			// ConvertUtil.convertToTimeStamp(shipTime));
			bindMap.put("ShipTime", materialPackingData.getShipTime());
			bindMap.put("ShipUser", materialPackingData.getShipUser());
			bindMap.put("ReasonCodeType",
					materialPackingData.getReasonCodeType());
			bindMap.put("ReasonCode", materialPackingData.getReasonCode());
			bindMap.put("ErpLocation", materialPackingData.getErpLocation());
			bindMap.put("EtcState", materialPackingData.getEtcState());
			bindMap.put("ErpFactory", materialPackingData.getErpFactory());
			bindMap.put("StockInType", materialPackingData.getStockInType());
			// add item
			bindMap.put("oqaResult", materialPackingData.getOqaResult());
			bindMap.put("oqaResultState",
					materialPackingData.getOqaResultState());
			bindMap.put("charge", materialPackingData.getCharge());
			bindMap.put("supplierName", materialPackingData.getSupplierName());
			bindMap.put("unDoID", materialPackingData.getUnDoID());
			bindMap.put("unDoDetailName",
					materialPackingData.getUnDoDetailName());
			bindMap.put("erpEventTime", materialPackingData.getErpEventTime());
			createInfo.setUserColumns(bindMap);
			MaterialPackingServiceProxy.getMaterialPackingService().create(
					eventInfo, createInfo);
			// 写SplitMergeTable
			/*
			 * String strCondition =
			 * "INSERT INTO  BS_MATERIALPACKINGSPLITMERGE " +
			 * "(SITENAME,MATERIALPACKINGNAME,DESTMATERIALPACKINGNAMENAME,ACTIONTIMEKEY,ACTIONTYPE,PACKINGGRADE,ACTIONTIME,ACTIONUSER,MATERIALQUANTITY,DESTMATERIALQUANTITY)"
			 * + "VALUES "+ "('"+siteName+"','"+materialPackingName+"','"+
			 * origalmaterialPackingName
			 * +"','"+TimeStampUtil.getCurrentEventTimeKey()+
			 * ",'Split'"+"','"+TimeStampUtil
			 * .getCurrentEventTimeKey()+"','"+ActionUser
			 * +"','"+materialquantity+
			 * "','"+materialPackingData.getMaterialQuantity()+"');";
			 */

			String strCondition = "INSERT INTO  BS_MATERIALPACKINGSPLITMERGE (SITENAME,MATERIALPACKINGNAME,DESTMATERIALPACKINGNAMENAME,"
					+ "ACTIONTIMEKEY,ACTIONTYPE,PACKINGGRADE,ACTIONTIME,ACTIONUSER,MATERIALQUANTITY,DESTMATERIALQUANTITY)"
					+ "VALUES (?,?,?,?,?,?,?,?,?,?)";

			/*
			 * Map<String, Object> bindMapSql = new HashMap<String, Object>();
			 * bindMapSql.put("SITENAME", siteName);
			 * bindMapSql.put("MATERIALPACKINGNAME", materialPackingName);
			 * bindMapSql.put("DESTMATERIALPACKINGNAMENAME",
			 * origalmaterialPackingName); bindMapSql.put("ACTIONTIMEKEY",
			 * TimeStampUtil.getCurrentEventTimeKey().toString());
			 * bindMapSql.put("ACTIONTYPE", "Split");
			 * bindMapSql.put("PACKINGGRADE",
			 * materialPackingData.getPackingGrade());
			 * bindMapSql.put("ACTIONTIME",
			 * TimeStampUtil.getCurrentTimestamp());
			 * bindMapSql.put("ACTIONUSER", ActionUser);
			 * bindMapSql.put("MATERIALQUANTITY",
			 * Double.parseDouble(materialquantity));
			 * bindMapSql.put("DESTMATERIALQUANTITY",
			 * materialPackingData.getMaterialQuantity());
			 */

			// Object[] bind= new
			// Object[]{siteName,materialPackingName,origalmaterialPackingName,TimeStampUtil.getCurrentEventTimeKey().toString(),"Split",
			// materialPackingData.getPackingGrade(),TimeStampUtil.getCurrentTimestamp(),ActionUser,Double.parseDouble(materialquantity),materialPackingData.getMaterialQuantity()};
			Object[] bind = new Object[] { siteName, origalmaterialPackingName,
					materialPackingName,
					TimeStampUtil.getCurrentEventTimeKey().toString(), "Split",
					materialPackingData.getPackingGrade(),
					TimeStampUtil.getCurrentTimestamp(), ActionUser,
					materialPackingData.getMaterialQuantity(),
					Double.parseDouble(materialquantity) };
			IDMFrameServiceProxy.getSqlTemplate().update(strCondition, bind);
		} catch (IDMFrameDBErrorSignal e) {
			e.printStackTrace();
		}
	}

	public void PDAOrigalBoxSplit(EventInfo eventInfo, String siteName,
			String origalmaterialPackingName) {
		try {
			// 更新原BOX信息；
			MaterialPackingKey origalmaterialPackingKey = new MaterialPackingKey();
			origalmaterialPackingKey
					.setMaterialPackingName(origalmaterialPackingName);
			origalmaterialPackingKey.setSiteName(siteName);
			SetEventInfo setEventInfo = new SetEventInfo();
			Map<String, Object> origalbindMap = new HashMap<String, Object>();
			origalbindMap.put("PackingState", "Emptied");
			origalbindMap.put("MaterialQuantity", Double.parseDouble("0"));// 数量
			setEventInfo.setUserColumns(origalbindMap);
			MaterialPackingServiceProxy.getMaterialPackingService().setEvent(
					origalmaterialPackingKey, eventInfo, setEventInfo);

		} catch (IDMFrameDBErrorSignal e) {
			e.printStackTrace();
		}
	}

	public void PDAOrigalPalletSplit(EventInfo eventInfo, String siteName,
			String origalmaterialPackingName,String smaterialQuantity) {
		try {
			// 更新原BOX信息；
			MaterialPackingKey origalmaterialPackingKey = new MaterialPackingKey();
			origalmaterialPackingKey
					.setMaterialPackingName(origalmaterialPackingName);
			origalmaterialPackingKey.setSiteName(siteName);
			SetEventInfo setEventInfo = new SetEventInfo();
			Map<String, Object> origalbindMap = new HashMap<String, Object>();
			//origalbindMap.put("PackingState", "Emptied");
			origalbindMap.put("MaterialQuantity",smaterialQuantity);// 数量
			setEventInfo.setUserColumns(origalbindMap);
			MaterialPackingServiceProxy.getMaterialPackingService().setEvent(
					origalmaterialPackingKey, eventInfo, setEventInfo);

		} catch (IDMFrameDBErrorSignal e) {
			e.printStackTrace();
		}
	}
	
	public void checkActState( String receiveActNo)throws Exception {
		try{
			String sql2 = "SELECT * FROM materialpacking "
					+ "WHERE  receiveActNo=:receiveActNo and erpstate='ERPSUCCESS' ";

			Map<String, Object> bindMap3 = new HashMap<String, Object>();
			bindMap3.put("receiveActNo", receiveActNo);

			List<Map<String, Object>> queryResult2 = IDMFrameServiceProxy
					.getSqlTemplate()
					.queryForList(sql2, bindMap3);
			if (queryResult2.size() > 0)
			{
				throw new  CustomException("AccoutTimeOut","","");
			}
			String sql="SELECT RECEIVEACTSTATE FROM MATERIALRECEIVEACT WHERE RECEIVEACTNO=:receiveActNo FOR UPDATE";
			Map<String, Object> bindMap1 = new HashMap<String, Object>();
			bindMap1.put("receiveActNo", receiveActNo);
			List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
					.getSqlTemplate()
					.queryForList(sql, bindMap1);
			if(!(sqlResult.size()==0||sqlResult.get(0).get("RECEIVEACTSTATE").toString().equals("Created")))
			{
				throw new CustomException("ACTSTATEERROR","","");
			}
			}catch (Exception ex) {
				 ex.printStackTrace();
				 throw ex;
			}	
		}
	public String  findActNo( EventInfo eventInfo, String receiveRequestName,String siteName,String actType)throws Exception {
		try{
			String sql="SELECT RECEIVEACTNO FROM MATERIALRECEIVEACT WHERE RECEIVEREQUESTNAME=:receiveRequestName AND RECEIVEACTSTATE= 'Created' AND ACTTYPE=:actType ";
			Map<String, Object> bindMap1 = new HashMap<String, Object>();
			bindMap1.put("receiveRequestName", receiveRequestName);
			bindMap1.put("actType", actType);
			List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
					.getSqlTemplate()
					.queryForList(sql, bindMap1);
			String receiveActNo="";
			if(sqlResult.size()==0)
			{
				receiveActNo=com.cim.idm.mwmsextend.materialreceiverequest.service.MaterialReceiveRequestServiceImpl.GenerateMaterialReceiveRequestName("","", siteName, actType, "","");
				com.cim.idm.mwmsextend.materialreceiverequest.service.MaterialReceiveRequestServiceImpl.CreateMaterialRRActByLabel(eventInfo,siteName, receiveRequestName, receiveActNo,actType);
				return receiveActNo;
			}
			else
			{
				String sql2 = "SELECT * FROM materialpacking "
						+ "WHERE sitename = :sitename AND receiveRequestName = :receiveRequestName  and receiveActNo=:receiveActNo and erpstate='ERPSUCCESS' ";

				Map<String, Object> bindMap3 = new HashMap<String, Object>();
				bindMap3.put("sitename", siteName);
				bindMap3.put("receiveRequestName", receiveRequestName);
				bindMap3.put("receiveActNo", sqlResult.get(0).get("RECEIVEACTNO").toString());

				List<Map<String, Object>> queryResult2 = IDMFrameServiceProxy
						.getSqlTemplate()
						.queryForList(sql2, bindMap3);
				if (queryResult2.size() > 0)
				{
					throw new  CustomException("AccoutTimeOut","","");
				}
				return sqlResult.get(0).get("RECEIVEACTNO").toString();
			}
			}catch (Exception ex) {
				 ex.printStackTrace();
				 throw ex;
			}	
		}
	
	public String  findActNoByShipRequest( EventInfo eventInfo, String ShipRequestName,String siteName)throws Exception {
		try{
			String sql="SELECT RECEIVEACTNO FROM MATERIALRECEIVEACT WHERE RECEIVEREQUESTNAME=:receiveRequestName AND RECEIVEACTSTATE= 'Created' ";
			Map<String, Object> bindMap1 = new HashMap<String, Object>();
			bindMap1.put("receiveRequestName", ShipRequestName);
			List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
					.getSqlTemplate()
					.queryForList(sql, bindMap1);
			String receiveActNo="";
			if(sqlResult.size()==0)
			{
				String actType=getShipRequestActType(ShipRequestName);
				receiveActNo=com.cim.idm.mwmsextend.materialreceiverequest.service.MaterialReceiveRequestServiceImpl.GenerateMaterialReceiveRequestName("","", siteName, actType, "","");
				com.cim.idm.mwmsextend.materialreceiverequest.service.MaterialReceiveRequestServiceImpl.CreateMaterialRRActByLabel(eventInfo,siteName, ShipRequestName, receiveActNo,actType);
				return receiveActNo;
			}
			else
			{
				return sqlResult.get(0).get("RECEIVEACTNO").toString();
			}
			}catch (Exception ex) {
				 ex.printStackTrace();
				 throw ex;
			}	
		}
	public String  findActNoByOEMShipRequest( EventInfo eventInfo, String ShipRequestName,String siteName)throws Exception {
		try{
			String sql="SELECT RECEIVEACTNO FROM MATERIALRECEIVEACT WHERE RECEIVEREQUESTNAME=:receiveRequestName AND RECEIVEACTSTATE= 'Created' AND ACTTYPE='POOEM' ";
			Map<String, Object> bindMap1 = new HashMap<String, Object>();
			bindMap1.put("receiveRequestName", ShipRequestName);
			List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
					.getSqlTemplate()
					.queryForList(sql, bindMap1);
			String receiveActNo="";
			if(sqlResult.size()==0)
			{
				String actType="POOEM";
				receiveActNo=com.cim.idm.mwmsextend.materialreceiverequest.service.MaterialReceiveRequestServiceImpl.GenerateMaterialReceiveRequestName("","", siteName, actType, "","");
				com.cim.idm.mwmsextend.materialreceiverequest.service.MaterialReceiveRequestServiceImpl.CreateMaterialRRActByLabel(eventInfo,siteName, ShipRequestName, receiveActNo,actType);
				return receiveActNo;
			}
			else
			{
				return sqlResult.get(0).get("RECEIVEACTNO").toString();
			}
			}catch (Exception ex) {
				 ex.printStackTrace();
				 throw ex;
			}	
		}
	
	public String  findActNoForPCBA( EventInfo eventInfo, String receiveRequestName,String siteName,String actType)throws Throwable {
		try{
			String sql="SELECT RECEIVEACTNO FROM MATERIALRECEIVEACT WHERE RECEIVEREQUESTNAME=:receiveRequestName AND RECEIVEACTSTATE= 'Created' AND ACTTYPE=:actType ";
			Map<String, Object> bindMap1 = new HashMap<String, Object>();
			bindMap1.put("receiveRequestName", receiveRequestName);
			bindMap1.put("actType", actType);
			List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
					.getSqlTemplate()
					.queryForList(sql, bindMap1);
			String receiveActNo="";
			if(sqlResult.size()==0)
			{
				SimpleDateFormat sd = new SimpleDateFormat("yyyyMMdd");
				String tranactionNo = sd.format(new Date())+"001";
				receiveActNo=com.cim.idm.mwmsextend.materialpacking.service.MaterialPackingServiceImpl.generateShipRequestDetailName(tranactionNo);
				receiveActNo=receiveRequestName+receiveActNo.substring(11);//pcba收货，抬头文本为流水码加序列号
				com.cim.idm.mwmsextend.materialreceiverequest.service.MaterialReceiveRequestServiceImpl.CreateMaterialRRActByLabel(eventInfo,siteName, receiveRequestName, receiveActNo,actType);
				return receiveActNo;
			}
			else
			{
				String sql2 = "SELECT * FROM materialpacking "
						+ "WHERE sitename = :sitename AND receiveRequestName = :receiveRequestName  and receiveActNo=:receiveActNo and erpstate='ERPSUCCESS' ";

				Map<String, Object> bindMap3 = new HashMap<String, Object>();
				bindMap3.put("sitename", siteName);
				bindMap3.put("receiveRequestName", receiveRequestName);
				bindMap3.put("receiveActNo", sqlResult.get(0).get("RECEIVEACTNO").toString());

				List<Map<String, Object>> queryResult2 = IDMFrameServiceProxy
						.getSqlTemplate()
						.queryForList(sql2, bindMap3);
				if (queryResult2.size() > 0)
				{
					throw new  CustomException("AccoutTimeOut","","");
				}
				return sqlResult.get(0).get("RECEIVEACTNO").toString();
			}
			}catch (Exception ex) {
				 ex.printStackTrace();
				 throw ex;
			}	
		}
	
	// /*
	// * Name : createXmlByList
	// * Desc : This function is createXml List
	// * Author : AIM Systems, Inc
	// * Date : 2011.01.20
	// */
	// public static String createXmlByList(SqlCursorItemReader reader, String
	// messageName,
	// String sourceSubject,
	// String targetSubject,
	// String transactionId,
	// String queryID, String version) throws Exception {
	//
	// Document doc = new Document();
	// Element message = new Element("Message");
	// Element header = new Element("Header");
	// header.addContent(new Element("MESSAGENAME").setText(messageName));
	// header.addContent(new Element("SOURCESUBJECT").setText(sourceSubject));
	// header.addContent(new Element("TARGETSUBJECT").setText(targetSubject));
	// header.addContent(new Element("TRANSACTIONID").setText(transactionId));
	// message.addContent(header);
	//
	// Element body = new Element("Body");
	// body.addContent(new Element("QUERYID").setText(queryID));
	// body.addContent(new Element("VERSION").setText(version));
	// Element dataList = new Element("DATALIST");
	//
	// reader.open();
	// int dataSize = 0;
	// reader.setListMapper();
	// reader.setAppendSpace("          ");
	// while(true)
	// {
	// try {
	// ListOrderedMap orderMap = (ListOrderedMap)reader.read();
	// if (orderMap == null) break;
	// MapIterator map = orderMap.mapIterator();
	// dataSize++;
	// Element data = new Element("DATA");
	// while (map.hasNext()) {
	// String Key = (String) map.next();
	// String value = null;
	// if (map.getValue() == null) {
	// value = "";
	// } else if (map.getValue() instanceof String){
	// value = (String) map.getValue();
	// }else{
	// value = map.getValue().toString();
	// }
	// data.addContent(new Element(Key).setText(value));
	// }
	// dataList.addContent(data);
	// orderMap.clear();
	// } catch (Exception e) {
	// break;
	// }
	// }
	// reader.close();
	// body.addContent(dataList);
	// message.addContent(body);
	// Element returnElement = new Element("Return");
	// returnElement.addContent(new
	// Element(SMessageUtil.Result_ReturnCode).setText("0"));
	// returnElement.addContent(new Element(SMessageUtil.Result_ErrorMessage));
	// message.addContent(returnElement);
	// doc.setRootElement(message);
	// log.info(">> Create Message : " + dataSize);
	// log.info("After - createXml");
	//
	// String sXmlMsg = JdomUtils.toString(doc);
	// return sXmlMsg;
	// }

	/*
	 * Name : generateBoxName Desc : This function is generateBoxName
	 */
	public static String generateBoxName(String ruleName, String quantity,
			String SiteName, String receiveActNo, String line,
			String revisionCode) throws CustomException {
		List<String> args = new ArrayList<String>();
		// 获取系统当前时间
		// java.util.Calendar c=java.util.Calendar.getInstance();
		// java.text.SimpleDateFormat f=new
		// java.text.SimpleDateFormat("yyyyMMdd");

		String receiveActNo1 = receiveActNo.substring(0, 13);

		args.add(receiveActNo1);

		String boxName;

		boxName = NameServiceProxy.getNameRuleDefService()
				.generateName("BOXIDNEW", args, 1).get(0);
		try {
			return boxName;
		} catch (Throwable e) {
			args = new ArrayList<String>();
			args.add(receiveActNo1);
			return NameServiceProxy.getNameRuleDefService()
					.generateName("BOXIDNEW", args, 1).get(0);
		}
	}

	/*
	 * Name : Packing Desc : Packing Author : boe cim dev. Date : 2016.01.27
	 */

	public void CreateBoxByLabel(EventInfo eventInfo, String siteName,
			String receiveActNo, String receiveRequestName,
			String materialPackingName, String poDetailName, String makeDate,
			String receiveQuantity, String materialSpecName,
			String supplierName, String NPFlag,String expiringDate,String erpLocation) throws Exception {
				// 获取MaterialSpec信息
				MaterialSpec materialSpec = new MaterialSpec();
				MaterialSpecKey materialSpecKey = new MaterialSpecKey();
				materialSpecKey.setMaterialSpecName(materialSpecName);
				materialSpecKey.setSiteName(siteName);
				materialSpec = MaterialServiceProxy.getMaterialSpecService()
						.selectByKey(materialSpecKey);

				MaterialReceiveRequestDetail materialReceiveRequestDetail = new MaterialReceiveRequestDetail();
				MaterialReceiveRequestDetailKey matetialReceiveRequestDetailKey = new MaterialReceiveRequestDetailKey();
				matetialReceiveRequestDetailKey
						.setReceiveRequestName(receiveRequestName);
				matetialReceiveRequestDetailKey.setSiteName(siteName);
				matetialReceiveRequestDetailKey
						.setReceiveRequestDetailName(poDetailName);

				materialReceiveRequestDetail = ReceiveRequestDetailServiceProxy
						.getReceiveRequestDetailService().selectByKey(
								matetialReceiveRequestDetailKey);

				String sql2="SELECT * FROM MATERIALPACKING WHERE MATERIALPACKINGNAME=:materialPackingNmae AND STOCKSTATE='StockOut' AND SITENAME=:siteName";
				Map<String, Object> bindMap2 = new HashMap<String, Object>();
				bindMap2.put("materialPackingNmae", materialPackingName);
				bindMap2.put("siteName", siteName);
				List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
						.getSqlTemplate()
						.queryForList(sql2, bindMap2);
				
				// PO前缀36的寄售到货，添加标识specFlag，寄售到货：K，其它：N
				String poPrefix = receiveRequestName.substring(0, 2);
				String specialFlag = poPrefix.equals("36") ? "K" : "N";
				
				if(!(sqlResult.size()==0||sqlResult.get(0).get("MATERIALPACKINGNAME").toString().equals("")))
				{
					MaterialPackingKey materialPackingKey= new MaterialPackingKey();
					materialPackingKey.setMaterialPackingName(materialPackingName);
					materialPackingKey.setSiteName(siteName);
					MaterialPacking mp=MaterialPackingServiceProxy.getMaterialPackingService().selectByKey(materialPackingKey);
					String charge;
			        if(materialReceiveRequestDetail.getErpFactory().equals("2001"))
			        {
			        	charge="E0000001";
			        }
			        else{
			        	charge="";
			        }
					Map<String, Object> bindMap = new HashMap<String, Object>();
					bindMap.put("receiveActNo", receiveActNo);
					bindMap.put("receiveRequestName", receiveRequestName);
					bindMap.put("receiveRequestDetailName", poDetailName);

					bindMap.put("materialQuantity", receiveQuantity);
					bindMap.put("materialCreateQuantity", receiveQuantity);
					bindMap.put("packingState", "Created");// 标记Box是刚创建的
					bindMap.put("materialType", materialSpec.getMaterialType());
					bindMap.put("materialSpecName", materialSpecName);
					bindMap.put("stockState", "");
					bindMap.put("holdState", "N");
					bindMap.put("areaName", "");
					bindMap.put("createUser", eventInfo.getEventUser());
					bindMap.put("createTime", eventInfo.getEventTime());
					//makeDate=makeDate+" 00:00:00";
					bindMap.put("makeDate", makeDate);
					bindMap.put("expiringDate", expiringDate);
//					if(materialReceiveRequestDetail.getErpLocation().toString()!=erpLocation){
//						bindMap.put("erpLocation", erpLocation);
//					}else{
//						bindMap.put("erpLocation",materialReceiveRequestDetail.getErpLocation());
//					}
					bindMap.put("erpLocation", erpLocation);
					if(materialReceiveRequestDetail.getErpLocation()==null||materialReceiveRequestDetail.getErpLocation().equals(""))
					{
						throw new CustomException("ERPLOCATIONLOSS","","");
					}
					bindMap.put("erpFactory", materialReceiveRequestDetail.getErpFactory());
					bindMap.put("stockInType", "");
					bindMap.put("charge", charge);
					bindMap.put("supplierName", supplierName);
					bindMap.put("npFlag", NPFlag);					
					bindMap.put("specialFlag", specialFlag);
					
//					bindMap.put("reasonCodeType", eventInfo.getReasonCodeType());
//					bindMap.put("reasonCode", eventInfo.getReasonCode());
					eventInfo.setReasonCode("0001");
					eventInfo.setReasonCodeType("101");

					SetEventInfo setEventInfo=new SetEventInfo();
					setEventInfo.setUserColumns(bindMap);
					MaterialPackingServiceProxy.getMaterialPackingService().setEvent(materialPackingKey, eventInfo, setEventInfo);
				}
				else {
					// 创建Box
					CreateInfo materialPacking = new CreateInfo();
					materialPacking.setMaterialPackingName(materialPackingName);
					materialPacking.setSiteName(siteName);
					materialPacking.setContentMaterialType("");
					materialPacking.setMaterialPackingType("Box");
					String charge;
			        if(materialReceiveRequestDetail.getErpFactory().equals("2001"))
			        {
			        	charge="E0000001";
			        }
			        else{
			        	charge="";
			        }
					Map<String, Object> bindMap = new HashMap<String, Object>();
					bindMap.put("receiveActNo", receiveActNo);
					bindMap.put("receiveRequestName", receiveRequestName);
					bindMap.put("receiveRequestDetailName", poDetailName);

					bindMap.put("materialQuantity", receiveQuantity);
					bindMap.put("materialCreateQuantity", receiveQuantity);
					bindMap.put("packingState", "Created");// 标记Box是刚创建的
					bindMap.put("materialType", materialSpec.getMaterialType());
					bindMap.put("materialSpecName", materialSpecName);
					bindMap.put("stockState", "");
					bindMap.put("holdState", "N");
					bindMap.put("areaName", "");
					bindMap.put("createUser", eventInfo.getEventUser());
					bindMap.put("createTime", eventInfo.getEventTime());
					//makeDate=makeDate+" 00:00:00";
					bindMap.put("makeDate", makeDate);
					bindMap.put("expiringDate", expiringDate);
//					if(materialReceiveRequestDetail.getErpLocation().toString()!=erpLocation){
//						bindMap.put("erpLocation", erpLocation);
//					}else{
//						bindMap.put("erpLocation",materialReceiveRequestDetail.getErpLocation());
//					}
					bindMap.put("erpLocation", erpLocation);
					if(materialReceiveRequestDetail.getErpLocation()==null||materialReceiveRequestDetail.getErpLocation().equals(""))
					{
						throw new CustomException("ERPLOCATIONLOSS","","");
					}
					bindMap.put("erpFactory", materialReceiveRequestDetail.getErpFactory());
					bindMap.put("stockInType", "");
					bindMap.put("charge", charge);
					bindMap.put("supplierName", supplierName);
					bindMap.put("npFlag", NPFlag);
					bindMap.put("specialFlag", specialFlag);

//					bindMap.put("reasonCodeType", eventInfo.getReasonCodeType());
//					bindMap.put("reasonCode", eventInfo.getReasonCode());

					materialPacking.setUserColumns(bindMap);
					eventInfo.setReasonCode("0001");
					eventInfo.setReasonCodeType("101");
					MaterialPackingServiceProxy.getMaterialPackingService().create(
							eventInfo, materialPacking);
				}
				

				// 创建批次

				CreateActDetailInfo createActDetailInfo = new CreateActDetailInfo();

				MaterialReceiveActDetailKey materialReceiveActDetailKey = new MaterialReceiveActDetailKey();
				materialReceiveActDetailKey.setSiteName(siteName);
				materialReceiveActDetailKey.setReceiveRequestName(receiveRequestName);
				materialReceiveActDetailKey.setReceiveRequestDetailName(poDetailName);
				materialReceiveActDetailKey.setReceiveActNO(receiveActNo);
				
				materialReceiveActDetailKey.setMakeDate(Timestamp.valueOf(makeDate));

				String sql = "SELECT * FROM materialreceiveactdetail "
						+ "WHERE sitename = :sitename AND receiveRequestName = :receiveRequestName and ReceiveRequestDetailName=:ReceiveRequestDetailName and receiveActNo=:receiveActNo"
						+ " and makeDate=:makeDate ";

				Map<String, Object> bindMap1 = new HashMap<String, Object>();
				bindMap1.put("sitename", siteName);
				bindMap1.put("receiveRequestName", receiveRequestName);
				bindMap1.put("ReceiveRequestDetailName", poDetailName);
				bindMap1.put("receiveActNo", receiveActNo);
				bindMap1.put("makeDate", Timestamp.valueOf(makeDate));

				List<Map<String, Object>> queryResult = IDMFrameServiceProxy
						.getSqlTemplate()
						.queryForList(sql, bindMap1);

				if (queryResult.size() == 0) {
					createActDetailInfo.setReceiveActNO(receiveActNo);
					createActDetailInfo.setReceiveRequestName(receiveRequestName);
					createActDetailInfo.setReceiveRequestDetailName(poDetailName);
					createActDetailInfo.setSiteName(siteName);

					// Date date1 = new Date();//获取当前时间
					// SimpleDateFormat sdf = new
					// SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					// String str = sdf.format(date1);//时间存储为字符串
					// System.out.println(str);
					createActDetailInfo.setMakeDate(Timestamp.valueOf(makeDate));
					createActDetailInfo.setReceiveQuantity(Double
							.parseDouble(receiveQuantity));
					Map<String, Object> bindMap3 = new HashMap<String, Object>();
					bindMap3.put("receiveActState", "Created");
					// bindMap3.put("receiveQuantity",
					// Double.parseDouble(receiveQuantity));
					createActDetailInfo.setUserColumns(bindMap3);

					MaterialReceiveRequestActDetailServiceProxy
							.getMaterialReceiveRequestActDetailService().create(
									eventInfo, createActDetailInfo);
				} else {
					ActDetailIncreaseInfo actDetailIncreaseInfo = new ActDetailIncreaseInfo();
					actDetailIncreaseInfo.setReceiveQuantity(Double
							.parseDouble(receiveQuantity));

					MaterialReceiveRequestActDetailServiceProxy
							.getMaterialReceiveRequestActDetailService()
							.increaseReceivedQuantity(materialReceiveActDetailKey,
									eventInfo, actDetailIncreaseInfo);
				}

				MakeDetailIncreaseReceivedInfo makeDetailIncreaseReceivedInfo = new MakeDetailIncreaseReceivedInfo();
				MaterialReceiveRequestDetailKey materialReceiveRequestDetailKey = new MaterialReceiveRequestDetailKey();
				materialReceiveRequestDetailKey
						.setReceiveRequestName(receiveRequestName);
				materialReceiveRequestDetailKey.setSiteName(siteName);
				materialReceiveRequestDetailKey
						.setReceiveRequestDetailName(poDetailName);

				makeDetailIncreaseReceivedInfo.setIncreaseQuantity(Double
						.parseDouble(receiveQuantity));

				ReceiveRequestDetailServiceProxy.getReceiveRequestDetailService()
						.increaseReceivedQuantity(materialReceiveRequestDetailKey,
								eventInfo, makeDetailIncreaseReceivedInfo);

			}
	
	public void CreateBoxByBMDTLabel(EventInfo eventInfo, String siteName,
			String receiveActNo, String receiveRequestName,
			String materialPackingName, String poDetailName, String makeDate,
			String receiveQuantity, String materialSpecName,
			String supplierName, String NPFlag,String expiringDate,String erpLocation,String improvmentFlag) throws Exception {
				
				// 获取MaterialSpec信息
						MaterialSpec materialSpec = new MaterialSpec();
						MaterialSpecKey materialSpecKey = new MaterialSpecKey();
						materialSpecKey.setMaterialSpecName(materialSpecName);
						materialSpecKey.setSiteName(siteName);
						materialSpec = MaterialServiceProxy.getMaterialSpecService()
								.selectByKey(materialSpecKey);	
				//BMDT区分预留和PO
				if(receiveRequestName.substring(0, 1).equals("3")){
		        	MaterialReceiveRequestDetail materialReceiveRequestDetail = new MaterialReceiveRequestDetail();
		    		MaterialReceiveRequestDetailKey matetialReceiveRequestDetailKey = new MaterialReceiveRequestDetailKey();
		    		matetialReceiveRequestDetailKey
		    				.setReceiveRequestName(receiveRequestName);
		    		matetialReceiveRequestDetailKey.setSiteName(siteName);
		    		matetialReceiveRequestDetailKey
		    				.setReceiveRequestDetailName(poDetailName);

		    		materialReceiveRequestDetail = ReceiveRequestDetailServiceProxy
		    				.getReceiveRequestDetailService().selectByKey(
		    						matetialReceiveRequestDetailKey);
		        }else{
		        	MaterialShipRequestDetail materialReceiveRequestDetail = new MaterialShipRequestDetail();
		    		MaterialShipRequestDetailKey matetialReceiveRequestDetailKey = new MaterialShipRequestDetailKey();
		    		matetialReceiveRequestDetailKey
		    				.setShipRequestName(receiveRequestName);
		    		matetialReceiveRequestDetailKey.setSiteName(siteName);
		    		matetialReceiveRequestDetailKey
		    				.setShipRequestDetailName(poDetailName);

		    		materialReceiveRequestDetail = MaterialShipRequestDetailServiceProxy
		    				.getMaterialShipRequestDetailService().selectByKey(
		    						matetialReceiveRequestDetailKey);
		        }
				//MaterialShipRequestDetail materialReceiveRequestDetail = new MaterialShipRequestDetail();
				//MaterialShipRequestDetailKey matetialReceiveRequestDetailKey = new MaterialShipRequestDetailKey();
				//matetialReceiveRequestDetailKey
				//		.setShipRequestName(receiveRequestName);
				//matetialReceiveRequestDetailKey.setSiteName(siteName);
				//matetialReceiveRequestDetailKey
				//		.setShipRequestDetailName(poDetailName);
				//materialReceiveRequestDetail = MaterialShipRequestDetailServiceProxy
				//		.getMaterialShipRequestDetailService().selectByKey(
				//				matetialReceiveRequestDetailKey);
				String sql2="SELECT * FROM MATERIALPACKING WHERE MATERIALPACKINGNAME=:materialPackingNmae AND STOCKSTATE='StockOut' AND SITENAME=:siteName";
				Map<String, Object> bindMap2 = new HashMap<String, Object>();
				bindMap2.put("materialPackingNmae", materialPackingName);
				bindMap2.put("siteName", siteName);
				List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
						.getSqlTemplate()
						.queryForList(sql2, bindMap2);
				if(!(sqlResult.size()==0||sqlResult.get(0).get("MATERIALPACKINGNAME").toString().equals("")))
				{
					MaterialPackingKey materialPackingKey= new MaterialPackingKey();
					materialPackingKey.setMaterialPackingName(materialPackingName);
					materialPackingKey.setSiteName(siteName);
					MaterialPacking mp=MaterialPackingServiceProxy.getMaterialPackingService().selectByKey(materialPackingKey);
					mp.setContentMaterialType("");
					mp.setMaterialPackingType("Box");
					Map<String, Object> bindMap = new HashMap<String, Object>();
					bindMap.put("receiveActNo", receiveActNo);
					bindMap.put("receiveRequestName", receiveRequestName);
					bindMap.put("receiveRequestDetailName", poDetailName);
					
					bindMap.put("materialQuantity", receiveQuantity);
					bindMap.put("materialCreateQuantity", receiveQuantity);
					bindMap.put("packingState", "Created");// 标记Box是刚创建的

					bindMap.put("materialType", materialSpec.getMaterialType());
					bindMap.put("materialSpecName", materialSpecName);
					bindMap.put("stockState", "");
					bindMap.put("holdState", "N");
					bindMap.put("areaName", "");
					//bindMap.put("createUser", eventInfo.getEventUser());
					//bindMap.put("createTime", eventInfo.getEventTime());
					//makeDate=makeDate+" 00:00:00";
					bindMap.put("makeDate", makeDate);
					bindMap.put("erpLocation",erpLocation);
					bindMap.put("erpFactory", "2002");
					bindMap.put("stockInType", "");
					bindMap.put("charge", "");
					bindMap.put("supplierName", supplierName);
					bindMap.put("npFlag", "");
					bindMap.put("improvmentFlag", improvmentFlag);
					bindMap.put("expiringDate", expiringDate);
//					bindMap.put("reasonCodeType", eventInfo.getReasonCodeType());
//					bindMap.put("reasonCode", eventInfo.getReasonCode());


					eventInfo.setReasonCode("0001");
					eventInfo.setReasonCodeType("Z53");
					SetEventInfo setEventInfo=new SetEventInfo();
					setEventInfo.setUserColumns(bindMap);
					MaterialPackingServiceProxy.getMaterialPackingService().setEvent(materialPackingKey, eventInfo, setEventInfo);
				}
				else {
				// 创建Box
				CreateInfo materialPacking = new CreateInfo();
				materialPacking.setMaterialPackingName(materialPackingName);
				materialPacking.setSiteName(siteName);
				materialPacking.setContentMaterialType("");
				materialPacking.setMaterialPackingType("Box");

				Map<String, Object> bindMap = new HashMap<String, Object>();
				bindMap.put("receiveActNo", receiveActNo);
				bindMap.put("receiveRequestName", receiveRequestName);
				bindMap.put("receiveRequestDetailName", poDetailName);
				
				bindMap.put("materialQuantity", receiveQuantity);
				bindMap.put("materialCreateQuantity", receiveQuantity);
				bindMap.put("packingState", "Created");// 标记Box是刚创建的

				bindMap.put("materialType", materialSpec.getMaterialType());
				bindMap.put("materialSpecName", materialSpecName);
				bindMap.put("stockState", "");
				bindMap.put("holdState", "N");
				bindMap.put("areaName", "");
				bindMap.put("createUser", eventInfo.getEventUser());
				bindMap.put("createTime", eventInfo.getEventTime());
				//makeDate=makeDate+" 00:00:00";
				bindMap.put("makeDate", makeDate);
				bindMap.put("erpLocation",erpLocation);
				bindMap.put("erpFactory", "2002");
				bindMap.put("stockInType", "");
				bindMap.put("charge", "");
				bindMap.put("supplierName", supplierName);
				bindMap.put("npFlag", "");
				bindMap.put("improvmentFlag", improvmentFlag);
				bindMap.put("expiringDate", expiringDate);
//				bindMap.put("reasonCodeType", eventInfo.getReasonCodeType());
//				bindMap.put("reasonCode", eventInfo.getReasonCode());

				materialPacking.setUserColumns(bindMap);
				eventInfo.setReasonCode("0001");
				eventInfo.setReasonCodeType("Z53");
				MaterialPackingServiceProxy.getMaterialPackingService().create(
						eventInfo, materialPacking);
				}
				// 创建批次

				CreateActDetailInfo createActDetailInfo = new CreateActDetailInfo();

				MaterialReceiveActDetailKey materialReceiveActDetailKey = new MaterialReceiveActDetailKey();
				materialReceiveActDetailKey.setSiteName(siteName);
				materialReceiveActDetailKey.setReceiveRequestName(receiveRequestName);
				materialReceiveActDetailKey.setReceiveRequestDetailName(poDetailName);
				materialReceiveActDetailKey.setReceiveActNO(receiveActNo);
				materialReceiveActDetailKey.setMakeDate(Timestamp.valueOf(makeDate));

				String sql = "SELECT * FROM materialreceiveactdetail "
						+ "WHERE sitename = :sitename AND receiveRequestName = :receiveRequestName and ReceiveRequestDetailName=:ReceiveRequestDetailName and receiveActNo=:receiveActNo"
						+ " and makeDate=:makeDate ";

				Map<String, Object> bindMap1 = new HashMap<String, Object>();
				bindMap1.put("sitename", siteName);
				bindMap1.put("receiveRequestName", receiveRequestName);
				bindMap1.put("ReceiveRequestDetailName", poDetailName);
				bindMap1.put("receiveActNo", receiveActNo);
				bindMap1.put("makeDate", Timestamp.valueOf(makeDate));

				List<Map<String, Object>> queryResult = IDMFrameServiceProxy
						.getSqlTemplate()
						.queryForList(sql, bindMap1);

				if (queryResult.size() == 0) {
					createActDetailInfo.setReceiveActNO(receiveActNo);
					createActDetailInfo.setReceiveRequestName(receiveRequestName);
					createActDetailInfo.setReceiveRequestDetailName(poDetailName);
					createActDetailInfo.setSiteName(siteName);

					// Date date1 = new Date();//获取当前时间
					// SimpleDateFormat sdf = new
					// SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					// String str = sdf.format(date1);//时间存储为字符串
					// System.out.println(str);
					createActDetailInfo.setMakeDate(Timestamp.valueOf(makeDate));
					createActDetailInfo.setReceiveQuantity(Double
							.parseDouble(receiveQuantity));
					Map<String, Object> bindMap3 = new HashMap<String, Object>();
					bindMap3.put("receiveActState", "Created");
					// bindMap3.put("receiveQuantity",
					// Double.parseDouble(receiveQuantity));
					createActDetailInfo.setUserColumns(bindMap3);

					MaterialReceiveRequestActDetailServiceProxy
							.getMaterialReceiveRequestActDetailService().create(
									eventInfo, createActDetailInfo);
				} else {
					ActDetailIncreaseInfo actDetailIncreaseInfo = new ActDetailIncreaseInfo();
					actDetailIncreaseInfo.setReceiveQuantity(Double
							.parseDouble(receiveQuantity));

					MaterialReceiveRequestActDetailServiceProxy
							.getMaterialReceiveRequestActDetailService()
							.increaseReceivedQuantity(materialReceiveActDetailKey,
									eventInfo, actDetailIncreaseInfo);
				}

				if(receiveRequestName.substring(0, 1).equals("3")){
					MakeDetailIncreaseReceivedInfo makeDetailIncreaseReceivedInfo = new MakeDetailIncreaseReceivedInfo();
					MaterialReceiveRequestDetailKey matetialShipRequestDetailKey = new MaterialReceiveRequestDetailKey();
					matetialShipRequestDetailKey
							.setReceiveRequestName(receiveRequestName);
					matetialShipRequestDetailKey.setSiteName(siteName);
					matetialShipRequestDetailKey
							.setReceiveRequestDetailName(poDetailName);
					makeDetailIncreaseReceivedInfo.setIncreaseQuantity(Double
							.parseDouble(receiveQuantity));
					ReceiveRequestDetailServiceProxy.getReceiveRequestDetailService()
							.increaseReceivedQuantity(matetialShipRequestDetailKey,eventInfo, makeDetailIncreaseReceivedInfo);
				}
				else{
					MakeShipDetailIncreaseAssignedInfo makeDetailIncreaseReceivedInfo = new MakeShipDetailIncreaseAssignedInfo();
					
					MaterialShipRequestDetailKey matetialShipRequestDetailKey = new MaterialShipRequestDetailKey();
					matetialShipRequestDetailKey
							.setShipRequestName(receiveRequestName);
					matetialShipRequestDetailKey.setSiteName(siteName);
					matetialShipRequestDetailKey
							.setShipRequestDetailName(poDetailName);
					makeDetailIncreaseReceivedInfo.setAssignedQuantity(Double
							.parseDouble(receiveQuantity));
					MaterialShipRequestDetailServiceProxy.getMaterialShipRequestDetailService()
							.increaseAssignedQuantity(matetialShipRequestDetailKey, makeDetailIncreaseReceivedInfo);
				}
			}
	
	public void PDACreateBoxByLabel(EventInfo eventInfo, String siteName,
			String receiveActNo, String receiveRequestName,
			String materialPackingName, String poDetailName, String makeDate,
			String receiveQuantity, String materialSpecName,
			String supplierName, String NPFlag,String palletID,String improvmentFlag,String erpLocation,String erpFactory,String invoiceType,String charge,String expiringDate) throws Exception {
				try {
					//根据单据获取物料类型和批次信息
					String queryPO="SELECT MS.MATERIALTYPE FROM MATERIALRECEIVEREQUESTDETAIL MD"                         
								+" LEFT JOIN MATERIALSPEC MS  ON MS.SITENAME=MD.SITENAME AND MD.MATERIALSPECNAME=MS.MATERIALSPECNAME"
								+" WHERE MD.SITENAME=:SITENAME AND MD.RECEIVEREQUESTNAME=:RECEIVEREQUESTNAME AND MD.RECEIVEREQUESTDETAILNAME=:RECEIVEREQUESTDETAILNAME";
					String queryShip="SELECT MS.MATERIALTYPE FROM MATERIALSHIPREQUESTDETAIL MD"                              
									+" LEFT JOIN MATERIALSPEC MS  ON MS.SITENAME=MD.SITENAME AND MD.MATERIALSPECNAME=MS.MATERIALSPECNAME"
									+" WHERE MD.SITENAME=:SITENAME AND MD.SHIPREQUESTNAME =:RECEIVEREQUESTNAME AND MD.SHIPREQUESTDETAILNAME =:RECEIVEREQUESTDETAILNAME";
					Map<String,Object> map=new HashMap<String, Object>();
					map.put("SITENAME", siteName);
					map.put("RECEIVEREQUESTNAME", receiveRequestName);
					map.put("RECEIVEREQUESTDETAILNAME", poDetailName);
					List<Map<String,Object>> result=IDMFrameServiceProxy.getSqlTemplate().queryForList(invoiceType.equals("PO")?queryPO:queryShip, map);
					if(result==null || result.size()<=0)
						throw new CustomException("OEMSPEC","","");
					String sql2="SELECT * FROM MATERIALPACKING WHERE MATERIALPACKINGNAME=:materialPackingNmae AND STOCKSTATE='StockOut' AND SITENAME=:siteName";
					Map<String, Object> bindMap2 = new HashMap<String, Object>();
					bindMap2.put("materialPackingNmae", materialPackingName);
					bindMap2.put("siteName", siteName);
					List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
							.getSqlTemplate()
							.queryForList(sql2, bindMap2);
					CreateInfo materialPacking = new CreateInfo();
					MaterialPacking mp =new MaterialPacking();
					if(!(sqlResult.size()==0||sqlResult.get(0).get("MATERIALPACKINGNAME").toString().equals("")))
					{
						MaterialPackingKey materialPackingKey= new MaterialPackingKey();
						materialPackingKey.setMaterialPackingName(materialPackingName);
						materialPackingKey.setSiteName(siteName);
						Map<String, Object> bindMap = new HashMap<String, Object>();
						bindMap.put("receiveActNo", receiveActNo);
						bindMap.put("receiveRequestName", receiveRequestName);
						bindMap.put("receiveRequestDetailName", poDetailName);
						bindMap.put("materialPackingType", "Box");
						bindMap.put("materialQuantity", receiveQuantity);
						bindMap.put("materialCreateQuantity", receiveQuantity);
						bindMap.put("packingState", "Created");// 标记Box是刚创建的

						bindMap.put("materialType", result.get(0).get("MATERIALTYPE").toString());
						bindMap.put("materialSpecName", materialSpecName);
						bindMap.put("stockState", "");
						bindMap.put("holdState", "N");
						bindMap.put("areaName", "");
						//bindMap.put("createUser", eventInfo.getEventUser());
						//bindMap.put("createTime", eventInfo.getEventTime());
						makeDate=makeDate+" 00:00:00";
						bindMap.put("makeDate", Timestamp.valueOf(makeDate));
						bindMap.put("erpLocation",erpLocation);
						bindMap.put("erpFactory", erpFactory);
						bindMap.put("stockInType", "");
						bindMap.put("charge", charge);
						bindMap.put("supplierName", supplierName);
						bindMap.put("npFlag", NPFlag);
						bindMap.put("superMaterialPackingName", palletID);
						bindMap.put("improvmentFlag", improvmentFlag);
						//bindMap.put("reasonCodeType", eventInfo.getReasonCodeType());
						//bindMap.put("reasonCode", eventInfo.getReasonCode());
						bindMap.put("expiringDate", Timestamp.valueOf(expiringDate+" 00:00:00"));
						eventInfo.setReasonCode("0001");
						eventInfo.setReasonCodeType(eventInfo.getReasonCodeType());
						SetEventInfo setEventInfo=new SetEventInfo();
						setEventInfo.setUserColumns(bindMap);
						MaterialPackingServiceProxy.getMaterialPackingService().setEvent(materialPackingKey, eventInfo, setEventInfo);
					}
					else {
					// 创建Box
					materialPacking.setMaterialPackingName(materialPackingName);
					materialPacking.setSiteName(siteName);
					materialPacking.setContentMaterialType("");
					materialPacking.setMaterialPackingType("Box");

					Map<String, Object> bindMap = new HashMap<String, Object>();
					bindMap.put("receiveActNo", receiveActNo);
					bindMap.put("receiveRequestName", receiveRequestName);
					bindMap.put("receiveRequestDetailName", poDetailName);

					bindMap.put("materialQuantity", receiveQuantity);
					bindMap.put("materialCreateQuantity", receiveQuantity);
					bindMap.put("packingState", "Created");// 标记Box是刚创建的

					bindMap.put("materialType", result.get(0).get("MATERIALTYPE").toString());
					bindMap.put("materialSpecName", materialSpecName);
					bindMap.put("stockState", "");
					bindMap.put("holdState", "N");
					bindMap.put("areaName", "");
					bindMap.put("createUser", eventInfo.getEventUser());
					bindMap.put("createTime", eventInfo.getEventTime());
					makeDate=makeDate+" 00:00:00";
					bindMap.put("makeDate", Timestamp.valueOf(makeDate));
					bindMap.put("erpLocation",erpLocation);
					bindMap.put("erpFactory", erpFactory);
					bindMap.put("stockInType", "");
					bindMap.put("charge", charge);
					bindMap.put("supplierName", supplierName);
					bindMap.put("npFlag", NPFlag);
					bindMap.put("superMaterialPackingName", palletID);
					bindMap.put("improvmentFlag", improvmentFlag);
					//bindMap.put("reasonCodeType", eventInfo.getReasonCodeType());
					//bindMap.put("reasonCode", eventInfo.getReasonCode());
					bindMap.put("expiringDate", Timestamp.valueOf(expiringDate+" 00:00:00"));
					materialPacking.setUserColumns(bindMap);
					eventInfo.setReasonCode("0001");
					//修改原来的写死Z53  
					//eventInfo.setReasonCodeType("Z53");
					eventInfo.setReasonCodeType(eventInfo.getReasonCodeType());
					MaterialPackingServiceProxy.getMaterialPackingService().create(
							eventInfo, materialPacking);
					}
					//更新Pallet存在时，更新总托数量
					if(!palletID.equalsIgnoreCase(""))
					{				
						String query_pallet="SELECT MATERIALQUANTITY,MATERIALSPECNAME,EXPIRINGDATE FROM MATERIALPACKING WHERE SITENAME= ? AND MATERIALPACKINGNAME= ?";
						Object[] bindSet={siteName,palletID};
						List<Map<String,Object>> palletInfo=IDMFrameServiceProxy.getSqlTemplate().queryForList(query_pallet, bindSet);
						if(palletInfo.size()>0)
						{
							//当Pallet信息已创建，正托数量为已收数量+本次创建数量					
							MaterialPackingKey mpk=new MaterialPackingKey();
							mpk.setSiteName(siteName);
							mpk.setMaterialPackingName(palletID);
							MaterialPacking pallet=MaterialPackingServiceProxy.getMaterialPackingService().selectByKey(mpk);
							if(pallet.getMaterialSpecName().equals(materialSpecName))
							{						
								pallet.setMaterialQuantity(Double.parseDouble(palletInfo.get(0).get("MATERIALQUANTITY").toString())+Double.parseDouble(receiveQuantity));
								SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); 
								Date palletDate=sdf.parse(pallet.getExpiringDate().toString());
								Date boxDate=sdf.parse(expiringDate);
								if(boxDate.before(palletDate))
									pallet.setExpiringDate(Timestamp.valueOf(expiringDate+" 00:00:00"));
								MaterialPackingServiceProxy.getMaterialPackingService().update(pallet);
							}else
								throw new CustomException("PALLET-001","","");
						}else
						{
							if(materialPacking==null ||materialPacking.getMaterialPackingName()==null||materialPacking.getMaterialPackingName().equals(""))
							{
								materialPacking.setMaterialPackingName(materialPackingName);
								materialPacking.setSiteName(siteName);
								materialPacking.setContentMaterialType("MaterialPacking");
								materialPacking.setMaterialPackingType("Pallet");

								Map<String, Object> bindMap = new HashMap<String, Object>();
								bindMap.put("receiveActNo", receiveActNo);
								bindMap.put("receiveRequestName", receiveRequestName);
								bindMap.put("receiveRequestDetailName", poDetailName);

								bindMap.put("materialQuantity", receiveQuantity);
								bindMap.put("materialCreateQuantity", receiveQuantity);
								bindMap.put("packingState", "Created");// 标记Box是刚创建的

								bindMap.put("materialType", result.get(0).get("MATERIALTYPE").toString());
								bindMap.put("materialSpecName", materialSpecName);
								bindMap.put("stockState", "");
								bindMap.put("holdState", "N");
								bindMap.put("areaName", "");
								bindMap.put("createUser", eventInfo.getEventUser());
								bindMap.put("createTime", eventInfo.getEventTime());
								makeDate=makeDate+" 00:00:00";
								bindMap.put("makeDate", Timestamp.valueOf(makeDate));
								bindMap.put("erpLocation",erpLocation);
								bindMap.put("erpFactory", erpFactory);
								bindMap.put("stockInType", "");
								bindMap.put("charge", charge);
								bindMap.put("supplierName", supplierName);
								bindMap.put("npFlag", NPFlag);
								bindMap.put("superMaterialPackingName", palletID);
								bindMap.put("improvmentFlag", improvmentFlag);
								//bindMap.put("reasonCodeType", eventInfo.getReasonCodeType());
								//bindMap.put("reasonCode", eventInfo.getReasonCode());
								bindMap.put("expiringDate", Timestamp.valueOf(expiringDate+" 00:00:00"));
								materialPacking.setUserColumns(bindMap);
								eventInfo.setReasonCode("0001");
								eventInfo.setReasonCodeType("Z53");
								MaterialPackingServiceProxy.getMaterialPackingService().create(
										eventInfo, materialPacking);
							}
							else{
							//当Pallet信息未创建时，新增一条Pallet记录
							materialPacking.setMaterialPackingName(palletID);
							materialPacking.setMaterialPackingType("Pallet");
							materialPacking.setContentMaterialType("MaterialPacking");
							MaterialPackingServiceProxy.getMaterialPackingService().create(
									eventInfo, materialPacking);
							}
						}
					}
					//更新单据接收数量
					if(invoiceType.equals("PO"))
					{
						MakeDetailIncreaseReceivedInfo makeDetailIncreaseReceivedInfo = new MakeDetailIncreaseReceivedInfo();
						MaterialReceiveRequestDetailKey materialReceiveRequestDetailKey = new MaterialReceiveRequestDetailKey();
						materialReceiveRequestDetailKey
								.setReceiveRequestName(receiveRequestName);
						materialReceiveRequestDetailKey.setSiteName(siteName);
						materialReceiveRequestDetailKey
								.setReceiveRequestDetailName(poDetailName);
			
						makeDetailIncreaseReceivedInfo.setIncreaseQuantity(Double
								.parseDouble(receiveQuantity));
			
						ReceiveRequestDetailServiceProxy.getReceiveRequestDetailService()
								.increaseReceivedQuantity(materialReceiveRequestDetailKey,
										eventInfo, makeDetailIncreaseReceivedInfo);
					}else
					{
						MaterialShipRequestDetailKey key=new MaterialShipRequestDetailKey();
						key.setSiteName(siteName);
						key.setShipRequestName(receiveRequestName);
						key.setShipRequestDetailName(poDetailName);
						MakeShipDetailIncreaseAssignedInfo info=new MakeShipDetailIncreaseAssignedInfo();
						info.setAssignedQuantity(Double.parseDouble(receiveQuantity));
						MaterialShipRequestDetailServiceProxy.getMaterialShipRequestDetailService().increaseAssignedQuantity(key, info);
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					 throw e;
				}

			}

	
	public void PoCreateBoxByLabel(EventInfo eventInfo, String siteName,
			String receiveActNo, String receiveRequestName,
			String materialPackingName, String poDetailName, String makeDate,
			String receiveQuantity, String materialSpecName,
			String supplierName, String NPFlag,String palletID,String EXPIRINGDATE) throws Exception {
		// 获取MaterialSpec信息
		// PO前缀36的寄售到货，添加标识specFlag，寄售到货：K，其它：N
		String poPrefix = receiveRequestName.substring(0, 2);
		String specialFlag = poPrefix.equals("36") ? "K" : "N";
		try {
			if(poDetailName.equals(""))
			{
				throw new CustomException("FindDetailError","","");
			}
			
			MaterialSpec materialSpec = new MaterialSpec();
			MaterialSpecKey materialSpecKey = new MaterialSpecKey();
			materialSpecKey.setMaterialSpecName(materialSpecName);
			materialSpecKey.setSiteName(siteName);
			materialSpec = MaterialServiceProxy.getMaterialSpecService()
					.selectByKey(materialSpecKey);

			MaterialReceiveRequestDetail materialReceiveRequestDetail = new MaterialReceiveRequestDetail();
			MaterialReceiveRequestDetailKey matetialReceiveRequestDetailKey = new MaterialReceiveRequestDetailKey();
			matetialReceiveRequestDetailKey
					.setReceiveRequestName(receiveRequestName);
			matetialReceiveRequestDetailKey.setSiteName(siteName);
			matetialReceiveRequestDetailKey
					.setReceiveRequestDetailName(poDetailName);

			materialReceiveRequestDetail = ReceiveRequestDetailServiceProxy
					.getReceiveRequestDetailService().selectByKey(
							matetialReceiveRequestDetailKey);
			// 创建Pallet信息
			if(!(palletID==null||palletID.equals("")))
			{
				String sql="SELECT MATERIALPACKINGNAME,MATERIALSPECNAME,to_char(EXPIRINGDATE,'yyyy-MM-dd') EXPIRINGDATE,MATERIALQUANTITY  FROM MATERIALPACKING WHERE MATERIALPACKINGNAME=:materialPackingName AND SITENAME=:siteName AND PACKINGSTATE='Created' ";
				Map<String, Object> bindMap1 = new HashMap<String, Object>();
				bindMap1.put("materialPackingName", palletID);
				bindMap1.put("siteName", siteName);
				List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
						.getSqlTemplate()
						.queryForList(sql, bindMap1);	
				if(sqlResult.size()==0)
				{
					CreateInfo materialPacking = new CreateInfo();
					materialPacking.setMaterialPackingName(palletID);
					materialPacking.setSiteName(siteName);
					materialPacking.setContentMaterialType("MaterialPacking");
					materialPacking.setMaterialPackingType("Pallet");
					Map<String, Object> bindMap = new HashMap<String, Object>();
					//bindMap.put("receiveActNo", receiveActNo);
					bindMap.put("receiveRequestName", receiveRequestName);
					bindMap.put("receiveRequestDetailName", poDetailName);
					bindMap.put("packingState", "Created");// 标记Box是刚创建的
					bindMap.put("materialQuantity", receiveQuantity);
					bindMap.put("materialSpecName", materialSpecName);
					bindMap.put("erpLocation",
							materialReceiveRequestDetail.getErpLocation());
					bindMap.put("erpFactory", materialReceiveRequestDetail.getErpFactory());
					bindMap.put("stockInType", "Normal");
					bindMap.put("supplierName", supplierName);
					bindMap.put("superMaterialPackingName", palletID);
					bindMap.put("expiringDate", Timestamp.valueOf(EXPIRINGDATE+" 00:00:00"));
					bindMap.put("makeDate", Timestamp.valueOf(makeDate+" 00:00:00"));
					bindMap.put("supplierName", supplierName);
					bindMap.put("createUser", eventInfo.getEventUser());
					bindMap.put("createTime", eventInfo.getEventTime());
					bindMap.put("holdState", "N");
					bindMap.put("packingState", "Created");// 标记Box是刚创建的
					materialPacking.setUserColumns(bindMap);
					MaterialPackingServiceProxy.getMaterialPackingService().create(
							eventInfo, materialPacking);
				}
				else
				{
					if(sqlResult.get(0).get("MATERIALSPECNAME").toString().equals(materialSpecName))
					{
						MaterialPacking  pallet=new MaterialPacking();
						MaterialPackingKey key =new MaterialPackingKey();
						key.setMaterialPackingName(palletID);
						key.setSiteName(siteName);
						Map<String, Object> bindMap = new HashMap<String, Object>();
						if(sqlResult.get(0).get("EXPIRINGDATE").toString().compareTo(EXPIRINGDATE)>0)
						{
							bindMap.put("expiringDate", Timestamp.valueOf(EXPIRINGDATE+" 00:00:00"));
						}
						bindMap.put("materialQuantity",String.valueOf(Double.valueOf(receiveQuantity)+ Double.valueOf(sqlResult.get(0).get("MATERIALQUANTITY").toString())));
						bindMap.put("erpLocation",
								materialReceiveRequestDetail.getErpLocation());
						bindMap.put("erpFactory", materialReceiveRequestDetail.getErpFactory());
						SetEventInfo setEventInfo=new SetEventInfo();
						setEventInfo.setUserColumns(bindMap);
						pallet=MaterialPackingServiceProxy.getMaterialPackingService().setEvent(key, eventInfo, setEventInfo);
					}
					else 
						throw new CustomException("FindDetailError","","");
				}
			}
			
			CreateInfo materialPacking = new CreateInfo();
			materialPacking.setMaterialPackingName(materialPackingName);
			materialPacking.setSiteName(siteName);
			materialPacking.setContentMaterialType("");
			materialPacking.setMaterialPackingType("Box");

			Map<String, Object> bindMap = new HashMap<String, Object>();
			bindMap.put("receiveActNo", receiveActNo);
			bindMap.put("receiveRequestName", receiveRequestName);
			bindMap.put("receiveRequestDetailName", poDetailName);

			bindMap.put("materialQuantity", receiveQuantity);
			bindMap.put("materialCreateQuantity", receiveQuantity);
			bindMap.put("packingState", "Created");// 标记Box是刚创建的
			EXPIRINGDATE=EXPIRINGDATE+" 00:00:00";
			bindMap.put("materialType", materialSpec.getMaterialType());
			bindMap.put("materialSpecName", materialSpecName);
			bindMap.put("stockState", "");
			bindMap.put("holdState", "N");
			bindMap.put("areaName", "");
			bindMap.put("createUser", eventInfo.getEventUser());
			bindMap.put("createTime", eventInfo.getEventTime());
			makeDate=makeDate+" 00:00:00";
			bindMap.put("makeDate", Timestamp.valueOf(makeDate));
			bindMap.put("erpLocation",
					materialReceiveRequestDetail.getErpLocation());
			bindMap.put("erpFactory", materialReceiveRequestDetail.getErpFactory());
			bindMap.put("stockInType", "");
			bindMap.put("charge", materialReceiveRequestDetail.getCharge());
			bindMap.put("supplierName", supplierName);
			bindMap.put("npFlag", NPFlag);
			// 寄售到货
			bindMap.put("specialFlag", specialFlag);
			
			bindMap.put("superMaterialPackingName", palletID);
			bindMap.put("expiringDate", Timestamp.valueOf(EXPIRINGDATE));
			//bindMap.put("reasonCodeType", eventInfo.getReasonCodeType());
			//bindMap.put("reasonCode", eventInfo.getReasonCode());

			materialPacking.setUserColumns(bindMap);
			eventInfo.setReasonCode("0001");
			eventInfo.setReasonCodeType("101");
			MaterialPackingServiceProxy.getMaterialPackingService().create(
					eventInfo, materialPacking);
//
//			// 创建批次
//
			CreateActDetailInfo createActDetailInfo = new CreateActDetailInfo();
//
			MaterialReceiveActDetailKey materialReceiveActDetailKey = new MaterialReceiveActDetailKey();
			materialReceiveActDetailKey.setSiteName(siteName);
			materialReceiveActDetailKey.setReceiveRequestName(receiveRequestName);
			materialReceiveActDetailKey.setReceiveRequestDetailName(poDetailName);
			materialReceiveActDetailKey.setReceiveActNO(receiveActNo);
			materialReceiveActDetailKey.setMakeDate(Timestamp.valueOf(makeDate));

			String sql = "SELECT * FROM materialreceiveactdetail "
					+ "WHERE sitename = :sitename AND receiveRequestName = :receiveRequestName and ReceiveRequestDetailName=:ReceiveRequestDetailName and receiveActNo=:receiveActNo"
					+ " and makeDate=:makeDate ";

			Map<String, Object> bindMap1 = new HashMap<String, Object>();
			bindMap1.put("sitename", siteName);
			bindMap1.put("receiveRequestName", receiveRequestName);
			bindMap1.put("ReceiveRequestDetailName", poDetailName);
			bindMap1.put("receiveActNo", receiveActNo);
			bindMap1.put("makeDate", Timestamp.valueOf(makeDate));

			List<Map<String, Object>> queryResult = IDMFrameServiceProxy
					.getSqlTemplate()
					.queryForList(sql, bindMap1);

			if (queryResult.size() == 0) {
				createActDetailInfo.setReceiveActNO(receiveActNo);
				createActDetailInfo.setReceiveRequestName(receiveRequestName);
				createActDetailInfo.setReceiveRequestDetailName(poDetailName);
				createActDetailInfo.setSiteName(siteName);

				// Date date1 = new Date();//获取当前时间
				// SimpleDateFormat sdf = new
				// SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				// String str = sdf.format(date1);//时间存储为字符串
				// System.out.println(str);
				createActDetailInfo.setMakeDate(Timestamp.valueOf(makeDate));
				createActDetailInfo.setReceiveQuantity(Double
						.parseDouble(receiveQuantity));
				Map<String, Object> bindMap3 = new HashMap<String, Object>();
				bindMap3.put("receiveActState", "Created");
				// bindMap3.put("receiveQuantity",
				// Double.parseDouble(receiveQuantity));
				createActDetailInfo.setUserColumns(bindMap3);

				MaterialReceiveRequestActDetailServiceProxy
						.getMaterialReceiveRequestActDetailService().create(
								eventInfo, createActDetailInfo);
			} else {
				ActDetailIncreaseInfo actDetailIncreaseInfo = new ActDetailIncreaseInfo();
				actDetailIncreaseInfo.setReceiveQuantity(Double
						.parseDouble(receiveQuantity));

				MaterialReceiveRequestActDetailServiceProxy
						.getMaterialReceiveRequestActDetailService()
						.increaseReceivedQuantity(materialReceiveActDetailKey,
								eventInfo, actDetailIncreaseInfo);
			}

			MakeDetailIncreaseReceivedInfo makeDetailIncreaseReceivedInfo = new MakeDetailIncreaseReceivedInfo();
			MaterialReceiveRequestDetailKey materialReceiveRequestDetailKey = new MaterialReceiveRequestDetailKey();
			materialReceiveRequestDetailKey
					.setReceiveRequestName(receiveRequestName);
			materialReceiveRequestDetailKey.setSiteName(siteName);
			materialReceiveRequestDetailKey
					.setReceiveRequestDetailName(poDetailName);

			makeDetailIncreaseReceivedInfo.setIncreaseQuantity(Double
					.parseDouble(receiveQuantity));

			ReceiveRequestDetailServiceProxy.getReceiveRequestDetailService()
					.increaseReceivedQuantity(materialReceiveRequestDetailKey,
							eventInfo, makeDetailIncreaseReceivedInfo);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			
			e.printStackTrace();
			throw e;
		}

	}

	public void ShipRequestCreateBoxByLabel(EventInfo eventInfo, String siteName,
			String receiveActNo, String receiveRequestName,
			String materialPackingName, String poDetailName, String makeDate,
			String receiveQuantity, String materialSpecName,
			String supplierName, String NPFlag,String palletID,String EXPIRINGDATE,String charge) throws Exception {
				// 获取MaterialSpec信息
				try {
					if(poDetailName.equals(""))
					{
						throw new CustomException("FindDetailError","","");
					}
					MaterialSpec materialSpec = new MaterialSpec();
					MaterialSpecKey materialSpecKey = new MaterialSpecKey();
					materialSpecKey.setMaterialSpecName(materialSpecName);
					materialSpecKey.setSiteName(siteName);
					materialSpec = MaterialServiceProxy.getMaterialSpecService()
							.selectByKey(materialSpecKey);

					MaterialShipRequestDetail materialShipRequestDetail = new MaterialShipRequestDetail();
					MaterialShipRequestDetailKey matetialReceiveRequestDetailKey = new MaterialShipRequestDetailKey();
					matetialReceiveRequestDetailKey
							.setShipRequestName(receiveRequestName);
					matetialReceiveRequestDetailKey.setSiteName(siteName);
					matetialReceiveRequestDetailKey
							.setShipRequestDetailName(poDetailName);

					materialShipRequestDetail = MaterialShipRequestDetailServiceProxy.getMaterialShipRequestDetailService().selectByKey(
									matetialReceiveRequestDetailKey);

					// 创建Pallet信息
					if(!(palletID==null||palletID.equals("")))
						{
							String sql="SELECT MATERIALPACKINGNAME,MATERIALSPECNAME,to_char(EXPIRINGDATE,'yyyy-MM-dd') EXPIRINGDATE,MATERIALQUANTITY  FROM MATERIALPACKING WHERE MATERIALPACKINGNAME=:materialPackingName AND SITENAME=:siteName AND PACKINGSTATE='Created' ";
							Map<String, Object> bindMap1 = new HashMap<String, Object>();
							bindMap1.put("materialPackingName", palletID);
							bindMap1.put("siteName", siteName);
							List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
									.getSqlTemplate()
									.queryForList(sql, bindMap1);	
							if(sqlResult.size()==0)
								{
									CreateInfo materialPacking = new CreateInfo();
									materialPacking.setMaterialPackingName(palletID);
									materialPacking.setSiteName(siteName);
									materialPacking.setContentMaterialType("MaterialPacking");
									materialPacking.setMaterialPackingType("Pallet");
									Map<String, Object> bindMap = new HashMap<String, Object>();
									//bindMap.put("receiveActNo", receiveActNo);
									bindMap.put("receiveRequestName", receiveRequestName);
									bindMap.put("receiveRequestDetailName", poDetailName);
									bindMap.put("packingState", "Created");// 标记Box是刚创建的
									bindMap.put("materialQuantity", receiveQuantity);
									bindMap.put("materialSpecName", materialSpecName);
									//EXPIRINGDATE=EXPIRINGDATE+" 00:00:00";
									bindMap.put("erpLocation",
											materialShipRequestDetail.getErpLocation());
									bindMap.put("erpFactory", materialShipRequestDetail.getErpFactoryName());
									bindMap.put("stockInType", "Refund");
									bindMap.put("supplierName", supplierName);
									bindMap.put("superMaterialPackingName", palletID);
									bindMap.put("expiringDate", Timestamp.valueOf(EXPIRINGDATE+" 00:00:00"));
									bindMap.put("supplierName", supplierName);
									bindMap.put("createUser", eventInfo.getEventUser());
									bindMap.put("createTime", eventInfo.getEventTime());
									bindMap.put("holdState", "N");
									bindMap.put("packingState", "Created");// 标记Box是刚创建的
									materialPacking.setUserColumns(bindMap);
									MaterialPackingServiceProxy.getMaterialPackingService().create(
											eventInfo, materialPacking);
								}
							else
								{
									if(sqlResult.get(0).get("MATERIALSPECNAME").toString().equals(materialSpecName))
										{
											MaterialPacking  pallet=new MaterialPacking();
											MaterialPackingKey key =new MaterialPackingKey();
											key.setMaterialPackingName(palletID);
											key.setSiteName(siteName);
											Map<String, Object> bindMap = new HashMap<String, Object>();
											if(sqlResult.get(0).get("EXPIRINGDATE").toString().compareTo(EXPIRINGDATE)>0)
											{
												bindMap.put("expiringDate", Timestamp.valueOf(EXPIRINGDATE+" 00:00:00"));
											}
											bindMap.put("materialQuantity",String.valueOf(Double.valueOf(receiveQuantity)+ Double.valueOf(sqlResult.get(0).get("MATERIALQUANTITY").toString())));
											bindMap.put("erpLocation",
													materialShipRequestDetail.getErpLocation());
											bindMap.put("erpFactory", materialShipRequestDetail.getErpFactoryName());
											SetEventInfo setEventInfo=new SetEventInfo();
											setEventInfo.setUserColumns(bindMap);
											pallet=MaterialPackingServiceProxy.getMaterialPackingService().setEvent(key, eventInfo, setEventInfo);
										}
										else 
											throw new CustomException("FindDetailError","","");
								}
						}
					
					String sql2="SELECT * FROM MATERIALPACKING WHERE MATERIALPACKINGNAME=:materialPackingNmae AND STOCKSTATE='StockOut' AND SITENAME=:siteName";
					Map<String, Object> bindMap2 = new HashMap<String, Object>();
					bindMap2.put("materialPackingNmae", materialPackingName);
					bindMap2.put("siteName", siteName);
					List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
							.getSqlTemplate()
							.queryForList(sql2, bindMap2);
					if(!(sqlResult.size()==0||sqlResult.get(0).get("MATERIALPACKINGNAME").toString().equals("")))
					{
						MaterialPackingKey materialPackingKey= new MaterialPackingKey();
						materialPackingKey.setMaterialPackingName(materialPackingName);
						materialPackingKey.setSiteName(siteName);
						MaterialPacking mp=MaterialPackingServiceProxy.getMaterialPackingService().selectByKey(materialPackingKey);
						Map<String, Object> bindMap = new HashMap<String, Object>();
						bindMap.put("receiveActNo", receiveActNo);
						bindMap.put("receiveRequestName", receiveRequestName);
						bindMap.put("receiveRequestDetailName", poDetailName);

						bindMap.put("materialQuantity", receiveQuantity);
						bindMap.put("materialCreateQuantity", receiveQuantity);
						bindMap.put("packingState", "Created");// 标记Box是刚创建的

						bindMap.put("materialType", materialSpec.getMaterialType());
						bindMap.put("materialSpecName", materialSpecName);
						bindMap.put("stockState", "");
						bindMap.put("holdState", "N");
						bindMap.put("areaName", "");
						//bindMap.put("createUser", eventInfo.getEventUser());
						//bindMap.put("createTime", eventInfo.getEventTime());
						makeDate=makeDate+" 00:00:00";
						EXPIRINGDATE=EXPIRINGDATE+" 00:00:00";
						bindMap.put("makeDate", Timestamp.valueOf(makeDate));
						bindMap.put("erpLocation",
								materialShipRequestDetail.getErpLocation());
						bindMap.put("erpFactory", materialShipRequestDetail.getErpFactoryName());
						bindMap.put("stockInType", "");
						bindMap.put("charge", charge);
						bindMap.put("supplierName", supplierName);
						bindMap.put("npFlag", NPFlag);
						bindMap.put("superMaterialPackingName", palletID);
						bindMap.put("expiringDate", Timestamp.valueOf(EXPIRINGDATE));
						//bindMap.put("reasonCodeType", eventInfo.getReasonCodeType());
						//bindMap.put("reasonCode", eventInfo.getReasonCode());


						SetEventInfo setEventInfo=new SetEventInfo();
						setEventInfo.setUserColumns(bindMap);
						MaterialPackingServiceProxy.getMaterialPackingService().setEvent(materialPackingKey, eventInfo, setEventInfo);
					}
					else {
					// 创建Box
					CreateInfo materialPacking = new CreateInfo();
					materialPacking.setMaterialPackingName(materialPackingName);
					materialPacking.setSiteName(siteName);
					materialPacking.setContentMaterialType("");
					materialPacking.setMaterialPackingType("Box");

					Map<String, Object> bindMap = new HashMap<String, Object>();
					bindMap.put("receiveActNo", receiveActNo);
					bindMap.put("receiveRequestName", receiveRequestName);
					bindMap.put("receiveRequestDetailName", poDetailName);

					bindMap.put("materialQuantity", receiveQuantity);
					bindMap.put("materialCreateQuantity", receiveQuantity);
					bindMap.put("packingState", "Created");// 标记Box是刚创建的

					bindMap.put("materialType", materialSpec.getMaterialType());
					bindMap.put("materialSpecName", materialSpecName);
					bindMap.put("stockState", "");
					bindMap.put("holdState", "N");
					bindMap.put("areaName", "");
					bindMap.put("createUser", eventInfo.getEventUser());
					bindMap.put("createTime", eventInfo.getEventTime());
					makeDate=makeDate+" 00:00:00";
					EXPIRINGDATE=EXPIRINGDATE+" 00:00:00";
					bindMap.put("makeDate", Timestamp.valueOf(makeDate));
					bindMap.put("erpLocation",
							materialShipRequestDetail.getErpLocation());
					bindMap.put("erpFactory", materialShipRequestDetail.getErpFactoryName());
					bindMap.put("stockInType", "");
					bindMap.put("charge", charge);
					bindMap.put("supplierName", supplierName);
					bindMap.put("npFlag", NPFlag);
					bindMap.put("superMaterialPackingName", palletID);
					bindMap.put("expiringDate", Timestamp.valueOf(EXPIRINGDATE));
					//bindMap.put("reasonCodeType", eventInfo.getReasonCodeType());
					//bindMap.put("reasonCode", eventInfo.getReasonCode());

					materialPacking.setUserColumns(bindMap);
					//eventInfo.setReasonCode("0001");
					//eventInfo.setReasonCodeType("101");
					MaterialPackingServiceProxy.getMaterialPackingService().create(
							eventInfo, materialPacking);
					}
		//
//					// 创建批次
		//
					CreateActDetailInfo createActDetailInfo = new CreateActDetailInfo();
		//
					MaterialReceiveActDetailKey materialReceiveActDetailKey = new MaterialReceiveActDetailKey();
					materialReceiveActDetailKey.setSiteName(siteName);
					materialReceiveActDetailKey.setReceiveRequestName(receiveRequestName);
					materialReceiveActDetailKey.setReceiveRequestDetailName(poDetailName);
					materialReceiveActDetailKey.setReceiveActNO(receiveActNo);
					materialReceiveActDetailKey.setMakeDate(Timestamp.valueOf(makeDate));

					String sql = "SELECT * FROM materialreceiveactdetail "
							+ "WHERE sitename = :sitename AND receiveRequestName = :receiveRequestName and ReceiveRequestDetailName=:ReceiveRequestDetailName and receiveActNo=:receiveActNo"
							+ " and makeDate=:makeDate ";

					Map<String, Object> bindMap1 = new HashMap<String, Object>();
					bindMap1.put("sitename", siteName);
					bindMap1.put("receiveRequestName", receiveRequestName);
					bindMap1.put("ReceiveRequestDetailName", poDetailName);
					bindMap1.put("receiveActNo", receiveActNo);
					bindMap1.put("makeDate", Timestamp.valueOf(makeDate));

					List<Map<String, Object>> queryResult = IDMFrameServiceProxy
							.getSqlTemplate()
							.queryForList(sql, bindMap1);

					if (queryResult.size() == 0) {
						createActDetailInfo.setReceiveActNO(receiveActNo);
						createActDetailInfo.setReceiveRequestName(receiveRequestName);
						createActDetailInfo.setReceiveRequestDetailName(poDetailName);
						createActDetailInfo.setSiteName(siteName);

						// Date date1 = new Date();//获取当前时间
						// SimpleDateFormat sdf = new
						// SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						// String str = sdf.format(date1);//时间存储为字符串
						// System.out.println(str);
						createActDetailInfo.setMakeDate(Timestamp.valueOf(makeDate));
						createActDetailInfo.setReceiveQuantity(Double
								.parseDouble(receiveQuantity));
						Map<String, Object> bindMap3 = new HashMap<String, Object>();
						bindMap3.put("receiveActState", "Created");
						// bindMap3.put("receiveQuantity",
						// Double.parseDouble(receiveQuantity));
						createActDetailInfo.setUserColumns(bindMap3);

						MaterialReceiveRequestActDetailServiceProxy
								.getMaterialReceiveRequestActDetailService().create(
										eventInfo, createActDetailInfo);
					} else {
						ActDetailIncreaseInfo actDetailIncreaseInfo = new ActDetailIncreaseInfo();
						actDetailIncreaseInfo.setReceiveQuantity(Double
								.parseDouble(receiveQuantity));

						MaterialReceiveRequestActDetailServiceProxy
								.getMaterialReceiveRequestActDetailService()
								.increaseReceivedQuantity(materialReceiveActDetailKey,
										eventInfo, actDetailIncreaseInfo);
					}

					MakeShipDetailIncreaseAssignedInfo makeDetailIncreaseAssignedInfo = new MakeShipDetailIncreaseAssignedInfo();
					MaterialShipRequestDetailKey materialShipRequestDetailKey = new MaterialShipRequestDetailKey();
					materialShipRequestDetailKey
							.setShipRequestName(receiveRequestName);
					materialShipRequestDetailKey.setSiteName(siteName);
					materialShipRequestDetailKey
							.setShipRequestDetailName(poDetailName);

					makeDetailIncreaseAssignedInfo.setAssignedQuantity(Double
							.parseDouble(receiveQuantity));

					MaterialShipRequestDetailServiceProxy.getMaterialShipRequestDetailService()
							.increaseAssignedQuantity(materialShipRequestDetailKey,makeDetailIncreaseAssignedInfo);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
	public void OEMRefundCreateBoxByLabel(EventInfo eventInfo, String siteName,
			String receiveActNo, String receiveRequestName,
			String materialPackingName, String poDetailName, String makeDate,
			String receiveQuantity, String materialSpecName,
			String supplierName, String NPFlag,String palletID,String EXPIRINGDATE,String charge) throws Exception {
				// 获取MaterialSpec信息
				try {
					if(poDetailName.equals(""))
					{
						throw new CustomException("FindDetailError","","");
					}
					MaterialSpec materialSpec = new MaterialSpec();
					MaterialSpecKey materialSpecKey = new MaterialSpecKey();
					materialSpecKey.setMaterialSpecName(materialSpecName);
					materialSpecKey.setSiteName(siteName);
					materialSpec = MaterialServiceProxy.getMaterialSpecService()
							.selectByKey(materialSpecKey);
					MaterialReceiveRequestDetail materialReceiveRequestDetail = new MaterialReceiveRequestDetail();
					MaterialReceiveRequestDetailKey materialReceiveRequestDetailKey = new MaterialReceiveRequestDetailKey();
					materialReceiveRequestDetailKey.setReceiveRequestDetailName(poDetailName);
					materialReceiveRequestDetailKey.setReceiveRequestName(receiveRequestName);
					materialReceiveRequestDetailKey.setSiteName(siteName);
					materialReceiveRequestDetail=ReceiveRequestDetailServiceProxy.getReceiveRequestDetailService().selectByKey(materialReceiveRequestDetailKey);
			
					// 创建Pallet信息
					if(!(palletID==null||palletID.equals("")))
						{
							String sql="SELECT MATERIALPACKINGNAME,MATERIALSPECNAME,to_char(EXPIRINGDATE,'yyyy-MM-dd') EXPIRINGDATE,MATERIALQUANTITY  FROM MATERIALPACKING WHERE MATERIALPACKINGNAME=:materialPackingName AND SITENAME=:siteName AND PACKINGSTATE='Created' ";
							Map<String, Object> bindMap1 = new HashMap<String, Object>();
							bindMap1.put("materialPackingName", palletID);
							bindMap1.put("siteName", siteName);
							List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
									.getSqlTemplate()
									.queryForList(sql, bindMap1);	
							if(sqlResult.size()==0)
								{
									CreateInfo materialPacking = new CreateInfo();
									materialPacking.setMaterialPackingName(palletID);
									materialPacking.setSiteName(siteName);
									materialPacking.setContentMaterialType("MaterialPacking");
									materialPacking.setMaterialPackingType("Pallet");
									Map<String, Object> bindMap = new HashMap<String, Object>();
									//bindMap.put("receiveActNo", receiveActNo);
									bindMap.put("receiveRequestName", receiveRequestName);
									bindMap.put("receiveRequestDetailName", poDetailName);
									bindMap.put("packingState", "Created");// 标记Box是刚创建的
									bindMap.put("materialQuantity", receiveQuantity);
									bindMap.put("materialSpecName", materialSpecName);
									//EXPIRINGDATE=EXPIRINGDATE+" 00:00:00";
									bindMap.put("erpLocation",
											materialReceiveRequestDetail.getErpLocation());
									bindMap.put("erpFactory", materialReceiveRequestDetail.getErpFactory());
									bindMap.put("stockInType", "Refund");
									bindMap.put("supplierName", supplierName);
									bindMap.put("superMaterialPackingName", palletID);
									bindMap.put("expiringDate", Timestamp.valueOf(EXPIRINGDATE+" 00:00:00"));
									bindMap.put("supplierName", supplierName);
									bindMap.put("createUser", eventInfo.getEventUser());
									bindMap.put("createTime", eventInfo.getEventTime());
									bindMap.put("holdState", "N");
									bindMap.put("packingState", "Created");// 标记Box是刚创建的
									materialPacking.setUserColumns(bindMap);
									MaterialPackingServiceProxy.getMaterialPackingService().create(
											eventInfo, materialPacking);
								}
							else
								{
									if(sqlResult.get(0).get("MATERIALSPECNAME").toString().equals(materialSpecName))
										{
											MaterialPacking  pallet=new MaterialPacking();
											MaterialPackingKey key =new MaterialPackingKey();
											key.setMaterialPackingName(palletID);
											key.setSiteName(siteName);
											Map<String, Object> bindMap = new HashMap<String, Object>();
											if(sqlResult.get(0).get("EXPIRINGDATE").toString().compareTo(EXPIRINGDATE)>0)
											{
												bindMap.put("expiringDate", Timestamp.valueOf(EXPIRINGDATE+" 00:00:00"));
											}
											bindMap.put("materialQuantity",String.valueOf(Double.valueOf(receiveQuantity)+ Double.valueOf(sqlResult.get(0).get("MATERIALQUANTITY").toString())));
											bindMap.put("erpLocation",
													materialReceiveRequestDetail.getErpLocation());
											bindMap.put("erpFactory", materialReceiveRequestDetail.getErpFactory());
											SetEventInfo setEventInfo=new SetEventInfo();
											setEventInfo.setUserColumns(bindMap);
											pallet=MaterialPackingServiceProxy.getMaterialPackingService().setEvent(key, eventInfo, setEventInfo);
										}
										else 
											throw new CustomException("FindDetailError","","");
								}
						}
					String sql2="SELECT * FROM MATERIALPACKING WHERE MATERIALPACKINGNAME=:materialPackingNmae AND STOCKSTATE='StockOut' AND SITENAME=:siteName";
					Map<String, Object> bindMap2 = new HashMap<String, Object>();
					bindMap2.put("materialPackingNmae", materialPackingName);
					bindMap2.put("siteName", siteName);
					List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
							.getSqlTemplate()
							.queryForList(sql2, bindMap2);
					if(!(sqlResult.size()==0||sqlResult.get(0).get("MATERIALPACKINGNAME").toString().equals("")))
					{
						MaterialPackingKey materialPackingKey= new MaterialPackingKey();
						materialPackingKey.setMaterialPackingName(materialPackingName);
						materialPackingKey.setSiteName(siteName);
						MaterialPacking mp=MaterialPackingServiceProxy.getMaterialPackingService().selectByKey(materialPackingKey);
						Map<String, Object> bindMap = new HashMap<String, Object>();
						bindMap.put("receiveActNo", receiveActNo);
						bindMap.put("receiveRequestName", receiveRequestName);
						bindMap.put("receiveRequestDetailName", poDetailName);

						bindMap.put("materialQuantity", receiveQuantity);
						bindMap.put("materialCreateQuantity", receiveQuantity);
						bindMap.put("packingState", "Created");// 标记Box是刚创建的

						bindMap.put("materialType", materialSpec.getMaterialType());
						bindMap.put("materialSpecName", materialSpecName);
						bindMap.put("stockState", "");
						bindMap.put("holdState", "N");
						bindMap.put("areaName", "");
						//bindMap.put("createUser", eventInfo.getEventUser());
						//bindMap.put("createTime", eventInfo.getEventTime());
						makeDate=makeDate+" 00:00:00";
						EXPIRINGDATE=EXPIRINGDATE+" 00:00:00";
						bindMap.put("makeDate", Timestamp.valueOf(makeDate));
						bindMap.put("erpLocation",
								materialReceiveRequestDetail.getErpLocation());
						bindMap.put("erpFactory", materialReceiveRequestDetail.getErpFactory());
						bindMap.put("stockInType", "");
						bindMap.put("charge", charge);
						bindMap.put("supplierName", supplierName);
						bindMap.put("npFlag", NPFlag);
						bindMap.put("superMaterialPackingName", palletID);
						bindMap.put("expiringDate", Timestamp.valueOf(EXPIRINGDATE));
						//bindMap.put("reasonCodeType", eventInfo.getReasonCodeType());
						//bindMap.put("reasonCode", eventInfo.getReasonCode());

						SetEventInfo setEventInfo=new SetEventInfo();
						setEventInfo.setUserColumns(bindMap);
						MaterialPackingServiceProxy.getMaterialPackingService().setEvent(materialPackingKey, eventInfo, setEventInfo);
					}
					else {
					// 创建Box
					CreateInfo materialPacking = new CreateInfo();
					materialPacking.setMaterialPackingName(materialPackingName);
					materialPacking.setSiteName(siteName);
					materialPacking.setContentMaterialType("");
					materialPacking.setMaterialPackingType("Box");

					Map<String, Object> bindMap = new HashMap<String, Object>();
					bindMap.put("receiveActNo", receiveActNo);
					bindMap.put("receiveRequestName", receiveRequestName);
					bindMap.put("receiveRequestDetailName", poDetailName);

					bindMap.put("materialQuantity", receiveQuantity);
					bindMap.put("materialCreateQuantity", receiveQuantity);
					bindMap.put("packingState", "Created");// 标记Box是刚创建的

					bindMap.put("materialType", materialSpec.getMaterialType());
					bindMap.put("materialSpecName", materialSpecName);
					bindMap.put("stockState", "");
					bindMap.put("holdState", "N");
					bindMap.put("areaName", "");
					bindMap.put("createUser", eventInfo.getEventUser());
					bindMap.put("createTime", eventInfo.getEventTime());
					makeDate=makeDate+" 00:00:00";
					EXPIRINGDATE=EXPIRINGDATE+" 00:00:00";
					bindMap.put("makeDate", Timestamp.valueOf(makeDate));
					bindMap.put("erpLocation",
							materialReceiveRequestDetail.getErpLocation());
					bindMap.put("erpFactory", materialReceiveRequestDetail.getErpFactory());
					bindMap.put("stockInType", "");
					bindMap.put("charge", charge);
					bindMap.put("supplierName", supplierName);
					bindMap.put("npFlag", NPFlag);
					bindMap.put("superMaterialPackingName", palletID);
					bindMap.put("expiringDate", Timestamp.valueOf(EXPIRINGDATE));
					//bindMap.put("reasonCodeType", eventInfo.getReasonCodeType());
					//bindMap.put("reasonCode", eventInfo.getReasonCode());

					materialPacking.setUserColumns(bindMap);
					//eventInfo.setReasonCode("0001");
					//eventInfo.setReasonCodeType("101");
					MaterialPackingServiceProxy.getMaterialPackingService().create(
							eventInfo, materialPacking);
					}
		//
//					// 创建批次
		//
					CreateActDetailInfo createActDetailInfo = new CreateActDetailInfo();
		//
					MaterialReceiveActDetailKey materialReceiveActDetailKey = new MaterialReceiveActDetailKey();
					materialReceiveActDetailKey.setSiteName(siteName);
					materialReceiveActDetailKey.setReceiveRequestName(receiveRequestName);
					materialReceiveActDetailKey.setReceiveRequestDetailName(poDetailName + "_"+materialSpecName);
					materialReceiveActDetailKey.setReceiveActNO(receiveActNo);
					materialReceiveActDetailKey.setMakeDate(Timestamp.valueOf(makeDate));

					String sql = "SELECT * FROM materialreceiveactdetail "
							+ "WHERE sitename = :sitename AND receiveRequestName = :receiveRequestName and ReceiveRequestDetailName=:ReceiveRequestDetailName and receiveActNo=:receiveActNo"
							+ " and makeDate=:makeDate ";

					Map<String, Object> bindMap1 = new HashMap<String, Object>();
					bindMap1.put("sitename", siteName);
					bindMap1.put("receiveRequestName", receiveRequestName);
					bindMap1.put("ReceiveRequestDetailName",poDetailName + "_"+materialSpecName);
					bindMap1.put("receiveActNo", receiveActNo);
					bindMap1.put("makeDate", Timestamp.valueOf(makeDate));

					List<Map<String, Object>> queryResult = IDMFrameServiceProxy
							.getSqlTemplate()
							.queryForList(sql, bindMap1);

					if (queryResult.size() == 0) {
						createActDetailInfo.setReceiveActNO(receiveActNo);
						createActDetailInfo.setReceiveRequestName(receiveRequestName);
						createActDetailInfo.setReceiveRequestDetailName(poDetailName + "_"+materialSpecName);
						createActDetailInfo.setSiteName(siteName);

						// Date date1 = new Date();//获取当前时间
						// SimpleDateFormat sdf = new
						// SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						// String str = sdf.format(date1);//时间存储为字符串
						// System.out.println(str);
						createActDetailInfo.setMakeDate(Timestamp.valueOf(makeDate));
						createActDetailInfo.setReceiveQuantity(Double
								.parseDouble(receiveQuantity));
						Map<String, Object> bindMap3 = new HashMap<String, Object>();
						bindMap3.put("receiveActState", "Created");
						// bindMap3.put("receiveQuantity",
						// Double.parseDouble(receiveQuantity));
						createActDetailInfo.setUserColumns(bindMap3);

						MaterialReceiveRequestActDetailServiceProxy
								.getMaterialReceiveRequestActDetailService().create(
										eventInfo, createActDetailInfo);
					} else {
						ActDetailIncreaseInfo actDetailIncreaseInfo = new ActDetailIncreaseInfo();
						actDetailIncreaseInfo.setReceiveQuantity(Double
								.parseDouble(receiveQuantity));

						MaterialReceiveRequestActDetailServiceProxy
								.getMaterialReceiveRequestActDetailService()
								.increaseReceivedQuantity(materialReceiveActDetailKey,
										eventInfo, actDetailIncreaseInfo);
					}
					MaterialShipRequestToOEMKey matetialReceiveRequestDetailKey = new MaterialShipRequestToOEMKey();
					matetialReceiveRequestDetailKey.setReceiveRequestName(receiveRequestName);
					matetialReceiveRequestDetailKey.setSiteName(siteName);
					matetialReceiveRequestDetailKey.setReceiveRequestDetailName(poDetailName);
					matetialReceiveRequestDetailKey.setSubMaterialSpecName(materialSpecName);
					MakeOEMDecreaseAssignedInfo makeOEMDecreaseAssignedInfo = new MakeOEMDecreaseAssignedInfo();
					makeOEMDecreaseAssignedInfo.setAssignedQuantity(Double.valueOf(receiveQuantity));
					MaterialShipRequestToOEMServiceProxy
							.getMaterialShipRequestToOEMService()
							.decreaseAssignedQuantity(matetialReceiveRequestDetailKey,
									eventInfo, makeOEMDecreaseAssignedInfo);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					throw e;
				}

			}

	public void insertUnDoBoxInfo(String siteName, String invoiceNo,
			String unDoID, String unDoDetailName, String unDoIdDate) {

		String sql = insertUnDOMaterialPackingInfo_v1
				+ "SELECT PALLET.SITENAME,PALLET.MATERIALPACKINGNAME,LASTEVENTTIMEKEY  FROM MATERIALPACKING PALLET,"
				+ "(SELECT RD.*  FROM  MATERIALSHIPREQUEST R, MATERIALSHIPREQUESTDETAIL RD  "
				+ "WHERE R.SHIPREQUESTNAME = RD.SHIPREQUESTNAME   AND RD.SITENAME=R.SITENAME   "
				+ "AND R.SHIPREQUESTNAME = :INVOICENO   AND RD.SITENAME=:SITENAME   ) RD   "
				+ "WHERE PALLET.SITENAME=RD.SITENAME   AND PALLET.SHIPREQUESTNAME = RD.SHIPREQUESTNAME   "
				+ "AND PALLET.SHIPREQUESTDETAILNAME = RD.SHIPREQUESTDETAILNAME )  ";
		// + "AND MATERIALPACKINGTYPE='Pallet'  "
		// + " AND CONTENTMATERIALTYPE='MATERIALPACKING'"

		Map<String, String> bindMap = new HashMap<String, String>();
		bindMap.put("unDoID", unDoID);
		bindMap.put("INVOICENO", invoiceNo);
		bindMap.put("SITENAME", siteName);
		bindMap.put("unDoDetailName", unDoDetailName);
		bindMap.put("unDoIdDate", unDoIdDate);

		int resultCount = IDMFrameServiceProxy.getSqlTemplate()
				.update(sql, bindMap);

		/**
		 * 先更新Materialpacking表、MaterialPackingHistory中的UnDoID
		 */

		/**
		 * sql=update MATERIALPACKING PALLET set undoid=:unDoID where
		 * (sitename,materialpackingname) in ( SELECT
		 * PALLET.SITENAME,PALLET.MATERIALPACKINGNAME FROM MATERIALPACKING
		 * PALLET,(SELECT RD.* FROM MATERIALSHIPREQUEST R,
		 * MATERIALSHIPREQUESTDETAIL RD WHERE R.SHIPREQUESTNAME =
		 * RD.SHIPREQUESTNAME AND RD.SITENAME=R.SITENAME AND R.SHIPREQUESTNAME =
		 * :INVOICENO AND RD.SITENAME=:SITENAME ) RD WHERE
		 * PALLET.SITENAME=RD.SITENAME AND PALLET.SHIPREQUESTNAME =
		 * RD.SHIPREQUESTNAME AND PALLET.SHIPREQUESTDETAILNAME =
		 * RD.SHIPREQUESTDETAILNAME AND MATERIALPACKINGTYPE='Pallet' AND
		 * CONTENTMATERIALTYPE='MATERIALPACKING' )
		 */
		/**
		 * sql="update MATERIALPACKING set undoid=:unDoID    " +
		 * "where (sitename,materialpackingname) in ( " +
		 * "SELECT PALLET.SITENAME,PALLET.MATERIALPACKINGNAME  FROM MATERIALPACKING PALLET,"
		 * +
		 * "(SELECT RD.*  FROM  MATERIALSHIPREQUEST R, MATERIALSHIPREQUESTDETAIL RD  "
		 * +
		 * "WHERE R.SHIPREQUESTNAME = RD.SHIPREQUESTNAME   AND RD.SITENAME=R.SITENAME   "
		 * +
		 * "AND R.SHIPREQUESTNAME = :INVOICENO   AND RD.SITENAME=:SITENAME   ) RD   "
		 * +
		 * "WHERE PALLET.SITENAME=RD.SITENAME   AND PALLET.SHIPREQUESTNAME = RD.SHIPREQUESTNAME   "
		 * + "AND PALLET.SHIPREQUESTDETAILNAME = RD.SHIPREQUESTDETAILNAME   " //
		 * + "AND MATERIALPACKINGTYPE='Pallet'  " // +
		 * " AND CONTENTMATERIALTYPE='MATERIALPACKING'" ;
		 * 
		 * 
		 * resultCount =
		 * IDMFrameServiceProxy.getSqlTemplate().getSimpleJdbcTemplate
		 * ().update(sql, bindMap);
		 * 
		 * sql="update MATERIALPACKINGHISTORY set undoid=:unDoID    " +
		 * "where (sitename,materialpackingname,TIMEKEY) in ( " +
		 * "SELECT PALLET.SITENAME,PALLET.MATERIALPACKINGNAME,LASTEVENTTIMEKEY  FROM MATERIALPACKING PALLET,"
		 * +
		 * "(SELECT RD.*  FROM  MATERIALSHIPREQUEST R, MATERIALSHIPREQUESTDETAIL RD  "
		 * +
		 * "WHERE R.SHIPREQUESTNAME = RD.SHIPREQUESTNAME   AND RD.SITENAME=R.SITENAME   "
		 * +
		 * "AND R.SHIPREQUESTNAME = :INVOICENO   AND RD.SITENAME=:SITENAME   ) RD   "
		 * +
		 * "WHERE PALLET.SITENAME=RD.SITENAME   AND PALLET.SHIPREQUESTNAME = RD.SHIPREQUESTNAME   "
		 * + "AND PALLET.SHIPREQUESTDETAILNAME = RD.SHIPREQUESTDETAILNAME )  "
		 * // + "AND MATERIALPACKINGTYPE='Pallet'  " // +
		 * " AND CONTENTMATERIALTYPE='MATERIALPACKING'" ;
		 * 
		 * resultCount =
		 * IDMFrameServiceProxy.getSqlTemplate().getSimpleJdbcTemplate
		 * ().update(sql, bindMap);
		 * 
		 * /** insert into BS_MATERIALPACKINGUNDOINFO
		 * (unDoID,preundoid,undoidstate,SITENAME, MATERIALPACKINGNAME,
		 * MATERIALPACKINGTYPE, CONTENTMATERIALTYPE, MATERIALTYPE,
		 * MATERIALSPECNAME, SUPERMATERIALPACKINGNAME, PACKINGGRADE,
		 * SUBPACKINGQUANTITY, MATERIALCREATEQUANTITY, MATERIALQUANTITY,
		 * PACKINGSTATE, OLDPACKINGSTATE, STOCKSTATE, OLDSTOCKSTATE, HOLDSTATE,
		 * AREANAME, LOCATIONNAME, DURABLENAME, MATERIALPROCESSGROUPNAME,
		 * LASTEVENTNAME, LASTEVENTTIMEKEY, LASTEVENTTIME, LASTEVENTUSER,
		 * LASTEVENTCOMMENT, CREATETIME, CREATEUSER, RECEIVEREQUESTNAME,
		 * RECEIVEREQUESTDETAILNAME, MAKEDATE, RECEIVEACTNO, STOCKINTYPE,
		 * RECEIVETIME, RECEIVEUSER, SHIPREQUESTNAME, SHIPREQUESTDETAILNAME,
		 * SHIPTIME, SHIPUSER, REASONCODETYPE, OQARESULTSTATE, OQARESULT,
		 * ERPLOCATION, ERPFACTORY, REASONCODE, CHARGE, SUPPLIERNAME, ETCSTATE)
		 * select :unDoID as unDoID,undoid as preundoid,'Created' as
		 * undoidstate, SITENAME, MATERIALPACKINGNAME, MATERIALPACKINGTYPE,
		 * CONTENTMATERIALTYPE, MATERIALTYPE, MATERIALSPECNAME,
		 * SUPERMATERIALPACKINGNAME, PACKINGGRADE, SUBPACKINGQUANTITY,
		 * MATERIALCREATEQUANTITY, MATERIALQUANTITY, PACKINGSTATE,
		 * OLDPACKINGSTATE, STOCKSTATE, OLDSTOCKSTATE, HOLDSTATE, AREANAME,
		 * LOCATIONNAME, DURABLENAME, MATERIALPROCESSGROUPNAME, LASTEVENTNAME,
		 * LASTEVENTTIMEKEY, LASTEVENTTIME, LASTEVENTUSER, LASTEVENTCOMMENT,
		 * CREATETIME, CREATEUSER, RECEIVEREQUESTNAME, RECEIVEREQUESTDETAILNAME,
		 * MAKEDATE, RECEIVEACTNO, STOCKINTYPE, RECEIVETIME, RECEIVEUSER,
		 * SHIPREQUESTNAME, SHIPREQUESTDETAILNAME, SHIPTIME, SHIPUSER,
		 * REASONCODETYPE, OQARESULTSTATE, OQARESULT, ERPLOCATION, ERPFACTORY,
		 * REASONCODE, CHARGE, SUPPLIERNAME,ETCSTATE from MATERIALPACKING m
		 * where (sitename,materialpackingname) in ( SELECT
		 * PALLET.SITENAME,PALLET.MATERIALPACKINGNAME FROM MATERIALPACKING
		 * PALLET,(SELECT RD.* FROM MATERIALSHIPREQUEST R,
		 * MATERIALSHIPREQUESTDETAIL RD WHERE R.SHIPREQUESTNAME =
		 * RD.SHIPREQUESTNAME AND RD.SITENAME=R.SITENAME AND R.SHIPREQUESTNAME =
		 * :INVOICENO AND RD.SITENAME=:SITENAME ) RD WHERE
		 * PALLET.SITENAME=RD.SITENAME AND PALLET.SHIPREQUESTNAME =
		 * RD.SHIPREQUESTNAME AND PALLET.SHIPREQUESTDETAILNAME =
		 * RD.SHIPREQUESTDETAILNAME -- AND MATERIALPACKINGTYPE='Pallet' -- AND
		 * CONTENTMATERIALTYPE='MATERIALPACKING' )
		 */
		/**
		 * sql=
		 * "insert into BS_MATERIALPACKINGUNDOINFO (unDoID,preundoid,undoidstate,"
		 * +
		 * "SITENAME, MATERIALPACKINGNAME, MATERIALPACKINGTYPE, CONTENTMATERIALTYPE,"
		 * +
		 * "MATERIALTYPE, MATERIALSPECNAME, SUPERMATERIALPACKINGNAME, PACKINGGRADE, SUBPACKINGQUANTITY, MATERIALCREATEQUANTITY,"
		 * +
		 * "MATERIALQUANTITY, PACKINGSTATE, OLDPACKINGSTATE, STOCKSTATE, OLDSTOCKSTATE, HOLDSTATE, AREANAME, LOCATIONNAME,"
		 * +
		 * "DURABLENAME, MATERIALPROCESSGROUPNAME, LASTEVENTNAME, LASTEVENTTIMEKEY, LASTEVENTTIME, LASTEVENTUSER,"
		 * +
		 * "LASTEVENTCOMMENT, CREATETIME, CREATEUSER, RECEIVEREQUESTNAME, RECEIVEREQUESTDETAILNAME,"
		 * +
		 * "MAKEDATE, RECEIVEACTNO, STOCKINTYPE, RECEIVETIME, RECEIVEUSER, SHIPREQUESTNAME, SHIPREQUESTDETAILNAME, SHIPTIME,"
		 * +
		 * "SHIPUSER, REASONCODETYPE, OQARESULTSTATE, OQARESULT, ERPLOCATION, ERPFACTORY, REASONCODE, CHARGE, SUPPLIERNAME,ETCSTATE)"
		 * +
		 * "select :unDoID as unDoID,undoid as preundoid,'Created' as undoidstate,"
		 * // +
		 * "SITENAME, MATERIALPACKINGNAME, MATERIALPACKINGTYPE, CONTENTMATERIALTYPE,"
		 * +
		 * "MATERIALTYPE, MATERIALSPECNAME, SUPERMATERIALPACKINGNAME, PACKINGGRADE, SUBPACKINGQUANTITY, MATERIALCREATEQUANTITY,"
		 * +
		 * "MATERIALQUANTITY, PACKINGSTATE, OLDPACKINGSTATE, STOCKSTATE, OLDSTOCKSTATE, HOLDSTATE, AREANAME, LOCATIONNAME,"
		 * +
		 * "DURABLENAME, MATERIALPROCESSGROUPNAME, LASTEVENTNAME, LASTEVENTTIMEKEY, LASTEVENTTIME, LASTEVENTUSER,"
		 * +
		 * "LASTEVENTCOMMENT, CREATETIME, CREATEUSER, RECEIVEREQUESTNAME, RECEIVEREQUESTDETAILNAME,"
		 * +
		 * "MAKEDATE, RECEIVEACTNO, STOCKINTYPE, RECEIVETIME, RECEIVEUSER, SHIPREQUESTNAME, SHIPREQUESTDETAILNAME, SHIPTIME,"
		 * +
		 * "SHIPUSER, REASONCODETYPE, OQARESULTSTATE, OQARESULT, ERPLOCATION, ERPFACTORY, REASONCODE, CHARGE, SUPPLIERNAME,ETCSTATE"
		 * + " from MATERIALPACKING m" +
		 * "where (sitename,materialpackingname,TIMEKEY) in ( " +
		 * "SELECT PALLET.SITENAME,PALLET.MATERIALPACKINGNAME,LASTEVENTTIMEKEY  FROM MATERIALPACKING PALLET,"
		 * +
		 * "(SELECT RD.*  FROM  MATERIALSHIPREQUEST R, MATERIALSHIPREQUESTDETAIL RD  "
		 * +
		 * "WHERE R.SHIPREQUESTNAME = RD.SHIPREQUESTNAME   AND RD.SITENAME=R.SITENAME   "
		 * +
		 * "AND R.SHIPREQUESTNAME = :INVOICENO   AND RD.SITENAME=:SITENAME   ) RD   "
		 * +
		 * "WHERE PALLET.SITENAME=RD.SITENAME   AND PALLET.SHIPREQUESTNAME = RD.SHIPREQUESTNAME   "
		 * + "AND PALLET.SHIPREQUESTDETAILNAME = RD.SHIPREQUESTDETAILNAME )  ";
		 * 
		 * resultCount =
		 * IDMFrameServiceProxy.getSqlTemplate().getSimpleJdbcTemplate
		 * ().update(sql, bindMap);
		 */
	}

	public void UpdateUnDoInfo(EventInfo eventInfo, String siteName,
			List<String> materialPackingKeyList, String unDoID,
			String unDoDetailName, String eventUser, String eventComment) {

		try {
			String lastEventTimeKey = TimeStampUtil.getCurrentEventTimeKey();
			// List<MaterialPacking> packingList = new
			// ArrayList<MaterialPacking>();
			List<MaterialPackingKey> packingKeyList = new ArrayList<MaterialPackingKey>();
			Timestamp lastEventTime = new Timestamp(System.currentTimeMillis());

			SetEventInfo setEventInfo = new SetEventInfo();

			Map<String, Object> bindMap = new HashMap<String, Object>();
			bindMap.put("unDoID", unDoID);
			bindMap.put("unDoDetailName", unDoDetailName);

			setEventInfo.setUserColumns(bindMap);

			for (int i = 0; i < materialPackingKeyList.size(); i++) {

				MaterialPackingKey keyInfo = new MaterialPackingKey();
				keyInfo.setSiteName(siteName);
				keyInfo.setMaterialPackingName((String) materialPackingKeyList
						.get(i));
				MaterialPacking dataInfo = selectByKey(keyInfo);
				dataInfo.setUnDoID(unDoID);
				dataInfo.setUnDoDetailName(unDoDetailName);
				dataInfo.setShipTime(lastEventTime);
				dataInfo.setLocationName("");
				dataInfo.setLastEventTime(lastEventTime);
				dataInfo.setLastEventUser(eventUser);
				dataInfo.setLastEventTimeKey(lastEventTimeKey);
				dataInfo.setLastEventComment(eventComment);
				packingKeyList.add(keyInfo);
				MaterialPackingServiceProxy.getMaterialPackingService().update(
						dataInfo);
			}
			MaterialPackingServiceProxy.getMaterialPackingService().setEvent(
					packingKeyList, eventInfo, setEventInfo);
		} catch (IDMFrameDBErrorSignal e) {
			e.printStackTrace();
		}

	}

	/*
	 * Name : ModifyBoxQty Desc : This function is ModifyBoxQty Author : boe cim
	 * dev. Date : 2016.03.10
	 */
	public static void ModifyBoxQty(EventInfo eventInfo, org.jdom.Document doc)
			throws Exception {
		MaterialPackingKey materialPackingKey = new MaterialPackingKey();
		Element root = doc.getDocument().getRootElement();
		Element bodyElement = root.getChild("Body");
		Element materialPackingListElement = bodyElement
				.getChild("MATERIALPACKINGLIST");
		MaterialPacking materialPackingData = new MaterialPacking();

		List<MaterialPacking> listMaterialPacking = new ArrayList<MaterialPacking>();
		List<MaterialPackingKey> listMaterialPacking1 = new ArrayList<MaterialPackingKey>();

		try {
			if (materialPackingListElement != null) {
				for (Iterator<?> iterator = materialPackingListElement
						.getChildren().iterator(); iterator.hasNext();) {
					Element panelE = (Element) iterator.next();
					String materialPackingName1 = panelE.getChild(
							"MATERIALPACKINGNAME").getText();
					String materialQuantity1 = panelE.getChild(
							"MATERIALQUANTITY").getText();
					String siteName = panelE.getChild("SITENAME").getText();

					materialPackingKey
							.setMaterialPackingName(materialPackingName1);
					materialPackingKey.setSiteName(siteName);

					try {
						materialPackingData = MaterialPackingServiceProxy
								.getMaterialPackingService().selectByKey(
										materialPackingKey);

						if (materialPackingData.getMaterialQuantity() != Double
								.parseDouble(materialQuantity1)
								&& Double.parseDouble(materialQuantity1) != 0) {
							materialPackingData.setMaterialQuantity(Double
									.parseDouble(materialQuantity1));
							materialPackingData.setMaterialCreateQuantity(Double
									.parseDouble(materialQuantity1));
						}

						else if (Double.parseDouble(materialQuantity1) == 0) {
							listMaterialPacking1.add(materialPackingData
									.getKey());
						}
						listMaterialPacking.add(materialPackingData);
					} catch (Exception e) {
						throw new CustomException();
					}

				}

				MaterialPackingServiceProxy.getMaterialPackingService().update(
						listMaterialPacking);
				MaterialPackingServiceProxy.getMaterialPackingService().delete(
						listMaterialPacking1);
			}
		} catch (Exception e) {
			throw e;
		}

	}

	public void materialLife() throws Exception {
		List<String> siteName = getSiteList();
		for (int i = 0; i < siteName.size(); i++) {
			String sql = "SELECT DISTINCT"
					+ " A.MATERIALSPECNAME,"
					+ " A.DESCRIPTION,"
					+ " B.ERPLOCATION,"
					+ " B.OQARESULTSTATE,"
					+ " (SELECT sum(materialquantity) FROM  MATERIALPACKING WHERE "
					+ "     MATERIALSPECNAME = B.MATERIALSPECNAME"
					+ "    AND  SITENAME = B.SITENAME "
					+ "    AND OQARESULTSTATE= B.OQARESULTSTATE"
					+ "   GROUP BY MATERIALSPECNAME,OQARESULTSTATE) AS MATERIALQUANTITY,"
					+ " A.MATERIALUNIT,"
					+ " B.MAKEDATE,"
					+ " B.RECEIVETIME,"
					+ " B.LOCATIONNAME,"
					+ " ADD_MONTHS(MAKEDATE, EXPIRATIONDAY ) AS EXPIRATIONDAY,"
					+ " round(ADD_MONTHS(MAKEDATE, EXPIRATIONDAY )-sysdate) AS DAYS"
					+ " FROM MATERIALSPEC A,MATERIALPACKING B"
					+ " WHERE A.EXPIRATIONDATEFLAG = 'Y'"
					+ " AND A.BOARDFLAG = 'Y'" + " AND A.SITENAME = B.SITENAME"
					+ " AND B.SITENAME = :SITENAME"
					+ " AND A.MATERIALSPECNAME = B.MATERIALSPECNAME"
					+ " ORDER BY DAYS";

			Map<String, String> bindMap = new HashMap<String, String>();
			bindMap.put("SITENAME", siteName.get(i));
			List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
					.getSqlTemplate()
					.queryForList(sql, bindMap);
			String result = "";
			// List resultList =
			// IDMFrameServiceProxy.getSqlTemplate().queryForList(sql);
			result = ClientServiceUtil.createXmlByListName(sqlResult,
					"materialLife", "sourceSubject", "targetSubject",
					"transactionId", "queryId", "version");
			ESBService esb = new ESBService();
			esb.send(oicPulishSubject, result);
		}
	}

	public void preStocked() throws Exception {
		List<String> siteName = getSiteList();
		for (int i = 0; i < siteName.size(); i++) {

			String sql = " SELECT MATERIALPROCESSGROUPNAME,MATERIALSPECNAME, "
					+

					" SUM(CASE WHEN PACKINGSTATE='Created' THEN MATERIALQUANTITY ELSE NULL END )UNSTOCKINQTY ,"
					+ " SUM(CASE WHEN PACKINGSTATE='Released' THEN MATERIALQUANTITY ELSE NULL END )UNLOCATIONQTY,MAKEDATE,ERPFACTORY,ERPLOCATION,"
					+ " DESC_CN AS DESCRIPTION,RECEIVEACTNO from ( "
					+ " SELECT "
					+ " A.ERPFACTORY,"
					+ " A.ERPLOCATION,"
					+ " A.PACKINGSTATE,"
					+ " A.MATERIALPACKINGNAME,"
					+ " A.MATERIALSPECNAME,"
					+ " B.DESC_CN,"
					+ " A.RECEIVEACTNO,"
					+ " A.MATERIALQUANTITY,"
					+ " A.MATERIALPROCESSGROUPNAME,"
					+ " A.MAKEDATE"
					+ " FROM MATERIALPACKING A, MATERIALSPEC B "
					+ " WHERE "
					+ " A.LOCATIONNAME IS NULL"
					+ " AND A.MATERIALSPECNAME = B.MATERIALSPECNAME"
					+ " AND A.SITENAME = B.SITENAME "
					+ " AND A.PACKINGSTATE='Created' "
					+ " AND A.STOCKSTATE=NULL "
					+ " AND A.SITENAME = :SITENAME)"
					+ " GROUP BY MATERIALSPECNAME,ERPFACTORY,ERPLOCATION,MATERIALPROCESSGROUPNAME,MAKEDATE,DESC_CN,RECEIVEACTNO "
					+ " ORDER BY MAKEDATE ASC";

			String result = "";
			Map<String, String> bindMap = new HashMap<String, String>();
			bindMap.put("SITENAME", siteName.get(i));
			List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
					.getSqlTemplate()
					.queryForList(sql, bindMap);
			result = ClientServiceUtil.createXmlByListName(sqlResult,
					"preStocked", "sourceSubject", "targetSubject",
					"transactionId", "queryId", "version");
			ESBService esb = new ESBService();
			esb.send(oicPulishSubject, result);
		}

	}

	public void unReturned() throws Exception {
		// String sql_site="select Distinct SITENAME from SITE ";
		List<String> siteName = getSiteList();
		// siteName=IDMFrameServiceProxy.getSqlTemplate().queryForList(sql_site);
		for (int i = 0; i < siteName.size(); i++) {

			String sql = "SELECT DISTINCT" + " A.MATERIALSPECNAME,"
					+ " B.MATERIALTYPE," + " B.LASTEVENTUSER,"
					+ " A.MATERIALPACKINGNAME," + " A.Etcoutqty,"
					+ " A.Etcouttime," + " A.Etcoutuser"
					+ " FROM materialPackingETC A ,materialpacking B"
					+ " WHERE A.ETCSTATE = 'EtcOut' "
					+ " AND A.MATERIALSPECNAME = B.MATERIALSPECNAME"
					+ " AND A.MATERIALPACKINGNAME = B.MATERIALPACKINGNAME"
					+ " AND B.SITENAME = :SITENAME";

			Map<String, String> bindMap = new HashMap<String, String>();
			bindMap.put("SITENAME", siteName.get(i));
			List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
					.getSqlTemplate()
					.queryForList(sql, bindMap);
			String result = "";
			// List resultList =
			// IDMFrameServiceProxy.getSqlTemplate().queryForList(sql);
			result = ClientServiceUtil.createXmlByListName(sqlResult,
					"unReturned", "sourceSubject", "targetSubject",
					"transactionId", "queryId", "version");
			ESBService esb = new ESBService();
			esb.send(oicPulishSubject, result);
		}

	}
	
	public void MESReserve() throws Exception {
		// String sql_site="select Distinct SITENAME from SITE ";
		List<String> siteName = getSiteList();
		// siteName=IDMFrameServiceProxy.getSqlTemplate().queryForList(sql_site);
		for (int i = 0; i < siteName.size(); i++) {

			String sql = "select * from materialshiprequest left join materialshiprequestdetail "
					+ "using(sitename,shiprequestname) where sitename=:SITENAME "
					+ "and shiprequeststate='Created' and systemtype='MES'";

			Map<String, String> bindMap = new HashMap<String, String>();
			bindMap.put("SITENAME", siteName.get(i));
			List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
					.getSqlTemplate()
					.queryForList(sql, bindMap);
			String result = "";
			// List resultList =
			// IDMFrameServiceProxy.getSqlTemplate().queryForList(sql);
			result = ClientServiceUtil.createXmlByListName(sqlResult,
					"MESReserve", "sourceSubject", "targetSubject",
					"transactionId", "queryId", "version");
			ESBService esb = new ESBService();
			esb.send(oicPulishSubject, result);
		}

	}

	public void OQAPreInspect() throws Exception {
		/*List<String> siteName = getSiteList();
		for (int i = 0; i < siteName.size(); i++) {
			String sql = "SELECT MAILTIMES,MAILLASTDATE,SITENAME,MATERIALPROCESSGROUPNAME,MATERIALSPECNAME,"
					+ " SUM(MATERIALQUANTITY) AS MATERIALQUANTITY ,MATERIALUNIT,RECEIVETIME,ERPLOCATION,DESC_CN AS DESCRIPTION,RECEIVEACTNO,SUPPLIERNAME,"
					+ " CASE WHEN OQARESULTSTATE ='PREOQA' THEN SUM(MATERIALQUANTITY)  END AS PRECOUNT,"
					+ "　CASE WHEN OQARESULTSTATE='CONTINUE' THEN SUM(MATERIALQUANTITY) END AS CONTINUECOUNT"
					+ " FROM ("
					+ " SELECT "
					+ " C.MAILTIMES,C.MAILLASTDATE,A.SITENAME,"
					+ " A.MATERIALPACKINGNAME,"
					+ " A.MATERIALSPECNAME,"
					+ " B.DESC_CN,"
					+ " A.RECEIVEACTNO,"
					+ " D.SUPPLIERNAME,"
					+ " A.MATERIALQUANTITY,"
					+ " B.MATERIALUNIT ,"
					+ " A.ERPLOCATION,"
					+ " A.MATERIALPROCESSGROUPNAME,"
					+ " A.RECEIVETIME,"
					+ " A.OQARESULTSTATE AS OQARESULTSTATE"
					+ " FROM MATERIALPACKING A, MATERIALSPEC B, MATERIALPROCESSGROUP C, SUPPLIER D"
					+ " WHERE C.PROCESSGROUPSTATE <>'END'  "
					+ " AND C.MATERIALPROCESSGROUPNAME = A.MATERIALPROCESSGROUPNAME"
					+ " AND A.MATERIALSPECNAME = B.MATERIALSPECNAME"
					+ " AND A.SITENAME = B.SITENAME "
					+ " AND A.SITENAME = :SITENAME "
					+ " AND D.SUPPLIERNO = A.SUPPLIERNAME"
					+ " AND A.SITENAME = C.SITENAME )  GROUP BY "
					+ " MAILTIMES,MAILLASTDATE,SITENAME,MATERIALSPECNAME,MATERIALPROCESSGROUPNAME,MATERIALUNIT,RECEIVETIME,ERPLOCATION,DESC_CN,RECEIVEACTNO,SUPPLIERNAME,OQARESULTSTATE ORDER BY RECEIVETIME ASC";
			Map<String, String> bindMap = new HashMap<String, String>();
			bindMap.put("SITENAME", siteName.get(i));
			List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
					.getSqlTemplate()
					.queryForList(sql, bindMap);
			String result = "";
			// List resultList =
			// IDMFrameServiceProxy.getSqlTemplate().queryForList(sql);
			result = ClientServiceUtil.createXmlByListName(sqlResult,
					"OQAPreInspect", "sourceSubject", "targetSubject",
					"transactionId", "queryId", "version", siteName.get(i));
			ESBService esb = new ESBService();
			esb.send(oicPulishSubject, result);
		}*/
	}

	public List<String> getSiteList() {
		String sql = "select distinct SITENAME from SITE ";
		List<String> siteName = new ArrayList<String>();
		List<Map<String, Object>> siteNameList = IDMFrameServiceProxy
				.getSqlTemplate().queryForList(sql);
		for (int i = 0; i < siteNameList.size(); i++) {
			siteName.add(siteNameList.get(i).get("SITENAME").toString());
		}
		return siteName;
	}
	public String getPODetail(String receiveRequestName,String materialSpecName,String materialQuantity,String custom) {
		String poDetailName="";
		if(custom==null||custom.equals(""))
		{
		String sql = "SELECT a.RECEIVEREQUESTDETAILNAME, a.REQUESTQUANTITY-a.RECEIVEDQUANTITY as QUANTITY FROM MATERIALRECEIVEREQUESTDETAIL a WHERE RECEIVEREQUESTNAME=:receiveRequestName and MATERIALSPECNAME=:materialSpecName and (RETURNFLAG is null or RETURNFLAG <>'X') ";
		Map<String, String> bindMap = new HashMap<String, String>();
		bindMap.put("receiveRequestName", receiveRequestName);
		bindMap.put("materialSpecName", materialSpecName);
		List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
				.getSqlTemplate()
				.queryForList(sql, bindMap);
		
		for (int i = 0; i < sqlResult.size(); i++) {
			if((Double.parseDouble(sqlResult.get(i).get("QUANTITY").toString())-(Double.parseDouble(materialQuantity))>=0))
			{
				poDetailName= sqlResult.get(i).get("RECEIVEREQUESTDETAILNAME").toString();
				break;
			}
		}
		}
		else
		{
			String sql = "SELECT a.RECEIVEREQUESTDETAILNAME, a.REQUESTQUANTITY-a.RECEIVEDQUANTITY as QUANTITY FROM MATERIALRECEIVEREQUESTDETAIL a WHERE ZFPHM=:custom and RECEIVEREQUESTNAME=:receiveRequestName and MATERIALSPECNAME=:materialSpecName and (RETURNFLAG is null or RETURNFLAG <>'X') ";
			Map<String, String> bindMap = new HashMap<String, String>();
			bindMap.put("receiveRequestName", receiveRequestName);
			bindMap.put("materialSpecName", materialSpecName);
			bindMap.put("custom", custom);
			List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
					.getSqlTemplate()
					.queryForList(sql, bindMap);
			
			for (int i = 0; i < sqlResult.size(); i++) {
				if((Double.parseDouble(sqlResult.get(i).get("QUANTITY").toString())-(Double.parseDouble(materialQuantity))>=0))
				{
					poDetailName= sqlResult.get(i).get("RECEIVEREQUESTDETAILNAME").toString();
					break;
				}
		}
		}
		return poDetailName;

	}
	public String getReturnPODetail(String receiveRequestName,String materialSpecName,String materialQuantity) {
		String poDetailName="";
		String sql = "SELECT a.RECEIVEREQUESTDETAILNAME, a.REQUESTQUANTITY-a.RECEIVEDQUANTITY as QUANTITY FROM MATERIALRECEIVEREQUESTDETAIL a WHERE RECEIVEREQUESTNAME=:receiveRequestName and MATERIALSPECNAME=:materialSpecName and  RETURNFLAG ='X' ";
		Map<String, String> bindMap = new HashMap<String, String>();
		bindMap.put("receiveRequestName", receiveRequestName);
		bindMap.put("materialSpecName", materialSpecName);
		List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
				.getSqlTemplate()
				.queryForList(sql, bindMap);
		for (int i = 0; i < sqlResult.size(); i++) {
			if((Double.parseDouble(sqlResult.get(i).get("QUANTITY").toString())-(Double.parseDouble(materialQuantity))>=0))
			{
				poDetailName= sqlResult.get(i).get("RECEIVEREQUESTDETAILNAME").toString();
				break;
			}
		}
		return poDetailName;
	}
	public String getDeassignPODetail(String materialPackingName,String receiveactNo) {
		String poDetailName="";
		String sql = "SELECT a.shiprequestname, a.shiprequestdetailname FROM materialpacking a WHERE materialpackingname=:materialpackingname and receiveactno=:receiveactno  ";
		Map<String, String> bindMap = new HashMap<String, String>();
		bindMap.put("materialpackingname", materialPackingName);
		bindMap.put("receiveactno", receiveactNo);
		List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
				.getSqlTemplate()
				.queryForList(sql, bindMap);
		for (int i = 0; i < sqlResult.size(); i++) {
				poDetailName= sqlResult.get(i).get("SHIPREQUESTDETAILNAME").toString();
				break;
		}
		return poDetailName;
	}
	
	public String getReturnUndoDetail(String receiveRequestName,String materialSpecName,String materialQuantity)throws Exception {
		String poDetailName="";
		String sql = "SELECT C.UNDODETAILNAME AS RECEIVEREQUESTDETAILNAME,(C.REQUESTQUANTITY-(CASE WHEN D.RECEIVEDQUANTITY IS NULL THEN 0 ELSE D.RECEIVEDQUANTITY END))AS QUANTITY FROM "+
				"(SELECT A.UNDODETAILNAME,SUM(MATERIALQUANTITY) AS REQUESTQUANTITY "+
				"FROM BS_MATERIALPACKINGUNDOINFO A "+
				"WHERE A.UNDOID=:receiveRequestName "+
				"AND A.MATERIALSPECNAME=:materialSpecName "+ 
				"GROUP BY A.UNDODETAILNAME,RECEIVEREQUESTDETAILNAME) C "+
				"LEFT JOIN  "+
				"(SELECT B.SHIPREQUESTNAME,B.SHIPREQUESTDETAILNAME,SUM(B.MATERIALQUANTITY)AS RECEIVEDQUANTITY "+
				" FROM MATERIALPACKING B "+
				"WHERE B.SHIPREQUESTNAME=:receiveRequestName "+
				"AND B.MATERIALSPECNAME=:materialSpecName "+
				"GROUP BY SHIPREQUESTNAME,SHIPREQUESTDETAILNAME)D "+
				"ON "+
				"C.UNDODETAILNAME=D.SHIPREQUESTDETAILNAME ";
		Map<String, String> bindMap = new HashMap<String, String>();
		bindMap.put("receiveRequestName", receiveRequestName);
		bindMap.put("materialSpecName", materialSpecName);
		List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
				.getSqlTemplate()
				.queryForList(sql, bindMap);
		for (int i = 0; i < sqlResult.size(); i++) {
			if((Double.parseDouble(sqlResult.get(i).get("QUANTITY").toString())-(Double.parseDouble(materialQuantity))>=0))
			{
				poDetailName= sqlResult.get(i).get("RECEIVEREQUESTDETAILNAME").toString();
				break;
			}
		}
		if(poDetailName.equals(""))
		throw new CustomException("FindDetailError","","");
		return poDetailName;
	}
	public String getReturnUndoPoDetail(String receiveRequestName,String materialPackingName,String materialQuantity)throws Exception {
		String poDetailName="";
		String sql = "SELECT B.SHIPREQUESTNAME,B.SHIPREQUESTDETAILNAME,SUM(B.MATERIALQUANTITY)AS RECEIVEDQUANTITY "+
				" FROM MATERIALPACKING B "+
				"WHERE B.SHIPREQUESTNAME=:receiveRequestName "+
				"AND B.MATERIALPACKINGNAME=:materialPackingName "+
				"GROUP BY SHIPREQUESTNAME,SHIPREQUESTDETAILNAME ";
		Map<String, String> bindMap = new HashMap<String, String>();
		bindMap.put("receiveRequestName", receiveRequestName);
		bindMap.put("materialPackingName", materialPackingName);
		List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
				.getSqlTemplate()
				.queryForList(sql, bindMap);
		for (int i = 0; i < sqlResult.size(); i++) {
				poDetailName= sqlResult.get(i).get("SHIPREQUESTDETAILNAME").toString();
				break;
		}
		if(poDetailName.equals(""))
		throw new CustomException("FindDetailError","","");
		return poDetailName;
	}
	public String getShipRequestDetail(String shipRequestName,String materialSpecName,String materialQuantity)throws Exception {
		String shipRequestDetailName="";
		String sql = "SELECT a.SHIPREQUESTDETAILNAME, a.REQUESTQUANTITY-a.ASSIGNEDQUANTITY as QUANTITY FROM MATERIALSHIPREQUESTDETAIL a WHERE SHIPREQUESTNAME=:shipRequestName and MATERIALSPECNAME=:materialSpecName  ";
		Map<String, String> bindMap = new HashMap<String, String>();
		bindMap.put("shipRequestName", shipRequestName);
		bindMap.put("materialSpecName", materialSpecName);
		List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
				.getSqlTemplate()
				.queryForList(sql, bindMap);
		if(sqlResult.size()>0)
		{
			for (int i = 0; i < sqlResult.size(); i++) {
				if((Double.parseDouble(sqlResult.get(i).get("QUANTITY").toString())-(Double.parseDouble(materialQuantity))>=0))
				{
					shipRequestDetailName= sqlResult.get(i).get("SHIPREQUESTDETAILNAME").toString();
					break;
				}
			}
		}
		if(shipRequestDetailName.equals(""))
			throw new CustomException("FindDetailError","","");
		return shipRequestDetailName;
	}
	public String getOEMRefundDetail(String shipRequestName,String materialSpecName,String materialQuantity)throws Exception {
		String shipRequestDetailName="";
		String sql = "SELECT a.RECEIVEREQUESTNAME, RECEIVEREQUESTDETAILNAME,SUBMATERIALSPECNAME,a.ASSIGNEDQUANTITY as QUANTITY FROM MATERIALSHIPREQUESTTOOEM a WHERE RECEIVEREQUESTNAME=:shipRequestName and SUBMATERIALSPECNAME=:materialSpecName  ";
		Map<String, String> bindMap = new HashMap<String, String>();
		bindMap.put("shipRequestName", shipRequestName);
		bindMap.put("materialSpecName", materialSpecName);
		List<Map<String, Object>> sqlResult = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, bindMap);
		if(sqlResult.size()>0)
		{
			for (int i = 0; i < sqlResult.size(); i++) {
				if((Double.parseDouble(sqlResult.get(i).get("QUANTITY").toString())-(Double.parseDouble(materialQuantity))>=0))
				{
					shipRequestDetailName= sqlResult.get(i).get("RECEIVEREQUESTDETAILNAME").toString();
					break;
				}
			}
		}
		if(shipRequestDetailName.equals(""))
			throw new CustomException("FindDetailError","","");
		return shipRequestDetailName;
	}
	public String getShipRequestActType(String shipRequestName) {
		String actType="";
		String sql = "SELECT a.DELIVERYTYPE, a.SHIPREQUESTDETAILTYPE,a.SYSTEMTYPE FROM MATERIALSHIPREQUEST a WHERE SHIPREQUESTNAME=:shipRequestName   ";
		Map<String, String> bindMap = new HashMap<String, String>();
		bindMap.put("shipRequestName", shipRequestName);
		List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
				.getSqlTemplate()
				.queryForList(sql, bindMap);
		if(sqlResult.size()>0)
		{
			String DELIVERYTYPE= sqlResult.get(0).get("DELIVERYTYPE").toString();
			if(DELIVERYTYPE.equals("WO"))
			{
				actType="WO";
			}
			if(DELIVERYTYPE.equals("Delivery"))
			{
				actType="Refund";
			}
			if(DELIVERYTYPE .equals( "Reserve"))
			{
				String sql2 = "SELECT a.OPERATIONNAME FROM BS_ERPSHIPTYPEINFO a WHERE SHIPREQUESTDETAILTYPE=:shipRequestDetailType   ";
				Map<String, String> bindMap2 = new HashMap<String, String>();
				bindMap2.put("shipRequestDetailType", sqlResult.get(0).get("SHIPREQUESTDETAILTYPE").toString());
				List<Map<String, Object>> sqlResult2 = IDMFrameServiceProxy
						.getSqlTemplate()
						.queryForList(sql2, bindMap2);
				if(sqlResult.get(0).get("SYSTEMTYPE").toString().equals("ERP"))
				{
				if(sqlResult2.get(0).get("OPERATIONNAME").toString().equals("Refund"))
				{
					actType="Refund";
				}
				else{
					actType="Reserve";
				}
				}
				else
				{
					actType="Manual";
				}
				
			}
		}
		return actType;
	}
	public void getQueryResult(String messageName, String queryId,
			String version, String senderName, String siteName)
			throws Exception {

		String usrSql = "SELECT queryString FROM BS_CustomQuery WHERE queryId = ? and version = ? ";

		String[] args = new String[] { queryId, version };

		List<Map<String, Object>> resultList = IDMFrameServiceProxy.getSqlTemplate().queryForList(
				usrSql, args);

		if (resultList.size() == 0)
			throw new CustomException("CanNotFoundQueryID", queryId, version);

		Map<String, Object> queryMap = (Map<String, Object>) resultList.get(0);
		String dbSql = queryMap.get("queryString").toString();
		// dbSql = dbSql.replaceFirst(";\\s*$", "");
		Map<String, String> bindMap = new HashMap<String, String>();
		bindMap.put("SITENAME", siteName);

		List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
				.getSqlTemplate()
				.queryForList(dbSql, bindMap);

		String result = "";

		result = ClientServiceUtil.createXmlByListName(sqlResult,
				"OQAPreInspect", "sourceSubject", "targetSubject",
				"transactionId", queryId, version);

		ESBService esb = new ESBService();

		esb.send(oicPulishSubject, result, senderName);
//      new MailUtil().SendSimpleMail();
	}

	public void PDAStockOutCheck(EventInfo eventInfo, String siteName,
			String materialPackingName, String locationName) throws Exception {
		try {
			MaterialPackingKey materialPackingKey = new MaterialPackingKey();

			SetEventInfo setEventInfo = new SetEventInfo();

			Map<String, Object> bindMap = new HashMap<String, Object>();

			MaterialPacking fmp = new MaterialPacking();

			materialPackingKey.setMaterialPackingName(materialPackingName);
			materialPackingKey.setSiteName(siteName);
			fmp = MaterialPackingServiceProxy.getMaterialPackingService()
					.selectByKey(materialPackingKey);

			// CreateInfo materialPacking = new CreateInfo();
			bindMap.put("locationName", "");

			setEventInfo.setUserColumns(bindMap);

			MaterialPackingServiceProxy.getMaterialPackingService().setEvent(
					materialPackingKey, eventInfo, setEventInfo);
		} catch (IDMFrameDBErrorSignal e) {
			e.printStackTrace();

		}
	}

	public void DeleteBox(String siteName) {
		// 删除状态为PreeCreated的Box
		String sql1 = "delete from materialpacking a  where a.packingstate=:packingstate";
		Map<String, Object> args = new HashMap<String, Object>();

		args.put("packingstate", "PreeCreated");
		IDMFrameServiceProxy.getSqlTemplate()
				.update(sql1, args);

		// 删除历史表
		String sql2 = "delete from materialpackinghistory a  where a.packingstate=:packingstate";

		Map<String, Object> args1 = new HashMap<String, Object>();

		args1.put("packingstate", "PreeCreated");
		IDMFrameServiceProxy.getSqlTemplate()
				.update(sql2, args);
	}

	public void insertStockOutInfo(List<MaterialUnDoinfo> materialUnDoinfoList,
			EventInfo eventInfo,String receiveActNo) throws Exception {
		// List<MaterialUnDoinfo> materialUnDoinfoList=new
		// ERPInterfaceServiceImpl().erpInterface_WMS19(shipType,requestDetailName,eventInfo);

		if (materialUnDoinfoList.size() == 0) {
			throw new CustomException("PK-0001", "", "");
		}

		try {
			String sql_sel = "SELECT MATERIALPACKINGNAME,SITENAME FROM MATERIALPACKING  where UNDODETAILNAME=:seq and RECEIVEACTNO = :receiveActNo";
			String update="UPDATE MATERIALPACKING SET STOCKSTATE='StockOut' where UNDODETAILNAME=:seq and RECEIVEACTNO = :receiveActNo";
			
			String upACT = "UPDATE MATERIALRECEIVEACT T SET T.RECEIVEACTSTATE = 'Received' WHERE T.RECEIVEACTNO = :receiveActNo";// 更新抬头文本

		//String sql_sel2 = "SELECT MATERIALPACKINGNAME,SITENAME ，LASTEVENTTIMEKEY FROM MATERIALPACKING  where UNDODETAILNAME=:seq";
			// String
			// sql="update MATERIALPACKING set UNDODETAILNAME=:unDoDetailName,UNDOID=:unDoID where UNDODETAILNAME=:seq";
			String sql2 = insertUnDOMaterialPackingInfo_v3
					+ "select P.SITENAME,P.MATERIALPACKINGNAME,P.LASTEVENTTIMEKEY FROM MATERIALPACKING P WHERE P.UNDODETAILNAME=:seq and P.RECEIVEACTNO = :receiveActNo )	";

			String seq="";
			for (int i = 0; i < materialUnDoinfoList.size(); i++) {
				Map<String, Object> bindMap = new HashMap<String, Object>();
				Map<String, Object> bindMap1 = new HashMap<String, Object>();
				if(materialUnDoinfoList.get(i).getUnDoID().equalsIgnoreCase("0000")||materialUnDoinfoList.get(i).getUnDoID().equalsIgnoreCase("0000")){
					continue;
				}
				if(materialUnDoinfoList.get(i).getSeq().length()>15)
				{
					seq=materialUnDoinfoList.get(i).getSeq().substring(15);
					bindMap1.put("seq", seq);
				}
				else
				{
					seq=materialUnDoinfoList.get(i).getSeq();
					bindMap1.put("seq", seq);
				}
				bindMap1.put("receiveActNo", receiveActNo);
				log.info("seq:"+seq+" receiveActNo:"+receiveActNo);
				List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
						.getSqlTemplate()
						.queryForList(sql_sel, bindMap1);
				List<MaterialPackingKey> materialPackingKeyList = new ArrayList<MaterialPackingKey>();
				for (int j = 0; j < sqlResult.size(); j++) {
					MaterialPackingKey keyInfo = new MaterialPackingKey();
					keyInfo.setMaterialPackingName(sqlResult.get(j)
							.get("MATERIALPACKINGNAME").toString());
					keyInfo.setSiteName(sqlResult.get(j).get("SITENAME")
							.toString());
					// materialPackingInfo.setKey(keyInfo);
					materialPackingKeyList.add(keyInfo);
				}
				SetEventInfo setEventInfo = new SetEventInfo();
				Map<String, Object> bindMap2 = new HashMap<String, Object>();
				bindMap2.put("unDoDetailName", materialUnDoinfoList.get(i)
						.getUnDoDetailName());
				bindMap2.put("unDoID", materialUnDoinfoList.get(i).getUnDoID());
				bindMap2.put("erpState", "SUCCESS");
				bindMap2.put("stockState", "StockOut");
				bindMap2.put("oldStockState", "Stocked");
				setEventInfo.setUserColumns(bindMap2);
				bindMap.put("unDoDetailName", materialUnDoinfoList.get(i)
						.getUnDoDetailName());
				bindMap.put("unDoID", materialUnDoinfoList.get(i).getUnDoID());
				if(materialUnDoinfoList.get(i).getSeq().length()>15)
				{
					bindMap.put("seq", materialUnDoinfoList.get(i).getSeq().substring(15));
				}
				else
				{
					bindMap.put("seq", materialUnDoinfoList.get(i).getSeq());
				}
				//bindMap.put("seq", materialUnDoinfoList.get(i).getSeq().substring(15));
				bindMap.put("UNDOIDDATE", materialUnDoinfoList.get(i)
						.getUnDoIdDate());
				bindMap.put("receiveActNo", receiveActNo);
				bindMap.put("LASTEVENTNAME", eventInfo.getEventName());
				bindMap.put("LASTEVENTCOMMENT", eventInfo.getEventComment());
				/**
				 * 出库时，会出现1个物料，绑定2个BOX的情况,所以修改为根据抬头文本和SEQ插入BS_MATERIALPACKINGUNDOINFO
				 * 2024-10-12*/
				
				IDMFrameServiceProxy.getSqlTemplate().update(update, bindMap1);

				IDMFrameServiceProxy.getSqlTemplate().update(upACT, bindMap1);
				
				int count = IDMFrameServiceProxy.getSqlTemplate().update(sql2, bindMap);

				MaterialPackingServiceProxy.getMaterialPackingService()
						.setEvent(materialPackingKeyList, eventInfo,
								setEventInfo);
			}
			// MaterialPackingServiceProxy.getMaterialPackingService().makeScrapped(materialPackingKey,
			// eventInfo, makeScrappedInfo);
		} catch (IDMFrameDBErrorSignal ex) {
			log.error(ex, ex);
			throw ex;
		} catch (NotFoundSignal ex) {
			log.error(ex, ex);
			throw ex;
		}
	}

	
	public void insertStockOutInfo(List<MaterialUnDoinfo> materialUnDoinfoList,
			EventInfo eventInfo) throws Exception {
		// List<MaterialUnDoinfo> materialUnDoinfoList=new
		// ERPInterfaceServiceImpl().erpInterface_WMS19(shipType,requestDetailName,eventInfo);

		if (materialUnDoinfoList.size() == 0) {
			throw new CustomException("PK-0001", "", "");
		}

		try {
			String sql_sel = "SELECT MATERIALPACKINGNAME,SITENAME FROM MATERIALPACKING  where UNDODETAILNAME=:seq and receiveactno='ChangeERPLocation'";
			
		//String sql_sel2 = "SELECT MATERIALPACKINGNAME,SITENAME ，LASTEVENTTIMEKEY FROM MATERIALPACKING  where UNDODETAILNAME=:seq";
			// String
			// sql="update MATERIALPACKING set UNDODETAILNAME=:unDoDetailName,UNDOID=:unDoID where UNDODETAILNAME=:seq";
			String sql2 = insertUnDOMaterialPackingInfo_v3
					+ "select P.SITENAME,P.MATERIALPACKINGNAME,P.LASTEVENTTIMEKEY FROM MATERIALPACKING P WHERE P.UNDODETAILNAME=:seq and receiveactno='ChangeERPLocation' )	";

			for (int i = 0; i < materialUnDoinfoList.size(); i++) {
				Map<String, Object> bindMap = new HashMap<String, Object>();
				Map<String, Object> bindMap1 = new HashMap<String, Object>();
				if(materialUnDoinfoList.get(i).getSeq().length()>15)//add by mxh for seq change
				{
					bindMap1.put("seq", materialUnDoinfoList.get(i).getSeq().substring(15));
				}
				else
				{
					bindMap1.put("seq", materialUnDoinfoList.get(i).getSeq());
				}
				//bindMap1.put("seq", materialUnDoinfoList.get(i).getSeq().substring(15));
				//bindMap1.put("receiveActNo", receiveActNo);
				List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
						.getSqlTemplate()
						.queryForList(sql_sel, bindMap1);
				List<MaterialPackingKey> materialPackingKeyList = new ArrayList<MaterialPackingKey>();
				for (int j = 0; j < sqlResult.size(); j++) {
					MaterialPackingKey keyInfo = new MaterialPackingKey();
					keyInfo.setMaterialPackingName(sqlResult.get(j)
							.get("MATERIALPACKINGNAME").toString());
					keyInfo.setSiteName(sqlResult.get(j).get("SITENAME")
							.toString());
					// materialPackingInfo.setKey(keyInfo);
					materialPackingKeyList.add(keyInfo);
				}
				SetEventInfo setEventInfo = new SetEventInfo();
				Map<String, Object> bindMap2 = new HashMap<String, Object>();
				bindMap2.put("unDoDetailName", materialUnDoinfoList.get(i)
						.getUnDoDetailName());
				bindMap2.put("unDoID", materialUnDoinfoList.get(i).getUnDoID());
				bindMap2.put("erpState", "SUCCESS");
				setEventInfo.setUserColumns(bindMap2);
				bindMap.put("unDoDetailName", materialUnDoinfoList.get(i)
						.getUnDoDetailName());
				bindMap.put("unDoID", materialUnDoinfoList.get(i).getUnDoID());
				if(materialUnDoinfoList.get(i).getSeq().length()>15)
				{
					bindMap.put("seq", materialUnDoinfoList.get(i).getSeq().substring(15));
				}
				else
				{
					bindMap.put("seq", materialUnDoinfoList.get(i).getSeq());
				}
				//bindMap.put("seq", materialUnDoinfoList.get(i).getSeq());
				bindMap.put("UNDOIDDATE", materialUnDoinfoList.get(i)
						.getUnDoIdDate());
				//bindMap.put("receiveActNo", receiveActNo);
				bindMap.put("LASTEVENTNAME", eventInfo.getEventName());
				bindMap.put("LASTEVENTCOMMENT", eventInfo.getEventComment());
				// IDMFrameServiceProxy.getSqlTemplate().update(sql2,
				// bindMap1);
				int count=IDMFrameServiceProxy.getSqlTemplate()
						.update(sql2, bindMap);
				MaterialPackingServiceProxy.getMaterialPackingService()
						.setEvent(materialPackingKeyList, eventInfo,
								setEventInfo);
			}
			// MaterialPackingServiceProxy.getMaterialPackingService().makeScrapped(materialPackingKey,
			// eventInfo, makeScrappedInfo);
			System.out.println("8888888888888888888888888888888888");
		} catch (IDMFrameDBErrorSignal ex) {
			log.error(ex, ex);
			throw ex;
		} catch (NotFoundSignal ex) {
			log.error(ex, ex);
			throw ex;
		}
	}
	public void saveERPLocation(List<MaterialUnDoinfo> materialUnDoinfoList,
			EventInfo eventInfo,String boxStr,String siteName,String toERPLocation,String toERPFactory,String reasonType,String receiptor) throws Exception {
		if (materialUnDoinfoList.size() == 0) {
			throw new CustomException("PK-0001", "", "");
		}
		try {
			String sql_sel = "SELECT MATERIALPACKINGNAME,MATERIALPACKINGTYPE FROM MATERIALPACKING" 
						+" WHERE SITENAME=:SITENAME AND  MATERIALPACKINGNAME IN (SELECT REGEXP_SUBSTR(:BOXSTR,'[^,]+', 1, LEVEL) AS BOXID FROM DUAL"
						+" CONNECT BY REGEXP_SUBSTR(:BOXSTR, '[^,]+', 1, LEVEL) IS NOT NULL) AND UNDODETAILNAME=:SEQ "
						+" GROUP BY MATERIALPACKINGNAME,MATERIALPACKINGTYPE";
			String sql_insertUndoInfo = insertUnDOMaterialPackingInfo_v3
					+ "select P.SITENAME,P.MATERIALPACKINGNAME,P.LASTEVENTTIMEKEY FROM MATERIALPACKING P WHERE P.UNDODETAILNAME=:unDoDetailName AND P.MATERIALPACKINGNAME IN (SELECT REGEXP_SUBSTR(:BOXSTR,'[^,]+', 1, LEVEL) AS BOXID FROM DUAL"
					+" CONNECT BY REGEXP_SUBSTR(:BOXSTR, '[^,]+', 1, LEVEL) IS NOT NULL) )	";
			SimpleDateFormat df = new SimpleDateFormat(
					"yyyy-MM-dd HH:mm:ss");
			Date date=new Date();
			String eventTime = df.format(date);
			for (int i = 0; i < materialUnDoinfoList.size(); i++) {
				Map<String, Object> bindMap = new HashMap<String, Object>();				
				if(materialUnDoinfoList.get(i).getSeq().length()>15)//add by mxh for seq change				
					bindMap.put("SEQ", materialUnDoinfoList.get(i).getSeq().substring(15));				
				else				
					bindMap.put("SEQ", materialUnDoinfoList.get(i).getSeq());	
				bindMap.put("SITENAME", siteName);
				bindMap.put("BOXSTR", boxStr);	
				List<Map<String, Object>> sqlResult = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql_sel, bindMap);
				List<MaterialPackingKey> materialPackingKeyList = new ArrayList<MaterialPackingKey>();
				for (int j = 0; j < sqlResult.size(); j++) {
					MaterialPackingKey keyInfo = new MaterialPackingKey();
					keyInfo.setMaterialPackingName(sqlResult.get(j)
							.get("MATERIALPACKINGNAME").toString());
					keyInfo.setSiteName(siteName);
					materialPackingKeyList.add(keyInfo);
					//如果当前为Pallet，获取该拍下所有BOX
					if(sqlResult.get(j).get("MATERIALPACKINGTYPE").toString().equalsIgnoreCase("PALLET"))
					{
						String queryPallet="SELECT MATERIALPACKINGNAME FROM MATERIALPACKING WHERE SUPERMATERIALPACKINGNAME=:SUPERMATERIALPACKINGNAME";
						Map<String,Object> map=new HashMap<String, Object>();
						map.put("SUPERMATERIALPACKINGNAME", keyInfo.getMaterialPackingName());
						List<Map<String,Object>> result=IDMFrameServiceProxy.getSqlTemplate().queryForList(queryPallet, map);
						if(result.size()>0)
						{ 
							
							for(int m= 0;m<result.size();m++)
							{
								MaterialPackingKey mpk=new MaterialPackingKey();
								mpk.setSiteName(siteName);
								mpk.setMaterialPackingName(result.get(m).get("MATERIALPACKINGNAME").toString());
								materialPackingKeyList.add(mpk);
							}
						}				
					}
				}
				SetEventInfo setEventInfo = new SetEventInfo();
				Map<String, Object> bindMap2 = new HashMap<String, Object>();
				bindMap2.put("unDoDetailName", materialUnDoinfoList.get(i).getUnDoDetailName());
				bindMap2.put("unDoID", materialUnDoinfoList.get(i).getUnDoID());
				bindMap2.put("erpState", "SUCCESS");
				bindMap2.put("erpFactory", toERPFactory);
				bindMap2.put("erpLocation", toERPLocation);
				bindMap2.put("locationName", "");
				bindMap2.put("erpEventTime",Timestamp.valueOf(eventTime));
				if (receiptor == null) receiptor = "";//目前之后B11会用这个接收人，其余现地解析的时候可能为null
				bindMap2.put("receiptor", receiptor);
				setEventInfo.setUserColumns(bindMap2);
				bindMap.put("unDoDetailName", materialUnDoinfoList.get(i)
						.getUnDoDetailName());
				bindMap.put("unDoID", materialUnDoinfoList.get(i).getUnDoID());				
				bindMap.put("BOXSTR", boxStr);
				bindMap.put("REASONCODETYPE",reasonType);
				bindMap.put("UNDOIDDATE", materialUnDoinfoList.get(i)
						.getUnDoIdDate());
				bindMap.put("LASTEVENTNAME", eventInfo.getEventName());
				bindMap.put("LASTEVENTCOMMENT", eventInfo.getEventComment());
				
				MaterialPackingServiceProxy.getMaterialPackingService()
						.setEvent(materialPackingKeyList, eventInfo,
								setEventInfo);
				int count=IDMFrameServiceProxy.getSqlTemplate()
						.update(sql_insertUndoInfo, bindMap);
				
			}
		} catch (IDMFrameDBErrorSignal ex) {
			log.error(ex, ex);
			throw ex;
		} catch (NotFoundSignal ex) {
			log.error(ex, ex);
			throw ex;
		}
	}
	/*
	 * Name : CreateBoxAndActInfo Desc : CreateBoxAndActInfo Author : boe cim
	 * dev. Date : 2016.05.03
	 */
	public void SaveDumpStockInList2(String sitename, String receiveActNO,
			EventInfo eventInfo, String shipRequestName) {
		if (receiveActNO != "") {

			MaterialShipRequestKey shipRequestKey = new MaterialShipRequestKey();
			shipRequestKey.setSiteName(sitename);
			shipRequestKey.setShipRequestName(shipRequestName);
			// 根据主键获取 MaterialShipRequest
			MaterialShipRequest shipRequest = MaterialShipRequestServiceProxy
					.getMaterialShipRequestService()
					.selectByKey(shipRequestKey);
			// 目的Factory，Location，SiteName
			String destinationFactory = shipRequest.getErpReceiveFactory();
			String destinationLocation = shipRequest.getErpReceiveLocation();
			String destinationSiteName = new CommonValidation()
					.getSiteName(destinationFactory);

			String sql = "SELECT MATERIALPACKINGNAME,REASONCODE,REASONCODETYPE FROM MATERIALPACKING WHERE SHIPREQUESTNAME=:SHIPREQUESTNAME AND SITENAME=:SITENAME";
			Map<String, Object> bindMap = new HashMap<String, Object>();
			bindMap.put("SHIPREQUESTNAME", shipRequestName);
			bindMap.put("SITENAME", sitename);
			// 根据抬头文本获取要出库BOX集合
			List<Map<String, Object>> resultList = IDMFrameServiceProxy
					.getSqlTemplate()
					.queryForList(sql, bindMap);
			Date date = new Date();
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String receiveDate = df.format(date);

			String updateSql = "UPDATE MATERIALPACKING SET SITENAME =:SITENAME WHERE MATERIALPACKINGNAME=:MATERIALPACKINGNAME AND SITENAME=:OLDSITENAME";
			Map<String, Object> siteMap = new HashMap<String, Object>();
			siteMap.put("SITENAME", destinationSiteName);
			siteMap.put("OLDSITENAME", sitename);
			for (int i = 0; i < resultList.size(); i++) {
				MaterialPackingKey mpKey = new MaterialPackingKey();
				mpKey.setSiteName(destinationSiteName);
				mpKey.setMaterialPackingName(resultList.get(i)
						.get("MATERIALPACKINGNAME").toString());
				siteMap.put("MATERIALPACKINGNAME",
						resultList.get(i).get("MATERIALPACKINGNAME").toString());
				// 更新Box的SiteName信息
				IDMFrameServiceProxy.getSqlTemplate()
						.update(updateSql, siteMap);

				Map<String, Object> columnMap = new HashMap<String, Object>();
				columnMap.put("erpFactory", destinationFactory);
				columnMap.put("packingState", "Released");
				columnMap.put("stockState", "Stocked");
				columnMap.put("erpLocation", destinationLocation);
				columnMap.put("receiveUser", eventInfo.getEventUser());
				columnMap.put("receiveTime", Timestamp.valueOf(receiveDate));
				//转储入库改变lastEventName,清空原有shipRequestName,添加StockInType added by wh
				//columnMap.put("lastEventName", "RefundStockIn");
				//columnMap.put("lastEventComment", "RefundStockIn");
				columnMap.put("shipRequestName", shipRequestName);
				columnMap.put("shipRequestDetailName", "");
				columnMap.put("stockInType", "Refund:301");				
				SetEventInfo setevent = new SetEventInfo();// 以后改成可传参的
				setevent.setUserColumns(columnMap);
				eventInfo.setEventName("RefundStockIn");
				eventInfo.setEventComment("RefundStockIn");
				eventInfo.setReasonCode(resultList.get(i).get("REASONCODE")
						.toString());
				eventInfo.setReasonCodeType(resultList.get(i)
						.get("REASONCODETYPE").toString());
				MaterialPackingServiceProxy.getMaterialPackingService()
						.setEvent(mpKey, eventInfo, setevent);
				//MaterialPacking a=MaterialPackingServiceProxy.getMaterialPackingService().selectByKey(mpKey);
			}
		}

	}
	//20190704
		public void SaveDumpStockInForB3(String sitename, String receiveActNO,
				EventInfo eventInfo, String shipRequestName,String charge) {
			if (receiveActNO != "") {

				MaterialShipRequestKey shipRequestKey = new MaterialShipRequestKey();
				shipRequestKey.setSiteName(sitename);
				shipRequestKey.setShipRequestName(shipRequestName);
				// 根据主键获取 MaterialShipRequest
				MaterialShipRequest shipRequest = MaterialShipRequestServiceProxy
						.getMaterialShipRequestService()
						.selectByKey(shipRequestKey);
				// 目的Factory，Location，SiteName
				String destinationFactory = shipRequest.getErpReceiveFactory();
				String destinationLocation = shipRequest.getErpReceiveLocation();
				String destinationSiteName = new CommonValidation()
						.getSiteName(destinationFactory);

				String sql = "SELECT MATERIALPACKINGNAME,REASONCODE,REASONCODETYPE FROM MATERIALPACKING WHERE SHIPREQUESTNAME=:SHIPREQUESTNAME AND SITENAME=:SITENAME";
				Map<String, Object> bindMap = new HashMap<String, Object>();
				bindMap.put("SHIPREQUESTNAME", shipRequestName);
				bindMap.put("SITENAME", sitename);
				// 根据抬头文本获取要出库BOX集合
				List<Map<String, Object>> resultList = IDMFrameServiceProxy
						.getSqlTemplate()
						.queryForList(sql, bindMap);
				Date date = new Date();
				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				String receiveDate = df.format(date);

				String updateSql = "UPDATE MATERIALPACKING SET SITENAME =:SITENAME WHERE MATERIALPACKINGNAME=:MATERIALPACKINGNAME AND SITENAME=:OLDSITENAME";
				Map<String, Object> siteMap = new HashMap<String, Object>();
				siteMap.put("SITENAME", destinationSiteName);
				siteMap.put("OLDSITENAME", sitename);
				for (int i = 0; i < resultList.size(); i++) {
					MaterialPackingKey mpKey = new MaterialPackingKey();
					mpKey.setSiteName(destinationSiteName);
					mpKey.setMaterialPackingName(resultList.get(i)
							.get("MATERIALPACKINGNAME").toString());
					siteMap.put("MATERIALPACKINGNAME",
							resultList.get(i).get("MATERIALPACKINGNAME").toString());
					// 更新Box的SiteName信息
					IDMFrameServiceProxy.getSqlTemplate()
							.update(updateSql, siteMap);

					Map<String, Object> columnMap = new HashMap<String, Object>();
					columnMap.put("erpFactory", destinationFactory);
					columnMap.put("packingState", "Released");
					columnMap.put("stockState", "Stocked");
					columnMap.put("erpLocation", destinationLocation);
					columnMap.put("receiveUser", eventInfo.getEventUser());
					columnMap.put("receiveTime", Timestamp.valueOf(receiveDate));
					columnMap.put("charge", charge);//转储填写批次为最新box批次
					columnMap.put("shipRequestName", shipRequestName);
					columnMap.put("shipRequestDetailName", "");
					columnMap.put("stockInType", "Refund:301");				
					SetEventInfo setevent = new SetEventInfo();// 以后改成可传参的
					setevent.setUserColumns(columnMap);
					eventInfo.setEventName("RefundStockIn");
					eventInfo.setEventComment("RefundStockIn");
					eventInfo.setReasonCode(resultList.get(i).get("REASONCODE")
							.toString());
					eventInfo.setReasonCodeType(resultList.get(i)
							.get("REASONCODETYPE").toString());
					MaterialPackingServiceProxy.getMaterialPackingService()
							.setEvent(mpKey, eventInfo, setevent);
					//MaterialPacking a=MaterialPackingServiceProxy.getMaterialPackingService().selectByKey(mpKey);
				}
			}

		}
	public void UpdateStockOutInfo(String shipRequestName, 
			EventInfo eventInfo,String siteName) throws Exception {
		// List<MaterialUnDoinfo> materialUnDoinfoList=new
		// ERPInterfaceServiceImpl().erpInterface_WMS19(shipType,requestDetailName,eventInfo);
		try {
			MaterialShipRequestKey shipRequestKey = new MaterialShipRequestKey();
			shipRequestKey.setSiteName(siteName);
			shipRequestKey.setShipRequestName(shipRequestName);
			// 根据主键获取 MaterialShipRequest
			MaterialShipRequest shipRequest = MaterialShipRequestServiceProxy
					.getMaterialShipRequestService()
					.selectByKey(shipRequestKey);
			 //目的Factory，Location，SiteName
			String destinationFactory = shipRequest.getErpReceiveFactory();
			//String destinationLocation = shipRequest.getErpReceiveLocation();
			String destinationSiteName = new CommonValidation()
					.getSiteName(destinationFactory);
			String queryBox = "SELECT SITENAME,ERPLOCATION,ERPFACTORY,UNDOID,MATERIALPACKINGNAME,LASTEVENTNAME,LASTEVENTCOMMENT,STOCKINTYPE,PACKINGSTATE,STOCKSTATE,SHIPREQUESTDETAILNAME"
					+ " FROM MATERIALPACKING WHERE SHIPREQUESTNAME=:SHIPREQUESTNAME ";
			Map<String, Object> bindMap = new HashMap<String, Object>();
			bindMap.put("SHIPREQUESTNAME", shipRequestName);
			//bindMap.put("SITENAME", destinationSiteName);
			// 根据抬头文本获取要出库BOX集合
			List<Map<String, Object>> boxList = IDMFrameServiceProxy
					.getSqlTemplate()
					.queryForList(queryBox, bindMap);
				
			String updateSql = "UPDATE BS_MATERIALPACKINGUNDOINFO SET SITENAME=:SITENAME,ERPLOCATION=:ERPLOCATION,ERPFACTORY=:ERPFACTORY,RECEIVEREQUESTNAME=:RECEIVEREQUESTNAME,"
					+ " LASTEVENTNAME=:LASTEVENTNAME,LASTEVENTCOMMENT=:LASTEVENTCOMMENT,STOCKINTYPE=:STOCKINTYPE,PACKINGSTATE=:PACKINGSTATE,RECEIVEREQUESTDETAILNAME=:RECEIVEREQUESTDETAILNAME,"
					+ " STOCKSTATE=:STOCKSTATE,SHIPREQUESTNAME=:SHIPREQUESTNAME,SHIPREQUESTDETAILNAME=:SHIPREQUESTDETAILNAME"
					+ " WHERE (UNDOID=:UNDOID AND SITENAME=:OLDSITENAME AND MATERIALPACKINGNAME=:MATERIALPACKINGNAME)";			
			for(int i=0;i<boxList.size();i++)
			{							
			Map<String,Object> undoMap=new HashMap<String, Object>();
			undoMap.put("UNDOID", boxList.get(i).get("UNDOID").toString());
			undoMap.put("ERPFACTORY", boxList.get(i).get("ERPFACTORY").toString());
			undoMap.put("ERPLOCATION", boxList.get(i).get("ERPLOCATION").toString());
			undoMap.put("SITENAME",boxList.get(i).get("SITENAME").toString());
			//更新相关字段,与materialpacking保持一致
			undoMap.put("LASTEVENTNAME",boxList.get(i).get("LASTEVENTNAME")==null?"":boxList.get(i).get("LASTEVENTNAME").toString());
			undoMap.put("LASTEVENTCOMMENT",boxList.get(i).get("LASTEVENTCOMMENT")==null?"":boxList.get(i).get("LASTEVENTCOMMENT").toString());
			undoMap.put("STOCKINTYPE",boxList.get(i).get("STOCKINTYPE")==null?"":boxList.get(i).get("STOCKINTYPE").toString());
			undoMap.put("PACKINGSTATE",boxList.get(i).get("PACKINGSTATE")==null?"":boxList.get(i).get("PACKINGSTATE").toString());
			undoMap.put("STOCKSTATE",boxList.get(i).get("STOCKSTATE")==null?"":boxList.get(i).get("STOCKSTATE").toString());
			undoMap.put("SHIPREQUESTNAME","");
			undoMap.put("SHIPREQUESTDETAILNAME","");
			//将shiprequestname存入receiverequestname中，用于返回物料凭证和冲销
			undoMap.put("RECEIVEREQUESTNAME",shipRequestName);
			undoMap.put("RECEIVEREQUESTDETAILNAME",boxList.get(i).get("SHIPREQUESTDETAILNAME")==null?"":boxList.get(i).get("SHIPREQUESTDETAILNAME").toString());
			undoMap.put("OLDSITENAME", siteName);
			undoMap.put("MATERIALPACKINGNAME", boxList.get(i).get("MATERIALPACKINGNAME").toString());
			IDMFrameServiceProxy.getSqlTemplate()
					.update(updateSql, undoMap);
			}
			//清空box的SHIPREQUESTNAME，SHIPREQUESTDETAILNAME
			String clearSql="UPDATE MATERIALPACKING SET SHIPREQUESTNAME=:SHIPREQUESTNAME,SHIPREQUESTDETAILNAME=:SHIPREQUESTDETAILNAME WHERE SHIPREQUESTNAME=:OLDSHIPREQUESTNAME";
			Map<String,Object> clearMap=new HashMap<String, Object>();
			clearMap.put("SHIPREQUESTNAME", "");
			clearMap.put("SHIPREQUESTDETAILNAME", "");
			clearMap.put("OLDSHIPREQUESTNAME", shipRequestName);
			IDMFrameServiceProxy.getSqlTemplate().update(clearSql, clearMap);
		} catch (IDMFrameDBErrorSignal ex) {
			log.error(ex, ex);
			throw ex;
		} catch (NotFoundSignal ex) {
			log.error(ex, ex);
			throw ex;
		}
	}

	public static String CreateBoxAndActInfo(EventInfo eventInfo,
			String siteName, String areaName, String receiveQty,
			String boxQuantity, String EveryBoxQuantity, String boxFlag,
			String receiveRequestName, String receiveRequestDetailName,
			String materialSpecName, String receiveActNo, String makeDate,
			String shipRequestName, String shipRequestDetailName,
			String reasonCodeType, String reasonCode, String erpLocation,
			String erpFactory, String charge, String supplierName,
			String actType, String subMaterialSpecName) throws Exception {
		// 创建抬头文本
		String actType1 = "";
		String newReceiveRequestDetailName = "";
		if (actType.equals("POOEM")) {
			newReceiveRequestDetailName = receiveRequestDetailName + "_"
					+ subMaterialSpecName;
		}
		// receiveRequestName="lixiaolongtest1";
		// ReceiveRequestDetailName="lixiaolongtestDetail";
		// makeDate="2016-02-17 20:17:59";
		// receiveActNo="testabc1";

		/*
		 * SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		 * Timestamp date = (Timestamp) sdf.parse(makeDate);
		 */

		Double ReceiveQuantity = Double.parseDouble(receiveQty);

		// receiveActInfo
		MaterialReceiveActDetailKey materialReceiveActDetailKey = new MaterialReceiveActDetailKey();
		// MaterialReceiveActDetail materialReceiveActDetail = new
		// MaterialReceiveActDetail();
		CreateActDetailInfo createActDetailInfo = new CreateActDetailInfo();
		//
		materialReceiveActDetailKey.setSiteName(siteName);
		materialReceiveActDetailKey.setReceiveRequestName(receiveRequestName);
		if (actType.equals("POOEM")) {
			materialReceiveActDetailKey
					.setReceiveRequestDetailName(newReceiveRequestDetailName);
		} else {
			materialReceiveActDetailKey
					.setReceiveRequestDetailName(receiveRequestDetailName);
		}

		materialReceiveActDetailKey.setReceiveActNO(receiveActNo);
		materialReceiveActDetailKey.setMakeDate(Timestamp.valueOf(makeDate));

		// materialReceiveActDetail=
		// MaterialReceiveRequestActDetailServiceProxy.getMaterialReceiveRequestActDetailService().selectByKey(materialReceiveActDetailKey);

		String sql = "SELECT * FROM materialreceiveactdetail "
				+ "WHERE sitename = :sitename AND receiveRequestName = :receiveRequestName and ReceiveRequestDetailName=:ReceiveRequestDetailName and receiveActNo=:receiveActNo"
				+ " and makeDate=:makeDate ";

		Map<String, Object> bindMap = new HashMap<String, Object>();
		bindMap.put("sitename", siteName);
		bindMap.put("receiveRequestName", receiveRequestName);
		if (actType.equals("POOEM")) {
			bindMap.put("ReceiveRequestDetailName", newReceiveRequestDetailName);
		} else {
			bindMap.put("ReceiveRequestDetailName", receiveRequestDetailName);
		}
		bindMap.put("receiveActNo", receiveActNo);
		bindMap.put("makeDate", Timestamp.valueOf(makeDate));

		List<Map<String, Object>> queryResult = IDMFrameServiceProxy
				.getSqlTemplate()
				.queryForList(sql, bindMap);

		String sql1 = "SELECT * FROM materialreceiveact "
				+ "WHERE sitename = :sitename AND receiveRequestName = :receiveRequestName  and receiveActNo=:receiveActNo ";

		Map<String, Object> bindMap1 = new HashMap<String, Object>();
		bindMap1.put("sitename", siteName);
		bindMap1.put("receiveRequestName", receiveRequestName);
		bindMap1.put("receiveActNo", receiveActNo);

		List<Map<String, Object>> queryResult1 = IDMFrameServiceProxy
				.getSqlTemplate()
				.queryForList(sql1, bindMap1);
		if (queryResult1.size() != 0) {
			actType1 = queryResult1.get(0).get("ACTTYPE").toString();
		}
		if (queryResult1.size() == 0) {
			CreateReceiveRequestBatchInfo createActBatchInfo = new CreateReceiveRequestBatchInfo();
			List<CreateReceiveRequestBatchInfo> createReceiveRequestBatchInfo = new ArrayList<CreateReceiveRequestBatchInfo>();

			Map<String, Object> bindMap2 = new HashMap<String, Object>();

			List<String> materialReceiveRequestAct;
			// String quantity="10";
			String product = "qwe";
			String grade = "w";
			String line = "q";
			String revisionCode = "r";

			createActBatchInfo.setSiteName(siteName);
			createActBatchInfo.setReceiveRequestName(receiveRequestName);
			createActBatchInfo.setReceiveactNO(receiveActNo);
			createActBatchInfo.setReceiveActState("Created");

			bindMap2.put("actType", actType);
			// bindMap2.put("receiveActState", );
			createActBatchInfo.setUserColumns(bindMap2);

			createReceiveRequestBatchInfo.add(createActBatchInfo);

			MaterialReceiveRequestActServiceProxy
					.getReceiveRequestBatchService().create(eventInfo,
							createReceiveRequestBatchInfo);
		}

		if (queryResult.size() == 0) {
			createActDetailInfo.setReceiveActNO(receiveActNo);
			createActDetailInfo.setReceiveRequestName(receiveRequestName);
			if (actType.equals("POOEM")) {
				createActDetailInfo
						.setReceiveRequestDetailName(newReceiveRequestDetailName);
			} else {
				createActDetailInfo
						.setReceiveRequestDetailName(receiveRequestDetailName);
			}
			createActDetailInfo.setSiteName(siteName);

			// Date date1 = new Date();//获取当前时间
			// SimpleDateFormat sdf = new
			// SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			// String str = sdf.format(date1);//时间存储为字符串
			// System.out.println(str);
			createActDetailInfo.setMakeDate(Timestamp.valueOf(makeDate));
			createActDetailInfo.setReceiveQuantity(ReceiveQuantity);

			Map<String, Object> bindMap3 = new HashMap<String, Object>();
			bindMap3.put("receiveActState", "Cteated");

			createActDetailInfo.setUserColumns(bindMap3);

			MaterialReceiveRequestActDetailServiceProxy
					.getMaterialReceiveRequestActDetailService().create(
							eventInfo, createActDetailInfo);
		} else {
			ActDetailIncreaseInfo actDetailIncreaseInfo = new ActDetailIncreaseInfo();
			actDetailIncreaseInfo.setReceiveQuantity(ReceiveQuantity);

			MaterialReceiveRequestActDetailServiceProxy
					.getMaterialReceiveRequestActDetailService()
					.increaseReceivedQuantity(materialReceiveActDetailKey,
							eventInfo, actDetailIncreaseInfo);
		}

		if (actType.equals("Normal") || actType1.equals("Normal")) {
			MakeDetailIncreaseReceivedInfo makeDetailIncreaseReceivedInfo = new MakeDetailIncreaseReceivedInfo();
			MaterialReceiveRequestDetailKey materialReceiveRequestDetailKey = new MaterialReceiveRequestDetailKey();
			materialReceiveRequestDetailKey
					.setReceiveRequestName(receiveRequestName);
			materialReceiveRequestDetailKey.setSiteName(siteName);
			materialReceiveRequestDetailKey
					.setReceiveRequestDetailName(receiveRequestDetailName);

			makeDetailIncreaseReceivedInfo.setIncreaseQuantity(ReceiveQuantity);

			ReceiveRequestDetailServiceProxy.getReceiveRequestDetailService()
					.increaseReceivedQuantity(materialReceiveRequestDetailKey,
							eventInfo, makeDetailIncreaseReceivedInfo);

		}
		// else if(actType.equals("POOEM"))
		// {
		// MakeOEMIncreaseInfo makeOEMIncreaseInfo =new MakeOEMIncreaseInfo();
		// MaterialShipRequestToOEMKey materialShipRequestToOEMKey =new
		// MaterialShipRequestToOEMKey();
		// materialShipRequestToOEMKey.setReceiveRequestName(receiveRequestName);
		// materialShipRequestToOEMKey.setSiteName(siteName);
		// materialShipRequestToOEMKey.setReceiveRequestDetailName(ReceiveRequestDetailName);
		//
		// makeOEMIncreaseInfo.setIncreaseQuantity(ReceiveQuantity);
		//
		// MaterialShipRequestToOEMServiceProxy.getMaterialShipRequestToOEMService().in(materialShipRequestToOEMKey,
		// eventInfo, makeOEMIncreaseInfo);
		// }
		else if (actType.equals("POOEM") || actType1.equals("POOEM")) {

			MakeOEMDecreaseAssignedInfo makeOEMDecreaseAssignedInfo = new MakeOEMDecreaseAssignedInfo();
			MaterialShipRequestToOEMKey materialShipRequestToOEMKey = new MaterialShipRequestToOEMKey();
			materialShipRequestToOEMKey
					.setReceiveRequestName(receiveRequestName);
			materialShipRequestToOEMKey.setSiteName(siteName);
			materialShipRequestToOEMKey
					.setReceiveRequestDetailName(receiveRequestDetailName);
			materialShipRequestToOEMKey
					.setSubMaterialSpecName(subMaterialSpecName);
			makeOEMDecreaseAssignedInfo.setAssignedQuantity(ReceiveQuantity);

			MaterialShipRequestToOEMServiceProxy
					.getMaterialShipRequestToOEMService()
					.decreaseAssignedQuantity(materialShipRequestToOEMKey,
							eventInfo, makeOEMDecreaseAssignedInfo);
		}
		// else if(!actType.equals("POOEM")||!actType1.equals("POOEM"))
		else {
			MakeShipDetailIncreaseAssignedInfo makeShipDetailIncreaseAssignedInfo = new MakeShipDetailIncreaseAssignedInfo();
			MaterialShipRequestDetailKey materialShipRequestDetailKey = new MaterialShipRequestDetailKey();
			materialShipRequestDetailKey.setShipRequestName(receiveRequestName);
			materialShipRequestDetailKey.setSiteName(siteName);
			materialShipRequestDetailKey
					.setShipRequestDetailName(receiveRequestDetailName);

			makeShipDetailIncreaseAssignedInfo
					.setAssignedQuantity(ReceiveQuantity);

			MaterialShipRequestDetailServiceProxy
					.getMaterialShipRequestDetailService()
					.increaseAssignedQuantity(materialShipRequestDetailKey,
							makeShipDetailIncreaseAssignedInfo);
		}

		// 创建Box

		String receiveActNo1 = receiveActNo.substring(5);
		String lastEventTimeKey = "";
		List<CreateInfo> listMaterialPacking = new ArrayList<CreateInfo>();

		List<String> boxId;
		double EveryBoxQuantity1 = 0;
		try {
			if (boxFlag.equals("Y")) {
				double tempV = Math.round((Double.valueOf(receiveQty) - (Double
						.valueOf(boxQuantity) - 1)
						* Double.valueOf(EveryBoxQuantity)) * 100);
				// Double v=(Double) (tempV/100.00);
				EveryBoxQuantity1 = (Double) (tempV / 100.00);
				// Double num=(Double)(Math.round(totalPrice*100)/100)
			}

			boxId = MaterialPackingServiceImpl.generateBoxID("BOXID", siteName,
					boxQuantity, receiveActNo1);

			MaterialSpec materialSpec = new MaterialSpec();
			MaterialSpecKey materialSpecKey = new MaterialSpecKey();
			materialSpecKey.setMaterialSpecName(materialSpecName);
			materialSpecKey.setSiteName(siteName);

			materialSpec = MaterialServiceProxy.getMaterialSpecService()
					.selectByKey(materialSpecKey);

			// try{
			// materialSpec=MaterialServiceProxy.getMaterialSpecService().selectByKey(materialSpecKey);
			// }
			// catch(NotFoundSignal e)
			// {
			// e.s
			// }
			int i = 0;
			for (; i < boxId.size(); i++) {
				CreateInfo materialPacking = new CreateInfo();
				materialPacking.setMaterialPackingName(boxId.get(i));
				materialPacking.setSiteName(siteName);
				materialPacking.setContentMaterialType("MaterialPacking");
				materialPacking.setMaterialPackingType("Pallet");

				Map<String, Object> bindMap2 = new HashMap<String, Object>();
				bindMap2.put("materialQuantity", EveryBoxQuantity);
				bindMap2.put("materialCreateQuantity", EveryBoxQuantity);
				bindMap2.put("packingState", "Created");// 标记Box是刚创建的

				// bindMap2.put("materialPackingType","Pallet");
				// bindMap2.put("contentMaterialType", "MaterialPacking");
				bindMap2.put("materialType", materialSpec.getMaterialType());
				bindMap2.put("materialSpecName", materialSpecName);
				bindMap2.put("stockState", "");
				bindMap2.put("holdState", "N");
				bindMap2.put("areaName", areaName);
				bindMap2.put("createUser", eventInfo.getEventUser());
				bindMap2.put("createTime", eventInfo.getEventTime());
				bindMap2.put("receiveRequestName", receiveRequestName);
				bindMap2.put("receiveRequestDetailName",
						receiveRequestDetailName);
				bindMap2.put("makeDate", makeDate);
				bindMap2.put("receiveActNo", receiveActNo);
				bindMap2.put("shipRequestName", shipRequestName);
				bindMap2.put("shipRequestDetailName", shipRequestDetailName);
				bindMap2.put("reasonCodeType", reasonCodeType);
				bindMap2.put("reasonCode", reasonCode);
				bindMap2.put("erpLocation", erpLocation);
				bindMap2.put("erpFactory", erpFactory);
				bindMap2.put("stockInType", "");
				bindMap2.put("charge", charge);
				bindMap2.put("supplierName", supplierName);

				materialPacking.setUserColumns(bindMap2);

				listMaterialPacking.add(materialPacking);

			}

			if (EveryBoxQuantity1 > 0) {
				CreateInfo materialPacking = new CreateInfo();
				Map<String, Object> bindMap3 = new HashMap<String, Object>();
				bindMap3.put("materialQuantity", EveryBoxQuantity1);
				bindMap3.put("materialCreateQuantity", EveryBoxQuantity1);
				bindMap3.put("packingState", "Created");// 标记Box是刚创建的

				materialPacking = listMaterialPacking.get(boxId.size() - 1);
				materialPacking.setUserColumns(bindMap3);

				listMaterialPacking.remove(boxId.size() - 1);
				listMaterialPacking.add(materialPacking);
			}

			MaterialPackingServiceProxy.getMaterialPackingService().create(
					eventInfo, listMaterialPacking);

			lastEventTimeKey = eventInfo.getEventTimeKey();

		} catch (CustomException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return lastEventTimeKey;
	}

	/*
	 * Name : deleteActNO Desc : This function is deleteActNO Author : boe cim
	 * dev. Date : 2016.01.27
	 */
	public static void deleteActNO(String receiveActNo) throws CustomException {
		IDMFrameServiceProxy.getTxDataSourceManager().beginTransaction();
		String receiveActNo1 = receiveActNo.substring(0,
				receiveActNo.length() - 4).toString();
		String lastserialno = String
				.valueOf(Integer.parseInt(receiveActNo.substring(
						receiveActNo.length() - 4, receiveActNo.length())) - 1);
		if (lastserialno.length() == 1) {
			lastserialno = "000" + lastserialno;
		} else if (lastserialno.length() == 2) {
			lastserialno = "00" + lastserialno;
		} else if (lastserialno.length() == 3) {
			lastserialno = "0" + lastserialno;
		}

		String sql = "UPDATE nameruleserial a set a.lastserialno=:lastserialno  where a.rulename='ReceiveActNo' and a.prefix=:receiveActNo1";

		Map<String, Object> bindMap2 = new HashMap<String, Object>();
		bindMap2.put("lastserialno", lastserialno);
		bindMap2.put("receiveActNo1", receiveActNo1);
		IDMFrameServiceProxy.getSqlTemplate()
				.update(sql, bindMap2);
		IDMFrameServiceProxy.getTxDataSourceManager().commitTransaction();
	}

	/*
	 * Name : ModifyMaterialPackingQuantity Desc : This function is
	 * ModifyMaterialPackingQuantity Author : boe cim dev. Date : 2016.01.27
	 */
	public static void ModifyMaterialPackingQuantity(EventInfo eventInfo,
			org.jdom.Document doc) throws Exception {
		MaterialPackingKey materialPackingKey = new MaterialPackingKey();
		Element root = doc.getDocument().getRootElement();
		Element bodyElement = root.getChild("Body");
		Element materialPackingListElement = bodyElement
				.getChild("MATERIALPACKINGLIST");
		MaterialPacking materialPackingData = new MaterialPacking();
		MaterialPacking materialPackingData1 = new MaterialPacking();

		List<MaterialPacking> listMaterialPacking = new ArrayList<MaterialPacking>();

		try {
			if (materialPackingListElement != null) {
				for (Iterator<?> iterator = materialPackingListElement
						.getChildren().iterator(); iterator.hasNext();) {
					Element panelE = (Element) iterator.next();
					String materialPackingName1 = panelE.getChild(
							"MATERIALPACKINGNAME").getText();
					String materialQuantity1 = panelE.getChild(
							"MATERIALQUANTITY").getText();

					materialPackingKey
							.setMaterialPackingName(materialPackingName1);
					materialPackingKey.setSiteName(panelE.getChild("SITENAME")
							.getText());

					try {
						materialPackingData = MaterialPackingServiceProxy
								.getMaterialPackingService().selectByKey(
										materialPackingKey);
					} catch (Exception e) {
						materialPackingData = null;
					}

					if (materialPackingData != null) {
						materialPackingData.setMaterialQuantity(Double
								.parseDouble(materialQuantity1));
						materialPackingData.setMaterialCreateQuantity(Double
								.parseDouble(materialQuantity1));

						materialPackingData.setPackingState("Created");
						listMaterialPacking.add(materialPackingData);
						materialPackingData1 = materialPackingData;
					}

					else if (materialPackingData == null) {
						CreateInfo createInfo = new CreateInfo();
						createInfo.setMaterialPackingName(materialPackingName1);
						createInfo.setSiteName(panelE.getChild("SITENAME")
								.getText());
						createInfo.setContentMaterialType("");
						createInfo.setMaterialPackingType("Box");

						Map<String, Object> bindMap = new HashMap<String, Object>();

						bindMap.put("materialType",
								materialPackingData1.getMaterialType());
						bindMap.put("materialSpecName",
								materialPackingData1.getMaterialSpecName());
						bindMap.put("stockState", "");
						bindMap.put("holdState", "N");
						bindMap.put("areaName",
								materialPackingData1.getAreaName());
						bindMap.put("createUser", eventInfo.getEventUser());
						bindMap.put("createTime", eventInfo.getEventTime());
						bindMap.put("receiveRequestName",
								materialPackingData1.getReceiveRequestName());
						bindMap.put("receiveRequestDetailName",
								materialPackingData1
										.getReceiveRequestDetailName());
						bindMap.put("makeDate",
								materialPackingData1.getMakeDate());
						//更新到期日信息
						bindMap.put("expiringDate", materialPackingData1.getExpiringDate());
						bindMap.put("receiveActNo",
								materialPackingData1.getReceiveActNo());
						bindMap.put("shipRequestName",
								materialPackingData1.getShipRequestName());
						bindMap.put("shipRequestDetailName",
								materialPackingData1.getShipRequestDetailName());
						bindMap.put("reasonCodeType",
								materialPackingData1.getReasonCodeType());
						bindMap.put("reasonCode",
								materialPackingData1.getReasonCode());
						bindMap.put("erpLocation",
								materialPackingData1.getErpLocation());
						bindMap.put("erpFactory",
								materialPackingData1.getErpFactory());
						bindMap.put("stockInType", "");
						bindMap.put("charge", materialPackingData1.getCharge());
						bindMap.put("supplierName",
								materialPackingData1.getSupplierName());
						bindMap.put("npFlag", materialPackingData1.getNpFlag());
						bindMap.put("materialQuantity",
								Double.parseDouble(materialQuantity1));
						bindMap.put("materialCreateQuantity",
								Double.parseDouble(materialQuantity1));
						bindMap.put("packingState", "Created");
						createInfo.setUserColumns(bindMap);

						eventInfo.setEventName("TrackOutBox");
						eventInfo.setEventComment("TrackOutBox");
						MaterialPackingServiceProxy.getMaterialPackingService()
								.create(eventInfo, createInfo);
					}

				}

				MaterialPackingServiceProxy.getMaterialPackingService().update(
						listMaterialPacking);
			}

			// //删除状态为PreeCreated的Box
			// String sql1 =
			// "delete from materialpacking a  where a.packingstate=:packingstate";
			// Map<String, Object> args = new HashMap<String, Object>();
			//
			// args.put("packingstate", "PreeCreated");
			// IDMFrameServiceProxy.getSqlTemplate().update(sql1,
			// args);
			//
			// //删除历史表
			// String sql2 =
			// "delete from materialpackinghistory a  where a.packingstate=:packingstate";
			//
			// Map<String, Object> args1 = new HashMap<String, Object>();
			//
			// args1.put("packingstate", "PreeCreated");
			// IDMFrameServiceProxy.getSqlTemplate().update(sql2,
			// args);

		} catch (Exception e) {
			throw e;
		}

	}

	/*
	 * Name : generateVirtualUndoName Desc : This function is
	 * generateVirtualUndoName
	 */
	public static String generateVirtualUndoName(String SiteName)
			throws CustomException {
		List<String> args = new ArrayList<String>();
		// 获取系统当前时间
		// java.util.Calendar c=java.util.Calendar.getInstance();
		// java.text.SimpleDateFormat f=new
		// java.text.SimpleDateFormat("yyyyMMdd");

		args.add("UNDO-");
		if (SiteName.equals("B5")) {
			args.add("B5");
		} else if (SiteName.equals("TM1")) {
			args.add("T1");
		}else if (SiteName.equals("B10")) {
			args.add("BA");
		}else if (SiteName.equals("BMDT")) {
			args.add("BM");
		} else if ("B12".equals(SiteName)) {
			args.add("BC");
		} 
		else{
			args.add(SiteName);
		}

		String virtualundoid;

		virtualundoid = NameServiceProxy.getNameRuleDefService()
				.generateName("VirtualUndoID", args, 1).get(0);
		try {
			return virtualundoid;
		} catch (Throwable e) {
			args = new ArrayList<String>();
			args.add("undo-");
			if (SiteName.equals("B5") || SiteName.equals("TM1")) {
				args.add("B5");
			} else if (SiteName.equals("TM1")) {
				args.add("T1");
			}else if (SiteName.equals("B10")) {
				args.add("BA");
			}else if (SiteName.equals("BMDT")) {
				args.add("BM");
			} else if ("B12".equals(SiteName)) {
				args.add("BC");
			}
			else{
				args.add(SiteName);
			}
			return NameServiceProxy.getNameRuleDefService()
					.generateName("VirtualUndoID", args, 1).get(0);
		}
	}

	/*
	 * Name : generateVirtualOQAName Desc : This function is
	 * generateVirtualOQAName
	 */
	public static String generateVirtualOQAName(String SiteName)
			throws CustomException {
		List<String> args = new ArrayList<String>();
		// 获取系统当前时间
		// java.util.Calendar c=java.util.Calendar.getInstance();
		// java.text.SimpleDateFormat f=new
		// java.text.SimpleDateFormat("yyyyMMdd");

		args.add("OQA-");
		if (SiteName.equals("B5")) {
			args.add("B5");
		} else if (SiteName.equals("TM1")) {
			args.add("T1");
		}else if (SiteName.equals("B10")) {
			args.add("BA");
		}else if (SiteName.equals("BMDT")) {
			args.add("BM");
		} else if ("B12".equals(SiteName)) {
			args.add("BC");
		}
		else{
			args.add(SiteName);
		}

		String virtualOQAid;

		virtualOQAid = NameServiceProxy.getNameRuleDefService()
				.generateName("VirtualOQA", args, 1).get(0);
		try {
			return virtualOQAid;
		} catch (Throwable e) {
			args = new ArrayList<String>();
			args.add("OQA-");
			if (SiteName.equals("B5") || SiteName.equals("TM1")) {
				args.add("B5");
			} else if (SiteName.equals("TM1")) {
				args.add("T1");
			}else if (SiteName.equals("B10")) {
				args.add("BA");
			}else if (SiteName.equals("BMDT")) {
				args.add("BM");
			} else if ("B12".equals(SiteName)) {
				args.add("BC");
			}else{
				args.add(SiteName);
			}
			return NameServiceProxy.getNameRuleDefService()
					.generateName("VirtualOQA", args, 1).get(0);
		}
	}

	/*
	 * Name : generateVirtualPOName Desc : This function is
	 * generateVirtualPOName
	 */
	public static String generateVirtualPOName(String siteName)
			throws CustomException {
		List<String> args = new ArrayList<String>();
		// 获取系统当前时间
		// java.util.Calendar c=java.util.Calendar.getInstance();
		// java.text.SimpleDateFormat f=new
		// java.text.SimpleDateFormat("yyyyMMdd");

		args.add("PO-");
		if (siteName.equals("B5")) {
			args.add("B5");
		} else if (siteName.equals("TM1")) {
			args.add("T1");
		}else if (siteName.equals("B10")) {
			args.add("BA");
		}else if (siteName.equals("BMDT")) {
			args.add("BM");
		} else if ("B12".equals(siteName)) {
			args.add("BC");
		}
		else{
			args.add(siteName);
		}

		String virtualOQAid;

		virtualOQAid = NameServiceProxy.getNameRuleDefService()
				.generateName("VirtualPO", args, 1).get(0);
		try {
			return virtualOQAid;
		} catch (Throwable e) {
			args = new ArrayList<String>();
			args.add("PO-");
			if (siteName.equals("B5") || siteName.equals("TM1")) {
				args.add("B5");
			} else if (siteName.equals("TM1")) {
				args.add("T1");
			}else if (siteName.equals("B10")) {
				args.add("BA");
			}else if (siteName.equals("BMDT")) {
				args.add("BM");
			} else if ("B12".equals(siteName)) {
				args.add("BC");
			}
			else{
				args.add(siteName);
			}
			return NameServiceProxy.getNameRuleDefService()
					.generateName("VirtualPO", args, 1).get(0);
		}
	}
	
	public static String generateShipRequestName(String siteName)
			throws Throwable {
		List<String> args = new ArrayList<String>();
		// 获取系统当前时间
		// java.util.Calendar c=java.util.Calendar.getInstance();
		// java.text.SimpleDateFormat f=new
		// java.text.SimpleDateFormat("yyyyMMdd");

		Date dt=new Date();
		
	    SimpleDateFormat matter1=new SimpleDateFormat("yyyyMMdd");
	    	   
		String time = matter1.format(dt);
		
		
		args.add(time);

		String virtualOQAid;

		virtualOQAid = NameServiceProxy.getNameRuleDefService()
				.generateName("ShipRequestName", args, 1).get(0);
		try {
			return virtualOQAid;
		} catch (Throwable e) {
			
			throw e;
		}
	}
	
	public static String generateShipRequestDetailName(String shipRequestName)
			throws Throwable {
		
		List<String> args = new ArrayList<String>();
	
	
		args.add(shipRequestName);

		String virtualOQAid;

		virtualOQAid = NameServiceProxy.getNameRuleDefService()
				.generateName("ShipRequestDetailName", args, 1).get(0);
		try {
			return virtualOQAid;
		} catch (Throwable e) {
			
			throw e;
		}
	}
	
	public static String generateReceiveRequestDetailName(String receiveRequestName)
			throws Throwable {
		
		List<String> args = new ArrayList<String>();
	
	
		args.add(receiveRequestName);

		String virtualOQAid;

		virtualOQAid = NameServiceProxy.getNameRuleDefService()
				.generateName("receiveRequestDetailName", args, 1).get(0);
		try {
			return virtualOQAid;
		} catch (Throwable e) {
			
			throw e;
		}
	}
	
	public void RevertNPStockIn(EventInfo eventInfo,
			List<MaterialUnDoinfo> newUnDoList1, String UnDoID,
			String erpEventTime, List<String> siteNameList,
			List<String> unDoDetailNameList)throws Exception{
		CommonValidation cv = new CommonValidation();
		if (unDoDetailNameList.size() == 0) {
			throw new CustomException("PK-0001", "", "");
		}
		try {
			String sql_selUndoBoxInfo = " SELECT SITENAME,MATERIALPACKINGNAME ,SHIPREQUESTNAME "
					+ "FROM MATERIALPACKING "
					+ "WHERE (SITENAME,MATERIALPACKINGNAME) IN( "
					+ "SELECT SITENAME,DESTMATERIALPACKINGNAMENAME AS MATERIALPACKINGNAME  "
					+ "FROM BS_MATERIALPACKINGSPLITMERGE "
					+ "CONNECT BY  MATERIALPACKINGNAME=PRIOR DESTMATERIALPACKINGNAMENAME "
					+ "START WITH (SITENAME,MATERIALPACKINGNAME) IN( "
					+ "SELECT SITENAME,MATERIALPACKINGNAME "
					+ " FROM BS_MATERIALPACKINGUNDOINFO BS "
					+ " WHERE BS.UNDOID=:UNDOID AND "
					+ "BS.SITENAME=:sitename AND BS.UNDODETAILNAME=:undodetailname "
					+ " AND LASTEVENTNAME='NormalStockIn' )"
					+ " union "
					+ "SELECT SITENAME,MATERIALPACKINGNAME "
					+ "FROM BS_MATERIALPACKINGUNDOINFO BS "
					+ "WHERE BS.UNDOID=:UNDOID AND "
					+ "BS.SITENAME=:sitename AND BS.UNDODETAILNAME=:undodetailname "
					+ "AND LASTEVENTNAME='NormalStockIn' "
					+ ")"
					+ "and PACKINGSTATE<>'Emptied'"
					+ "and NPFLAG ='Y'";
			String sql_selPreUndoInfo = "select DISTINCT ERPLOCATION,ERPFACTORY "
					+ "FROM BS_MATERIALPACKINGUNDOINFO A "
					+ "WHERE A.UNDOID IN( "
					+ "SELECT B.PREUNDOID FROM BS_MATERIALPACKINGUNDOINFO B "
					+ "WHERE B.UNDOID=:OLDUNDOID AND B.UNDODETAILNAME=:OLDUNDODETAILNAME "
					+ ") "
					+ "AND A.MATERIALPACKINGNAME IN( "
					+ "SELECT B.MATERIALPACKINGNAME FROM BS_MATERIALPACKINGUNDOINFO B "
					+ "WHERE B.UNDOID=:OLDUNDOID AND B.UNDODETAILNAME=:OLDUNDODETAILNAME "
					+ ")";
			HashMap<String, String> unDoDetailNameListMap = new HashMap<String, String>();
//			MaterialUnDoinfo eundo = new MaterialUnDoinfo();
//			eundo.setUnDoDetailName("test1");
//			eundo.setUnDoID("Test");
//			eundo.setSeq("1");
//			eundo.setUnDoIdDate("2016");
//			//newUnDoList.add(eundo);
//			List<MaterialUnDoinfo> newUnDoList1 = new ArrayList<MaterialUnDoinfo>();
//			newUnDoList1.add(eundo);
			for (int i = 0; i < newUnDoList1.size(); i++) {
				unDoDetailNameListMap.put(Integer.toString(i + 1),
						unDoDetailNameList.get(i));

			}

			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Date erpdate = sdf.parse(cv.getDate(erpEventTime));
			for (int i = 0; i < newUnDoList1.size(); i++) {
				List<MaterialPackingKey> materialPackingKeyList = new ArrayList<MaterialPackingKey>();
				Map<String, Object> bindMap_selUndoBoxInfo = new HashMap<String, Object>();
				Map<String, Object> bindMap_sql_selPreUndoInfo = new HashMap<String, Object>();
				bindMap_selUndoBoxInfo.put("sitename", siteNameList.get(i));
				bindMap_selUndoBoxInfo.put("UNDOID", UnDoID);
				bindMap_selUndoBoxInfo.put("undodetailname",
						unDoDetailNameListMap.get(newUnDoList1.get(i).getSeq()));
				bindMap_sql_selPreUndoInfo.put("OLDUNDOID", UnDoID);
				bindMap_sql_selPreUndoInfo.put("OLDUNDODETAILNAME",
						unDoDetailNameListMap.get(newUnDoList1.get(i).getSeq()));
				// bindMap_UndoBoxInfo.put("REQUESTDETAILNAME",requestDetailName);
				List<Map<String, Object>> queryResult_BoxInfo = IDMFrameServiceProxy
						.getSqlTemplate()
						
						.queryForList(sql_selUndoBoxInfo,
								bindMap_selUndoBoxInfo);
				List<Map<String, Object>> queryResult_PreUndoInfo = IDMFrameServiceProxy
						.getSqlTemplate()
						
						.queryForList(sql_selPreUndoInfo,
								bindMap_sql_selPreUndoInfo);
				for (int j = 0; j < queryResult_BoxInfo.size(); j++) {
					MaterialPackingKey keyInfo = new MaterialPackingKey();
					keyInfo.setMaterialPackingName(queryResult_BoxInfo.get(j)
							.get("MATERIALPACKINGNAME").toString());
					keyInfo.setSiteName(queryResult_BoxInfo.get(j)
							.get("SITENAME").toString());
					// keyInfo=(materialPackingList.get(i).getKey());
					materialPackingKeyList.add(keyInfo);
				}
//				String shipRequestName = queryResult_BoxInfo.get(0)
//						.get("SHIPREQUESTNAME").toString();
//				String siteName = siteNameList.get(0);
//				MaterialShipRequestKey materialShipRequestKey = new MaterialShipRequestKey();
//				materialShipRequestKey.setShipRequestName(shipRequestName);
//				materialShipRequestKey.setSiteName(siteName);
//
//				MaterialShipRequestMakeReservedInfo makeReservedInfo = new MaterialShipRequestMakeReservedInfo();

				SetEventInfo setEventInfo = new SetEventInfo();
				Map<String, Object> bindMap = new HashMap<String, Object>();
				//bindMap.put("packingState", queryResult_PreUndoInfo.get(0).get("PACKINGSTATE"));
				//bindMap.put("stockState", queryResult_PreUndoInfo.get(0).get("STOCKSTATE"));
				//bindMap.put("oqaResultState", queryResult_PreUndoInfo.get(0).get("OQARESULTSTATE"));
				bindMap.put("erpEventTime", erpdate);
				bindMap.put("erpState","SUCCESS");
				bindMap.put("unDoID", newUnDoList1.get(i).getUnDoID());
				bindMap.put("unDoDetailName", newUnDoList1.get(i)
						.getUnDoDetailName());
//				bindMap.put("erpLocation",
//						queryResult_PreUndoInfo.get(0).get("ERPLOCATION"));
//				bindMap.put("erpFactory",
//						queryResult_PreUndoInfo.get(0).get("ERPFACTORY"));
				setEventInfo.setUserColumns(bindMap);
//				MaterialShipRequestServiceProxy.getMaterialShipRequestService()
//						.makeReserved(materialShipRequestKey, eventInfo,
//								makeReservedInfo);
				MaterialPackingServiceProxy.getMaterialPackingService()
						.setEvent(materialPackingKeyList, eventInfo,
								setEventInfo);
			}

			String sql_UndoBoxInfo = " UPDATE BS_MATERIALPACKINGUNDOINFO A SET UNDOIDSTATE='N' WHERE A.UNDOID=:UNDOID AND MATERIALPACKINGNAME IN (SELECT MATERIALPACKINGNAME"
					+ " FROM BS_MATERIALPACKINGUNDOINFO BS"
					+ " WHERE BS.UNDOID=:UNDOID AND("
					+ " ("
					+ " BS.UNDODETAILNAME=:UNDODETAILNAME"
					+ " AND BS.SITENAME=:SITENAME"
					+ " )"
					+ " AND UNDOIDSTATE<>'N'" + " AND LASTEVENTNAME<>'MToM'))";
			String sql_UndoBoxInfo1 ="UPDATE BS_MATERIALPACKINGUNDOINFO A SET UNDOIDSTATE='Created' "
					+ "WHERE MATERIALPACKINGNAME IN "
					+ "(SELECT MATERIALPACKINGNAME FROM BS_MATERIALPACKINGUNDOINFO BS "
					+ "WHERE BS.UNDOID=:UNDOID AND BS.UNDODETAILNAME=:UNDODETAILNAME AND BS.SITENAME=:SITENAME) "
					+ "AND A.LASTEVENTNAME='NoPOStockIn' AND A.UNDOIDSTATE='N'";
			String sql_insert = insertUnDOMaterialPackingInfo_v2
					+ " AND UNDODETAILNAME = :unDoDetailName ";
			for (int i = 0; i < unDoDetailNameList.size(); i++) {
				Map<String, Object> bindMap_UndoBoxInfo = new HashMap<String, Object>();
				Map<String, Object> bindMap_insert = new HashMap<String, Object>();
				bindMap_UndoBoxInfo.put("SITENAME", siteNameList.get(i));
				bindMap_UndoBoxInfo.put("UNDOID", UnDoID);
				bindMap_UndoBoxInfo.put("UNDODETAILNAME",
						unDoDetailNameList.get(i));
				bindMap_insert.put("unDoID", newUnDoList1.get(i).getUnDoID());
				bindMap_insert.put("oldUndoid", UnDoID);
				bindMap_insert.put("UNDOIDDATE", newUnDoList1.get(i)
						.getUnDoIdDate());
				bindMap_insert.put("unDoDetailName", newUnDoList1.get(i)
						.getUnDoDetailName());
				IDMFrameServiceProxy.getSqlTemplate()
						.update(sql_UndoBoxInfo, bindMap_UndoBoxInfo);
				IDMFrameServiceProxy.getSqlTemplate()
				.update(sql_UndoBoxInfo1, bindMap_UndoBoxInfo);
				IDMFrameServiceProxy.getSqlTemplate()
						.update(sql_insert, bindMap_insert);

			}

		} catch (IDMFrameDBErrorSignal ex) {
			log.error(ex, ex);
			throw ex;
		} catch (NotFoundSignal ex) {
			log.error(ex, ex);
			throw ex;
		}
	}
	
	/*
	 * Name : checkBoxOQA  Desc : Whether this function is done oqa
	 */
	public static String checkBoxOQA(String shipRequestName,
			String shipRequestDetailName,String siteName,String stockState) throws Throwable
	{
       try{
    	   String sql = "select siteName ,materialPackingName from materialPacking where shiprequestname=:shiprequestname"
    	   		+ " and shiprequestdetailname =:shiprequestdetailname and sitename =:sitename and stockstate =:stockstate";
    	   
    	   Map<String, Object> bindMap = new HashMap<String, Object>();
    	   
    	   bindMap.put("shiprequestname", shipRequestName);
    	   bindMap.put("shiprequestdetailname", shipRequestDetailName);
    	   bindMap.put("sitename", siteName);
    	   bindMap.put("stockstate", stockState);
    	   
    	   List<Map<String, Object>> arg =IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, bindMap);
    	   
    	   int i=0;
    	   MaterialPackingNoPOStockInImpl objMaterialPackingNoPOStockInImpl = new MaterialPackingNoPOStockInImpl();
    	   
    	   List<MaterialPackingKey> materialPakcingKeyList = new ArrayList<MaterialPackingKey>();
    	   for(;i<arg.size();i++)
    	   {
    		   MaterialPackingKey objMaterialPackingKey = new MaterialPackingKey();
    		   objMaterialPackingKey.setSiteName(siteName);
    		   objMaterialPackingKey.setMaterialPackingName(arg.get(i).get("MaterialPackingName").toString());
    		   
    		   if(objMaterialPackingNoPOStockInImpl.checkOQA(objMaterialPackingKey))
    		   {
    			   materialPakcingKeyList.add(objMaterialPackingKey);
    		   }
    		   else
    		   {
    			   throw new CustomException("PK-0001", "", ""); 
    		   }
    		   
    	   }
    	   
       }
       catch(Throwable e) {
			
			throw e;
		}
		return null;
		
	}
	
	public static String moveDB2BD(String toSiteName,String DBLink,
			String shipRequestName,EventInfo eventinfo) throws Throwable
	{
       try{
		   Date date = new Date();
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String receiveDate = df.format(date);
    	   
    	   Map<String, Object> bindMapShipRequest = new HashMap<String, Object>();
      	   bindMapShipRequest.put("shiprequestname", shipRequestName); 
      	   bindMapShipRequest.put("siteName", toSiteName); 
      	   String sqlSelect = "select erpreceivelocation,erpreceivefactory from materialshiprequest where shiprequestname=:shiprequestname";
  	       List<Map<String, Object>> map = IDMFrameServiceProxy.getSqlTemplate().queryForList(sqlSelect, bindMapShipRequest);
    	   
  	       Map<String, Object> bindMapUpdate = new HashMap<String, Object>();
  	       bindMapUpdate.put("erpLocation",map.get(0).get("ERPRECEIVELOCATION").toString());
		   bindMapUpdate.put("erpFactory",map.get(0).get("ERPRECEIVEFACTORY").toString());
		   bindMapUpdate.put("stockState","Stocked");
		   bindMapUpdate.put("packingState","Released");
		   bindMapUpdate.put("stockInType","Refund:301");
		   bindMapUpdate.put("receiveTime", Timestamp.valueOf(receiveDate));		   
		   bindMapUpdate.put("shiprequestname", shipRequestName);
		   String sqlUpdate = "update materialPacking set erpLocation=:erpLocation,erpFactory=:erpFactory,stockState=:stockState,packingState=:packingState,receiveTime=:receiveTime where shiprequestname=:shiprequestname";
		   IDMFrameServiceProxy.getSqlTemplate().update(sqlUpdate, bindMapUpdate);
  	       
		  /* String sqlInsertDB = "insert into " + "materialPacking"+DBLink+ " select * from materialPacking where shiprequestname=:shiprequestname"; 
    	   IDMFrameServiceProxy.getSqlTemplate().update(sqlInsertDB, bindMapShipRequest);  
    	   
    	   String sqlUpdateDB1 = "update materialPacking"+DBLink+ " set siteName=:siteName,shiprequestname='',shiprequestdetailname='' where shiprequestname=:shiprequestname";
		   IDMFrameServiceProxy.getSqlTemplate().update(sqlUpdateDB1, bindMapShipRequest);
		   */
		   String sqlUpdateDB2 = "update materialPacking set stockState='StockOut' where shiprequestname=:shiprequestname";
		   IDMFrameServiceProxy.getSqlTemplate().update(sqlUpdateDB2, bindMapShipRequest);

       }
       catch(Throwable e) {
			
			e.printStackTrace();
			throw e;
		}
		return null;
	}
	
	public void ModifySupplierAndMakeDate(String siteName, String materialPackingName,
			String supplierName, String makeDate, EventInfo eventInfo) throws Exception {
		try {
			String sql = "update materialPacking set supplierName = :supplierName, makeDate = :makeDate," +
					"lastEventComment = :lastEventComment, lastEventName = :lastEventName," +
					"lastEventTime = :lastEventTime, lastEventTimeKey = :lastEventTimeKey," +
					"lastEventUser = :lastEventUser where siteName = :siteName and " +
					"materialPackingName = :materialPackingName";
			Map<String, Object> bindMap = new HashMap<String, Object>();
			bindMap.put("supplierName", supplierName);
			bindMap.put("makeDate", Timestamp.valueOf(makeDate));
			bindMap.put("lastEventComment", eventInfo.getEventComment());
			bindMap.put("lastEventName", eventInfo.getEventName());
			bindMap.put("lastEventTime", eventInfo.getEventTime());
			bindMap.put("lastEventTimeKey", eventInfo.getLastEventTimekey());
			bindMap.put("lastEventUser", eventInfo.getEventUser());
			bindMap.put("siteName", siteName);
			bindMap.put("materialPackingName", materialPackingName);
			
			IDMFrameServiceProxy.getSqlTemplate().update(sql, bindMap);
		} catch (IDMFrameDBErrorSignal e) {
			e.printStackTrace();
		}
	}
	public void updateMaterialreceiveactState(EventInfo eventInfo,
			String siteName, String receiveRequestName, String receiveActNo,
			String state) throws CustomException, ParseException 
	{
		MaterialReceiveAct act=new MaterialReceiveAct();
		MaterialReceiveActKey actKey=new MaterialReceiveActKey();
		actKey.setSiteName(siteName);
		actKey.setReceiveactNO(receiveActNo);
		actKey.setReceiveRequestName(receiveRequestName);
		act.setReceiveActState(state);
		act.setKey(actKey);
		MaterialReceiveRequestActServiceProxy.getReceiveRequestBatchService().update(act);
	}
	public void insertPreStockOutInfo(List<MaterialUnDoinfo> materialUnDoinfoList,
			EventInfo eventInfo,String receiveActNo,String siteName,String receiptor) throws Exception {
		if (materialUnDoinfoList.size() == 0) {
			throw new CustomException("PK-0001", "", "");
		}
		try {
			String sql_sel = "SELECT MATERIALPACKINGNAME,MATERIALPACKINGTYPE FROM MATERIALPACKING  where UNDODETAILNAME=:seq and RECEIVEACTNO = :receiveActNo";			
			String sql2 = insertUnDOMaterialPackingInfo_v3
					+ "select P.SITENAME,P.MATERIALPACKINGNAME,P.LASTEVENTTIMEKEY FROM MATERIALPACKING P WHERE P.UNDODETAILNAME=:unDoDetailName and P.RECEIVEACTNO = :receiveActNo )	";
			for (int i = 0; i < materialUnDoinfoList.size(); i++) {
				Map<String, Object> bindMap = new HashMap<String, Object>();
				Map<String, Object> bindMap1 = new HashMap<String, Object>();
				if(materialUnDoinfoList.get(i).getUnDoID().equalsIgnoreCase("0000")||materialUnDoinfoList.get(i).getUnDoID().equalsIgnoreCase("0000")){
					throw new CustomException("ERP-0002","","");
				}
				if(materialUnDoinfoList.get(i).getSeq().length()>15)
				{
					bindMap1.put("seq", materialUnDoinfoList.get(i).getSeq().substring(15));
				}
				else
				{
					bindMap1.put("seq", materialUnDoinfoList.get(i).getSeq());
				}
				bindMap1.put("receiveActNo", receiveActNo);
				List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
						.getSqlTemplate()
						.queryForList(sql_sel, bindMap1);
				List<MaterialPackingKey> materialPackingKeyList = new ArrayList<MaterialPackingKey>();
				for (int j = 0; j < sqlResult.size(); j++) {
					MaterialPackingKey keyInfo = new MaterialPackingKey();
					keyInfo.setMaterialPackingName(sqlResult.get(j)
							.get("MATERIALPACKINGNAME").toString());
					keyInfo.setSiteName(siteName);
					materialPackingKeyList.add(keyInfo);
					if(sqlResult.get(j).get("MATERIALPACKINGTYPE").toString().equals("Pallet"))
					{
						String queryPallet="SELECT MATERIALPACKINGNAME FROM MATERIALPACKING WHERE SUPERMATERIALPACKINGNAME=:SUPERMATERIALPACKINGNAME";
						Map<String,Object> map=new HashMap<String, Object>();
						map.put("SUPERMATERIALPACKINGNAME", sqlResult.get(j).get("MATERIALPACKINGNAME").toString());
						List<Map<String,Object>> result=IDMFrameServiceProxy.getSqlTemplate().queryForList(queryPallet, map);
						if(result.size()>0)
						{ 							
							//获取该pallet下所有box
							for(int m= 0;m<result.size();m++)
							{
								keyInfo.setMaterialPackingName(result.get(m).get("MATERIALPACKINGNAME").toString());								
								materialPackingKeyList.add(keyInfo);
							}							
						}	
					}
					
				}
				Timestamp lastEventTime = new Timestamp(System.currentTimeMillis());
				SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
				CommonValidation cv = new CommonValidation();

				SetEventInfo setEventInfo = new SetEventInfo();
				Map<String, Object> bindMap2 = new HashMap<String, Object>();
				bindMap2.put("unDoDetailName", materialUnDoinfoList.get(i).getUnDoDetailName());
				bindMap2.put("unDoID", materialUnDoinfoList.get(i).getUnDoID());
				bindMap2.put("shipTime", lastEventTime);
				bindMap2.put("erpEventTime", lastEventTime);
				bindMap2.put("erpState", "SUCCESS");
				bindMap2.put("stockState", "StockOut");
				bindMap2.put("oldStockState", "Stocked");
				bindMap2.put("locationName", "");
				if (receiptor == null) receiptor = "";//目前之后B11会用这个接收人，其余现地解析的时候可能为null
				bindMap2.put("receiptor", receiptor);
				setEventInfo.setUserColumns(bindMap2);
				bindMap.put("unDoDetailName", materialUnDoinfoList.get(i)
						.getUnDoDetailName());
				bindMap.put("unDoID", materialUnDoinfoList.get(i).getUnDoID());
				bindMap.put("seq", Integer.valueOf(materialUnDoinfoList.get(i).getUnDoDetailName()));
				bindMap.put("UNDOIDDATE", materialUnDoinfoList.get(i)
						.getUnDoIdDate());
				bindMap.put("receiveActNo", receiveActNo);
				bindMap.put("LASTEVENTNAME", eventInfo.getEventName());
				bindMap.put("LASTEVENTCOMMENT", eventInfo.getEventComment());				
//				IDMFrameServiceProxy.getSqlTemplate()
//				.update(update, bindMap1);			
				MaterialPackingServiceProxy.getMaterialPackingService()
						.setEvent(materialPackingKeyList, eventInfo,
								setEventInfo);		
				int count=IDMFrameServiceProxy.getSqlTemplate()
						.update(sql2, bindMap);
			}
		} catch (IDMFrameDBErrorSignal ex) {
			log.error(ex, ex);
			throw ex;
		} catch (NotFoundSignal ex) {
			log.error(ex, ex);
			throw ex;
		}
	}
	public void SplitPallet(String newPallet,String oldPallet,String siteName,String boxStr,EventInfo eventInfo)
	{
		String[] boxList=boxStr.split(",");
		MaterialPacking mp=new MaterialPacking();
		MaterialPackingKey mpk=new MaterialPackingKey();
		List<MaterialPacking> newPalletList=new ArrayList<MaterialPacking>();
		mpk.setSiteName(siteName);
		double totalQuantity=0;//新Pallet数量
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");	
		List<Timestamp> dateList=new ArrayList<Timestamp>();
		for (String boxID : boxList) {
			mpk.setMaterialPackingName(boxID);
			mp = MaterialPackingServiceProxy.getMaterialPackingService().selectByKey(mpk);
			mp.setSuperMaterialPackingName(newPallet);
			newPalletList.add(mp);
			totalQuantity += mp.getMaterialQuantity();
			if(dateList.size()==0)
				dateList.add(mp.getExpiringDate());
			else
			{
				if(mp.getExpiringDate().before(dateList.get(0)))
				{
					dateList=new ArrayList<Timestamp>();
					dateList.add(mp.getExpiringDate());
				}
			}
		}		
		//移出BOX的PalletID更新为NewPalletID
		MaterialPackingServiceProxy.getMaterialPackingService().update(newPalletList);
		
		mpk.setMaterialPackingName(oldPallet);
		MaterialPacking oPallet=MaterialPackingServiceProxy.getMaterialPackingService().selectByKey(mpk);
		//原Pallet数量更新为历史数量减去移除数量
		oPallet.setMaterialQuantity(oPallet.getMaterialQuantity()-totalQuantity);
		MaterialPackingServiceProxy.getMaterialPackingService().update(oPallet);
		//创建新Pallet
		mpk.setMaterialPackingName(newPallet);
		oPallet.setKey(mpk);
		oPallet.setMaterialQuantity(totalQuantity);
		oPallet.setSuperMaterialPackingName(newPallet);
		oPallet.setExpiringDate(dateList.get(0));
		MaterialPackingServiceProxy.getMaterialPackingService().insert(oPallet);
	}
	public void MergePallet(String fPallet,String sPallet,String siteName,EventInfo eventInfo)
	{		
		MaterialPackingKey mpk=new MaterialPackingKey();
		mpk.setSiteName(siteName);
		mpk.setMaterialPackingName(fPallet);
		MaterialPacking firstPallet=MaterialPackingServiceProxy.getMaterialPackingService().selectByKey(mpk);
		mpk.setMaterialPackingName(sPallet);
		MaterialPacking secondPallet=MaterialPackingServiceProxy.getMaterialPackingService().selectByKey(mpk);
		firstPallet.setMaterialQuantity(firstPallet.getMaterialQuantity()+secondPallet.getMaterialQuantity());
		//将Pallet数量更新为合并后的数量
		MaterialPackingServiceProxy.getMaterialPackingService().update(firstPallet);
		//将并入Pallet下全部子BOX的PalletID更新为fPallet
		String condition="  WHERE  SUPERMATERIALPACKINGNAME = ?";
		Object[] bind={sPallet};
		List<MaterialPacking> boxList=MaterialPackingServiceProxy.getMaterialPackingService().select(condition, bind);
		for (MaterialPacking materialPacking : boxList) {
			materialPacking.setSuperMaterialPackingName(fPallet);
		}
		MaterialPackingServiceProxy.getMaterialPackingService().update(boxList);		
		secondPallet.setPackingState("Empty");
		secondPallet.setMaterialQuantity(0);
		MaterialPackingServiceProxy.getMaterialPackingService().update(secondPallet);		
	}
	public void outSourceAssignShip(String invoice,String boxid,String siteName,EventInfo eventInfo,String actNO) throws Exception
	{
		try
		{
			String sql="WITH ERPFACTORY AS (SELECT DISTINCT ERPFACTORY FROM MATERIALRECEIVEREQUESTDETAIL WHERE RECEIVEREQUESTNAME=:RECEIVEREQUESTNAME )"
						+" SELECT SUBMATERIALSPECNAME AS MATERIALSPECNAME,(SELECT * FROM ERPFACTORY)  AS ERPFACTORY FROM  MATERIALSHIPREQUESTTOOEM" 
						+" WHERE SITENAME=:SITENAME AND RECEIVEREQUESTNAME=:RECEIVEREQUESTNAME";
			Map<String,String> map=new HashMap<String, String>();
			map.put("SITENAME", siteName);
			map.put("RECEIVEREQUESTNAME", invoice);
			List<Map<String,Object>> result=IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, map);
			if(result.size()>0)
			{
				MaterialPackingKey mpk=new MaterialPackingKey();
				mpk.setSiteName(siteName);
				mpk.setMaterialPackingName(boxid);
				MaterialPacking mp=MaterialPackingServiceProxy.getMaterialPackingService().selectByKey(mpk);
				if(!result.get(0).get("ERPFACTORY").toString().equals(mp.getErpFactory()))				
					throw new CustomException("OUTSOURCE-001","","");//组件出库拣配库存ERP工厂需与PO一致			
				else
				{  
					boolean existFlag=false;
					//校验当前BOX的料号是否与组件要求料号一致
					for(int i=0;i<result.size();i++)
					{
						if(result.get(i).get("MATERIALSPECNAME").equals(mp.getMaterialSpecName()))
						{
							existFlag=true;
							break;
						}
					}					
					if(!existFlag)
						throw new CustomException("OUTSOURCE-002","","");//组件出库拣配库存料号需与PO一致		
					else
					{						
						if(mp.getShipRequestName().equalsIgnoreCase("")&&mp.getStockState().equalsIgnoreCase("Stocked")&&mp.getHoldState().equalsIgnoreCase("N")
								&&mp.getMaterialQuantity()>0&&mp.getPackingGrade().equalsIgnoreCase("OK"))
						{
							String getDetail="SELECT OEM.RECEIVEREQUESTDETAILNAME  FROM MATERIALSHIPREQUESTTOOEM OEM "
									+" WHERE OEM.SITENAME=:SITENAME"
									+" AND OEM.SUBMATERIALSPECNAME=:SUBMATERIALSPECNAME"
									+" AND OEM.RECEIVEREQUESTNAME=:RECEIVEREQUESTNAME";
							Map<String,Object> detailMap=new HashMap<String, Object>();
							detailMap.put("SITENAME", siteName);
							detailMap.put("SUBMATERIALSPECNAME", mp.getMaterialSpecName());
							detailMap.put("RECEIVEREQUESTNAME", invoice);
							List<Map<String,Object>> detailList=IDMFrameServiceProxy.getSqlTemplate().queryForList(getDetail, detailMap);
							MaterialShipRequestToOEMKey keyInfo = new MaterialShipRequestToOEMKey(siteName, invoice,detailList.get(0).get("RECEIVEREQUESTDETAILNAME").toString(),mp.getMaterialSpecName());
							MakeOEMAssignedInfo makeOEMAssignedInfo=new MakeOEMAssignedInfo();
							makeOEMAssignedInfo.setAssignedQuantity(mp.getMaterialQuantity());
							MaterialShipRequestToOEMServiceProxy.getMaterialShipRequestToOEMService().increaseAssignedQuantity(keyInfo, eventInfo, makeOEMAssignedInfo);
							if(mp.getMaterialPackingType().equalsIgnoreCase("Pallet"))
							{
								List<MaterialPackingKey> keyList=new ArrayList<MaterialPackingKey>();
								keyList.add(mpk);
								String queryPallet="SELECT MATERIALPACKINGNAME FROM MATERIALPACKING WHERE SUPERMATERIALPACKINGNAME=:SUPERMATERIALPACKINGNAME";
								Map<String,Object> queryMap=new HashMap<String, Object>();
								map.put("SUPERMATERIALPACKINGNAME", boxid);
								List<Map<String,Object>> queryResult=IDMFrameServiceProxy.getSqlTemplate().queryForList(queryPallet, queryMap);
								if(queryResult.size()>0)
								{ 							
									for(int m= 0;m<result.size();m++)
									{
										mpk.setMaterialPackingName(result.get(m).get("MATERIALPACKINGNAME").toString());
										keyList.add(mpk);
									}
								}	
								Map<String,Object> updateMap=new HashMap<String, Object>();
								updateMap.put("shipRequestName", invoice);
								updateMap.put("shipRequestDetailName", keyInfo.getReceiveRequestDetailName());
								updateMap.put("receiveActNo", actNO);
		 						SetEventInfo setEventInfo=new SetEventInfo();
								setEventInfo.setUserColumns(updateMap);
								MaterialPackingServiceProxy.getMaterialPackingService().setEvent(keyList, eventInfo, setEventInfo);																																			
							}else
							{
								Timestamp lastEventTime = new Timestamp(System.currentTimeMillis());
								mp.setShipRequestName(invoice);
								mp.setShipRequestDetailName(keyInfo.getReceiveRequestDetailName());
								mp.setReceiveActNo(actNO);
								mp.setLastEventName("OutSourceAssign");
								mp.setLastEventTime(lastEventTime);									
								if(!mp.getSuperMaterialPackingName().equals(""))
								{
									MaterialPackingKey palletKey=new MaterialPackingKey();
									palletKey.setSiteName(siteName);
									palletKey.setMaterialPackingName(mp.getSuperMaterialPackingName());									
									MaterialPacking pallet=MaterialPackingServiceProxy.getMaterialPackingService().selectByKey(palletKey);
									pallet.setLastEventName("OutSourceAssign");
									pallet.setLastEventTime(lastEventTime);		
									pallet.setMaterialQuantity(pallet.getMaterialQuantity()-mp.getMaterialQuantity());
									MaterialPackingServiceProxy.getMaterialPackingService().update(pallet);		
									
									mp.setSuperMaterialPackingName("");
								}
								MaterialPackingServiceProxy.getMaterialPackingService().update(mp);
							}
							
						}
						else
							throw new CustomException("OUTSOURCE-003","","");//请选择在库、OK状态、未HOLD、未拆分的库存进行拣配
					}
				}
					
			}else
				throw new CustomException("OUTSOURCE-004","","");//没有组件单据信息			
		}
		catch(Exception e)
		{			
			throw e;
		}
	}
	
	public void deleteBoxByAct(String siteName,String boxStr,String receiveActNo,String invoice,String invoiceDetail,String invoiceType,EventInfo eventInfo) throws CustomException
	{
		MaterialPackingKey key=new MaterialPackingKey();
		//要删除BOX的物料总数
		double materialQuantity=0;
		key.setSiteName(siteName);
		String[] boxList= boxStr.split(",");
		for(int i=0;i<boxList.length;i++)
		{
			key.setMaterialPackingName(boxList[i]);
			MaterialPacking mp=MaterialPackingServiceProxy.getMaterialPackingService().selectByKey(key);
			//BOX为按Pallet管理的库存
			if(!mp.getSuperMaterialPackingName().equals("")&&mp.getMaterialPackingType().equalsIgnoreCase("BOX"))
			{
				MaterialPackingKey palletKey=new MaterialPackingKey();
				palletKey.setSiteName(siteName);
				palletKey.setMaterialPackingName(mp.getSuperMaterialPackingName());
				MaterialPacking pallet=MaterialPackingServiceProxy.getMaterialPackingService().selectByKey(palletKey);
				pallet.setLastEventName(eventInfo.getEventName());
				pallet.setLastEventUser(eventInfo.getEventUser());
				pallet.setMaterialQuantity(pallet.getMaterialQuantity()-mp.getMaterialQuantity());
				//将Pallet数量减去当前BOX数量
				MaterialPackingServiceProxy.getMaterialPackingService().update(pallet);
			}
			materialQuantity +=mp.getMaterialQuantity();
			//将用户勾选的BOX删除
			MaterialPackingServiceProxy.getMaterialPackingService().delete(key);
		}

		//修改单据已接受数量
		if(invoiceType.equalsIgnoreCase("PO"))
		{
			MaterialReceiveRequestDetailKey mdKey=new MaterialReceiveRequestDetailKey();
			mdKey.setSiteName(siteName);
			mdKey.setReceiveRequestName(invoice);
			mdKey.setReceiveRequestDetailName(invoiceDetail);
			MakeDetailDecreaseReceivedInfo info=new MakeDetailDecreaseReceivedInfo();
			info.setDecreaseQuantity(materialQuantity);
			ReceiveRequestDetailServiceProxy.getReceiveRequestDetailService().decreaseReceivedQuantity(mdKey, eventInfo, info);			
		}else
		{
			MaterialShipRequestDetailKey msKey=new MaterialShipRequestDetailKey();
			msKey.setSiteName(siteName);
			msKey.setShipRequestName(invoice);
			msKey.setShipRequestDetailName(invoiceDetail);
			MakeShipDetailDecreaseAssignedInfo info=new MakeShipDetailDecreaseAssignedInfo();
			info.setAssignedQuantity(materialQuantity);
			MaterialShipRequestDetailServiceProxy.getMaterialShipRequestDetailService().decreaseAssignedQuantity(msKey,info);
		}
	}

	

	public void ModifyMakeDate(EventInfo eventInfo, String siteName,
			String materialPackingName, String makeDate,String expiringDate,String charge) {
		try {

			SetEventInfo setEventInfo = new SetEventInfo();

			MaterialPackingKey MaterialPackingKey = new MaterialPackingKey();

			MaterialPackingKey.setSiteName(siteName);
			MaterialPackingKey.setMaterialPackingName(materialPackingName);

			Map<String, Object> bindMap = new HashMap<String, Object>();
            if(!makeDate.equals("")){
            	bindMap.put("makeDate", makeDate);
            }
            if(!expiringDate.equals("")){
            	bindMap.put("expiringDate",expiringDate);
            }
            if(!charge.equals("")){
            	bindMap.put("charge",charge);
            }
			

			setEventInfo.setUserColumns(bindMap);
			
			MaterialPackingServiceProxy.getMaterialPackingService().setEvent(
					MaterialPackingKey, eventInfo, setEventInfo);

			}

		catch (IDMFrameDBErrorSignal e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 修改311入库的库位，只修改WMS库位
	 * @param eventInfo
	 * @param siteName
	 * @param materialPackingName
	 */
	public void WMSLocationModify(EventInfo eventInfo, String siteName,
			String materialPackingName, String erpLocation,String erpFactory) {
		try {

			SetEventInfo setEventInfo = new SetEventInfo();

			MaterialPackingKey MaterialPackingKey = new MaterialPackingKey();

			MaterialPackingKey.setSiteName(siteName);
			MaterialPackingKey.setMaterialPackingName(materialPackingName);

			Map<String, Object> bindMap = new HashMap<String, Object>();
            if(!erpLocation.equals("")){
            	bindMap.put("erpLocation", erpLocation);
            }
            if(!erpFactory.equals("")){
            	bindMap.put("expiringDate",erpFactory);
            }
			

			setEventInfo.setUserColumns(bindMap);
			
			MaterialPackingServiceProxy.getMaterialPackingService().setEvent(
					MaterialPackingKey, eventInfo, setEventInfo);
			
			String sql = " UPDATE BS_MATERIALPACKINGUNDOINFO T\r\n"
					+ "                 SET T.ERPFACTORY  = :ERPFACTORY,\r\n"
					+ "                     T.ERPLOCATION = :ERPLOCATION\r\n"
					+ "               WHERE T.MATERIALPACKINGNAME = :MATERIALPACKINGNAME\r\n"
					+ "                 AND T.SITENAME = :SITENAME";
			Map<String, String> updateMap = new HashMap<String, String>();
			updateMap.put("SITENAME",siteName);
			updateMap.put("MATERIALPACKINGNAME", materialPackingName);
			
			updateMap.put("ERPFACTORY",erpFactory);
			updateMap.put("ERPLOCATION", erpLocation);
			 IDMFrameServiceProxy.getSqlTemplate().update(sql, updateMap);

			}

		catch (IDMFrameDBErrorSignal e) {
			e.printStackTrace();
		}
	}
	
	
	public String cancelPreAssign(String siteName,String boxID,String receiveActNo,EventInfo eventInfo) throws Exception
	{
		try
		{
			String shipRequestName="";
			String durableName ="";
			MaterialShipRequestDetailKey mdKey=new MaterialShipRequestDetailKey();
			//单个BOX解除绑定
			if(!boxID.equalsIgnoreCase(""))
			{
				MaterialPackingKey mpKey=new MaterialPackingKey();
				mpKey.setSiteName(siteName);
				mpKey.setMaterialPackingName(boxID);
				MaterialPacking mp = MaterialPackingServiceProxy.getMaterialPackingService().selectByKey(mpKey);			
				mdKey.setSiteName(siteName);
				mdKey.setShipRequestName(mp.getShipRequestName());
				mdKey.setShipRequestDetailName(mp.getShipRequestDetailName());
				shipRequestName = mp.getShipRequestName();
				//B17 MDL MES叫料解绑载具
				if(siteName.equals("B17")){
					MaterialShipRequestKey msKey =new MaterialShipRequestKey();
					msKey.setShipRequestName(shipRequestName);
					msKey.setSiteName(siteName);
					MaterialShipRequest ms = MaterialShipRequestServiceProxy.getMaterialShipRequestService().selectByKey(msKey);
					if(ms.getCustomerNO().equals("MDL")&&ms.getSystemType().equals("MESCALL")){
						durableName = mp.getDurableName();
						mp.setDurableName("");
						String searchSql = "SELECT ASSIGNEDPACKINGQUANTITY FROM DURABLE "
								+ " WHERE SITENAME=:SITENAME AND DURABLENAME=:DURABLENAME  ";
						
						String updateSql = "UPDATE DURABLE SET ASSIGNEDPACKINGQUANTITY=ASSIGNEDPACKINGQUANTITY-1"
								+ " WHERE SITENAME=:SITENAME AND DURABLENAME=:DURABLENAME ";
						Map<String, String> bindMap = new HashMap<String, String>();
				        bindMap.put("SITENAME",siteName);
				        bindMap.put("DURABLENAME", durableName);
				        List<Map<String,Object>> result=IDMFrameServiceProxy.getSqlTemplate().queryForList(searchSql, bindMap);
				        if(result.size()>0){
				        	if(result.get(0).get("ASSIGNEDPACKINGQUANTITY").toString().equals("1")){
					        	updateSql = "UPDATE DURABLE SET ASSIGNEDPACKINGQUANTITY=ASSIGNEDPACKINGQUANTITY-1,DURABLESTATE='IDLE' "
										+ " WHERE SITENAME=:SITENAME AND DURABLENAME=:DURABLENAME ";
					        }
					        IDMFrameServiceProxy.getSqlTemplate().update(updateSql, bindMap);
					        log.info(durableName+" Decreased 1 ASSIGNEDPACKINGQUANTITY Successful");
				        }
				        
					}
				}
				mp.setShipRequestName("");
				mp.setShipRequestDetailName("");
				mp.setReceiveActNo("");
				MaterialPackingServiceProxy.getMaterialPackingService().update(mp);
				//预留行项目减少已绑定数量
				MakeShipDetailDecreaseAssignedInfo makeShipDetailDecreaseAssignedInfo=new MakeShipDetailDecreaseAssignedInfo();
				makeShipDetailDecreaseAssignedInfo.setAssignedQuantity(mp.getMaterialQuantity());
				MaterialShipRequestDetailServiceProxy.getMaterialShipRequestDetailService().decreaseAssignedQuantity(mdKey, makeShipDetailDecreaseAssignedInfo);
				
			}
			//整个抬头下都解绑
			else
			{
				String sql="SELECT MP.SHIPREQUESTNAME,MP.SHIPREQUESTDETAILNAME,SUM(MP.MATERIALQUANTITY ) AS MATERIALQUANTITY FROM MATERIALPACKING MP" 
						+" WHERE MP.SITENAME=:SITENAME AND MP.RECEIVEACTNO=:RECEIVEACTNO"
						+" AND MP.MATERIALPACKINGTYPE='Box'"
						+" AND MP.SHIPREQUESTNAME IS NOT NULL AND MP.SHIPREQUESTDETAILNAME IS NOT NULL"
						+" GROUP BY MP.SHIPREQUESTNAME,MP.SHIPREQUESTDETAILNAME";
				Map<String,Object> map=new HashMap<String, Object>();
				map.put("SITENAME", siteName);
				map.put("RECEIVEACTNO", receiveActNo);
				List<Map<String,Object>> result=IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, map);
				if(result.size()>0 && !result.get(0).get("SHIPREQUESTNAME").toString().equalsIgnoreCase(""))
				{
					shipRequestName=result.get(0).get("SHIPREQUESTNAME").toString();
					//List<MaterialShipRequestDetailKey> keyList=new ArrayList<MaterialShipRequestDetailKey>();
					mdKey.setSiteName(siteName);	
					MakeShipDetailDecreaseAssignedInfo makeShipDetailDecreaseAssignedInfo=new MakeShipDetailDecreaseAssignedInfo();
					//List<MakeShipDetailDecreaseAssignedInfo> decreaseList=new ArrayList<MakeShipDetailDecreaseAssignedInfo>();
					for (int i = 0; i < result.size(); i++) {					
						mdKey.setShipRequestName(result.get(i).get("SHIPREQUESTNAME").toString());
						mdKey.setShipRequestDetailName(result.get(i).get("SHIPREQUESTDETAILNAME").toString());
						//keyList.add(mdKey);
						makeShipDetailDecreaseAssignedInfo.setAssignedQuantity(Double.parseDouble(result.get(i).get("MATERIALQUANTITY").toString()));
						//decreaseList.add(makeShipDetailDecreaseAssignedInfo);
						//减少预留已拣配数量
						MaterialShipRequestDetailServiceProxy.getMaterialShipRequestDetailService().decreaseAssignedQuantity(mdKey, makeShipDetailDecreaseAssignedInfo);
						
					}
					
					String condition=" WHERE SITENAME = ? AND RECEIVEACTNO = ? AND SHIPREQUESTNAME IS NOT NULL ";
					Object[] bind={siteName,receiveActNo};
					List<MaterialPacking> mpList=MaterialPackingServiceProxy.getMaterialPackingService().select(condition, bind);
					for (MaterialPacking materialPacking : mpList) {
						
						//B17 MDL MES叫料解绑载具
						if(siteName.equals("B17")){
							MaterialShipRequestKey msKey =new MaterialShipRequestKey();
							msKey.setShipRequestName(shipRequestName);
							msKey.setSiteName(siteName);
							MaterialShipRequest ms = MaterialShipRequestServiceProxy.getMaterialShipRequestService().selectByKey(msKey);
							if(ms.getCustomerNO().equals("MDL")&&ms.getSystemType().equals("MESCALL")){
								durableName = materialPacking.getDurableName();
								materialPacking.setDurableName("");
								String updateSql = "UPDATE DURABLE SET ASSIGNEDPACKINGQUANTITY='0',DURABLESTATE='IDLE' "
										+ " WHERE SITENAME=:SITENAME AND DURABLENAME=:DURABLENAME ";
								Map<String, String> bindMap = new HashMap<String, String>();
						        bindMap.put("SITENAME",siteName);
						        bindMap.put("DURABLENAME", durableName);
						        IDMFrameServiceProxy.getSqlTemplate().update(updateSql, bindMap);
						        log.info(durableName+" Decreased 1 ASSIGNEDPACKINGQUANTITY Successful");
							}
						}
						materialPacking.setShipRequestName("");
						materialPacking.setShipRequestDetailName("");
						materialPacking.setReceiveActNo("");
						materialPacking.setLastEventTime(eventInfo.getEventTime());
						materialPacking.setLastEventUser(eventInfo.getEventUser());
						materialPacking.setLastEventName(eventInfo.getEventName());
					}
					//清空BOX绑定单据
					MaterialPackingServiceProxy.getMaterialPackingService().update(mpList);																
				}
			}
			return shipRequestName;
		}catch(Exception e)
		{
			e.printStackTrace();
			throw e;
		}
	}	
	public void checkBoxAssigned(String siteName,String boxID) throws CustomException
	{
		try
		{
			MaterialPackingKey mpKey=new MaterialPackingKey();
			mpKey.setSiteName(siteName);
			mpKey.setMaterialPackingName(boxID);
			MaterialPacking mp=MaterialPackingServiceProxy.getMaterialPackingService().selectByKey(mpKey);
			if(!mp.getShipRequestName().equals(""))
				throw new CustomException("RepeatAssignError", "");
		}catch(CustomException ce){
			ce.printStackTrace();
			throw new CustomException("RepeatAssignError", "");
		}		
	}
	public void checkStockOutQuantity(String siteName,String shipRequestName) throws CustomException
	{
		try
		{
			String sql="SELECT MD.SHIPREQUESTDETAILNAME,MD.ASSIGNEDQUANTITY,NVL(SUM(MP.MATERIALQUANTITY),0) AS BOXQUANTITY FROM MATERIALSHIPREQUESTDETAIL MD"
						+" LEFT JOIN MATERIALPACKING MP "
						+" ON MD.SITENAME=MP.SITENAME AND MP.SHIPREQUESTNAME=MD.SHIPREQUESTNAME AND MP.SHIPREQUESTDETAILNAME = MD.SHIPREQUESTDETAILNAME AND MP.MATERIALPACKINGTYPE='Box' "
						+" WHERE MD.SITENAME =:SITENAME AND MD.SHIPREQUESTNAME=:SHIPREQUESTNAME"
						+" GROUP BY MD.SHIPREQUESTDETAILNAME,MD.ASSIGNEDQUANTITY";
			Map<String,Object> map=new HashMap<String, Object>();
			map.put("SITENAME", siteName);
			map.put("SHIPREQUESTNAME", shipRequestName);
			List<Map<String,Object>> result=IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, map);
			for(int i=0;i<result.size();i++)
			{	
				if(result.get(i).get("ASSIGNEDQUANTITY").equals(result.get(i).get("BOXQUANTITY")))
					continue;
				else
				{	
					log.debug("行项目"+result.get(i).get("SHIPREQUESTDETAILNAME").toString()+"绑定数量与Box数量不一致！");
					throw new CustomException("AssignedQuantityError", "");
				}
			}
		}catch(CustomException ce){
			ce.printStackTrace();			
			throw new CustomException("AssignedQuantityError", "");
		}		
	}

	public void UpdateBoxStateByMES(String siteName,String shipRequestName,String receiveActNo) throws CustomException
	{
		try
		{
			String updateSql="UPDATE MATERIALPACKING SET MESRECEIVEFLAG='Y',MESRECEIVETIME=SYSDATE  WHERE SITENAME=:SITENAME AND SHIPREQUESTNAME=:SHIPREQUESTNAME AND RECEIVEACTNO=:RECEIVEACTNO AND STOCKSTATE='StockOut'";
			Map<String,Object> map=new HashMap<String, Object>();
			map.put("SITENAME", siteName);
			map.put("SHIPREQUESTNAME", shipRequestName);
			map.put("RECEIVEACTNO", receiveActNo);
			IDMFrameServiceProxy.getSqlTemplate().update(updateSql, map);
		}catch(Exception e)
		{
			e.printStackTrace();
			log.info(e.getMessage());			
		}
	}

	//SMT新增方法
	public void SMTChangeEndDate(EventInfo eventInfo, Document message) throws Exception {
		String sqlCreat="UPDATE MATERIALPACKINGSMT  "
				+" SET ENDDATE=TO_DATE(:ENDDATE ,'YYYY-MM-DD') "
				+" ,LASTEVENTNAME=:LASTEVENTNAME"
				+" ,LASTEVENTTIMEKEY=:LASTEVENTTIMEKEY"
				+" ,LASTEVENTTIME=sysdate"
				+" ,LASTEVENTUSER=:LASTEVENTUSER"
				+" ,LASTEVENTCOMMENT=:LASTEVENTCOMMENT"
				+" WHERE MATERIALPACKINGNAME=:MATERIALPACKINGNAME "
				+" AND SITENAME=:SITENAME ";
				
		
		Element bodyElem = message.getRootElement().getChild("Body");
		Element headerElem = message.getRootElement().getChild("Header");
		String siteName = headerElem.getChildText("SITENAME");
		
		String BOEFactory=System.getProperty("factory");
		if(BOEFactory.equals("B5")){
			//B5/tm1的SMT在sitename按照SMTsitename+-+B5/TM1
			String [] sitelist=siteName.split("\\-");
			siteName = sitelist[0];
			BOEFactory = sitelist[1];
		}
		
		Map<String, String> bindMap = new HashMap<String, String>();
		        bindMap.put("ENDDATE",bodyElem.getChildText("ENDDATE"));
				bindMap.put("MATERIALPACKINGNAME",bodyElem.getChildText("MATERIALPACKINGNAME"));
				bindMap.put("LASTEVENTNAME",eventInfo.getEventName());
				bindMap.put("LASTEVENTTIMEKEY",TimeStampUtil.getCurrentEventTimeKey());
				bindMap.put("LASTEVENTUSER",eventInfo.getEventUser());
				bindMap.put("LASTEVENTCOMMENT",eventInfo.getEventComment());
				
				bindMap.put("SITENAME",siteName);
				
				IDMFrameServiceProxy.getSqlTemplate().update(sqlCreat, bindMap);
				CreateBoxHistorySMT(bodyElem.getChildText("MATERIALPACKINGNAME"),siteName,BOEFactory);
				log.info(bodyElem.getChildText("MATERIALPACKINGNAME") );
	}
	
	public void SMTChangeGrade(EventInfo eventInfo, Document message) throws Exception {
		String sqlCreat="UPDATE MATERIALPACKINGSMT  "
				+" SET PACKINGGRADE=:PACKINGGRADE "
				+" ,OQARESULT=:OQARESULT"
				+" ,LASTEVENTNAME=:LASTEVENTNAME"
				+" ,LASTEVENTTIMEKEY=:LASTEVENTTIMEKEY"
				+" ,LASTEVENTTIME=sysdate"
				+" ,LASTEVENTUSER=:LASTEVENTUSER"
				+" ,LASTEVENTCOMMENT=:LASTEVENTCOMMENT"
				+" WHERE MATERIALPACKINGNAME=:MATERIALPACKINGNAME "
				+" AND SITENAME=:SITENAME ";
				
		
		Element bodyElem = message.getRootElement().getChild("Body");
		Element headerElem = message.getRootElement().getChild("Header");
		String siteName = headerElem.getChildText("SITENAME");
		
		String BOEFactory=System.getProperty("factory");
		if(BOEFactory.equals("B5")){
			//B5/tm1的SMT在sitename按照SMTsitename+-+B5/TM1
			String [] sitelist=siteName.split("\\-");
			siteName = sitelist[0];
			BOEFactory = sitelist[1];
		}
		
		Map<String, String> bindMap = new HashMap<String, String>();
		        bindMap.put("PACKINGGRADE",bodyElem.getChildText("PACKINGGRADE"));
		        bindMap.put("OQARESULT",bodyElem.getChildText("OQARESULT"));
				bindMap.put("MATERIALPACKINGNAME",bodyElem.getChildText("MATERIALPACKINGNAME"));
				bindMap.put("LASTEVENTNAME",eventInfo.getEventName());
				bindMap.put("LASTEVENTTIMEKEY",TimeStampUtil.getCurrentEventTimeKey());
				bindMap.put("LASTEVENTUSER",eventInfo.getEventUser());
				bindMap.put("LASTEVENTCOMMENT",eventInfo.getEventComment());
				
				bindMap.put("SITENAME",siteName);
				
				IDMFrameServiceProxy.getSqlTemplate().update(sqlCreat, bindMap);
				CreateBoxHistorySMT(bodyElem.getChildText("MATERIALPACKINGNAME"),siteName,BOEFactory);
				log.info(bodyElem.getChildText("MATERIALPACKINGNAME") );
	}
	
	public void SMTChangeLocation(EventInfo eventInfo, Document message) throws Exception {
		String sqlCreat="UPDATE MATERIALPACKINGSMT  "
				+" SET LOCATIONNAME=:LOCATIONNAME "
				+" ,LASTEVENTNAME=:LASTEVENTNAME"
				+" ,LASTEVENTTIMEKEY=:LASTEVENTTIMEKEY"
				+" ,LASTEVENTTIME=sysdate"
				+" ,LASTEVENTUSER=:LASTEVENTUSER"
				+" ,LASTEVENTCOMMENT=:LASTEVENTCOMMENT"
				+" WHERE MATERIALPACKINGNAME=:MATERIALPACKINGNAME "
				+" AND SITENAME=:SITENAME ";
				
		
		Element bodyElem = message.getRootElement().getChild("Body");
		Element headerElem = message.getRootElement().getChild("Header");
		String siteName = headerElem.getChildText("SITENAME");
		
		String BOEFactory=System.getProperty("factory");
		if(BOEFactory.equals("B5")){
			//B5/tm1的SMT在sitename按照SMTsitename+-+B5/TM1
			String [] sitelist=siteName.split("\\-");
			siteName = sitelist[0];
			BOEFactory = sitelist[1];
		}
		
		Map<String, String> bindMap = new HashMap<String, String>();
		        bindMap.put("LOCATIONNAME",bodyElem.getChildText("LOCATIONNAME"));
				bindMap.put("MATERIALPACKINGNAME",bodyElem.getChildText("MATERIALPACKINGNAME"));
				bindMap.put("LASTEVENTNAME",eventInfo.getEventName());
				bindMap.put("LASTEVENTTIMEKEY",TimeStampUtil.getCurrentEventTimeKey());
				bindMap.put("LASTEVENTUSER",eventInfo.getEventUser());
				bindMap.put("LASTEVENTCOMMENT",eventInfo.getEventComment());
				
				bindMap.put("SITENAME",siteName);
				
				IDMFrameServiceProxy.getSqlTemplate().update(sqlCreat, bindMap);
				CreateBoxHistorySMT(bodyElem.getChildText("MATERIALPACKINGNAME"),siteName,BOEFactory);
				log.info(bodyElem.getChildText("MATERIALPACKINGNAME") );
	}
	
	public void CreateBoxHistorySMT(String boxName,String siteName,String BOEFactory) throws Exception {

		String sql=" INSERT INTO MATERIALPACKINGSMTHISTORY   "
				+" ( SITENAME                              "
				+" ,MATERIALPACKINGNAME                    "
				+" ,TIMEKEY                                "
				+" ,REASONCODETYPE                         "
				+" ,REASONCODE                             "
				+" ,MATERIALPACKINGTYPE                    "
				+" ,CONTENTMATERIALTYPE                    "
				+" ,MATERIALTYPE                           "
				+" ,MATERIALSPECNAME                       "
				+" ,SUPERMATERIALPACKINGNAME               "
				+" ,MAKEDATE                               "
				+" ,PACKINGGRADE                           "
				+" ,SUBPACKINGQUANTITY                     "
				+" ,MATERIALCREATEQUANTITY                 "
				+" ,MATERIALQUANTITY                       "
				+" ,OLDPACKINGSTATE                        "
				+" ,PACKINGSTATE                           "
				+" ,STOCKSTATE                             "
				+" ,OLDSTOCKSTATE                          "
				+" ,HOLDSTATE                              "
				+" ,AREANAME                               "
				+" ,LOCATIONNAME                           "
				+" ,DURABLENAME                            "
				+" ,MATERIALPROCESSGROUPNAME               "
				+" ,CREATETIME                             "
				+" ,CREATEUSER                             "
				+" ,RECEIVEREQUESTNAME                     "
				+" ,RECEIVEREQUESTDETAILNAME               "
				+" ,RECEIVEACTNO                           "
				+" ,RECEIVETIME                            "
				+" ,RECEIVEUSER                            "
				+" ,SHIPREQUESTNAME                        "
				+" ,SHIPREQUESTDETAILNAME                  "
				+" ,SHIPTIME                               "
				+" ,SHIPUSER                               "
				+" ,ERPLOCATION                            "
				+" ,ETCSTATE                               "
				+" ,ERPFACTORY                             "
				+" ,STOCKINTYPE                            "
				+" ,OQARESULTSTATE                         "
				+" ,OQARESULT                              "
				+" ,UNDOID                                 "
				+" ,SUPPLIERNAME                           "
				+" ,CHARGE                                 "
				+" ,UNDODETAILNAME                         "
				+" ,ERPEVENTTIME                           "
				+" ,EVENTNAME                              "
				+" ,EVENTTIME                              "
				+" ,EVENTUSER                              "
				+" ,EVENTCOMMENT                           "
				+" ,NPFLAG                                 "
				+" ,MESSAGEID                              "
				+" ,ERPSTATE                               "
				+" ,SAVEREASON                             "
				+" ,ENDDATE "
				+" ,SMTEVENTTIME                           "
				+ " ,TRANSACTIONID            "
				+ ",BOESITENAME               "
				+ ")            "
				+" SELECT SITENAME                         "
				+" ,MATERIALPACKINGNAME                    "
				+" ,LASTEVENTTIMEKEY            "// 修改回原来的LASTEVENTTIMEKEY
				+" ,REASONCODETYPE                         "
				+" ,REASONCODE                             "
				+" ,MATERIALPACKINGTYPE                    "
				+" ,CONTENTMATERIALTYPE                    "
				+" ,MATERIALTYPE                           "
				+" ,MATERIALSPECNAME                       "
				+" ,SUPERMATERIALPACKINGNAME               "
				+" ,MAKEDATE                               "
				+" ,PACKINGGRADE                           "
				+" ,SUBPACKINGQUANTITY                     "
				+" ,MATERIALCREATEQUANTITY                 "
				+" ,MATERIALQUANTITY                       "
				+" ,OLDPACKINGSTATE                        "
				+" ,PACKINGSTATE                           "
				+" ,STOCKSTATE                             "
				+" ,OLDSTOCKSTATE                          "
				+" ,HOLDSTATE                              "
				+" ,AREANAME                               "
				+" ,LOCATIONNAME                           "
				+" ,DURABLENAME                            "
				+" ,MATERIALPROCESSGROUPNAME               "
				+" ,CREATETIME                             "
				+" ,CREATEUSER                             "
				+" ,RECEIVEREQUESTNAME                     "
				+" ,RECEIVEREQUESTDETAILNAME               "
				+" ,RECEIVEACTNO                           "
				+" ,RECEIVETIME                            "
				+" ,RECEIVEUSER                            "
				+" ,SHIPREQUESTNAME                        "
				+" ,SHIPREQUESTDETAILNAME                  "
				+" ,SHIPTIME                               "
				+" ,SHIPUSER                               "
				+" ,ERPLOCATION                            "
				+" ,ETCSTATE                               "
				+" ,ERPFACTORY                             "
				+" ,STOCKINTYPE                            "
				+" ,OQARESULTSTATE                         "
				+" ,OQARESULT                              "
				+" ,UNDOID                                 "
				+" ,SUPPLIERNAME                           "
				+" ,CHARGE                                 "
				+" ,UNDODETAILNAME                         "
				+" ,ERPEVENTTIME                           "
				+" ,LASTEVENTNAME                          "
				+" ,LASTEVENTTIME                          "
				+" ,LASTEVENTUSER                          "
				+" ,LASTEVENTCOMMENT                       "
				+" ,NPFLAG                                 "
				+" ,MESSAGEID                              "
				+" ,ERPSTATE                               "
				+" ,SAVEREASON                             "
				+" ,ENDDATE                                "
				+" ,SMTEVENTTIME                           "
				+ " ,TRANSACTIONID                         "
				+ " ,BOESITENAME                           "
				+" FROM MATERIALPACKINGSMT                 "
				+" WHERE MATERIALPACKINGNAME=:MATERIALPACKINGNAME  "
				+"  AND LASTEVENTTIMEKEY=(SELECT MAX(LASTEVENTTIMEKEY) FROM MATERIALPACKINGSMT  "
				+"  WHERE MATERIALPACKINGNAME=  :MATERIALPACKINGNAME) "
				+ " AND SITENAME=:SITENAME "
				+ " AND BOESITENAME=:BOESITENAME ";     
	
		Map<String, String> bindMap = new HashMap<String, String>();
		bindMap.put("MATERIALPACKINGNAME", boxName);
		bindMap.put("SITENAME", siteName);
		bindMap.put("BOESITENAME", BOEFactory);
		IDMFrameServiceProxy.getSqlTemplate().update(sql, bindMap);
	}
	
public void SMTChangeOKToNG( EventInfo eventInfo,String shipType,String materialPackingName,String sqeComment,String siteName,String packingGrade) throws Exception {
		
		try {
			
			Map<String, Object> bindMap = new HashMap<String, Object>();
			bindMap.put("MATERIALPACKINGNAME", materialPackingName);
			bindMap.put("SITENAME", siteName);
			
			String sql1=" SELECT SITENAME,MATERIALPACKINGNAME from materialpackingsmt where materialpackingname in( "+ 
					" SELECT TRIM(REGEXP_SUBSTR(ID, '[^|]+' ,1 ,ROWNUM)) MATERIALPACKINGNAME "+ 
					" FROM (SELECT  :MATERIALPACKINGNAME   ID FROM DUAL) A "+
					" CONNECT BY ROWNUM- 1 <= LENGTH(REGEXP_REPLACE(ID, '[^|]+')) "+
					") and SITENAME=:SITENAME";
			List<Map<String, Object>> sqlResult1 = IDMFrameServiceProxy
					.getSqlTemplate()
					.queryForList(sql1, bindMap);
			
			
			for (int i = 0; i < sqlResult1.size(); i++) {
				
					/*MaterialPacking materialPacking = new MaterialPacking();
					MaterialPackingKey keyInfo = new MaterialPackingKey();
					keyInfo.setMaterialPackingName(sqlResult1.get(i).get("MATERIALPACKINGNAME").toString());		
					keyInfo.setSiteName(siteName);*/
					String sqlCreat="UPDATE MATERIALPACKINGSMT  "
							+" SET PACKINGGRADE=:PACKINGGRADE "
							+" ,OQARESULT=:OQARESULT"
							+" ,REASONCODETYPE=:REASONCODETYPE"
							+" ,LASTEVENTNAME=:LASTEVENTNAME"
							+" ,LASTEVENTTIMEKEY=:LASTEVENTTIMEKEY"
							+" ,LASTEVENTTIME=sysdate"
							+" ,LASTEVENTUSER=:LASTEVENTUSER"
							+" ,LASTEVENTCOMMENT=:LASTEVENTCOMMENT"
							+" WHERE MATERIALPACKINGNAME=:MATERIALPACKINGNAME "
							+" AND SITENAME=:SITENAME ";
					
					Map<String, String> bindMapu = new HashMap<String, String>();
					bindMapu.put("PACKINGGRADE",packingGrade);
					bindMapu.put("OQARESULT",sqeComment);
					bindMapu.put("REASONCODETYPE",shipType);
					bindMapu.put("MATERIALPACKINGNAME",sqlResult1.get(i).get("MATERIALPACKINGNAME").toString());
					bindMapu.put("LASTEVENTNAME",eventInfo.getEventName());
					bindMapu.put("LASTEVENTTIMEKEY",TimeStampUtil.getCurrentEventTimeKey());
					bindMapu.put("LASTEVENTUSER",eventInfo.getEventUser());
					bindMapu.put("LASTEVENTCOMMENT",eventInfo.getEventComment());
					
					bindMapu.put("SITENAME",siteName);
					
					IDMFrameServiceProxy.getSqlTemplate().update(sqlCreat, bindMapu);
					//暂时不用，先注释了
					//CreateBoxHistorySMT(sqlResult1.get(i).get("MATERIALPACKINGNAME").toString());
					log.info(sqlResult1.get(i).get("MATERIALPACKINGNAME").toString());

				}
				

				
		} catch (IDMFrameDBErrorSignal ex) {
			log.error(ex, ex);
			throw ex;
		} catch (NotFoundSignal ex) {
			log.error(ex, ex);
			throw ex;
		}
	}
  
public void SMTmakeCompleted(EventInfo eventInfo, String materialPackingName, Document message) throws Exception {
	Element headerElem = message.getRootElement().getChild("Header");
	String siteName=headerElem.getChildText("SITENAME");
	String BOEFactory=System.getProperty("factory");
	if(BOEFactory.equals("B5")){
		//B5/tm1的SMT在sitename按照SMTsitename+-+B5/TM1
		String [] sitelist=siteName.split("\\-");
		siteName = sitelist[0];
		BOEFactory = sitelist[1];
	}
	
	String sqlCreat="UPDATE MATERIALPACKINGSMT  "
			+" SET STOCKSTATE='Completed' "
			+" ,AREANAME=:AREANAME "
			+" ,LASTEVENTNAME=:LASTEVENTNAME"
			+" ,LASTEVENTTIMEKEY=:LASTEVENTTIMEKEY"
			+" ,LASTEVENTTIME=sysdate"
			+" ,SMTEVENTTIME=:SMTEVENTTIME"            //SMT操作时间增加
			+" ,LASTEVENTUSER=:LASTEVENTUSER"
			+" ,LASTEVENTCOMMENT=:LASTEVENTCOMMENT"
			+" WHERE MATERIALPACKINGNAME=:MATERIALPACKINGNAME"
			+"  AND STOCKSTATE<>'StockOut' "
			+" AND SITENAME=:SITENAME "
			+ " AND BOESITENAME=:BOESITENAME ";
			
	
	Map<String, String> bindMap = new HashMap<String, String>();
	        bindMap.put("AREANAME","");
			bindMap.put("MATERIALPACKINGNAME",materialPackingName);
			bindMap.put("LASTEVENTNAME",eventInfo.getEventName());
			bindMap.put("LASTEVENTTIMEKEY",TimeStampUtil.getCurrentEventTimeKey());
			bindMap.put("SMTEVENTTIME",headerElem.getChildText("EVENTTIME"));            //SMT操作时间增加
			bindMap.put("LASTEVENTUSER",eventInfo.getEventUser());
			bindMap.put("LASTEVENTCOMMENT",eventInfo.getEventComment());
			bindMap.put("SITENAME",siteName);
			bindMap.put("BOESITENAME", BOEFactory);
			
			
			IDMFrameServiceProxy.getSqlTemplate().update(sqlCreat, bindMap);
			//暂时不用，先注释了
			//CreateBoxHistorySMT(materialPackingName);
			log.info(materialPackingName );

}
	//新增SMT拆分Box方法
	public void SMTSplitBox(EventInfo eventInfo, String siteName,
			String materialPackingName, String materialType,
			String materialSPecName, String materialQuantity, String makeDate,
			String supplierNo, String endDate, String shipRequestName)
			{
		
	}
	

	public void SMTCreateBoxByLabel(EventInfo eventInfo, String siteName,
			String materialPackingName, String materialType,
			String materialSPecName, String materialQuantity, String makeDate,
			String supplierNo, String endDate, String shipRequestName, String eventTime,String sourceMaterialPackingName)
			throws Exception {
		
		String BOEFactory=System.getProperty("factory");
		if(BOEFactory.equals("B5")){
			//B5/tm1的SMT在sitename按照SMTsitename+-+B5/TM1
			String [] sitelist=siteName.split("\\-");
			siteName = sitelist[0];
			BOEFactory = sitelist[1];
		}
		
		String oqaResult = "OK";
		String erpFactory = "";
		String erpLocation = "";
		String packingGrade ="";
		
		//从原BOX中查到materialtype
		String sqlMaterialtype="SELECT MATERIALTYPE,OQARESULT,ERPLOCATION,ERPFACTORY,PACKINGGRADE FROM MATERIALPACKINGSMT "
				+ " WHERE SITENAME=:SITENAME "
				+ " AND MATERIALPACKINGNAME=:MATERIALPACKINGNAME "
				+ " AND BOESITENAME=:BOESITENAME ";
		Map<String, String> bindMapMaterialtype = new HashMap<String, String>();
		bindMapMaterialtype.put("SITENAME", siteName);
		bindMapMaterialtype.put("MATERIALPACKINGNAME", sourceMaterialPackingName);
		bindMapMaterialtype.put("BOESITENAME", BOEFactory);
		
		List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
				.getSqlTemplate()
				.queryForList(sqlMaterialtype, bindMapMaterialtype);
		if(sqlResult.size()>0){
			materialType=sqlResult.get(0).get("MATERIALTYPE").toString();
			oqaResult=sqlResult.get(0).get("OQARESULT").toString();
			erpLocation=sqlResult.get(0).get("ERPLOCATION").toString();
			erpFactory=sqlResult.get(0).get("ERPFACTORY").toString();
			packingGrade=sqlResult.get(0).get("PACKINGGRADE")==null?"":sqlResult.get(0).get("PACKINGGRADE").toString();
		}
		
		
		
		String sqlCreat = "INSERT INTO MATERIALPACKINGSMT  "
				+ "("
				+ "SITENAME                    "
				+ ",MATERIALPACKINGNAME        "
				+ ",MATERIALPACKINGTYPE        "
				+ ",CONTENTMATERIALTYPE        "
				+ ",MATERIALTYPE               "
				+ ",MATERIALSPECNAME           "
				+ ",SUPERMATERIALPACKINGNAME   "
				+ ",PACKINGGRADE               "
				+ ",SUBPACKINGQUANTITY         "
				+ ",MATERIALCREATEQUANTITY     "
				+ ",MATERIALQUANTITY           "
				+ ",PACKINGSTATE               "
				+ ",OLDPACKINGSTATE            "
				+ ",STOCKSTATE                 "
				+ ",OLDSTOCKSTATE              "
				+ ",HOLDSTATE                  "
				+ ",AREANAME                   "
				+ ",LOCATIONNAME               "
				+ ",DURABLENAME                "
				+ ",MATERIALPROCESSGROUPNAME   "
				+ ",LASTEVENTNAME              "
				+ ",LASTEVENTTIMEKEY           "
				+ ",LASTEVENTTIME              "
				+ ",SMTEVENTTIME               "
				+ ",LASTEVENTUSER              "
				+ ",LASTEVENTCOMMENT           "
				+ ",CREATETIME                 "
				+ ",CREATEUSER                 "
				+ ",RECEIVEREQUESTNAME         "
				+ ",RECEIVEREQUESTDETAILNAME   "
				+ ",MAKEDATE                   "
				+ ",RECEIVEACTNO               "
				+ ",RECEIVETIME                "
				+ ",RECEIVEUSER                "
				+ ",SHIPREQUESTNAME            "
				+ ",SHIPREQUESTDETAILNAME      "
				+ ",SHIPTIME                   "
				+ ",SHIPUSER                   "
				+ ",REASONCODETYPE             "
				+ ",REASONCODE                 "
				+ ",ERPLOCATION                "
				+ ",ETCSTATE                   "
				+ ",ERPFACTORY                 "
				+ ",STOCKINTYPE                "
				+ ",OQARESULTSTATE             "
				+ ",OQARESULT                  "
				+ ",CHARGE                     "
				+ ",SUPPLIERNAME               "
				+ ",UNDOID                     "
				+ ",UNDODETAILNAME             "
				+ ",ERPEVENTTIME               "
				+ ",NPFLAG                     "
				+ ",MESSAGEID                  "
				+ ",ERPSTATE                   "
				+ ",SAVEREASON                 "
				+ ",ENDDATE                    "
				+ ",BOESITENAME                "
				//+ ",PACKINGGRADE               "
				+ ")"
				+ " VALUES ("
				+ " :SITENAME                   "
				+ ",:MATERIALPACKINGNAME        "
				+ ",:MATERIALPACKINGTYPE        "
				+ ",:CONTENTMATERIALTYPE        "
				+ ",:MATERIALTYPE               "
				+ ",:MATERIALSPECNAME           "
				+ ",:SUPERMATERIALPACKINGNAME   "
				+ ",:PACKINGGRADE               "
				+ ",:SUBPACKINGQUANTITY         "
				+ ",:MATERIALCREATEQUANTITY     "
				+ ",:MATERIALQUANTITY           "
				+ ",:PACKINGSTATE               "
				+ ",:OLDPACKINGSTATE            "
				+ ",:STOCKSTATE                 "
				+ ",:OLDSTOCKSTATE              "
				+ ",:HOLDSTATE                  "
				+ ",:AREANAME                   "
				+ ",:LOCATIONNAME               "
				+ ",:DURABLENAME                "
				+ ",:MATERIALPROCESSGROUPNAME   "
				+ ",:LASTEVENTNAME              "
				+ ",:LASTEVENTTIMEKEY           "
				// +",:LASTEVENTTIME              "
				+ " ,SYSDATE "
				+ " ,:SMTEVENTTIME				"  //smt操作时间
				+ ",:LASTEVENTUSER              "
				+ ",:LASTEVENTCOMMENT           "
				// +",:CREATETIME                 "
				+ " ,SYSDATE " + ",:CREATEUSER                 "
				+ ",:RECEIVEREQUESTNAME         "
				+ ",:RECEIVEREQUESTDETAILNAME   "
				+ ",TO_DATE(:MAKEDATE ,'YYYY-MM-DD')                  "
				+ ",:RECEIVEACTNO               "
				+ ",:RECEIVETIME                "
				+ ",:RECEIVEUSER                "
				+ ",:SHIPREQUESTNAME            "
				+ ",:SHIPREQUESTDETAILNAME      "
				+ ",:SHIPTIME                   "
				+ ",:SHIPUSER                   "
				+ ",:REASONCODETYPE             "
				+ ",:REASONCODE                 "
				+ ",:ERPLOCATION                "
				+ ",:ETCSTATE                   "
				+ ",:ERPFACTORY                 "
				+ ",:STOCKINTYPE                "
				+ ",:OQARESULTSTATE             "
				+ ",:OQARESULT                  "
				+ ",:CHARGE                     "
				+ ",:SUPPLIERNAME               "
				+ ",:UNDOID                     "
				+ ",:UNDODETAILNAME             "
				+ ",:ERPEVENTTIME               "
				+ ",:NPFLAG                     "
				+ ",:MESSAGEID                  "
				+ ",:ERPSTATE                   "
				+ ",:SAVEREASON                 "
				+ ",TO_DATE(:ENDDATE ,'YYYY-MM-DD')  " 
				+ ",:BOESITENAME "
				//+ ",:PACKINGGRADE "
				+ " ) ";

		Map<String, String> bindMap = new HashMap<String, String>();
		bindMap.put("SITENAME", siteName);
		bindMap.put("MATERIALPACKINGNAME", materialPackingName);
		bindMap.put("MATERIALPACKINGTYPE", "");
		bindMap.put("CONTENTMATERIALTYPE", "");
		bindMap.put("MATERIALTYPE", materialType);
		bindMap.put("MATERIALSPECNAME", materialSPecName);
		bindMap.put("SUPERMATERIALPACKINGNAME", "");
		bindMap.put("PACKINGGRADE", "");
		bindMap.put("SUBPACKINGQUANTITY", "");
		bindMap.put("MATERIALCREATEQUANTITY", materialQuantity);
		bindMap.put("MATERIALQUANTITY", materialQuantity);
		bindMap.put("PACKINGSTATE", "Released");
		bindMap.put("OLDPACKINGSTATE", "");
		bindMap.put("STOCKSTATE", "Stocked");
		bindMap.put("OLDSTOCKSTATE", "");
		bindMap.put("HOLDSTATE", "");
		bindMap.put("AREANAME", "");
		bindMap.put("LOCATIONNAME", "");
		bindMap.put("DURABLENAME", "");
		bindMap.put("MATERIALPROCESSGROUPNAME", "");
		bindMap.put("LASTEVENTNAME", eventInfo.getEventName());
		bindMap.put("LASTEVENTTIMEKEY", TimeStampUtil.getCurrentEventTimeKey());
		// bindMap.put("LASTEVENTTIME",eventInfo.getEventTime().toString());
		bindMap.put("SMTEVENTTIME", eventTime);
		bindMap.put("LASTEVENTUSER", eventInfo.getEventUser());
		bindMap.put("LASTEVENTCOMMENT", eventInfo.getEventComment());
		// bindMap.put("CREATETIME",eventInfo.getEventTime().toString());
		bindMap.put("CREATEUSER", eventInfo.getEventUser());
		bindMap.put("RECEIVEREQUESTNAME", "");
		bindMap.put("RECEIVEREQUESTDETAILNAME", "");
		bindMap.put("MAKEDATE", makeDate);
		bindMap.put("RECEIVEACTNO", "");
		bindMap.put("RECEIVETIME", "");
		bindMap.put("RECEIVEUSER", "");
		bindMap.put("SHIPREQUESTNAME", shipRequestName);
		bindMap.put("SHIPREQUESTDETAILNAME", "");
		bindMap.put("SHIPTIME", "");
		bindMap.put("SHIPUSER", "");
		bindMap.put("REASONCODETYPE", "");
		bindMap.put("REASONCODE", "");
		bindMap.put("ERPLOCATION", erpLocation);
		bindMap.put("ETCSTATE", "");
		bindMap.put("ERPFACTORY", erpFactory);
		bindMap.put("STOCKINTYPE", "");
		bindMap.put("OQARESULTSTATE", "");
		bindMap.put("OQARESULT", oqaResult);
		bindMap.put("CHARGE", "");
		bindMap.put("SUPPLIERNAME", supplierNo);
		bindMap.put("UNDOID", "JumpERP");
		bindMap.put("UNDODETAILNAME", "");
		bindMap.put("ERPEVENTTIME", "");
		bindMap.put("NPFLAG", "");
		bindMap.put("MESSAGEID", "");
		bindMap.put("ERPSTATE", "");
		bindMap.put("SAVEREASON", "");
		bindMap.put("ENDDATE", endDate);
		bindMap.put("BOESITENAME",BOEFactory );
		bindMap.put("PACKINGGRADE", packingGrade);

		IDMFrameServiceProxy.getSqlTemplate()
				.update(sqlCreat, bindMap);
		CreateBoxHistorySMT(materialPackingName,siteName,BOEFactory);
		log.info(materialPackingName + " is created !");
	}
 
	//zd.2017.12.13 SMT入库前质检
	public void SMTSQEResult( EventInfo eventInfo,String shipType,String materialPackingName,String sqeComment,String siteName,String packingGrade) throws Exception {
		
		try {
			
			Map<String, Object> bindMap = new HashMap<String, Object>();
			bindMap.put("MATERIALPACKINGNAME", materialPackingName);
			bindMap.put("SITENAME", siteName);
			
			String sql1=" SELECT SITENAME,MATERIALPACKINGNAME from materialpackingsmtsqe where materialpackingname in( "+ 
					" SELECT TRIM(REGEXP_SUBSTR(ID, '[^|]+' ,1 ,ROWNUM)) MATERIALPACKINGNAME "+ 
					" FROM (SELECT  :MATERIALPACKINGNAME   ID FROM DUAL) A "+
					" CONNECT BY ROWNUM- 1 <= LENGTH(REGEXP_REPLACE(ID, '[^|]+')) "+
					") and SITENAME=:SITENAME";
			List<Map<String, Object>> sqlResult1 = IDMFrameServiceProxy
					.getSqlTemplate()
					.queryForList(sql1, bindMap);
			
			
			for (int i = 0; i < sqlResult1.size(); i++) {
				if(packingGrade.equals("冻结"))
				{
					String sqlDelete="delete from materialpackingsmtSQE where materialpackingname=:MATERIALPACKINGNAME and sitename=:SITENAME";
					Map<String, String> bindMapd = new HashMap<String, String>();
					
					bindMapd.put("MATERIALPACKINGNAME",sqlResult1.get(i).get("MATERIALPACKINGNAME").toString());
					bindMapd.put("SITENAME",siteName);
					IDMFrameServiceProxy.getSqlTemplate().update(sqlDelete, bindMapd);
					
				}
				
				else{
					String sqlCreat="UPDATE MATERIALPACKINGSMTSQE  "
							+" SET PACKINGGRADE=:PACKINGGRADE "
							+" ,OQARESULT=:OQARESULT"
							+" ,REASONCODETYPE=:REASONCODETYPE"
							+" ,LASTEVENTNAME=:LASTEVENTNAME"
							+" ,LASTEVENTTIMEKEY=:LASTEVENTTIMEKEY"
							+" ,LASTEVENTTIME=sysdate"
							+" ,LASTEVENTUSER=:LASTEVENTUSER"
							+" ,LASTEVENTCOMMENT=:LASTEVENTCOMMENT"
							+" WHERE MATERIALPACKINGNAME=:MATERIALPACKINGNAME "
							+" AND SITENAME=:SITENAME ";
					
					Map<String, String> bindMapu = new HashMap<String, String>();
					bindMapu.put("PACKINGGRADE",packingGrade);
					bindMapu.put("OQARESULT",sqeComment);
					bindMapu.put("REASONCODETYPE",shipType);
					bindMapu.put("MATERIALPACKINGNAME",sqlResult1.get(i).get("MATERIALPACKINGNAME").toString());
					bindMapu.put("LASTEVENTNAME",eventInfo.getEventName());
					bindMapu.put("LASTEVENTTIMEKEY",TimeStampUtil.getCurrentEventTimeKey());
					bindMapu.put("LASTEVENTUSER",eventInfo.getEventUser());
					bindMapu.put("LASTEVENTCOMMENT",eventInfo.getEventComment());
					
					bindMapu.put("SITENAME",siteName);
					
					IDMFrameServiceProxy.getSqlTemplate().update(sqlCreat, bindMapu);
					CreateBoxHistorySMTSQE(sqlResult1.get(i).get("MATERIALPACKINGNAME").toString());
					log.info(sqlResult1.get(i).get("MATERIALPACKINGNAME").toString());
					}

				}
				

				
		} catch (IDMFrameDBErrorSignal ex) {
			log.error(ex, ex);
			throw ex;
		} catch (NotFoundSignal ex) {
			log.error(ex, ex);
			throw ex;
		}
	}
		
public void PDACreateBoxByLabelSMT(EventInfo eventInfo, Document message) throws Exception {

	
	
	String sqlCreat="INSERT INTO MATERIALPACKINGSMT  "
			+"("
			+"SITENAME                    " 
			+",MATERIALPACKINGNAME        "
			+",MATERIALPACKINGTYPE        "
			+",CONTENTMATERIALTYPE        "
			+",MATERIALTYPE               "
			+",MATERIALSPECNAME           "
			+",SUPERMATERIALPACKINGNAME   "
			+",PACKINGGRADE               "
			+",SUBPACKINGQUANTITY         "
			+",MATERIALCREATEQUANTITY     "
			+",MATERIALQUANTITY           "
			+",PACKINGSTATE               "
			+",OLDPACKINGSTATE            "
			+",STOCKSTATE                 "
			+",OLDSTOCKSTATE              "
			+",HOLDSTATE                  "
			+",AREANAME                   "
			+",LOCATIONNAME               "
			+",DURABLENAME                "
			+",MATERIALPROCESSGROUPNAME   "
			+",LASTEVENTNAME              "
			+",LASTEVENTTIMEKEY           "
			+",LASTEVENTTIME              "
			+",LASTEVENTUSER              "
			+",LASTEVENTCOMMENT           "
			+",CREATETIME                 "
			+",CREATEUSER                 "
			+",RECEIVEREQUESTNAME         "
			+",RECEIVEREQUESTDETAILNAME   "
			+",MAKEDATE                   "
			+",RECEIVEACTNO               "
			+",RECEIVETIME                "
			+",RECEIVEUSER                "
			+",SHIPREQUESTNAME            "
			+",SHIPREQUESTDETAILNAME      "
			+",SHIPTIME                   "
			+",SHIPUSER                   "
			+",REASONCODETYPE             "
			+",REASONCODE                 "
			+",ERPLOCATION                "
			+",ETCSTATE                   "
			+",ERPFACTORY                 "
			+",STOCKINTYPE                "
			+",OQARESULTSTATE             "
			+",OQARESULT                  "
			+",CHARGE                     "
			+",SUPPLIERNAME               "
			+",UNDOID                     "
			+",UNDODETAILNAME             "
			+",ERPEVENTTIME               "
			+",NPFLAG                     "
			+",MESSAGEID                  "
			+",ERPSTATE                   "
			+",SAVEREASON                 "
			+",ENDDATE                    "
			+")"
			+" VALUES ("
			+" :SITENAME                   " 
			+",:MATERIALPACKINGNAME        "
			+",:MATERIALPACKINGTYPE        "
			+",:CONTENTMATERIALTYPE        "
			+",:MATERIALTYPE               "
			+",:MATERIALSPECNAME           "
			+",:SUPERMATERIALPACKINGNAME   "
			+",:PACKINGGRADE               "
			+",:SUBPACKINGQUANTITY         "
			+",:MATERIALCREATEQUANTITY     "
			+",:MATERIALQUANTITY           "
			+",:PACKINGSTATE               "
			+",:OLDPACKINGSTATE            "
			+",:STOCKSTATE                 "
			+",:OLDSTOCKSTATE              "
			+",:HOLDSTATE                  "
			+",:AREANAME                   "
			+",:LOCATIONNAME               "
			+",:DURABLENAME                "
			+",:MATERIALPROCESSGROUPNAME   "
			+",:LASTEVENTNAME              "
			+",:LASTEVENTTIMEKEY           "
			//+",:LASTEVENTTIME              "
			+" ,SYSDATE "
			+",:LASTEVENTUSER              "
			+",:LASTEVENTCOMMENT           "
			//+",:CREATETIME                 "
			+" ,SYSDATE "
			+",:CREATEUSER                 "
			+",:RECEIVEREQUESTNAME         "
			+",:RECEIVEREQUESTDETAILNAME   "
			+",TO_DATE(:MAKEDATE ,'YYYY-MM-DD')                  "
			+",:RECEIVEACTNO               "
			+",:RECEIVETIME                "
			+",:RECEIVEUSER                "
			+",:SHIPREQUESTNAME            "
			+",:SHIPREQUESTDETAILNAME      "
			+",:SHIPTIME                   "
			+",:SHIPUSER                   "
			+",:REASONCODETYPE             "
			+",:REASONCODE                 "
			+",:ERPLOCATION                "
			+",:ETCSTATE                   "
			+",:ERPFACTORY                 "
			+",:STOCKINTYPE                "
			+",:OQARESULTSTATE             "
			+",:OQARESULT                  "
			+",:CHARGE                     "
			+",:SUPPLIERNAME               "
			+",:UNDOID                     "
			+",:UNDODETAILNAME             "
			+",:ERPEVENTTIME               "
			+",:NPFLAG                     "
			+",:MESSAGEID                  "
			+",:ERPSTATE                   "
			+",:SAVEREASON                 "
			+",TO_DATE(:ENDDATE ,'YYYY-MM-DD')  "
			+")";
	
	Element bodyElem = message.getRootElement().getChild("Body");
	Map<String, String> bindMap = new HashMap<String, String>();
	        bindMap.put("SITENAME",bodyElem.getChildText("SITENAME"));
			bindMap.put("MATERIALPACKINGNAME",bodyElem.getChildText("MATERIALPACKINGNAME"));
			bindMap.put("MATERIALPACKINGTYPE","");
			bindMap.put("CONTENTMATERIALTYPE","");
			bindMap.put("MATERIALTYPE",bodyElem.getChildText("MATERIALTYPE"));
			bindMap.put("MATERIALSPECNAME",bodyElem.getChildText("MATERIALSPECNAME"));
			bindMap.put("SUPERMATERIALPACKINGNAME","");
			bindMap.put("PACKINGGRADE","");
			bindMap.put("SUBPACKINGQUANTITY","");
			bindMap.put("MATERIALCREATEQUANTITY",bodyElem.getChildText("MATERIALQUANTITY"));
			bindMap.put("MATERIALQUANTITY",bodyElem.getChildText("MATERIALQUANTITY"));
			bindMap.put("PACKINGSTATE","Released");
			bindMap.put("OLDPACKINGSTATE","");
			bindMap.put("STOCKSTATE","Stocked");
			bindMap.put("OLDSTOCKSTATE","");
			bindMap.put("HOLDSTATE","");
			bindMap.put("AREANAME","");
			bindMap.put("LOCATIONNAME","");
			bindMap.put("DURABLENAME","");
			bindMap.put("MATERIALPROCESSGROUPNAME","");
			bindMap.put("LASTEVENTNAME",eventInfo.getEventName());
			bindMap.put("LASTEVENTTIMEKEY",TimeStampUtil.getCurrentEventTimeKey());
			//bindMap.put("LASTEVENTTIME",eventInfo.getEventTime().toString());
			bindMap.put("LASTEVENTUSER",eventInfo.getEventUser());
			bindMap.put("LASTEVENTCOMMENT",eventInfo.getEventComment());
			//bindMap.put("CREATETIME",eventInfo.getEventTime().toString());
			bindMap.put("CREATEUSER",eventInfo.getEventUser());
			bindMap.put("RECEIVEREQUESTNAME","");
			bindMap.put("RECEIVEREQUESTDETAILNAME","");
			bindMap.put("MAKEDATE",bodyElem.getChildText("MAKEDATE"));
			bindMap.put("RECEIVEACTNO","");
			bindMap.put("RECEIVETIME","");
			bindMap.put("RECEIVEUSER","");
			bindMap.put("SHIPREQUESTNAME","");
			bindMap.put("SHIPREQUESTDETAILNAME","");
			bindMap.put("SHIPTIME","");
			bindMap.put("SHIPUSER","");
			bindMap.put("REASONCODETYPE","");
			bindMap.put("REASONCODE","");
			bindMap.put("ERPLOCATION","");
			bindMap.put("ETCSTATE","");
			bindMap.put("ERPFACTORY","");
			bindMap.put("STOCKINTYPE","");
			bindMap.put("OQARESULTSTATE","");
			bindMap.put("OQARESULT","");
			bindMap.put("CHARGE","");
			bindMap.put("SUPPLIERNAME",bodyElem.getChildText("SUPPLIERNO"));
			bindMap.put("UNDOID","");
			bindMap.put("UNDODETAILNAME","");
			bindMap.put("ERPEVENTTIME","");
			bindMap.put("NPFLAG","");
			bindMap.put("MESSAGEID","");
			bindMap.put("ERPSTATE","");
			bindMap.put("SAVEREASON","");
			bindMap.put("ENDDATE",bodyElem.getChildText("ENDDATE"));
			
			String materialType=bodyElem.getChildText("MATERIALTYPE");
			if(materialType.startsWith("调料原材")||materialType.equals("产线退料原材")||materialType.equals("成品返退"))
			{
				String checkExisSql="SELECT * from MATERIALPACKINGSMT WHERE SITENAME=:SITENAME AND MATERIALPACKINGNAME=:MATERIALPACKINGNAME "
						+" AND STOCKSTATE='StockOut'  ";
				Map<String, String> checkbindMap = new HashMap<String, String>();
				checkbindMap.put("SITENAME", bodyElem.getChildText("SITENAME"));
				checkbindMap.put("MATERIALPACKINGNAME", bodyElem.getChildText("MATERIALPACKINGNAME"));
				List<Map<String, Object>> sqlResultCheck = IDMFrameServiceProxy
						.getSqlTemplate()
						.queryForList(checkExisSql, checkbindMap);
				if(sqlResultCheck.size()==0)
				{
					IDMFrameServiceProxy.getSqlTemplate().update(sqlCreat, bindMap);
					//暂时不用，先注释了
					//CreateBoxHistorySMT(bodyElem.getChildText("MATERIALPACKINGNAME"));
					log.info(bodyElem.getChildText("MATERIALPACKINGNAME") +" is created !");
				}
				else
				{
					String sqlUpdate="UPDATE MATERIALPACKINGSMT  "
							+" SET STOCKSTATE='Stocked' "
							+" ,MATERIALTYPE=:MATERIALTYPE"
							+" ,AREANAME=null"
							+" ,NPFLAG='N' "
							+" ,LASTEVENTNAME=:LASTEVENTNAME"
							+" ,LASTEVENTTIMEKEY=:LASTEVENTTIMEKEY"
							+" ,LASTEVENTTIME=sysdate"
							+" ,LASTEVENTUSER=:LASTEVENTUSER"
							+" ,LASTEVENTCOMMENT=:LASTEVENTCOMMENT"
							+" WHERE MATERIALPACKINGNAME=:MATERIALPACKINGNAME "
							+" AND SITENAME=:SITENAME ";
							
					
					//Element bodyElem = message.getRootElement().getChild("Body");
					Element headerElem = message.getRootElement().getChild("Header");
					Map<String, String> bindMapUpdate = new HashMap<String, String>();
					
					bindMapUpdate.put("MATERIALTYPE",bodyElem.getChildText("MATERIALTYPE"));
					bindMapUpdate.put("MATERIALPACKINGNAME",bodyElem.getChildText("MATERIALPACKINGNAME"));
					bindMapUpdate.put("LASTEVENTNAME",eventInfo.getEventName());
					bindMapUpdate.put("LASTEVENTTIMEKEY",TimeStampUtil.getCurrentEventTimeKey());
					bindMapUpdate.put("LASTEVENTUSER",eventInfo.getEventUser());
					bindMapUpdate.put("LASTEVENTCOMMENT",eventInfo.getEventComment());
							
					bindMapUpdate.put("SITENAME",headerElem.getChildText("SITENAME"));
							
							IDMFrameServiceProxy.getSqlTemplate().update(sqlUpdate, bindMapUpdate);
							//暂时不用，先注释了
							//CreateBoxHistorySMT(bodyElem.getChildText("MATERIALPACKINGNAME"));
							log.info(bodyElem.getChildText("MATERIALPACKINGNAME") );
				}
			}
			else
			{
				IDMFrameServiceProxy.getSqlTemplate().update(sqlCreat, bindMap);
				//暂时不用，先注释了
				//CreateBoxHistorySMT(bodyElem.getChildText("MATERIALPACKINGNAME"));
				log.info(bodyElem.getChildText("MATERIALPACKINGNAME") +" is created !");
			}
			
		
			
	}

public void SMTmakeRemove(EventInfo eventInfo, String materialPackingName, Document message) throws Exception {
	String sqlCreat="UPDATE MATERIALPACKINGSMT  "
			+" SET  "
			+"  LASTEVENTNAME=:LASTEVENTNAME"
			+" ,LASTEVENTTIMEKEY=:LASTEVENTTIMEKEY"
			+" ,LASTEVENTTIME=sysdate"
			+" ,LASTEVENTUSER=:LASTEVENTUSER"
			+" ,LASTEVENTCOMMENT=:LASTEVENTCOMMENT"
			+" WHERE MATERIALPACKINGNAME=:MATERIALPACKINGNAME "
			+" AND SITENAME=:SITENAME ";
			
	Element headerElem = message.getRootElement().getChild("Header");
	Map<String, String> bindMap = new HashMap<String, String>();
			bindMap.put("MATERIALPACKINGNAME",materialPackingName);
			bindMap.put("LASTEVENTNAME",eventInfo.getEventName());
			bindMap.put("LASTEVENTTIMEKEY",TimeStampUtil.getCurrentEventTimeKey());
			bindMap.put("LASTEVENTUSER",eventInfo.getEventUser());
			bindMap.put("LASTEVENTCOMMENT",eventInfo.getEventComment());
			
			bindMap.put("SITENAME",headerElem.getChildText("SITENAME"));
			
			IDMFrameServiceProxy.getSqlTemplate().update(sqlCreat, bindMap);
			//暂时不用，先注释了
			//CreateBoxHistorySMT(materialPackingName);
			
			String sqlDelete="DELETE MATERIALPACKINGSMT  "
					+" WHERE MATERIALPACKINGNAME=:MATERIALPACKINGNAME "
					+" AND SITENAME=:SITENAME ";
			Map<String, String> bindMapDe = new HashMap<String, String>();
			bindMapDe.put("MATERIALPACKINGNAME",materialPackingName);
			
			bindMapDe.put("SITENAME",headerElem.getChildText("SITENAME"));
			
			IDMFrameServiceProxy.getSqlTemplate().update(sqlDelete, bindMapDe);
			log.info(materialPackingName );
}
  
//zd.2017.11.14
public void PDACreateBoxByLabelSMT_New(EventInfo eventInfo, Document message) throws Exception {
	
	
		Element bodyElement = message.getRootElement().getChild("Body");
		Element headerElem = message.getRootElement().getChild("Header");
		String materialPackingName = bodyElement.getChildText("MATERIALPACKINGNAME");
		String materialSpecName = bodyElement.getChildText("MATERIALSPECNAME");
		String materialQuantity = bodyElement.getChildText("MATERIALQUANTITY");
		String supplierNo = bodyElement.getChildText("SUPPLIERNO");
		String makeDate = bodyElement.getChildText("MAKEDATE");
		String endDate = bodyElement.getChildText("ENDDATE");
		String siteName = bodyElement.getChildText("SITENAME");
		String materialType = bodyElement.getChildText("MATERIALTYPE");
		String sMTeventTime = headerElem.getChildText("EVENTTIME");
		String LotNo = bodyElement.getChildText("LOTNO");
		String transactionId = headerElem.getChildText("TRANSACTIONID");
		
		String BOEFactory=System.getProperty("factory");
		if(BOEFactory.equals("B5")){
			//B5/tm1的SMT在sitename按照SMTsitename+-+B5/TM1
			String [] sitelist=siteName.split("\\-");
			siteName = sitelist[0];
			BOEFactory = sitelist[1];
		}

		
		String[] LotNoList = LotNo.split("\\|");
		String[] materialPackingNameList = materialPackingName.split("\\|");
		String[] materialSpecNameList = materialSpecName.split("\\|");
		String[] materialQuantityList = materialQuantity.split("\\|");
		String[] supplierNoList = supplierNo.split("\\|");
		String[] makeDateList = makeDate.split("\\|");
		String[] endDateList = endDate.split("\\|");

		String exceptionContent="";
		try{
		int packingNamelength=materialPackingNameList.length;
		if(packingNamelength!=materialSpecNameList.length||packingNamelength!=materialQuantityList.length||packingNamelength!=supplierNoList.length
				||packingNamelength!=makeDateList.length||packingNamelength!=endDateList.length){
			log.info("消息中对应BOX数量和料号、数量、供应商代码、生产日期、到期日个数不一致！");
			exceptionContent="消息中对应BOX数量和料号、数量、供应商代码、生产日期、到期日个数不一致！";
			throw new Exception(exceptionContent);
		}
		
		//增加erplocation/ERPFactory的插入
		String eRPLocation="";
		String ERPFactory = "";
		String sqlERPLocation="SELECT UMLGO,ERPFACTORY FROM BS_SMT_ENUMDEF WHERE SITENAME=:SITENAME AND MATERIALTYPE=:MATERIALTYPE "
				+ " AND BOESITENAME=:BOESITENAME ";
		Map<String, String> bindMaperplocation = new HashMap<String, String>();
		bindMaperplocation.put("SITENAME", siteName);
		bindMaperplocation.put("MATERIALTYPE", "正常成品");
		bindMaperplocation.put("BOESITENAME", BOEFactory);
		List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
				.getSqlTemplate()
				.queryForList(sqlERPLocation, bindMaperplocation);
		if(sqlResult.size()>0){
			eRPLocation=sqlResult.get(0).get("UMLGO").toString();
			ERPFactory=sqlResult.get(0).get("ERPFACTORY").toString();
		}
		
		for (int i = 0; i < materialPackingNameList.length; i++) {
			
			exceptionContent=materialPackingNameList[i]+"|请检查该BOX！！";
			String sqlCreat = "INSERT INTO MATERIALPACKINGSMT  "
					+ "("
					+ "SITENAME                    "
					+ ",MATERIALPACKINGNAME        "
					+ ",MATERIALPACKINGTYPE        "
					+ ",CONTENTMATERIALTYPE        "
					+ ",MATERIALTYPE               "
					+ ",MATERIALSPECNAME           "
					+ ",SUPERMATERIALPACKINGNAME   "
					+ ",PACKINGGRADE               "
					+ ",SUBPACKINGQUANTITY         "
					+ ",MATERIALCREATEQUANTITY     "
					+ ",MATERIALQUANTITY           "
					+ ",PACKINGSTATE               "
					+ ",OLDPACKINGSTATE            "
					+ ",STOCKSTATE                 "
					+ ",OLDSTOCKSTATE              "
					+ ",HOLDSTATE                  "
					+ ",AREANAME                   "
					+ ",LOCATIONNAME               "
					+ ",DURABLENAME                "
					+ ",MATERIALPROCESSGROUPNAME   "
					+ ",LASTEVENTNAME              "
					+ ",LASTEVENTTIMEKEY           "
					+ ",LASTEVENTTIME              "
					+ ",SMTEVENTTIME               "     //增加smt操作时间
					+ ",LASTEVENTUSER              "
					+ ",LASTEVENTCOMMENT           "
					+ ",CREATETIME                 "
					+ ",CREATEUSER                 "
					+ ",RECEIVEREQUESTNAME         "
					+ ",RECEIVEREQUESTDETAILNAME   "
					+ ",MAKEDATE                   "
					+ ",RECEIVEACTNO               "
					+ ",RECEIVETIME                "
					+ ",RECEIVEUSER                "
					+ ",SHIPREQUESTNAME            "
					+ ",SHIPREQUESTDETAILNAME      "
					+ ",SHIPTIME                   "
					+ ",SHIPUSER                   "
					+ ",REASONCODETYPE             "
					+ ",REASONCODE                 "
					+ ",ERPLOCATION                "
					+ ",ETCSTATE                   "
					+ ",ERPFACTORY                 "
					+ ",STOCKINTYPE                "
					+ ",OQARESULTSTATE             "
					+ ",OQARESULT                  "
					+ ",CHARGE                     "
					+ ",SUPPLIERNAME               "
					+ ",UNDOID                     "
					+ ",UNDODETAILNAME             "
					+ ",ERPEVENTTIME               "
					+ ",NPFLAG                     "
					+ ",MESSAGEID                  "
					+ ",ERPSTATE                   "
					+ ",SAVEREASON                 "
					+ ",ENDDATE                    "
					+ ",LOTNO                      "//增加插入LOTNO
					+ ",TRANSACTIONID           "
					+ ",BOESITENAME             "
					+ ")"
					+ " VALUES ("
					+ " :SITENAME                   "
					+ ",:MATERIALPACKINGNAME        "
					+ ",:MATERIALPACKINGTYPE        "
					+ ",:CONTENTMATERIALTYPE        "
					+ ",:MATERIALTYPE               "
					+ ",:MATERIALSPECNAME           "
					+ ",:SUPERMATERIALPACKINGNAME   "
					+ ",:PACKINGGRADE               "
					+ ",:SUBPACKINGQUANTITY         "
					+ ",:MATERIALCREATEQUANTITY     "
					+ ",:MATERIALQUANTITY           "
					+ ",:PACKINGSTATE               "
					+ ",:OLDPACKINGSTATE            "
					+ ",:STOCKSTATE                 "
					+ ",:OLDSTOCKSTATE              "
					+ ",:HOLDSTATE                  "
					+ ",:AREANAME                   "
					+ ",:LOCATIONNAME               "
					+ ",:DURABLENAME                "
					+ ",:MATERIALPROCESSGROUPNAME   "
					+ ",:LASTEVENTNAME              "
					+ ",:LASTEVENTTIMEKEY           "
					// +",:LASTEVENTTIME              "
					+ " ,SYSDATE "
					+ ",:SMTEVENTTIME               "
					+ ",:LASTEVENTUSER              "
					+ ",:LASTEVENTCOMMENT           "
					// +",:CREATETIME                 "
					+ " ,SYSDATE " + ",:CREATEUSER   "
					+ ",:RECEIVEREQUESTNAME         "
					+ ",:RECEIVEREQUESTDETAILNAME   "
					+ ",TO_DATE(:MAKEDATE ,'YYYY-MM-DD')  "
					+ ",:RECEIVEACTNO               "
					+ ",:RECEIVETIME                "
					+ ",:RECEIVEUSER                "
					+ ",:SHIPREQUESTNAME            "
					+ ",:SHIPREQUESTDETAILNAME      "
					+ ",:SHIPTIME                   "
					+ ",:SHIPUSER                   "
					+ ",:REASONCODETYPE             "
					+ ",:REASONCODE                 "
					+ ",:ERPLOCATION                "
					+ ",:ETCSTATE                   "
					+ ",:ERPFACTORY                 "
					+ ",:STOCKINTYPE                "
					+ ",:OQARESULTSTATE             "
					+ ",:OQARESULT                  "
					+ ",:CHARGE                     "
					+ ",:SUPPLIERNAME               "
					+ ",:UNDOID                     "
					+ ",:UNDODETAILNAME             "
					+ ",:ERPEVENTTIME               "
					+ ",:NPFLAG                     "
					+ ",:MESSAGEID                  "
					+ ",:ERPSTATE                   "
					+ ",:SAVEREASON                 "
					+ ",TO_DATE(:ENDDATE ,'YYYY-MM-DD')  "
					+ ",:LOTNO "
					+ ",:TRANSACTIONID      "
					+ ",:BOESITENAME        " 
					+ ")";
	
	//Element bodyElem = message.getRootElement().getChild("Body");
	Map<String, String> bindMap = new HashMap<String, String>();
	        bindMap.put("SITENAME",siteName);
			bindMap.put("MATERIALPACKINGNAME",materialPackingNameList[i]);
			bindMap.put("MATERIALPACKINGTYPE","");
			bindMap.put("CONTENTMATERIALTYPE","");
			bindMap.put("MATERIALTYPE",materialType);
			bindMap.put("MATERIALSPECNAME",materialSpecNameList[i]);
			bindMap.put("SUPERMATERIALPACKINGNAME","");
			bindMap.put("PACKINGGRADE","");
			bindMap.put("SUBPACKINGQUANTITY","");
			bindMap.put("MATERIALCREATEQUANTITY",materialQuantityList[i]);
			bindMap.put("MATERIALQUANTITY",materialQuantityList[i]);
			bindMap.put("PACKINGSTATE","Released");
			bindMap.put("OLDPACKINGSTATE","");
			bindMap.put("STOCKSTATE","Stocked");
			bindMap.put("OLDSTOCKSTATE","");
			bindMap.put("HOLDSTATE","");
			bindMap.put("AREANAME","");
			bindMap.put("LOCATIONNAME","");
			bindMap.put("DURABLENAME","");
			bindMap.put("MATERIALPROCESSGROUPNAME","");
			bindMap.put("LASTEVENTNAME",eventInfo.getEventName());
			bindMap.put("LASTEVENTTIMEKEY",TimeStampUtil.getCurrentEventTimeKey());
			//bindMap.put("LASTEVENTTIME",eventTime.toString());
			bindMap.put("SMTEVENTTIME",sMTeventTime);                                     //增加smt操作时间
			bindMap.put("LASTEVENTUSER",eventInfo.getEventUser());
			bindMap.put("LASTEVENTCOMMENT",eventInfo.getEventComment());
			//bindMap.put("CREATETIME",eventInfo.getEventTime().toString());
			bindMap.put("CREATEUSER",eventInfo.getEventUser());
			bindMap.put("RECEIVEREQUESTNAME","");
			bindMap.put("RECEIVEREQUESTDETAILNAME","");
			bindMap.put("MAKEDATE",makeDateList[i]);
			bindMap.put("RECEIVEACTNO","");
			bindMap.put("RECEIVETIME","");
			bindMap.put("RECEIVEUSER","");
			bindMap.put("SHIPREQUESTNAME","");
			bindMap.put("SHIPREQUESTDETAILNAME","");
			bindMap.put("SHIPTIME","");
			bindMap.put("SHIPUSER","");
			bindMap.put("REASONCODETYPE","");
			bindMap.put("REASONCODE","");
			bindMap.put("ERPLOCATION",eRPLocation);
			bindMap.put("ETCSTATE","");
			bindMap.put("ERPFACTORY",ERPFactory);//增加ERP工厂插入
			bindMap.put("STOCKINTYPE","");
			bindMap.put("OQARESULTSTATE","");
			bindMap.put("OQARESULT","OK");
			bindMap.put("CHARGE","");
			bindMap.put("SUPPLIERNAME",supplierNoList[i].length()==7?"000"+supplierNoList[i]:supplierNoList[i]);
			bindMap.put("UNDOID","");
			bindMap.put("UNDODETAILNAME","");
			bindMap.put("ERPEVENTTIME","");
			bindMap.put("NPFLAG","");
			bindMap.put("MESSAGEID","");
			bindMap.put("ERPSTATE","");
			bindMap.put("SAVEREASON","");
			bindMap.put("ENDDATE",endDateList[i]);
			bindMap.put("TRANSACTIONID", transactionId);
			bindMap.put("BOESITENAME", BOEFactory);
			if(LotNo.length()==0){
				bindMap.put("LOTNO", "");
			}
			else{
				bindMap.put("LOTNO", LotNoList[i]);
			}

			
			//String materialType=bodyElem.getChildText("MATERIALTYPE");
			if(materialType.startsWith("调料原材")||materialType.equals("产线退料原材")||materialType.equals("成品返退")||materialType.equals("正常原材"))
			{
				String checkExisSql="SELECT * from MATERIALPACKINGSMT WHERE SITENAME=:SITENAME AND MATERIALPACKINGNAME=:MATERIALPACKINGNAME "
						+" AND STOCKSTATE='StockOut'  "
						+ " AND BOESITENAME=:BOESITENAME ";
				Map<String, String> checkbindMap = new HashMap<String, String>();
				checkbindMap.put("SITENAME", siteName);
				checkbindMap.put("MATERIALPACKINGNAME", materialPackingNameList[i]);
				checkbindMap.put("BOESITENAME", BOEFactory);
				List<Map<String, Object>> sqlResultCheck = IDMFrameServiceProxy
						.getSqlTemplate()
						.queryForList(checkExisSql, checkbindMap);
				//String checkQty=sqlResultCheck.get(0).get("MATERIALQUANTITY").toString();//注释无用代码
				if(sqlResultCheck.size()==0)
				{
					IDMFrameServiceProxy.getSqlTemplate().update(sqlCreat, bindMap);
					CreateBoxHistorySMT(materialPackingNameList[i],siteName,BOEFactory);
					log.info(materialPackingNameList[i] +" is created !");
				}
				else
				{
					/*//判断数量是否和原来的一样
					if(materialQuantityList[i].equals(checkQty)){*/
					/*使用原Box的情况，更新数量*/
					String sqlUpdate="UPDATE MATERIALPACKINGSMT  "
							+" SET STOCKSTATE='Stocked' "
							+ " ,MATERIALSPECNAME=:MATERIALSPECNAME "
							+ " ,PACKINGSTATE='Released' "
							+" ,MATERIALTYPE=:MATERIALTYPE"
							+" ,AREANAME=null"
							+" ,NPFLAG='N' "
							+ " ,ERPLOCATION=:ERPLOCATION "
							+ " ,ERPFACTORY=:ERPFACTORY "
							+ " ,OQARESULTSTATE='' "
							+ " ,OQARESULT='OK' "
							+ " ,SUPPLIERNAME=:SUPPLIERNAME "
							+" ,LASTEVENTNAME=:LASTEVENTNAME"
							+" ,LASTEVENTTIMEKEY=:LASTEVENTTIMEKEY"
							+" ,LASTEVENTTIME=sysdate"
							+" ,SMTEVENTTIME=:SMTEVENTTIME"      //更新SMT操作时间
							+" ,LASTEVENTUSER=:LASTEVENTUSER"
							+" ,LASTEVENTCOMMENT=:LASTEVENTCOMMENT "
							+" ,MATERIALQUANTITY=:MATERIALQUANTITY "    //更新相同Box的数量
							+" ,LOTNO=:LOTNO "
							+ ",TRANSACTIONID=:TRANSACTIONID   "
							+" WHERE MATERIALPACKINGNAME=:MATERIALPACKINGNAME "
							+" AND SITENAME=:SITENAME "
							+ " AND BOESITENAME=:BOESITENAME";
							
					
					//Element bodyElem = message.getRootElement().getChild("Body");
					
					Map<String, String> bindMapUpdate = new HashMap<String, String>();
					
					bindMapUpdate.put("MATERIALTYPE",materialType);
					bindMapUpdate.put("MATERIALPACKINGNAME",materialPackingNameList[i]);
					bindMapUpdate.put("LASTEVENTNAME",eventInfo.getEventName());
					bindMapUpdate.put("SMTEVENTTIME",sMTeventTime);
					bindMapUpdate.put("LASTEVENTTIMEKEY",TimeStampUtil.getCurrentEventTimeKey());
					bindMapUpdate.put("LASTEVENTUSER",eventInfo.getEventUser());
					bindMapUpdate.put("LASTEVENTCOMMENT",eventInfo.getEventComment());
					bindMapUpdate.put("MATERIALQUANTITY", materialQuantityList[i]);
					bindMapUpdate.put("TRANSACTIONID", transactionId);
					bindMapUpdate.put("BOESITENAME", BOEFactory);
					bindMapUpdate.put("MATERIALQUANTITY", materialQuantityList[i]);
					bindMapUpdate.put("MATERIALSPECNAME", materialSpecNameList[i]);
					bindMapUpdate.put("ERPLOCATION", eRPLocation);
					bindMapUpdate.put("SUPPLIERNAME", supplierNoList[i].length()==7?"000"+supplierNoList[i]:supplierNoList[i]);
					bindMapUpdate.put("ERPFACTORY", ERPFactory);
					if(LotNo.length()==0){
						bindMapUpdate.put("LOTNO", "");
					}
					else{
						bindMapUpdate.put("LOTNO", LotNoList[i]);
					}
							
					bindMapUpdate.put("SITENAME",siteName);
					//IDMFrameServiceProxy.getTransactionManager().beginTransaction();
							
							IDMFrameServiceProxy.getSqlTemplate().update(sqlUpdate, bindMapUpdate);
							//IDMFrameServiceProxy.getTransactionManager().commitTransaction();
							CreateBoxHistorySMT(materialPackingNameList[i],siteName,BOEFactory);
							log.info(materialPackingNameList[i]);
					/*}
					else{
						return;
					}*/
				}
			}
			else
			{
				IDMFrameServiceProxy.getSqlTemplate().update(sqlCreat, bindMap);
				CreateBoxHistorySMT(materialPackingNameList[i],siteName,BOEFactory);
				log.info(materialPackingNameList[i] +" is created !");
			}
			
}
	}
		catch(Exception e)
		{
			e.getMessage();
			throw new Exception(exceptionContent);
			//throw e;
		}
					
}

public void PDACreateBoxByLabelSMTWithTLD_New(EventInfo eventInfo, Document message) throws Exception {
	
	Element bodyElement = message.getRootElement().getChild("Body");
	String materialPackingName=bodyElement.getChildText("MATERIALPACKINGNAME");
	String materialSpecName=bodyElement.getChildText("MATERIALSPECNAME");
	String materialQuantity=bodyElement.getChildText("MATERIALQUANTITY");
	String supplierNo=bodyElement.getChildText("SUPPLIERNO");
	String makeDate=bodyElement.getChildText("MAKEDATE");
	String endDate=bodyElement.getChildText("ENDDATE");
	String siteName=bodyElement.getChildText("SITENAME");
	String materialType=bodyElement.getChildText("MATERIALTYPE");
	String receiveRequestName=bodyElement.getChildText("RECEIVEREQUESTNAME");
	Element headElement = message.getRootElement().getChild("Header");
	String SMTeventTime=headElement.getChildText("EVENTTIME");
	String transactionID=headElement.getChildText("TRANSACTIONID");
	String LotNo = bodyElement.getChildText("LOTNO");
	
	String BOEFactory=System.getProperty("factory");
	if(BOEFactory.equals("B5")){
		//B5/tm1的SMT在sitename按照SMTsitename+-+B5/TM1
		String [] sitelist=siteName.split("\\-");
		siteName = sitelist[0];
		BOEFactory = sitelist[1];
	}

	String[] LotNoList = LotNo.split("\\|");
	String[] materialPackingNameList=materialPackingName.split("\\|");
	String[] materialSpecNameList=materialSpecName.split("\\|");
	String[] materialQuantityList=materialQuantity.split("\\|");
	String[] supplierNoList=supplierNo.split("\\|");
	String[] makeDateList=makeDate.split("\\|");
	String[] endDateList=endDate.split("\\|");
	
	String exceptionContent="";
	try{
	int packingNamelength=materialPackingNameList.length;
	if(packingNamelength!=materialSpecNameList.length||packingNamelength!=materialQuantityList.length||packingNamelength!=supplierNoList.length
			||packingNamelength!=makeDateList.length||packingNamelength!=endDateList.length){
		log.info("消息中对应BOX数量和料号、数量、供应商代码、生产日期、到期日个数不一致！");
		exceptionContent="消息中对应BOX数量和料号、数量、供应商代码、生产日期、到期日个数不一致！";
		throw new Exception(exceptionContent);
	}
	
	//增加erplocation的插入
			String eRPLocation="";
			String ERPFactory = "";
			String sqlERPLocation="SELECT UMLGO,ERPFACTORY FROM BS_SMT_ENUMDEF WHERE SITENAME=:SITENAME AND MATERIALTYPE=:MATERIALTYPE "
					+ " AND BOESITENAME=:BOESITENAME ";
			Map<String, String> bindMaperplocation = new HashMap<String, String>();
			bindMaperplocation.put("SITENAME", siteName);
			bindMaperplocation.put("MATERIALTYPE", "正常成品");
			bindMaperplocation.put("BOESITENAME", BOEFactory);
			List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
					.getSqlTemplate()
					.queryForList(sqlERPLocation, bindMaperplocation);
			if(sqlResult.size()>0){
				eRPLocation=sqlResult.get(0).get("UMLGO").toString();
				ERPFactory=sqlResult.get(0).get("ERPFACTORY").toString();
			}
	
	for(int i=0;i<materialPackingNameList.length;i++)
	{
		exceptionContent=materialPackingNameList[i]+"|请检查该BOX！！";
		String sqlCreat="INSERT INTO MATERIALPACKINGSMT  "
				+"("
				+"SITENAME                    " 
				+",MATERIALPACKINGNAME        "
				+",MATERIALPACKINGTYPE        "
				+",CONTENTMATERIALTYPE        "
				+",MATERIALTYPE               "
				+",MATERIALSPECNAME           "
				+",SUPERMATERIALPACKINGNAME   "
				+",PACKINGGRADE               "
				+",SUBPACKINGQUANTITY         "
				+",MATERIALCREATEQUANTITY     "
				+",MATERIALQUANTITY           "
				+",PACKINGSTATE               "
				+",OLDPACKINGSTATE            "
				+",STOCKSTATE                 "
				+",OLDSTOCKSTATE              "
				+",HOLDSTATE                  "
				+",AREANAME                   "
				+",LOCATIONNAME               "
				+",DURABLENAME                "
				+",MATERIALPROCESSGROUPNAME   "
				+",LASTEVENTNAME              "
				+",LASTEVENTTIMEKEY           "
				+",LASTEVENTTIME              "
				+",SMTEVENTTIME				  "      //SMT操作时间
				+",LASTEVENTUSER              "
				+",LASTEVENTCOMMENT           "
				+",CREATETIME                 "
				+",CREATEUSER                 "
				+",RECEIVEREQUESTNAME         "
				+",RECEIVEREQUESTDETAILNAME   "
				+",MAKEDATE                   "
				+",RECEIVEACTNO               "
				+",RECEIVETIME                "
				+",RECEIVEUSER                "
				+",SHIPREQUESTNAME            "
				+",SHIPREQUESTDETAILNAME      "
				+",SHIPTIME                   "
				+",SHIPUSER                   "
				+",REASONCODETYPE             "
				+",REASONCODE                 "
				+",ERPLOCATION                "
				+",ETCSTATE                   "
				+",ERPFACTORY                 "
				+",STOCKINTYPE                "
				+",OQARESULTSTATE             "
				+",OQARESULT                  "
				+",CHARGE                     "
				+",SUPPLIERNAME               "
				+",UNDOID                     "
				+",UNDODETAILNAME             "
				+",ERPEVENTTIME               "
				+",NPFLAG                     "
				+",MESSAGEID                  "
				+",ERPSTATE                   "
				+",SAVEREASON                 "
				+",ENDDATE                    "
				+",TRANSACTIONID              "
				+",LOTNO                      "
				+ ",BOESITENAME               "
				+")"
				+" VALUES ("
				+" :SITENAME                   " 
				+",:MATERIALPACKINGNAME        "
				+",:MATERIALPACKINGTYPE        "
				+",:CONTENTMATERIALTYPE        "
				+",:MATERIALTYPE               "
				+",:MATERIALSPECNAME           "
				+",:SUPERMATERIALPACKINGNAME   "
				+",:PACKINGGRADE               "
				+",:SUBPACKINGQUANTITY         "
				+",:MATERIALCREATEQUANTITY     "
				+",:MATERIALQUANTITY           "
				+",:PACKINGSTATE               "
				+",:OLDPACKINGSTATE            "
				+",:STOCKSTATE                 "
				+",:OLDSTOCKSTATE              "
				+",:HOLDSTATE                  "
				+",:AREANAME                   "
				+",:LOCATIONNAME               "
				+",:DURABLENAME                "
				+",:MATERIALPROCESSGROUPNAME   "
				+",:LASTEVENTNAME              "
				+",:LASTEVENTTIMEKEY           "
				//+",:LASTEVENTTIME              "
				+" ,SYSDATE "
				+",:SMTEVENTTIME			   "
				+",:LASTEVENTUSER              "
				+",:LASTEVENTCOMMENT           "
				//+",:CREATETIME                 "
				+" ,SYSDATE "
				+",:CREATEUSER                 "
				+",:RECEIVEREQUESTNAME         "
				+",:RECEIVEREQUESTDETAILNAME   "
				+",TO_DATE(:MAKEDATE ,'YYYY-MM-DD')                  "
				+",:RECEIVEACTNO               "
				+",:RECEIVETIME                "
				+",:RECEIVEUSER                "
				+",:SHIPREQUESTNAME            "
				+",:SHIPREQUESTDETAILNAME      "
				+",:SHIPTIME                   "
				+",:SHIPUSER                   "
				+",:REASONCODETYPE             "
				+",:REASONCODE                 "
				+",:ERPLOCATION                "
				+",:ETCSTATE                   "
				+",:ERPFACTORY                 "
				+",:STOCKINTYPE                "
				+",:OQARESULTSTATE             "
				+",:OQARESULT                  "
				+",:CHARGE                     "
				+",:SUPPLIERNAME               "
				+",:UNDOID                     "
				+",:UNDODETAILNAME             "
				+",:ERPEVENTTIME               "
				+",:NPFLAG                     "
				+",:MESSAGEID                  "
				+",:ERPSTATE                   "
				+",:SAVEREASON                 "
				+",TO_DATE(:ENDDATE ,'YYYY-MM-DD')  "
				+",:TRANSACTIONID              "
				+",:LOTNO       "//LOTNO信息插入
				+ ",:BOESITENAME   "//BOE sitename插入
				+")";
		
		//Element bodyElem = message.getRootElement().getChild("Body");
		Map<String, String> bindMap = new HashMap<String, String>();
		        bindMap.put("SITENAME",siteName);
				bindMap.put("MATERIALPACKINGNAME",materialPackingNameList[i]);
				bindMap.put("MATERIALPACKINGTYPE","");
				bindMap.put("CONTENTMATERIALTYPE","");
				bindMap.put("MATERIALTYPE",materialType);
				bindMap.put("MATERIALSPECNAME",materialSpecNameList[i]);
				bindMap.put("SUPERMATERIALPACKINGNAME","");
				bindMap.put("PACKINGGRADE","");
				bindMap.put("SUBPACKINGQUANTITY","");
				bindMap.put("MATERIALCREATEQUANTITY",materialQuantityList[i]);
				bindMap.put("MATERIALQUANTITY",materialQuantityList[i]);
				bindMap.put("PACKINGSTATE","Released");
				bindMap.put("OLDPACKINGSTATE","");
				bindMap.put("STOCKSTATE","Stocked");
				bindMap.put("OLDSTOCKSTATE","");
				bindMap.put("HOLDSTATE","");
				bindMap.put("AREANAME","");
				bindMap.put("LOCATIONNAME","");
				bindMap.put("DURABLENAME","");
				bindMap.put("MATERIALPROCESSGROUPNAME","");
				bindMap.put("LASTEVENTNAME",eventInfo.getEventName());
				bindMap.put("LASTEVENTTIMEKEY",TimeStampUtil.getCurrentEventTimeKey());
				//bindMap.put("LASTEVENTTIME",eventInfo.getEventTime().toString());
				bindMap.put("SMTEVENTTIME",SMTeventTime);                                   //SMT操作时间
				bindMap.put("LASTEVENTUSER",eventInfo.getEventUser());
				bindMap.put("LASTEVENTCOMMENT",eventInfo.getEventComment());
				//bindMap.put("CREATETIME",eventInfo.getEventTime().toString());
				bindMap.put("CREATEUSER",eventInfo.getEventUser());
				bindMap.put("RECEIVEREQUESTNAME",receiveRequestName);
				bindMap.put("RECEIVEREQUESTDETAILNAME","");
				bindMap.put("MAKEDATE",makeDateList[i]);
				bindMap.put("RECEIVEACTNO","");
				bindMap.put("RECEIVETIME","");
				bindMap.put("RECEIVEUSER","");
				bindMap.put("SHIPREQUESTNAME","");
				bindMap.put("SHIPREQUESTDETAILNAME","");
				bindMap.put("SHIPTIME","");
				bindMap.put("SHIPUSER","");
				bindMap.put("REASONCODETYPE","");
				bindMap.put("REASONCODE","");
				bindMap.put("ERPLOCATION",eRPLocation);
				bindMap.put("ETCSTATE","");
				bindMap.put("ERPFACTORY",ERPFactory);//插入ERP工厂
				bindMap.put("STOCKINTYPE","");
				bindMap.put("OQARESULTSTATE","");
				bindMap.put("OQARESULT","OK");
				bindMap.put("CHARGE","");
				bindMap.put("SUPPLIERNAME",supplierNoList[i].length()==7?"000"+supplierNoList[i]:supplierNoList[i]);
				bindMap.put("UNDOID","");
				bindMap.put("UNDODETAILNAME","");
				bindMap.put("ERPEVENTTIME","");
				bindMap.put("NPFLAG","");
				bindMap.put("MESSAGEID","");
				bindMap.put("ERPSTATE","");
				bindMap.put("SAVEREASON","");
				bindMap.put("ENDDATE",endDateList[i]);
				bindMap.put("TRANSACTIONID",transactionID);
				bindMap.put("BOESITENAME", BOEFactory);
				if(LotNo.length()==0){
					bindMap.put("LOTNO", "");
				}
				else{
					bindMap.put("LOTNO", LotNoList[i]);
				}
				
				//String materialType=bodyElem.getChildText("MATERIALTYPE");
				if(materialType.equals("产线退料原材")||materialType.equals("成品返退")||materialType.startsWith("调料原材"))
				{
					String checkExisSql="SELECT * from MATERIALPACKINGSMT WHERE SITENAME=:SITENAME AND MATERIALPACKINGNAME=:MATERIALPACKINGNAME "
							+" AND STOCKSTATE='StockOut'  "
							+ " AND BOESITENAME=:BOESITENAME ";
					Map<String, String> checkbindMap = new HashMap<String, String>();
					checkbindMap.put("SITENAME", siteName);
					checkbindMap.put("MATERIALPACKINGNAME", materialPackingNameList[i]);
					checkbindMap.put("BOESITENAME", BOEFactory);
					List<Map<String, Object>> sqlResultCheck = IDMFrameServiceProxy
							.getSqlTemplate()
							.queryForList(checkExisSql, checkbindMap);
					if(sqlResultCheck.size()==0)
					{
						IDMFrameServiceProxy.getSqlTemplate().update(sqlCreat, bindMap);
						CreateBoxHistorySMT(materialPackingNameList[i],siteName,BOEFactory);
						log.info(materialPackingNameList[i] +" is created !");
					}
					else
					{
						String sqlUpdate="UPDATE MATERIALPACKINGSMT  "
								+" SET STOCKSTATE='Stocked' "
								+ " ,MATERIALQUANTITY=:MATERIALQUANTITY "
								+ " ,MATERIALSPECNAME=:MATERIALSPECNAME "
								+ " ,PACKINGSTATE='Released' "
								+ " ,HOLDSTATE='' "
								+ " ,ERPLOCATION=:ERPLOCATION "
								+ " ,ERPFACTORY=:ERPFACTORY "
								+ " ,SMTEVENTTIME=:SMTEVENTTIME "
								+ " ,SUPPLIERNAME=:SUPPLIERNAME "
								+ " ,OQARESULTSTATE='' "
								+ " ,OQARESULT='OK' "
								+" ,MATERIALTYPE=:MATERIALTYPE"
								+" ,RECEIVEREQUESTNAME=:RECEIVEREQUESTNAME"
								+" ,AREANAME=null "
								+" ,NPFLAG='N' "
								+" ,LASTEVENTNAME=:LASTEVENTNAME"
								+" ,LASTEVENTTIMEKEY=:LASTEVENTTIMEKEY"
								+" ,LASTEVENTTIME=sysdate"
								+" ,LASTEVENTUSER=:LASTEVENTUSER"
								+" ,LASTEVENTCOMMENT=:LASTEVENTCOMMENT"
								+" WHERE MATERIALPACKINGNAME=:MATERIALPACKINGNAME "
								+" AND SITENAME=:SITENAME "
								+ " AND BOESITENAME=:BOESITENAME ";
								
						
						//Element bodyElem = message.getRootElement().getChild("Body");
						Element headerElem = message.getRootElement().getChild("Header");
						Map<String, String> bindMapUpdate = new HashMap<String, String>();
						
						bindMapUpdate.put("MATERIALTYPE",materialType);
						bindMapUpdate.put("RECEIVEREQUESTNAME",receiveRequestName);
						bindMapUpdate.put("MATERIALPACKINGNAME",materialPackingNameList[i]);
						bindMapUpdate.put("LASTEVENTNAME",eventInfo.getEventName());
						bindMapUpdate.put("LASTEVENTTIMEKEY",TimeStampUtil.getCurrentEventTimeKey());
						bindMapUpdate.put("LASTEVENTUSER",eventInfo.getEventUser());
						bindMapUpdate.put("LASTEVENTCOMMENT",eventInfo.getEventComment());
						bindMapUpdate.put("BOESITENAME", BOEFactory);		
						bindMapUpdate.put("SITENAME",siteName);
						bindMapUpdate.put("MATERIALQUANTITY", materialQuantityList[i]);
						bindMapUpdate.put("MATERIALSPECNAME", materialSpecNameList[i]);
						bindMapUpdate.put("ERPLOCATION", eRPLocation);
						bindMapUpdate.put("SMTEVENTTIME", SMTeventTime);
						bindMapUpdate.put("SUPPLIERNAME", supplierNoList[i].length()==7?"000"+supplierNoList[i]:supplierNoList[i]);
						bindMapUpdate.put("ERPFACTORY", ERPFactory);
								
								IDMFrameServiceProxy.getSqlTemplate().update(sqlUpdate, bindMapUpdate);
								CreateBoxHistorySMT(materialPackingNameList[i],siteName,BOEFactory);
								log.info(materialPackingNameList[i]);
					}
				}
				else
				{
					IDMFrameServiceProxy.getSqlTemplate().update(sqlCreat, bindMap);
					CreateBoxHistorySMT(materialPackingNameList[i],siteName,BOEFactory);
					log.info(materialPackingNameList[i] +" is created !");
				}
				
				/*//Increase 调料单详细行项目接收数量
				String sqlReceiveDetail="SELECT RECEIVEREQUESTDETAILNAME FROM MATERIALRECEIVEREQUESTDETAIL WHERE SITENAME=:SITENAME"
						+ " AND RECEIVEREQUESTNAME=:RECEIVEREQUESTNAME "
						+ " AND MATERIALSPECNAME=:MATERIALSPECNAME ";
				Map<String, Object> bindMapReceiveDetail = new HashMap<String, Object>();
				bindMapReceiveDetail.put("SITENAME", siteName);
				bindMapReceiveDetail.put("RECEIVEREQUESTNAME", receiveRequestName);
				bindMapReceiveDetail.put("MATERIALSPECNAME", materialSpecName);
				List<Map<String, Object>> sqlResultReceiveDetail
				= IDMFrameServiceProxy.getSqlTemplate().queryForList(sqlReceiveDetail, bindMapReceiveDetail);
				
				String poDetailName="";
				MakeDetailIncreaseReceivedInfo makeDetailIncreaseReceivedInfo = new MakeDetailIncreaseReceivedInfo();
				MaterialReceiveRequestDetailKey matetialShipRequestDetailKey = new MaterialReceiveRequestDetailKey();
				matetialShipRequestDetailKey
						.setReceiveRequestName(receiveRequestName);
				matetialShipRequestDetailKey.setSiteName(siteName);
				matetialShipRequestDetailKey
						.setReceiveRequestDetailName(poDetailName);
				makeDetailIncreaseReceivedInfo.setIncreaseQuantity(Double
						.parseDouble(materialQuantityList[i]));
				ReceiveRequestDetailServiceProxy.getReceiveRequestDetailService()
						.increaseReceivedQuantity(matetialShipRequestDetailKey,eventInfo, makeDetailIncreaseReceivedInfo);
				log.info("流水单号："+receiveRequestName+"行项目号："+poDetailName+"修改完成");*/
				
		}
	}
	catch(Exception e)
	{
		e.getMessage();
		throw new Exception(exceptionContent);
		//throw e;
	}			
			
			
	}
  
//zd.2017.12.12 SMT入库前先送SQE质检.插入materialpackingsmtsqe表
public void PDACreateBoxByLabelSMTSQE(EventInfo eventInfo, Document message) throws Exception {
	
	Element bodyElement = message.getRootElement().getChild("Body");
	String materialPackingName=bodyElement.getChildText("MATERIALPACKINGNAME");
	String materialSpecName=bodyElement.getChildText("MATERIALSPECNAME");
	String materialQuantity=bodyElement.getChildText("MATERIALQUANTITY");
	String supplierNo=bodyElement.getChildText("SUPPLIERNO");
	String makeDate=bodyElement.getChildText("MAKEDATE");
	String endDate=bodyElement.getChildText("ENDDATE");
	String siteName=bodyElement.getChildText("SITENAME");
	String materialType=bodyElement.getChildText("MATERIALTYPE");
	String shipRequestName=bodyElement.getChildText("SHIPREQUESTNAME");
	String packingGrade=bodyElement.getChildText("PACKINGGRADE");
	
	String[] materialPackingNameList=materialPackingName.split("\\|");
	String[] materialSpecNameList=materialSpecName.split("\\|");
	String[] materialQuantityList=materialQuantity.split("\\|");
	String[] supplierNoList=supplierNo.split("\\|");
	String[] makeDateList=makeDate.split("\\|");
	String[] endDateList=endDate.split("\\|");
	for(int i=0;i<materialPackingNameList.length;i++)
	{
		String sqlCreat="INSERT INTO MATERIALPACKINGSMTSQE  "
				+"("
				+"SITENAME                    " 
				+",MATERIALPACKINGNAME        "
				+",MATERIALPACKINGTYPE        "
				+",CONTENTMATERIALTYPE        "
				+",MATERIALTYPE               "
				+",MATERIALSPECNAME           "
				+",SUPERMATERIALPACKINGNAME   "
				+",PACKINGGRADE               "
				+",SUBPACKINGQUANTITY         "
				+",MATERIALCREATEQUANTITY     "
				+",MATERIALQUANTITY           "
				+",PACKINGSTATE               "
				+",OLDPACKINGSTATE            "
				+",STOCKSTATE                 "
				+",OLDSTOCKSTATE              "
				+",HOLDSTATE                  "
				+",AREANAME                   "
				+",LOCATIONNAME               "
				+",DURABLENAME                "
				+",MATERIALPROCESSGROUPNAME   "
				+",LASTEVENTNAME              "
				+",LASTEVENTTIMEKEY           "
				+",LASTEVENTTIME              "
				+",LASTEVENTUSER              "
				+",LASTEVENTCOMMENT           "
				+",CREATETIME                 "
				+",CREATEUSER                 "
				+",RECEIVEREQUESTNAME         "
				+",RECEIVEREQUESTDETAILNAME   "
				+",MAKEDATE                   "
				+",RECEIVEACTNO               "
				+",RECEIVETIME                "
				+",RECEIVEUSER                "
				+",SHIPREQUESTNAME            "
				+",SHIPREQUESTDETAILNAME      "
				+",SHIPTIME                   "
				+",SHIPUSER                   "
				+",REASONCODETYPE             "
				+",REASONCODE                 "
				+",ERPLOCATION                "
				+",ETCSTATE                   "
				+",ERPFACTORY                 "
				+",STOCKINTYPE                "
				+",OQARESULTSTATE             "
				+",OQARESULT                  "
				+",CHARGE                     "
				+",SUPPLIERNAME               "
				+",UNDOID                     "
				+",UNDODETAILNAME             "
				+",ERPEVENTTIME               "
				+",NPFLAG                     "
				+",MESSAGEID                  "
				+",ERPSTATE                   "
				+",SAVEREASON                 "
				+",ENDDATE                    "
				+")"
				+" VALUES ("
				+" :SITENAME                   " 
				+",:MATERIALPACKINGNAME        "
				+",:MATERIALPACKINGTYPE        "
				+",:CONTENTMATERIALTYPE        "
				+",:MATERIALTYPE               "
				+",:MATERIALSPECNAME           "
				+",:SUPERMATERIALPACKINGNAME   "
				+",:PACKINGGRADE               "
				+",:SUBPACKINGQUANTITY         "
				+",:MATERIALCREATEQUANTITY     "
				+",:MATERIALQUANTITY           "
				+",:PACKINGSTATE               "
				+",:OLDPACKINGSTATE            "
				+",:STOCKSTATE                 "
				+",:OLDSTOCKSTATE              "
				+",:HOLDSTATE                  "
				+",:AREANAME                   "
				+",:LOCATIONNAME               "
				+",:DURABLENAME                "
				+",:MATERIALPROCESSGROUPNAME   "
				+",:LASTEVENTNAME              "
				+",:LASTEVENTTIMEKEY           "
				//+",:LASTEVENTTIME              "
				+" ,SYSDATE "
				+",:LASTEVENTUSER              "
				+",:LASTEVENTCOMMENT           "
				//+",:CREATETIME                 "
				+" ,SYSDATE "
				+",:CREATEUSER                 "
				+",:RECEIVEREQUESTNAME         "
				+",:RECEIVEREQUESTDETAILNAME   "
				+",TO_DATE(:MAKEDATE ,'YYYY-MM-DD')                  "
				+",:RECEIVEACTNO               "
				+",:RECEIVETIME                "
				+",:RECEIVEUSER                "
				+",:SHIPREQUESTNAME            "
				+",:SHIPREQUESTDETAILNAME      "
				+",:SHIPTIME                   "
				+",:SHIPUSER                   "
				+",:REASONCODETYPE             "
				+",:REASONCODE                 "
				+",:ERPLOCATION                "
				+",:ETCSTATE                   "
				+",:ERPFACTORY                 "
				+",:STOCKINTYPE                "
				+",:OQARESULTSTATE             "
				+",:OQARESULT                  "
				+",:CHARGE                     "
				+",:SUPPLIERNAME               "
				+",:UNDOID                     "
				+",:UNDODETAILNAME             "
				+",:ERPEVENTTIME               "
				+",:NPFLAG                     "
				+",:MESSAGEID                  "
				+",:ERPSTATE                   "
				+",:SAVEREASON                 "
				+",TO_DATE(:ENDDATE ,'YYYY-MM-DD')  "
				+")";
		
		//Element bodyElem = message.getRootElement().getChild("Body");
		Map<String, String> bindMap = new HashMap<String, String>();
		        bindMap.put("SITENAME",siteName);
				bindMap.put("MATERIALPACKINGNAME",materialPackingNameList[i]);
				bindMap.put("MATERIALPACKINGTYPE","");
				bindMap.put("CONTENTMATERIALTYPE","");
				bindMap.put("MATERIALTYPE",materialType);
				bindMap.put("MATERIALSPECNAME",materialSpecNameList[i]);
				bindMap.put("SUPERMATERIALPACKINGNAME","");
				bindMap.put("PACKINGGRADE",packingGrade);
				bindMap.put("SUBPACKINGQUANTITY","");
				bindMap.put("MATERIALCREATEQUANTITY",materialQuantityList[i]);
				bindMap.put("MATERIALQUANTITY",materialQuantityList[i]);
				bindMap.put("PACKINGSTATE","Released");
				bindMap.put("OLDPACKINGSTATE","");
				bindMap.put("STOCKSTATE","Stocked");
				bindMap.put("OLDSTOCKSTATE","");
				bindMap.put("HOLDSTATE","");
				bindMap.put("AREANAME","");
				bindMap.put("LOCATIONNAME","");
				bindMap.put("DURABLENAME","");
				bindMap.put("MATERIALPROCESSGROUPNAME","");
				bindMap.put("LASTEVENTNAME",eventInfo.getEventName());
				bindMap.put("LASTEVENTTIMEKEY",TimeStampUtil.getCurrentEventTimeKey());
				//bindMap.put("LASTEVENTTIME",eventInfo.getEventTime().toString());
				bindMap.put("LASTEVENTUSER",eventInfo.getEventUser());
				bindMap.put("LASTEVENTCOMMENT",eventInfo.getEventComment());
				//bindMap.put("CREATETIME",eventInfo.getEventTime().toString());
				bindMap.put("CREATEUSER",eventInfo.getEventUser());
				bindMap.put("RECEIVEREQUESTNAME","");
				bindMap.put("RECEIVEREQUESTDETAILNAME","");
				bindMap.put("MAKEDATE",makeDateList[i]);
				bindMap.put("RECEIVEACTNO","");
				bindMap.put("RECEIVETIME","");
				bindMap.put("RECEIVEUSER","");
				bindMap.put("SHIPREQUESTNAME",shipRequestName);
				bindMap.put("SHIPREQUESTDETAILNAME","");
				bindMap.put("SHIPTIME","");
				bindMap.put("SHIPUSER","");
				bindMap.put("REASONCODETYPE","");
				bindMap.put("REASONCODE","");
				bindMap.put("ERPLOCATION","");
				bindMap.put("ETCSTATE","");
				bindMap.put("ERPFACTORY","");
				bindMap.put("STOCKINTYPE","");
				bindMap.put("OQARESULTSTATE","");
				bindMap.put("OQARESULT","");
				bindMap.put("CHARGE","");
				bindMap.put("SUPPLIERNAME",supplierNoList[i]);
				bindMap.put("UNDOID","");
				bindMap.put("UNDODETAILNAME","");
				bindMap.put("ERPEVENTTIME","");
				bindMap.put("NPFLAG","");
				bindMap.put("MESSAGEID","");
				bindMap.put("ERPSTATE","");
				bindMap.put("SAVEREASON","");
				bindMap.put("ENDDATE",endDateList[i]);
				
				
					IDMFrameServiceProxy.getSqlTemplate().update(sqlCreat, bindMap);
					CreateBoxHistorySMTSQE(materialPackingNameList[i]);
					log.info(materialPackingNameList[i] +" is created !");
	
	}
				
	}

public void PDACreateBoxByLabelSMTWithLot(EventInfo eventInfo, Document message) throws Exception {
	
	
	String sqlCreat="INSERT INTO MATERIALPACKINGSMT  "
			+"("
			+"SITENAME                    " 
			+",MATERIALPACKINGNAME        "
			+",MATERIALPACKINGTYPE        "
			+",CONTENTMATERIALTYPE        "
			+",MATERIALTYPE               "
			+",MATERIALSPECNAME           "
			+",SUPERMATERIALPACKINGNAME   "
			+",PACKINGGRADE               "
			+",SUBPACKINGQUANTITY         "
			+",MATERIALCREATEQUANTITY     "
			+",MATERIALQUANTITY           "
			+",PACKINGSTATE               "
			+",OLDPACKINGSTATE            "
			+",STOCKSTATE                 "
			+",OLDSTOCKSTATE              "
			+",HOLDSTATE                  "
			+",AREANAME                   "
			+",LOCATIONNAME               "
			+",DURABLENAME                "
			+",MATERIALPROCESSGROUPNAME   "
			+",LASTEVENTNAME              "
			+",LASTEVENTTIMEKEY           "
			+",LASTEVENTTIME              "
			+",LASTEVENTUSER              "
			+",LASTEVENTCOMMENT           "
			+",CREATETIME                 "
			+",CREATEUSER                 "
			+",RECEIVEREQUESTNAME         "
			+",RECEIVEREQUESTDETAILNAME   "
			+",MAKEDATE                   "
			+",RECEIVEACTNO               "
			+",RECEIVETIME                "
			+",RECEIVEUSER                "
			+",SHIPREQUESTNAME            "
			+",SHIPREQUESTDETAILNAME      "
			+",SHIPTIME                   "
			+",SHIPUSER                   "
			+",REASONCODETYPE             "
			+",REASONCODE                 "
			+",ERPLOCATION                "
			+",ETCSTATE                   "
			+",ERPFACTORY                 "
			+",STOCKINTYPE                "
			+",OQARESULTSTATE             "
			+",OQARESULT                  "
			+",CHARGE                     "
			+",SUPPLIERNAME               "
			+",UNDOID                     "
			+",UNDODETAILNAME             "
			+",ERPEVENTTIME               "
			+",NPFLAG                     "
			+",MESSAGEID                  "
			+",ERPSTATE                   "
			+",SAVEREASON                 "
			+",ENDDATE                    "
			+")"
			+" VALUES ("
			+" :SITENAME                   " 
			+",:MATERIALPACKINGNAME        "
			+",:MATERIALPACKINGTYPE        "
			+",:CONTENTMATERIALTYPE        "
			+",:MATERIALTYPE               "
			+",:MATERIALSPECNAME           "
			+",:SUPERMATERIALPACKINGNAME   "
			+",:PACKINGGRADE               "
			+",:SUBPACKINGQUANTITY         "
			+",:MATERIALCREATEQUANTITY     "
			+",:MATERIALQUANTITY           "
			+",:PACKINGSTATE               "
			+",:OLDPACKINGSTATE            "
			+",:STOCKSTATE                 "
			+",:OLDSTOCKSTATE              "
			+",:HOLDSTATE                  "
			+",:AREANAME                   "
			+",:LOCATIONNAME               "
			+",:DURABLENAME                "
			+",:MATERIALPROCESSGROUPNAME   "
			+",:LASTEVENTNAME              "
			+",:LASTEVENTTIMEKEY           "
			//+",:LASTEVENTTIME              "
			+" ,SYSDATE "
			+",:LASTEVENTUSER              "
			+",:LASTEVENTCOMMENT           "
			//+",:CREATETIME                 "
			+" ,SYSDATE "
			+",:CREATEUSER                 "
			+",:RECEIVEREQUESTNAME         "
			+",:RECEIVEREQUESTDETAILNAME   "
			+",TO_DATE(:MAKEDATE ,'YYYY-MM-DD')                  "
			+",:RECEIVEACTNO               "
			+",:RECEIVETIME                "
			+",:RECEIVEUSER                "
			+",:SHIPREQUESTNAME            "
			+",:SHIPREQUESTDETAILNAME      "
			+",:SHIPTIME                   "
			+",:SHIPUSER                   "
			+",:REASONCODETYPE             "
			+",:REASONCODE                 "
			+",:ERPLOCATION                "
			+",:ETCSTATE                   "
			+",:ERPFACTORY                 "
			+",:STOCKINTYPE                "
			+",:OQARESULTSTATE             "
			+",:OQARESULT                  "
			+",:CHARGE                     "
			+",:SUPPLIERNAME               "
			+",:UNDOID                     "
			+",:UNDODETAILNAME             "
			+",:ERPEVENTTIME               "
			+",:NPFLAG                     "
			+",:MESSAGEID                  "
			+",:ERPSTATE                   "
			+",:SAVEREASON                 "
			+",TO_DATE(:ENDDATE ,'YYYY-MM-DD')  "
			+")";
	
	Element bodyElem = message.getRootElement().getChild("Body");
	Map<String, String> bindMap = new HashMap<String, String>();
	        bindMap.put("SITENAME",bodyElem.getChildText("SITENAME"));
			bindMap.put("MATERIALPACKINGNAME",bodyElem.getChildText("MATERIALPACKINGNAME"));
			bindMap.put("MATERIALPACKINGTYPE","");
			bindMap.put("CONTENTMATERIALTYPE","");
			bindMap.put("MATERIALTYPE",bodyElem.getChildText("MATERIALTYPE"));
			bindMap.put("MATERIALSPECNAME",bodyElem.getChildText("MATERIALSPECNAME"));
			bindMap.put("SUPERMATERIALPACKINGNAME","");
			bindMap.put("PACKINGGRADE","");
			bindMap.put("SUBPACKINGQUANTITY","");
			bindMap.put("MATERIALCREATEQUANTITY",bodyElem.getChildText("MATERIALQUANTITY"));
			bindMap.put("MATERIALQUANTITY",bodyElem.getChildText("MATERIALQUANTITY"));
			bindMap.put("PACKINGSTATE","Released");
			bindMap.put("OLDPACKINGSTATE","");
			bindMap.put("STOCKSTATE","Stocked");
			bindMap.put("OLDSTOCKSTATE","");
			bindMap.put("HOLDSTATE","");
			bindMap.put("AREANAME","");
			bindMap.put("LOCATIONNAME","");
			bindMap.put("DURABLENAME","");
			bindMap.put("MATERIALPROCESSGROUPNAME","");
			bindMap.put("LASTEVENTNAME",eventInfo.getEventName());
			bindMap.put("LASTEVENTTIMEKEY",TimeStampUtil.getCurrentEventTimeKey());
			//bindMap.put("LASTEVENTTIME",eventInfo.getEventTime().toString());
			bindMap.put("LASTEVENTUSER",eventInfo.getEventUser());
			bindMap.put("LASTEVENTCOMMENT",eventInfo.getEventComment());
			//bindMap.put("CREATETIME",eventInfo.getEventTime().toString());
			bindMap.put("CREATEUSER",eventInfo.getEventUser());
			bindMap.put("RECEIVEREQUESTNAME","");
			bindMap.put("RECEIVEREQUESTDETAILNAME","");
			bindMap.put("MAKEDATE",bodyElem.getChildText("MAKEDATE"));
			bindMap.put("RECEIVEACTNO","");
			bindMap.put("RECEIVETIME","");
			bindMap.put("RECEIVEUSER","");
			bindMap.put("SHIPREQUESTNAME",bodyElem.getChildText("SHIPREQUESTNAME"));
			bindMap.put("SHIPREQUESTDETAILNAME","");
			bindMap.put("SHIPTIME","");
			bindMap.put("SHIPUSER","");
			bindMap.put("REASONCODETYPE","");
			bindMap.put("REASONCODE","");
			bindMap.put("ERPLOCATION","");
			bindMap.put("ETCSTATE","");
			bindMap.put("ERPFACTORY","");
			bindMap.put("STOCKINTYPE","");
			bindMap.put("OQARESULTSTATE","");
			bindMap.put("OQARESULT","");
			bindMap.put("CHARGE","");
			bindMap.put("SUPPLIERNAME",bodyElem.getChildText("SUPPLIERNO"));
			bindMap.put("UNDOID","");
			bindMap.put("UNDODETAILNAME","");
			bindMap.put("ERPEVENTTIME","");
			bindMap.put("NPFLAG","");
			bindMap.put("MESSAGEID","");
			bindMap.put("ERPSTATE","");
			bindMap.put("SAVEREASON","");
			bindMap.put("ENDDATE",bodyElem.getChildText("ENDDATE"));
			
			
		
			IDMFrameServiceProxy.getSqlTemplate().update(sqlCreat, bindMap);
			//暂时不用，先注释了
			//CreateBoxHistorySMT(bodyElem.getChildText("MATERIALPACKINGNAME"));
			log.info(bodyElem.getChildText("MATERIALPACKINGNAME") +" is created !");
		
		
}
	
/**
 * @param eventInfo
 * @param message
 * @throws Exception
 */
public void PDACreateBoxByLabelSMTWithLot_New(EventInfo eventInfo, Document message) throws Exception {
	
	Element bodyElement = message.getRootElement().getChild("Body");
	String materialPackingName=bodyElement.getChildText("MATERIALPACKINGNAME");
	String materialSpecName=bodyElement.getChildText("MATERIALSPECNAME");
	String materialQuantity=bodyElement.getChildText("MATERIALQUANTITY");
	String supplierNo=bodyElement.getChildText("SUPPLIERNO");
	String makeDate=bodyElement.getChildText("MAKEDATE");
	String endDate=bodyElement.getChildText("ENDDATE");
	String siteName=bodyElement.getChildText("SITENAME");
	String materialType=bodyElement.getChildText("MATERIALTYPE");
	String shipRequestName=bodyElement.getChildText("SHIPREQUESTNAME");
	Element headerElem = message.getRootElement().getChild("Header");
	String sMTeventtime = headerElem.getChildText("EVENTTIME");
	String transactionID=headerElem.getChildText("TRANSACTIONID");
	
	String BOEFactory=System.getProperty("factory");
	if(BOEFactory.equals("B5")){
		//B5/tm1的SMT在sitename按照SMTsitename+-+B5/TM1
		String [] sitelist=siteName.split("\\-");
		siteName = sitelist[0];
		BOEFactory = sitelist[1];
	}
	
	String[] materialPackingNameList=materialPackingName.split("\\|");
	String[] materialSpecNameList=materialSpecName.split("\\|");
	String[] materialQuantityList=materialQuantity.split("\\|");
	String[] supplierNoList=supplierNo.split("\\|");
	String[] makeDateList=makeDate.split("\\|");
	String[] endDateList=endDate.split("\\|");
	
	String exceptionContent="";
	try{
	int packingNamelength=materialPackingNameList.length;
	if(packingNamelength!=materialSpecNameList.length||packingNamelength!=materialQuantityList.length||packingNamelength!=supplierNoList.length
			||packingNamelength!=makeDateList.length||packingNamelength!=endDateList.length){
		log.info("消息中对应BOX数量和料号、数量、供应商代码、生产日期、到期日个数不一致！");
		exceptionContent="消息中对应BOX数量和料号、数量、供应商代码、生产日期、到期日个数不一致！";
		throw new Exception(exceptionContent);
	}
	
	//增加erplocation的插入
			String eRPLocation="";
			String ERPFactory = "";
			String sqlERPLocation="SELECT LGORT,ERPFACTORY FROM BS_SMT_ENUMDEF WHERE SITENAME=:SITENAME AND MATERIALTYPE=:MATERIALTYPE "
					+ "AND BOESITENAME=:BOESITENAME";
			Map<String, String> bindMaperplocation = new HashMap<String, String>();
			bindMaperplocation.put("SITENAME", siteName);
			bindMaperplocation.put("MATERIALTYPE", "正常成品");
			bindMaperplocation.put("BOESITENAME", BOEFactory);
			List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
					.getSqlTemplate()
					.queryForList(sqlERPLocation, bindMaperplocation);
			if(sqlResult.size()>0){
				eRPLocation=sqlResult.get(0).get("LGORT").toString();
				ERPFactory=sqlResult.get(0).get("ERPFACTORY").toString();
			}
	
	for(int i=0;i<packingNamelength;i++)
	{
		exceptionContent=materialPackingNameList[i]+"|请检查该BOX！！";
		String sqlCreat="INSERT INTO MATERIALPACKINGSMT  "
				+"("
				+"SITENAME                    " 
				+",MATERIALPACKINGNAME        "
				+",MATERIALPACKINGTYPE        "
				+",CONTENTMATERIALTYPE        "
				+",MATERIALTYPE               "
				+",MATERIALSPECNAME           "
				+",SUPERMATERIALPACKINGNAME   "
				+",PACKINGGRADE               "
				+",SUBPACKINGQUANTITY         "
				+",MATERIALCREATEQUANTITY     "
				+",MATERIALQUANTITY           "
				+",PACKINGSTATE               "
				+",OLDPACKINGSTATE            "
				+",STOCKSTATE                 "
				+",OLDSTOCKSTATE              "
				+",HOLDSTATE                  "
				+",AREANAME                   "
				+",LOCATIONNAME               "
				+",DURABLENAME                "
				+",MATERIALPROCESSGROUPNAME   "
				+",LASTEVENTNAME              "
				+",LASTEVENTTIMEKEY           "
				+",LASTEVENTTIME              "
				+",SMTEVENTTIME				  "
				+",LASTEVENTUSER              "
				+",LASTEVENTCOMMENT           "
				+",CREATETIME                 "
				+",CREATEUSER                 "
				+",RECEIVEREQUESTNAME         "
				+",RECEIVEREQUESTDETAILNAME   "
				+",MAKEDATE                   "
				+",RECEIVEACTNO               "
				+",RECEIVETIME                "
				+",RECEIVEUSER                "
				+",SHIPREQUESTNAME            "
				+",SHIPREQUESTDETAILNAME      "
				+",SHIPTIME                   "
				+",SHIPUSER                   "
				+",REASONCODETYPE             "
				+",REASONCODE                 "
				+",ERPLOCATION                "
				+",ETCSTATE                   "
				+",ERPFACTORY                 "
				+",STOCKINTYPE                "
				+",OQARESULTSTATE             "
				+",OQARESULT                  "
				+",CHARGE                     "
				+",SUPPLIERNAME               "
				+",UNDOID                     "
				+",UNDODETAILNAME             "
				+",ERPEVENTTIME               "
				+",NPFLAG                     "
				+",MESSAGEID                  "
				+",ERPSTATE                   "
				+",SAVEREASON                 "
				+",ENDDATE                    "
				+ ",TRANSACTIONID     "
				+ ",BOESITENAME       "
				+")"
				+" VALUES ("
				+" :SITENAME                   " 
				+",:MATERIALPACKINGNAME        "
				+",:MATERIALPACKINGTYPE        "
				+",:CONTENTMATERIALTYPE        "
				+",:MATERIALTYPE               "
				+",:MATERIALSPECNAME           "
				+",:SUPERMATERIALPACKINGNAME   "
				+",:PACKINGGRADE               "
				+",:SUBPACKINGQUANTITY         "
				+",:MATERIALCREATEQUANTITY     "
				+",:MATERIALQUANTITY           "
				+",:PACKINGSTATE               "
				+",:OLDPACKINGSTATE            "
				+",:STOCKSTATE                 "
				+",:OLDSTOCKSTATE              "
				+",:HOLDSTATE                  "
				+",:AREANAME                   "
				+",:LOCATIONNAME               "
				+",:DURABLENAME                "
				+",:MATERIALPROCESSGROUPNAME   "
				+",:LASTEVENTNAME              "
				+",:LASTEVENTTIMEKEY           "
				//+",:LASTEVENTTIME              "
				+" ,SYSDATE "
				+" ,:SMTEVENTTIME			   "
				+",:LASTEVENTUSER              "
				+",:LASTEVENTCOMMENT           "
				//+",:CREATETIME                 "
				+" ,SYSDATE "
				+",:CREATEUSER                 "
				+",:RECEIVEREQUESTNAME         "
				+",:RECEIVEREQUESTDETAILNAME   "
				+",TO_DATE(:MAKEDATE ,'YYYY-MM-DD')                  "
				+",:RECEIVEACTNO               "
				+",:RECEIVETIME                "
				+",:RECEIVEUSER                "
				+",:SHIPREQUESTNAME            "
				+",:SHIPREQUESTDETAILNAME      "
				+",:SHIPTIME                   "
				+",:SHIPUSER                   "
				+",:REASONCODETYPE             "
				+",:REASONCODE                 "
				+",:ERPLOCATION                "
				+",:ETCSTATE                   "
				+",:ERPFACTORY                 "
				+",:STOCKINTYPE                "
				+",:OQARESULTSTATE             "
				+",:OQARESULT                  "
				+",:CHARGE                     "
				+",:SUPPLIERNAME               "
				+",:UNDOID                     "
				+",:UNDODETAILNAME             "
				+",:ERPEVENTTIME               "
				+",:NPFLAG                     "
				+",:MESSAGEID                  "
				+",:ERPSTATE                   "
				+",:SAVEREASON                 "
				+",TO_DATE(:ENDDATE ,'YYYY-MM-DD')  "
				+ ",:TRANSACTIONID   "
				+ ",:BOESITENAME     "
				+")";
		
		//Element bodyElem = message.getRootElement().getChild("Body");
		Map<String, String> bindMap = new HashMap<String, String>();
		        bindMap.put("SITENAME",siteName);
				bindMap.put("MATERIALPACKINGNAME",materialPackingNameList[i]);
				bindMap.put("MATERIALPACKINGTYPE","");
				bindMap.put("CONTENTMATERIALTYPE","");
				bindMap.put("MATERIALTYPE",materialType);
				bindMap.put("MATERIALSPECNAME",materialSpecNameList[i]);
				bindMap.put("SUPERMATERIALPACKINGNAME","");
				bindMap.put("PACKINGGRADE","");
				bindMap.put("SUBPACKINGQUANTITY","");
				bindMap.put("MATERIALCREATEQUANTITY",materialQuantityList[i]);
				bindMap.put("MATERIALQUANTITY",materialQuantityList[i]);
				bindMap.put("PACKINGSTATE","Released");
				bindMap.put("OLDPACKINGSTATE","");
				bindMap.put("STOCKSTATE","Stocked");
				bindMap.put("OLDSTOCKSTATE","");
				bindMap.put("HOLDSTATE","");
				bindMap.put("AREANAME","");
				bindMap.put("LOCATIONNAME","");
				bindMap.put("DURABLENAME","");
				bindMap.put("MATERIALPROCESSGROUPNAME","");
				bindMap.put("LASTEVENTNAME",eventInfo.getEventName());
				bindMap.put("LASTEVENTTIMEKEY",TimeStampUtil.getCurrentEventTimeKey());
				//bindMap.put("LASTEVENTTIME",eventInfo.getEventTime().toString());
				bindMap.put("SMTEVENTTIME", sMTeventtime);
				bindMap.put("LASTEVENTUSER",eventInfo.getEventUser());
				bindMap.put("LASTEVENTCOMMENT",eventInfo.getEventComment());
				//bindMap.put("CREATETIME",eventInfo.getEventTime().toString());
				bindMap.put("CREATEUSER",eventInfo.getEventUser());
				bindMap.put("RECEIVEREQUESTNAME","");
				bindMap.put("RECEIVEREQUESTDETAILNAME","");
				bindMap.put("MAKEDATE",makeDateList[i]);
				bindMap.put("RECEIVEACTNO","");
				bindMap.put("RECEIVETIME","");
				bindMap.put("RECEIVEUSER","");
				bindMap.put("SHIPREQUESTNAME",shipRequestName);
				bindMap.put("SHIPREQUESTDETAILNAME","");
				bindMap.put("SHIPTIME","");
				bindMap.put("SHIPUSER","");
				bindMap.put("REASONCODETYPE","");
				bindMap.put("REASONCODE","");
				bindMap.put("ERPLOCATION",eRPLocation);
				bindMap.put("ETCSTATE","");
				bindMap.put("ERPFACTORY",ERPFactory);//插入ERP工厂
				bindMap.put("STOCKINTYPE","");
				bindMap.put("OQARESULTSTATE","");
				bindMap.put("OQARESULT","OK");
				bindMap.put("CHARGE","");
				bindMap.put("SUPPLIERNAME",supplierNoList[i].length()==7?"000"+supplierNoList[i]:supplierNoList[i]);
				bindMap.put("UNDOID","");
				bindMap.put("UNDODETAILNAME","");
				bindMap.put("ERPEVENTTIME","");
				bindMap.put("NPFLAG","");
				bindMap.put("MESSAGEID","");
				bindMap.put("ERPSTATE","");
				bindMap.put("SAVEREASON","");
				bindMap.put("ENDDATE",endDateList[i]);
				bindMap.put("TRANSACTIONID", transactionID);
				bindMap.put("BOESITENAME", BOEFactory);
				
				//String materialType=bodyElem.getChildText("MATERIALTYPE");
				if(materialType.startsWith("调料原材")||materialType.equals("产线退料原材")||materialType.equals("成品返退")||materialType.equals("产线重工成品"))
				{
					String checkExisSql="SELECT * from MATERIALPACKINGSMT WHERE SITENAME=:SITENAME AND MATERIALPACKINGNAME=:MATERIALPACKINGNAME "
							+" AND STOCKSTATE='StockOut'  "
							+ " AND BOESITENAME=:BOESITENAME ";
					Map<String, String> checkbindMap = new HashMap<String, String>();
					checkbindMap.put("SITENAME", siteName);
					checkbindMap.put("MATERIALPACKINGNAME", materialPackingNameList[i]);
					checkbindMap.put("BOESITENAME", BOEFactory);
					List<Map<String, Object>> sqlResultCheck = IDMFrameServiceProxy
							.getSqlTemplate()
							.queryForList(checkExisSql, checkbindMap);
					//String checkQty=sqlResultCheck.get(0).get("MATERIALQUANTITY").toString();//注释无用代码
					if(sqlResultCheck.size()==0)
					{
						IDMFrameServiceProxy.getSqlTemplate().update(sqlCreat, bindMap);
						CreateBoxHistorySMT(materialPackingNameList[i],siteName,BOEFactory);
						log.info(materialPackingNameList[i] +" is created !");
					}
					else
					{
						//核对是否数量与原数量一直
						/*if(materialQuantityList[i].equals(checkQty)){//取消对数量的校验*/  
						/*使用原Box退库时，更新数量*/
						String sqlUpdate="UPDATE MATERIALPACKINGSMT  "
								+" SET STOCKSTATE='Stocked' "
								+ " ,MATERIALSPECNAME=:MATERIALSPECNAME "
								+ " ,PACKINGSTATE='Released' "
								+ " ,ERPLOCATION=:ERPLOCATION "
								+ " ,ERPFACTORY=:ERPFACTORY "
								+ " ,OQARESULTSTATE='' "
								+ " ,OQARESULT='OK' "
								+ " ,SUPPLIERNAME=:SUPPLIERNAME "
								+" ,MATERIALTYPE=:MATERIALTYPE"
								+" ,AREANAME=null"
								+" ,NPFLAG='N' "
								+" ,LASTEVENTNAME=:LASTEVENTNAME"
								+" ,LASTEVENTTIMEKEY=:LASTEVENTTIMEKEY"
								+" ,LASTEVENTTIME=sysdate"
								+" ,SMTEVENTTIME=:SMTEVENTTIME "
								+" ,LASTEVENTUSER=:LASTEVENTUSER "
								+" ,LASTEVENTCOMMENT=:LASTEVENTCOMMENT "
								+" ,MATERIALQUANTITY=:MATERIALQUANTITY  "
								+ ",TRANSACTIONID=:TRANSACTIONID  "
								+" WHERE MATERIALPACKINGNAME=:MATERIALPACKINGNAME "
								+" AND SITENAME=:SITENAME "
								+ " AND BOESITENAME=:BOESITENAME ";
								
						
						//Element bodyElem = message.getRootElement().getChild("Body");
						//Element headerElem = message.getRootElement().getChild("Header");
						Map<String, String> bindMapUpdate = new HashMap<String, String>();
						
						bindMapUpdate.put("MATERIALTYPE",materialType);
						bindMapUpdate.put("MATERIALPACKINGNAME",materialPackingNameList[i]);
						bindMapUpdate.put("LASTEVENTNAME",eventInfo.getEventName());
						bindMapUpdate.put("LASTEVENTTIMEKEY",TimeStampUtil.getCurrentEventTimeKey());
						bindMapUpdate.put("LASTEVENTUSER",eventInfo.getEventUser());
						bindMapUpdate.put("SMTEVENTTIME",sMTeventtime);
						bindMapUpdate.put("LASTEVENTCOMMENT",eventInfo.getEventComment());
						bindMapUpdate.put("MATERIALQUANTITY",materialQuantityList[i]);        //增加数量
						bindMapUpdate.put("SITENAME",siteName);
						bindMapUpdate.put("TRANSACTIONID", transactionID);
						bindMapUpdate.put("BOESITENAME", BOEFactory);
						bindMapUpdate.put("MATERIALQUANTITY", materialQuantityList[i]);
						bindMapUpdate.put("MATERIALSPECNAME", materialSpecNameList[i]);
						bindMapUpdate.put("ERPLOCATION", eRPLocation);
						bindMapUpdate.put("SUPPLIERNAME", supplierNoList[i].length()==7?"000"+supplierNoList[i]:supplierNoList[i]);
						bindMapUpdate.put("ERPFACTORY", ERPFactory);
						
								IDMFrameServiceProxy.getSqlTemplate().update(sqlUpdate, bindMapUpdate);
								CreateBoxHistorySMT(materialPackingNameList[i],siteName,BOEFactory);
								log.info(materialPackingNameList[i]+"以原BOX入库！");
						/*}
						else{
							return;
						}*/
					}
				}
				else
				{
					IDMFrameServiceProxy.getSqlTemplate().update(sqlCreat, bindMap);
					CreateBoxHistorySMT(materialPackingNameList[i],siteName,BOEFactory);
					log.info(materialPackingNameList[i] +" is created !");
				}
				
	}
	}
	catch(Exception e)
	{
		e.getMessage();
		throw new Exception(exceptionContent);
		//throw e;
	}
				
			
			
	}	
/*
 * 2018.10.24
 * jing
 * 修改当个box入库为多个Box入库
 * 
 * */
public void BoxStockOutByLabelSMT(EventInfo eventInfo, Document message) throws Exception {
	try{
	Element bodyElem = message.getRootElement().getChild("Body");
	String materialpackingName=bodyElem.getChildText("MATERIALPACKINGNAME");
	String[] materialPackingNameList=materialpackingName.split("\\|"); 
	String areaName=bodyElem.getChildText("AREANAME");
	String siteName=bodyElem.getChildText("SITENAME");
	String shipRequestDetailName=bodyElem.getChildText("SHIPREQUESTDETAILNAME");
	Element headerElem = message.getRootElement().getChild("Header");
	String sMTeventtime = headerElem.getChildText("EVENTTIME");
	//Element headElem = message.getRootElement().getChild("Header");
	String transactionID=headerElem.getChildText("TRANSACTIONID");
	String eventTime=headerElem.getChildText("EVENTTIME");
	String eventName=headerElem.getChildText("EVENTNAME");
	String eventUser=headerElem.getChildText("EVENTUSER");
	String messageName=headerElem.getChildText("MESSAGENAME");
	String materialType=areaName;
	
	String BOEFactory=System.getProperty("factory");
	if(BOEFactory.equals("B5")){
		//B5/tm1的SMT在sitename按照SMTsitename+-+B5/TM1
		String [] sitelist=siteName.split("\\-");
		siteName = sitelist[0];
		BOEFactory = sitelist[1];
	}
	
	//Document转成String
		Format format = Format.getPrettyFormat();  
	    format.setEncoding("UTF-8");// 设置xml文件的字符为UTF-8，解决中文问题  
	    XMLOutputter xmlout = new XMLOutputter(format);  
	    ByteArrayOutputStream bo = new ByteArrayOutputStream();  
	    xmlout.output(message, bo);  
	    String messageLog=bo.toString();
		//Document转成String
		
		insertSMTMessageLogUtil(transactionID,
				eventTime,eventName, eventUser,
				siteName, messageLog, messageName,
				materialType);
	
	//int a=materialPackingNameList.length;
	log.info("BOX数量:"+materialPackingNameList.length+"-------"+materialpackingName);
	//采用批量update处理方式，避免for循环在BOX数量较多时，耗时过长
	double a= materialPackingNameList.length;
	int length4Split=30;
	double b=Math.ceil(a/length4Split);
	int circleTime =(int)b;
	log.info("materialPackingNameList.length>>>>>>: " + a+" Circle Times>>>:"+circleTime);
	//将materialpackingName按照30个一循环，循环批量处理，避免SQL过长
	for(int i=0;i<circleTime;i++){
		String BoxList="";
		if(i==circleTime-1){
			for(int j=0;j<(a-length4Split*(b-1));j++){
				String BoxLista=materialPackingNameList[i*length4Split+j]+"|";
				BoxList=BoxList+BoxLista;
			}
		}
		else{
			for(int j=0;j<length4Split;j++){
				String BoxLista=materialPackingNameList[i*length4Split+j]+"|";
				BoxList=BoxList+BoxLista;
			}
		}
		BoxList=BoxList.substring(0, BoxList.length()-1);
		log.info("Circle Count>>>: "+i+" BoxList>>>>>>: " + BoxList);
	//for( int i=0;i<a;i++){
		String sqlCreat="UPDATE MATERIALPACKINGSMT  "
				+" SET STOCKSTATE='StockOut' "
				+" ,AREANAME=:AREANAME "
				+" ,LASTEVENTNAME=:LASTEVENTNAME"
				+" ,LASTEVENTTIMEKEY=:LASTEVENTTIMEKEY"
				+" ,SHIPREQUESTDETAILNAME=:SHIPREQUESTDETAILNAME "
				+" ,LASTEVENTTIME=sysdate"
				+" ,SMTEVENTTIME=:SMTEVENTTIME"
				+" ,LASTEVENTUSER=:LASTEVENTUSER"
				+" ,LASTEVENTCOMMENT=:LASTEVENTCOMMENT "
				+ ",TRANSACTIONID=:TRANSACTIONID "
				+" WHERE MATERIALPACKINGNAME IN(select regexp_substr(id, '[^|]+' ,1 ,rownum) id from (select  :MATERIALPACKINGNAME id from dual) a "
				+ " connect by rownum- 1 <= length(regexp_replace(id, '[^|]+'))) "
				+" AND SITENAME=:SITENAME "
				+ " AND BOESITENAME=:BOESITENAME ";				
		Map<String, String> bindMap = new HashMap<String, String>();
		        bindMap.put("AREANAME",areaName);
				bindMap.put("MATERIALPACKINGNAME",BoxList);
				bindMap.put("LASTEVENTNAME",eventInfo.getEventName());
				bindMap.put("LASTEVENTTIMEKEY",TimeStampUtil.getCurrentEventTimeKey());
				bindMap.put("SHIPREQUESTDETAILNAME", shipRequestDetailName);
				bindMap.put("SMTEVENTTIME",sMTeventtime);
				bindMap.put("LASTEVENTUSER",eventInfo.getEventUser());
				bindMap.put("LASTEVENTCOMMENT",eventInfo.getEventComment());				
				bindMap.put("SITENAME",siteName);	
				bindMap.put("TRANSACTIONID", transactionID);
				bindMap.put("BOESITENAME", BOEFactory);
				
				log.info("UPDATE MaterialPackingname:"+BoxList);
				//IDMFrameServiceProxy.getTransactionManager().beginTransaction();
				IDMFrameServiceProxy.getSqlTemplate().update(sqlCreat, bindMap);
				CreateBoxHistorySMTbatch(BoxList,BOEFactory,siteName);
				//IDMFrameServiceProxy.getTransactionManager().commitTransaction();
				log.info(BoxList+"Record & History Updated");

	//}
	}
	String Undoid="JumpERP";
	String Undoiddetailname="";
	UpdateMaterialPackingSMTERPInfo(transactionID, siteName, Undoid, Undoiddetailname);
	UpdateMaterialpackingSMTHistory(transactionID, siteName, Undoid, Undoiddetailname);
	}
	catch(Exception e)
	{
		e.getMessage();
		throw e;
	}
}
/*
 * 2018.10.24
 * jing
 * 多个Box取消出库 
 * 
 * */
public void SMTmakeStocked(EventInfo eventInfo, String materialPackingName, Document message) throws Exception {
	Element bodyElem = message.getRootElement().getChild("Body");
	String materialpackingName=bodyElem.getChildText("MATERIALPACKINGNAME");
	String[] materialPackingNameList=materialpackingName.split("\\|"); 
	String siteName=bodyElem.getChildText("SITENAME");
	
	String BOEFactory=System.getProperty("factory");
	if(BOEFactory.equals("B5")){
		//B5/tm1的SMT在sitename按照SMTsitename+-+B5/TM1
		String [] sitelist=siteName.split("\\-");
		siteName = sitelist[0];
		BOEFactory = sitelist[1];
	}
	
	int a=materialPackingNameList.length;	
	for(int i=0;i<a;i++){
		String sqlCreat="UPDATE MATERIALPACKINGSMT  "
				+" SET STOCKSTATE='Stocked' "
				+" ,AREANAME=:AREANAME "
				+" ,LASTEVENTNAME=:LASTEVENTNAME"
				+" ,LASTEVENTTIMEKEY=:LASTEVENTTIMEKEY"
				+" ,LASTEVENTTIME=sysdate"
				+" ,LASTEVENTUSER=:LASTEVENTUSER"
				+" ,LASTEVENTCOMMENT=:LASTEVENTCOMMENT"
				+" WHERE MATERIALPACKINGNAME=:MATERIALPACKINGNAME "
				+" AND SITENAME=:SITENAME ";		
		Map<String, String> bindMap = new HashMap<String, String>();
		        bindMap.put("AREANAME","");
				bindMap.put("MATERIALPACKINGNAME",materialPackingNameList[i]);
				bindMap.put("LASTEVENTNAME",eventInfo.getEventName());
				bindMap.put("LASTEVENTTIMEKEY",TimeStampUtil.getCurrentEventTimeKey());
				bindMap.put("LASTEVENTUSER",eventInfo.getEventUser());
				bindMap.put("LASTEVENTCOMMENT",eventInfo.getEventComment());				
				bindMap.put("SITENAME",siteName);				
				IDMFrameServiceProxy.getSqlTemplate().update(sqlCreat, bindMap);
				CreateBoxHistorySMT(materialPackingNameList[i],siteName,BOEFactory);
				log.info(materialPackingNameList[i] );
	}
	
}

public void BoxStockOutByLabelSMT_New(EventInfo eventInfo, Document message) throws Exception {
	try{
	Element bodyElem = message.getRootElement().getChild("Body");
	Element headerElem = message.getRootElement().getChild("Header");
	String materialpackingName=bodyElem.getChildText("MATERIALPACKINGNAME");
	String[] materialPackingNameList=materialpackingName.split("\\|"); 
	String areaName=bodyElem.getChildText("AREANAME");
	String siteName=bodyElem.getChildText("SITENAME");
	String smteventTime = headerElem.getChildText("EVENTTIME");
	String TransactionID= headerElem.getChildText("TRANSACTIONID");
	
	String BOEFactory=System.getProperty("factory");
	if(BOEFactory.equals("B5")){
		//B5/tm1的SMT在sitename按照SMTsitename+-+B5/TM1
		String [] sitelist=siteName.split("\\-");
		siteName = sitelist[0];
		BOEFactory = sitelist[1];
	}
	
	//int a=materialPackingNameList.length;
	//for(int i=0;i<materialPackingNameList.length;i++)
	//{
	//批量update数据，避免BOX较多时，for循环耗时较长
	log.info("BOX数量："+materialPackingNameList.length+"---------"+materialpackingName);
	double a= materialPackingNameList.length;
	int length4Split=30;
	double b=Math.ceil(a/length4Split);
	int circleTime =(int)b;
	log.info("materialPackingNameList.length>>>>>>: " + a+" Circle Times>>>:"+circleTime);
	//将materialpackingName按照30个一循环，循环批量处理，避免SQL过长
	for(int i=0;i<circleTime;i++){
		String BoxList="";
		if(i==circleTime-1){
			for(int j=0;j<(a-length4Split*(b-1));j++){
				String BoxLista=materialPackingNameList[i*length4Split+j]+"|";
				BoxList=BoxList+BoxLista;
			}
		}
		else{
			for(int j=0;j<length4Split;j++){
				String BoxLista=materialPackingNameList[i*length4Split+j]+"|";
				BoxList=BoxList+BoxLista;
			}
		}
		BoxList=BoxList.substring(0, BoxList.length()-1);
		log.info("Circle Count>>>: "+i+" BoxList>>>>>>: " + BoxList);
		String sqlCreat="UPDATE MATERIALPACKINGSMT  "
				+" SET STOCKSTATE='StockOut' "
				+" ,AREANAME=:AREANAME "
				+" ,LASTEVENTNAME=:LASTEVENTNAME"
				+" ,LASTEVENTTIMEKEY=:LASTEVENTTIMEKEY"
				+" ,LASTEVENTTIME=sysdate"
				+" ,SMTEVENTTIME=:SMTEVENTTIME"
				+" ,LASTEVENTUSER=:LASTEVENTUSER"
				+" ,LASTEVENTCOMMENT=:LASTEVENTCOMMENT "
				+ ",TRANSACTIONID=:TRANSACTIONID"
				+" WHERE MATERIALPACKINGNAME  IN(select regexp_substr(id, '[^|]+' ,1 ,rownum) id from (select  :MATERIALPACKINGNAME id from dual) a "
				+ " connect by rownum- 1 <= length(regexp_replace(id, '[^|]+'))) "
				+" AND SITENAME=:SITENAME "
				+ " AND BOESITENAME=:BOESITENAME ";
				
		
		/*Element bodyElem = message.getRootElement().getChild("Body");
		Element headerElem = message.getRootElement().getChild("Header");*/
		Map<String, String> bindMap = new HashMap<String, String>();
		        bindMap.put("AREANAME",areaName);
				bindMap.put("MATERIALPACKINGNAME",BoxList);
				bindMap.put("LASTEVENTNAME",eventInfo.getEventName());
				bindMap.put("LASTEVENTTIMEKEY",TimeStampUtil.getCurrentEventTimeKey());
				bindMap.put("SMTEVENTTIME", smteventTime);
				bindMap.put("LASTEVENTUSER",eventInfo.getEventUser());
				bindMap.put("LASTEVENTCOMMENT",eventInfo.getEventComment());
				bindMap.put("TRANSACTIONID", TransactionID);
				bindMap.put("SITENAME",siteName);
				bindMap.put("BOESITENAME", BOEFactory);
				//IDMFrameServiceProxy.getTransactionManager().beginTransaction();
				IDMFrameServiceProxy.getSqlTemplate().update(sqlCreat, bindMap);
				//IDMFrameServiceProxy.getTransactionManager().commitTransaction();
				CreateBoxHistorySMTbatch(BoxList,BOEFactory,siteName);
				log.info(BoxList+"已完成出库更新！");
				//}
	}
	
			
	}
	catch(Exception e)
	{
		e.getMessage();
		throw e;
	}
}

public void BoxStockOutByLabelSMT_NewWithWo(EventInfo eventInfo, Document message) throws Exception {
	
	Element bodyElem = message.getRootElement().getChild("Body");
	Element headerElem = message.getRootElement().getChild("Header");
	String materialpackingName=bodyElem.getChildText("MATERIALPACKINGNAME");
	String[] materialPackingNameList=materialpackingName.split("\\|"); 
	String areaName=bodyElem.getChildText("AREANAME");
	String siteName=bodyElem.getChildText("SITENAME");
	String shipRequestName=bodyElem.getChildText("SHIPREQUESTNAME");  
	String smteventTime =headerElem.getChildText("EVENTTIME");
	String transactionID=headerElem.getChildText("TRANSACTIONID");
	
	String BOEFactory=System.getProperty("factory");
	if(BOEFactory.equals("B5")){
		//B5/tm1的SMT在sitename按照SMTsitename+-+B5/TM1
		String [] sitelist=siteName.split("\\-");
		siteName = sitelist[0];
		BOEFactory = sitelist[1];
	}
	
	int a=materialPackingNameList.length;
	log.info("materialPackingNameListlength:"+a+" areaName"+areaName +"---"+ materialpackingName);
	
	//优化代码，采用materialpackingName中“|”分隔符进行update数据库，避免BOX较多时for循环耗时
	//for(int i=0;i<materialPackingNameList.length;i++)
	//{
	String sqlCreat="UPDATE MATERIALPACKINGSMT  "
			+" SET STOCKSTATE='StockOut' "
			+" ,AREANAME=:AREANAME "
			+" ,SHIPREQUESTNAME=:SHIPREQUESTNAME "
			+" ,LASTEVENTNAME=:LASTEVENTNAME"
			+" ,LASTEVENTTIMEKEY=:LASTEVENTTIMEKEY"
			+" ,LASTEVENTTIME=sysdate"
			+" ,SMTEVENTTIME=:SMTEVENTTIME"
			+" ,LASTEVENTUSER=:LASTEVENTUSER"
			+" ,LASTEVENTCOMMENT=:LASTEVENTCOMMENT "
			+ ",TRANSACTIONID=:TRANSACTIONID "
			+" WHERE MATERIALPACKINGNAME  IN(select regexp_substr(id, '[^|]+' ,1 ,rownum) id from (select  :MATERIALPACKINGNAME id from dual) a "
			+ " connect by rownum- 1 <= length(regexp_replace(id, '[^|]+'))) "
			+" AND SITENAME=:SITENAME "
			+ " AND BOESITENAME=:BOESITENAME ";
			
	
	/*Element bodyElem = message.getRootElement().getChild("Body");
	Element headerElem = message.getRootElement().getChild("Header");*/
	Map<String, String> bindMap = new HashMap<String, String>();
	        bindMap.put("AREANAME",areaName);
	        bindMap.put("SHIPREQUESTNAME",shipRequestName);
			bindMap.put("MATERIALPACKINGNAME",materialpackingName);
			bindMap.put("LASTEVENTNAME",eventInfo.getEventName());
			bindMap.put("LASTEVENTTIMEKEY",TimeStampUtil.getCurrentEventTimeKey());
			bindMap.put("SMTEVENTTIME", smteventTime);
			bindMap.put("LASTEVENTUSER",eventInfo.getEventUser());
			bindMap.put("LASTEVENTCOMMENT",eventInfo.getEventComment());
			bindMap.put("TRANSACTIONID", transactionID);
			bindMap.put("SITENAME",siteName);
			bindMap.put("BOESITENAME", BOEFactory);
			
			//IDMFrameServiceProxy.getTransactionManager().beginTransaction();
			IDMFrameServiceProxy.getSqlTemplate().update(sqlCreat, bindMap);
			CreateBoxHistorySMTbatch(materialpackingName,BOEFactory,siteName);
			//IDMFrameServiceProxy.getTransactionManager().commitTransaction();
			log.info(materialpackingName+"已全部出库完成！");
			//}
}
/*
 * 2019.1.10
 * WSQ
 * SMTcheck BOX状态是否为Stocked
 * */
public String CheckSMTStockedBox(EventInfo eventInfo, Document message) throws Exception{
	Element bodyElem = message.getRootElement().getChild("Body");
	String siteName=bodyElem.getChildText("SITENAME");
	String materialpackingName=bodyElem.getChildText("MATERIALPACKINGNAME");
	String[] materialPackingNameList=materialpackingName.split("\\|");
	String checkresultStocked="OK|0";
	
	String BOEFactory=System.getProperty("factory");
	if(BOEFactory.equals("B5")){
		//B5/tm1的SMT在sitename按照SMTsitename+-+B5/TM1
		String [] sitelist=siteName.split("\\-");
		siteName = sitelist[0];
		BOEFactory = sitelist[1];
	}
	
	int materialPackingNameLength=materialPackingNameList.length;
	//for(int j=0;j<a;j++){
	String checkNumSql="select regexp_substr(id, '[^|]+' ,1 ,rownum) id from (select  :MATERIALPACKINGNAME id from dual) a "
			+ " connect by rownum- 1 <= length(regexp_replace(id, '[^|]+')) ";
	Map<String, String> bindMapNum = new HashMap<String, String>();
	bindMapNum.put("MATERIALPACKINGNAME", materialpackingName);
	List<Map<String, Object>> sqlResultNum = IDMFrameServiceProxy
			.getSqlTemplate()
			.queryForList(checkNumSql, bindMapNum);
	if(materialPackingNameLength>sqlResultNum.size()){
		checkresultStocked="MATERIALPACKINGNAME存在重复的BOX ID！|ERROR";
		return checkresultStocked;
	}
	
		String checkExisSql="SELECT MATERIALPACKINGNAME from MATERIALPACKINGSMT WHERE SITENAME=:SITENAME AND MATERIALPACKINGNAME IN(select regexp_substr(id, '[^|]+' ,1 ,rownum) id from (select  :MATERIALPACKINGNAME id from dual) a "
				+ " connect by rownum- 1 <= length(regexp_replace(id, '[^|]+'))) "
				+" AND STOCKSTATE='Stocked'  "
				+ " AND OQARESULT='OK'  "
				+ " AND BOESITENAME=:BOESITENAME ";
		Map<String, String> checkbindMap = new HashMap<String, String>();
		checkbindMap.put("SITENAME", siteName);
		checkbindMap.put("MATERIALPACKINGNAME", materialpackingName);
		checkbindMap.put("BOESITENAME", BOEFactory);
		List<Map<String, Object>> sqlResultCheck = IDMFrameServiceProxy
				.getSqlTemplate()
				.queryForList(checkExisSql, checkbindMap);
		if(sqlResultCheck.size()!=materialPackingNameLength){
			String notexistedBox="";
			for(int i=0;i<materialPackingNameLength;i++){
				String checkSql="SELECT MATERIALPACKINGNAME from MATERIALPACKINGSMT WHERE SITENAME=:SITENAME AND MATERIALPACKINGNAME =:MATERIALPACKINGNAME "
						+" AND STOCKSTATE='Stocked'  "
						+ " AND OQARESULT='OK'  "
						+ " AND BOESITENAME=:BOESITENAME ";
				Map<String, String> checkbindMapa = new HashMap<String, String>();
				checkbindMapa.put("SITENAME", siteName);
				checkbindMapa.put("MATERIALPACKINGNAME", materialPackingNameList[i]);
				checkbindMapa.put("BOESITENAME", BOEFactory);
				List<Map<String, Object>> sqlResultChecka = IDMFrameServiceProxy
						.getSqlTemplate()
						.queryForList(checkSql, checkbindMapa);
				if(sqlResultChecka.size()==0){
					notexistedBox=notexistedBox+"/"+materialPackingNameList[i];
				}

			}
			log.info("不符合条件Box："+notexistedBox);
			checkresultStocked=notexistedBox+"不是在库BOX或在库不是OK状态！|ERROR";
		}
	//}
	
	
	return checkresultStocked;
	
}
/*
 * 2018.10.24
 * jing
 * 当个box出库改为多个Box出库
 * */
public void BoxStockOutByLabelSMTWithTLD(EventInfo eventInfo, Document message) throws Exception {
	try{
	Element bodyElem = message.getRootElement().getChild("Body");
	Element headerElem = message.getRootElement().getChild("Header");
	String materialpackingName=bodyElem.getChildText("MATERIALPACKINGNAME");
	String[] materialPackingNameList=materialpackingName.split("\\|"); 
	String areaName=bodyElem.getChildText("AREANAME");
	String siteName=bodyElem.getChildText("SITENAME");
	String shipRequestName=bodyElem.getChildText("RECEIVEREQUESTNAME");  //20181106wsq修改括号内为receiverequestname

	String materialTypea=bodyElem.getChildText("MATERIALTYPE");
	String transactionID=headerElem.getChildText("TRANSACTIONID");
	String eventTime=headerElem.getChildText("EVENTTIME");
	String eventName=headerElem.getChildText("EVENTCOMMENT");
	String eventUser=headerElem.getChildText("EVENTUSER");
	String messageName=headerElem.getChildText("MESSAGENAME");
	String materialType="";
	if(materialTypea==null){
		materialType=areaName;
	}
	else{
		materialType=materialTypea;
	}
	
	String BOEFactory=System.getProperty("factory");
	if(BOEFactory.equals("B5")){
		//B5/tm1的SMT在sitename按照SMTsitename+-+B5/TM1
		String [] sitelist=siteName.split("\\-");
		siteName = sitelist[0];
		BOEFactory = sitelist[1];
	}
	
	//Document转成String
	Format format = Format.getPrettyFormat();  
    format.setEncoding("UTF-8");// 设置xml文件的字符为UTF-8，解决中文问题  
    XMLOutputter xmlout = new XMLOutputter(format);  
    ByteArrayOutputStream bo = new ByteArrayOutputStream();  
    xmlout.output(message, bo);  
    String messageLog=bo.toString();
	//Document转成String
	//int a=materialPackingNameList.length;	
	insertSMTMessageLogUtil(transactionID,
			eventTime,eventName, eventUser,
			siteName, messageLog, messageName,
			materialType);								//插入SMT消息
	
	
	//批量update数据，避免BOX较多时，for循环耗时较长
		log.info("BOX数量："+materialPackingNameList.length+"---------"+materialpackingName);
	//for(int i=0;i<a;i++){
		double a= materialPackingNameList.length;
		int length4Split=30;
		double b=Math.ceil(a/length4Split);
		int circleTime =(int)b;
		log.info("materialPackingNameList.length>>>>>>: " + a+" Circle Times>>>:"+circleTime);
		//将materialpackingName按照30个一循环，循环批量处理，避免SQL过长
		for(int i=0;i<circleTime;i++){
			String BoxList="";
			if(i==circleTime-1){
				for(int j=0;j<(a-length4Split*(b-1));j++){
					String BoxLista=materialPackingNameList[i*length4Split+j]+"|";
					BoxList=BoxList+BoxLista;
				}
			}
			else{
				for(int j=0;j<length4Split;j++){
					String BoxLista=materialPackingNameList[i*length4Split+j]+"|";
					BoxList=BoxList+BoxLista;
				}
			}
			BoxList=BoxList.substring(0, BoxList.length()-1);
			log.info("Circle Count>>>: "+i+" BoxList>>>>>>: " + BoxList);
			String sqlCreat="UPDATE MATERIALPACKINGSMT  "
					+" SET STOCKSTATE='StockOut' "
					+" ,AREANAME=:AREANAME "
					+" ,RECEIVEREQUESTNAME=:RECEIVEREQUESTNAME "
					+" ,LASTEVENTNAME=:LASTEVENTNAME"
					+" ,LASTEVENTTIMEKEY=:LASTEVENTTIMEKEY"
					+" ,LASTEVENTTIME=sysdate"
					+" ,SMTEVENTTIME=:SMTEVENTTIME"
					+" ,LASTEVENTUSER=:LASTEVENTUSER"
					+" ,LASTEVENTCOMMENT=:LASTEVENTCOMMENT "
					+ " ,TRANSACTIONID=:TRANSACTIONID "
					+" WHERE MATERIALPACKINGNAME  IN(select regexp_substr(id, '[^|]+' ,1 ,rownum) id from (select  :MATERIALPACKINGNAME id from dual) a "
				+ " connect by rownum- 1 <= length(regexp_replace(id, '[^|]+'))) "
					+" AND SITENAME=:SITENAME "
					+ " AND BOESITENAME=:BOESITENAME ";
			
			Map<String, String> bindMap = new HashMap<String, String>();
			        bindMap.put("AREANAME",areaName);
			        bindMap.put("RECEIVEREQUESTNAME",shipRequestName);
					bindMap.put("MATERIALPACKINGNAME",BoxList);
					bindMap.put("LASTEVENTNAME",eventInfo.getEventName());
					bindMap.put("LASTEVENTTIMEKEY",TimeStampUtil.getCurrentEventTimeKey());
					bindMap.put("SMTEVENTTIME", eventTime);                                     //SMT操作时间
					bindMap.put("LASTEVENTUSER",eventInfo.getEventUser());
					bindMap.put("LASTEVENTCOMMENT",eventInfo.getEventComment());				
					bindMap.put("SITENAME",siteName);	
					bindMap.put("TRANSACTIONID", transactionID);
					bindMap.put("BOESITENAME", BOEFactory);
					
					//IDMFrameServiceProxy.getTransactionManager().beginTransaction();
					IDMFrameServiceProxy.getSqlTemplate().update(sqlCreat, bindMap);
					//IDMFrameServiceProxy.getTransactionManager().commitTransaction();
					CreateBoxHistorySMTbatch(BoxList,BOEFactory,siteName);
					log.info(BoxList+"已完成出库！");
		//}

		}
	String Undoid="JumpERP";
	String Undoiddetailname="";
	UpdateMaterialPackingSMTERPInfo(transactionID, siteName, Undoid, Undoiddetailname);
	UpdateMaterialpackingSMTHistory(transactionID, siteName, Undoid, Undoiddetailname);
	}
	catch(Exception e)
	{
		e.getMessage();
		throw e;
	}
	
}
/*
 * 2018.10.24
 * jing
 * 增加多个Box出库功能
 * */
public void SMTStockOutWithPO(EventInfo eventInfo, Document message) throws Exception {
	try{
	Element bodyElem = message.getRootElement().getChild("Body");
	String materialpackingName=bodyElem.getChildText("MATERIALPACKINGNAME");
	String[] materialPackingNameList=materialpackingName.split("\\|"); 
	String areaName=bodyElem.getChildText("AREANAME");
	String siteName=bodyElem.getChildText("SITENAME");
	String shipRequestDetailName=bodyElem.getChildText("SHIPREQUESTDETAILNAME");
	String materialType=areaName;
	
	Element headElem = message.getRootElement().getChild("Header");
	String transactionID=headElem.getChildText("TRANSACTIONID");
	String eventTime=headElem.getChildText("EVENTTIME");
	String eventName=headElem.getChildText("EVENTNAME");
	String eventUser=headElem.getChildText("EVENTUSER");
	String messageName=headElem.getChildText("MESSAGENAME");
	
	String BOEFactory=System.getProperty("factory");
	if(BOEFactory.equals("B5")){
		//B5/tm1的SMT在sitename按照SMTsitename+-+B5/TM1
		String [] sitelist=siteName.split("\\-");
		siteName = sitelist[0];
		BOEFactory = sitelist[1];
	}

	//Document转成String
	Format format = Format.getPrettyFormat();  
    format.setEncoding("UTF-8");// 设置xml文件的字符为UTF-8，解决中文问题  
    XMLOutputter xmlout = new XMLOutputter(format);  
    ByteArrayOutputStream bo = new ByteArrayOutputStream();  
    xmlout.output(message, bo);  
    String messageLog=bo.toString();
	//Document转成String
	
	insertSMTMessageLogUtil(transactionID,
			eventTime,eventName, eventUser,
			siteName, messageLog, messageName,
			materialType);
	//int a=materialPackingNameList.length;
	//批量处理update数据，避免BOX较多时候for循环耗时较多
	log.info("BOX数量："+materialPackingNameList.length+"------"+materialpackingName);
	double a= materialPackingNameList.length;
	int length4Split=30;
	double b=Math.ceil(a/length4Split);
	int circleTime =(int)b;
	log.info("materialPackingNameList.length>>>>>>: " + a+" Circle Times>>>:"+circleTime);
	//将materialpackingName按照30个一循环，循环批量处理，避免SQL过长
	for(int i=0;i<circleTime;i++){
		String BoxList="";
		if(i==circleTime-1){
			for(int j=0;j<(a-length4Split*(b-1));j++){
				String BoxLista=materialPackingNameList[i*length4Split+j]+"|";
				BoxList=BoxList+BoxLista;
			}
		}
		else{
			for(int j=0;j<length4Split;j++){
				String BoxLista=materialPackingNameList[i*length4Split+j]+"|";
				BoxList=BoxList+BoxLista;
			}
		}
		BoxList=BoxList.substring(0, BoxList.length()-1);
		log.info("Circle Count>>>: "+i+" BoxList>>>>>>: " + BoxList);
	//for(int i=0;i<a;i++){
		String sqlCreat="UPDATE MATERIALPACKINGSMT  "
				+" SET STOCKSTATE='StockOut' "
				+" ,AREANAME=:AREANAME "
				//+" ,SHIPREQUESTNAME=:SHIPREQUESTNAME "
				+" ,SHIPREQUESTDETAILNAME=:SHIPREQUESTDETAILNAME "
				+" ,LASTEVENTNAME=:LASTEVENTNAME"
				+" ,LASTEVENTTIMEKEY=:LASTEVENTTIMEKEY"
				+" ,LASTEVENTTIME=sysdate"
				+" ,SMTEVENTTIME=:SMTEVENTTIME"
				+" ,LASTEVENTUSER=:LASTEVENTUSER"
				+" ,LASTEVENTCOMMENT=:LASTEVENTCOMMENT "
				+ " ,TRANSACTIONID=:TRANSACTIONID  "
				+" WHERE MATERIALPACKINGNAME  IN(select regexp_substr(id, '[^|]+' ,1 ,rownum) id from (select  :MATERIALPACKINGNAME id from dual) a "
				+ " connect by rownum- 1 <= length(regexp_replace(id, '[^|]+'))) "
				+" AND SITENAME=:SITENAME "
				+ " AND BOESITENAME=:BOESITENAME ";
				
		Map<String, String> bindMap = new HashMap<String, String>();
		        bindMap.put("AREANAME",areaName);
		        //bindMap.put("SHIPREQUESTNAME",bodyElem.getChildText("SHIPREQUESTNAME"));
		        bindMap.put("SHIPREQUESTDETAILNAME",shipRequestDetailName);
				bindMap.put("MATERIALPACKINGNAME",BoxList);
				bindMap.put("LASTEVENTNAME",eventInfo.getEventName());
				bindMap.put("LASTEVENTTIMEKEY",TimeStampUtil.getCurrentEventTimeKey());
				bindMap.put("SMTEVENTTIME",eventTime);                                      //smt实际操作时间
				bindMap.put("LASTEVENTUSER",eventInfo.getEventUser());
				bindMap.put("LASTEVENTCOMMENT",eventInfo.getEventComment());
				bindMap.put("TRANSACTIONID", transactionID);
				bindMap.put("SITENAME",siteName);
				bindMap.put("BOESITENAME", BOEFactory);

				IDMFrameServiceProxy.getSqlTemplate().update(sqlCreat, bindMap);
				CreateBoxHistorySMTbatch(BoxList,BOEFactory,siteName);

				log.info(BoxList+"已出库完成！" );
		
	}
		
	//}
	String Undoid="JumpERP";
	String Undoiddetailname="";
	UpdateMaterialPackingSMTERPInfo(transactionID, siteName, Undoid, Undoiddetailname);
	UpdateMaterialpackingSMTHistory(transactionID, siteName, Undoid, Undoiddetailname);
	}
	catch(Exception e)
	{
		e.getMessage();
		throw e;
	}
	
}

	public void CreateBoxHistorySMTSQE(String boxName) throws Exception {

		String sql=" INSERT INTO MATERIALPACKINGSMTSQEHISTORY   "
				+" ( SITENAME                              "
				+" ,MATERIALPACKINGNAME                    "
				+" ,TIMEKEY                                "
				+" ,REASONCODETYPE                         "
				+" ,REASONCODE                             "
				+" ,MATERIALPACKINGTYPE                    "
				+" ,CONTENTMATERIALTYPE                    "
				+" ,MATERIALTYPE                           "
				+" ,MATERIALSPECNAME                       "
				+" ,SUPERMATERIALPACKINGNAME               "
				+" ,MAKEDATE                               "
				+" ,PACKINGGRADE                           "
				+" ,SUBPACKINGQUANTITY                     "
				+" ,MATERIALCREATEQUANTITY                 "
				+" ,MATERIALQUANTITY                       "
				+" ,OLDPACKINGSTATE                        "
				+" ,PACKINGSTATE                           "
				+" ,STOCKSTATE                             "
				+" ,OLDSTOCKSTATE                          "
				+" ,HOLDSTATE                              "
				+" ,AREANAME                               "
				+" ,LOCATIONNAME                           "
				+" ,DURABLENAME                            "
				+" ,MATERIALPROCESSGROUPNAME               "
				+" ,CREATETIME                             "
				+" ,CREATEUSER                             "
				+" ,RECEIVEREQUESTNAME                     "
				+" ,RECEIVEREQUESTDETAILNAME               "
				+" ,RECEIVEACTNO                           "
				+" ,RECEIVETIME                            "
				+" ,RECEIVEUSER                            "
				+" ,SHIPREQUESTNAME                        "
				+" ,SHIPREQUESTDETAILNAME                  "
				+" ,SHIPTIME                               "
				+" ,SHIPUSER                               "
				+" ,ERPLOCATION                            "
				+" ,ETCSTATE                               "
				+" ,ERPFACTORY                             "
				+" ,STOCKINTYPE                            "
				+" ,OQARESULTSTATE                         "
				+" ,OQARESULT                              "
				+" ,UNDOID                                 "
				+" ,SUPPLIERNAME                           "
				+" ,CHARGE                                 "
				+" ,UNDODETAILNAME                         "
				+" ,ERPEVENTTIME                           "
				+" ,EVENTNAME                              "
				+" ,EVENTTIME                              "
				+" ,EVENTUSER                              "
				+" ,EVENTCOMMENT                           "
				+" ,NPFLAG                                 "
				+" ,MESSAGEID                              "
				+" ,ERPSTATE                               "
				+" ,SAVEREASON                             "
				+" ,ENDDATE                   )            "
				+" SELECT SITENAME                         "
				+" ,MATERIALPACKINGNAME                    "
				+" ,LASTEVENTTIMEKEY                       "
				+" ,REASONCODETYPE                         "
				+" ,REASONCODE                             "
				+" ,MATERIALPACKINGTYPE                    "
				+" ,CONTENTMATERIALTYPE                    "
				+" ,MATERIALTYPE                           "
				+" ,MATERIALSPECNAME                       "
				+" ,SUPERMATERIALPACKINGNAME               "
				+" ,MAKEDATE                               "
				+" ,PACKINGGRADE                           "
				+" ,SUBPACKINGQUANTITY                     "
				+" ,MATERIALCREATEQUANTITY                 "
				+" ,MATERIALQUANTITY                       "
				+" ,OLDPACKINGSTATE                        "
				+" ,PACKINGSTATE                           "
				+" ,STOCKSTATE                             "
				+" ,OLDSTOCKSTATE                          "
				+" ,HOLDSTATE                              "
				+" ,AREANAME                               "
				+" ,LOCATIONNAME                           "
				+" ,DURABLENAME                            "
				+" ,MATERIALPROCESSGROUPNAME               "
				+" ,CREATETIME                             "
				+" ,CREATEUSER                             "
				+" ,RECEIVEREQUESTNAME                     "
				+" ,RECEIVEREQUESTDETAILNAME               "
				+" ,RECEIVEACTNO                           "
				+" ,RECEIVETIME                            "
				+" ,RECEIVEUSER                            "
				+" ,SHIPREQUESTNAME                        "
				+" ,SHIPREQUESTDETAILNAME                  "
				+" ,SHIPTIME                               "
				+" ,SHIPUSER                               "
				+" ,ERPLOCATION                            "
				+" ,ETCSTATE                               "
				+" ,ERPFACTORY                             "
				+" ,STOCKINTYPE                            "
				+" ,OQARESULTSTATE                         "
				+" ,OQARESULT                              "
				+" ,UNDOID                                 "
				+" ,SUPPLIERNAME                           "
				+" ,CHARGE                                 "
				+" ,UNDODETAILNAME                         "
				+" ,ERPEVENTTIME                           "
				+" ,LASTEVENTNAME                          "
				+" ,LASTEVENTTIME                          "
				+" ,LASTEVENTUSER                          "
				+" ,LASTEVENTCOMMENT                       "
				+" ,NPFLAG                                 "
				+" ,MESSAGEID                              "
				+" ,ERPSTATE                               "
				+" ,SAVEREASON                             "
				+" ,ENDDATE                                "
				+" FROM MATERIALPACKINGSMTSQE                 "
				+" WHERE MATERIALPACKINGNAME=:MATERIALPACKINGNAME  "
				+"  AND LASTEVENTTIMEKEY=(SELECT MAX(LASTEVENTTIMEKEY) FROM MATERIALPACKINGSMTSQE  "
				+"  WHERE MATERIALPACKINGNAME=  :MATERIALPACKINGNAME)  ";     
	
		Map<String, String> bindMap = new HashMap<String, String>();
		bindMap.put("MATERIALPACKINGNAME", boxName);
		IDMFrameServiceProxy.getSqlTemplate().update(sql, bindMap);
	}
	
	//PMS接口表SQL
	public String sqlToPMS=" INSERT INTO PMSMATERIALINTERFACE "
            +" ( SITENAME, "
            +" MATERIALPACKINGNAME, "
            +" MATERIALSPECNAME, "
            +" MATERIALQTY, "
            +" UNIT, "
            +" RECEIVEACTNO, "
            +" STOCKOUTTIME, "
            +" SHIPREQUESTNAME, "
            +" SUPPLIERNO, "
            +" SUPPLIERNAME, "
            +" MAKEDATE, "
            +" EXPIRATIONDAY, "
            +" USERID, "
            +" COSTUSERID, "
            +" COSTCENTER ) "
            +"  SELECT  A.SITENAME"
            +", A.MATERIALPACKINGNAME, "
            +" A.MATERIALSPECNAME, "
            +" A.MATERIALQUANTITY AS MATERIALQTY, "
            +" C.MATERIALUNIT AS UNIT, "
            +" A.RECEIVEACTNO, "
            +" A.LASTEVENTTIME AS STOCKOUTTIME, "
            +" A.SHIPREQUESTNAME, "
            +" D.SUPPLIERNO, "
            +" D.SUPPLIERNAME, "
            +" A.MAKEDATE, "
            +" C.EXPIRATIONDAY, "
            +" A.LASTEVENTUSER AS USERID, "
            +" E.RECEIVER AS COSTUSERID, "
            +" E.COSTCENTER "
            +" FROM  "
            +" MATERIALPACKING A,MATERIALSPEC C,SUPPLIER D,MATERIALSHIPREQUEST E "
            +" WHERE  "
            +" A.SITENAME=:SITENAME "
            +" AND A.MATERIALSPECNAME=C.MATERIALSPECNAME "
            +" AND A.MATERIALPACKINGNAME=:MATERIALPACKINGNAME "
            +" AND A.SITENAME=C.SITENAME "
            +" AND A.SITENAME=E.SITENAME "
            +" AND A.SHIPREQUESTNAME=E.SHIPREQUESTNAME "
            +" AND A.SUPPLIERNAME=D.SUPPLIERNO "
            +" AND A.LASTEVENTNAME IN('CompleteShipRequest','PreShipRequestDetailStockOut') "
            +" AND A.SHIPREQUESTNAME=E.SHIPREQUESTNAME "
            +" GROUP BY A.SITENAME, "
            +" A.MATERIALPACKINGNAME, "
            +" A.MATERIALSPECNAME, "
            +" A.MATERIALQUANTITY, "
            +" C.MATERIALUNIT, "
            +" A.RECEIVEACTNO, "
            +" A.LASTEVENTTIME, "
            +" A.SHIPREQUESTNAME, "
            +" D.SUPPLIERNO, "
            +" D.SUPPLIERNAME, "
            +" A.MAKEDATE, "
            +" C.EXPIRATIONDAY, "
            +" A.LASTEVENTUSER, "
            +" E.COSTCENTER, "
            +" E.RECEIVER " ;
public String MaterialspexInfoSQL=" SELECT MATERIALTYPE FROM MATERIALPACKING WHERE SITENAME=:SITENAME AND MATERIALPACKINGNAME=:MATERIALPACKINGNAME ";

	public void InsertStockOutDataToPMS(String siteName,
			List<String> materialPackingKeyList) {
		for (int i = 0; i < materialPackingKeyList.size(); i++) {
			Map<String, String> bindMap = new HashMap<String, String>();
			bindMap.put("SITENAME", siteName);
			bindMap.put("MATERIALPACKINGNAME",
					(String) materialPackingKeyList.get(i));
			// 获取物料类别
			List<Map<String, Object>> sqlResult2 = IDMFrameServiceProxy
					.getSqlTemplate()
					.queryForList(MaterialspexInfoSQL, bindMap);
			// 将配件的数据写入接口表
			if ((sqlResult2.size()!=0)&&(sqlResult2.get(0).get("MATERIALTYPE").toString().equals("ERSA"))) {
				IDMFrameServiceProxy.getSqlTemplate()
						.update(sqlToPMS, bindMap);
			}
		}
	}
	//判断是否是备件，只有备件才发给pms系统
	public String SendToPMSFlag(String siteName,
			String shiprequestName,String receiveActno) {
		String flagSql=" SELECT DISTINCT MATERIALTYPE FROM MATERIALPACKING WHERE SITENAME=:SITENAME AND SHIPREQUESTNAME=:SHIPREQUESTNAME AND RECEIVEACTNO=:RECEIVEACTNO ";
			Map<String, String> bindMap = new HashMap<String, String>();
			bindMap.put("SITENAME", siteName);
			bindMap.put("SHIPREQUESTNAME",shiprequestName);
			bindMap.put("RECEIVEACTNO",receiveActno);
			// 获取物料类别
			List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
					.getSqlTemplate()
					.queryForList(flagSql, bindMap);

			if (sqlResult.get(0).get("MATERIALTYPE")!=null&&sqlResult.get(0).get("MATERIALTYPE").toString().equals("ERSA")) {
				return "Y";
			}
			return "N";
	}
	public void SendStockOutDataToPMS(String siteName,
			String shiprequestName,String receiveActno) {
		  
		String refundInCheck="select ";
		
		
		//PMS接口表SQL
		 String insertPMSSql=" INSERT INTO PMSMATERIALINTERFACE "
	            +" ( SITENAME,MATERIALPACKINGNAME,MATERIALSPECNAME,MATERIALQTY,UNIT,RECEIVEACTNO,STOCKOUTTIME,SHIPREQUESTNAME, "
	            +" SUPPLIERNO,MAKEDATE,EXPIRATIONDAY,USERID,COSTUSERID,COSTCENTER,SUPPLIERNAME ) "
	            +"  SELECT  A.SITENAME, A.MATERIALPACKINGNAME,A.MATERIALSPECNAME,A.MATERIALQUANTITY AS MATERIALQTY, "
	            +" C.MATERIALUNIT AS UNIT,A.RECEIVEACTNO,A.LASTEVENTTIME AS STOCKOUTTIME, A.SHIPREQUESTNAME, "
	            +" A.SUPPLIERNAME AS SUPPLIERNO, A.MAKEDATE, C.EXPIRATIONDAY, A.LASTEVENTUSER AS USERID,E.RECEIVER AS COSTUSERID, E.COSTCENTER, D.SUPPLIERNAME "
	            +" FROM  "
	            +" MATERIALSPEC C,MATERIALSHIPREQUEST E,MATERIALPACKING A LEFT JOIN  SUPPLIER D  ON A.SUPPLIERNAME=D.SUPPLIERNO "
	            +" WHERE  A.SITENAME=:SITENAME AND A.MATERIALSPECNAME=C.MATERIALSPECNAME AND A.SHIPREQUESTNAME=:SHIPREQUESTNAME "
	            +" AND A.RECEIVEACTNO=:RECEIVEACTNO AND A.SITENAME=C.SITENAME AND A.SITENAME=E.SITENAME  "
	            +"  AND A.SHIPREQUESTNAME=E.SHIPREQUESTNAME AND A.SHIPREQUESTNAME=E.SHIPREQUESTNAME "
	            +" GROUP BY A.SITENAME, A.MATERIALPACKINGNAME, A.MATERIALSPECNAME, A.MATERIALQUANTITY,C.MATERIALUNIT, "
	            +" A.RECEIVEACTNO,A.LASTEVENTTIME, A.SHIPREQUESTNAME, A.SUPPLIERNAME, A.MAKEDATE, "
	            +" C.EXPIRATIONDAY, A.LASTEVENTUSER,E.COSTCENTER, E.RECEIVER ,D.SUPPLIERNAME" ;
		// 将配件的数据写入接口表
			Map<String, String> bindMap = new HashMap<String, String>();
			bindMap.put("SITENAME", siteName);
			bindMap.put("SHIPREQUESTNAME",shiprequestName);
			bindMap.put("RECEIVEACTNO",receiveActno);
			// 将配件的数据写入接口表
				IDMFrameServiceProxy.getSqlTemplate()
						.update(insertPMSSql, bindMap);
		
	}
	// 备件出库，发消息到PMS系统，组装消息,发此消息时不做插入接口表操作
		public Document MessageForPMS(String siteName, String shiprequestName, String receiveActno) {

			String sendMessage = "SELECT  A.SITENAME, A.MATERIALPACKINGNAME, A.MATERIALSPECNAME,A.MATERIALQUANTITY AS MATERIALQTY,C.MATERIALUNIT AS UNIT, \r\n" + 
					"								 A.RECEIVEACTNO, A.LASTEVENTTIME AS STOCKOUTTIME,A.SHIPREQUESTNAME, D.SUPPLIERNO,D.SUPPLIERNAME, A.MAKEDATE, C.EXPIRATIONDAY, \r\n" + 
					"								 A.LASTEVENTUSER AS USERID,E.RECEIVER AS COSTUSERID,E.COSTCENTER,A.SHIPREQUESTDETAILNAME ,a.CHARGE ,a.RECEIVEREQUESTNAME ,a.BWTAR,A.ERPLOCATION,A.ERPFACTORY  \r\n" + 
					"								 FROM MATERIALPACKING A,MATERIALSPEC C,SUPPLIER D,MATERIALSHIPREQUEST E\r\n" + 
					"								 WHERE A.SITENAME=:SITENAME AND A.MATERIALSPECNAME=C.MATERIALSPECNAME AND A.SHIPREQUESTNAME=:SHIPREQUESTNAME AND A.RECEIVEACTNO=:RECEIVEACTNO\r\n" + 
					"								 AND A.SITENAME=C.SITENAME  AND A.SITENAME=E.SITENAME AND A.SHIPREQUESTNAME=E.SHIPREQUESTNAME AND A.SUPPLIERNAME=D.SUPPLIERNO \r\n" + 
					"								 AND A.SHIPREQUESTNAME=E.SHIPREQUESTNAME \r\n" + 
					"								 GROUP BY A.SITENAME,A.MATERIALPACKINGNAME, A.MATERIALSPECNAME,A.MATERIALQUANTITY, \r\n" + 
					"								 C.MATERIALUNIT,A.RECEIVEACTNO,A.LASTEVENTTIME,A.SHIPREQUESTNAME,D.SUPPLIERNO, \r\n" + 
					"								 D.SUPPLIERNAME,A.MAKEDATE, C.EXPIRATIONDAY,A.LASTEVENTUSER,E.COSTCENTER,E.RECEIVER,a.CHARGE ,a.RECEIVEREQUESTNAME ,a.BWTAR,a.SHIPREQUESTDETAILNAME,A.ERPLOCATION,A.ERPFACTORY  ";
			// 找出出库的box信息
			Map<String, String> bindMap = new HashMap<String, String>();
			bindMap.put("SITENAME", siteName);
			bindMap.put("SHIPREQUESTNAME", shiprequestName);
			bindMap.put("RECEIVEACTNO", receiveActno);
			List<Map<String, Object>> sqlResult = IDMFrameServiceProxy.getSqlTemplate().queryForList(sendMessage, bindMap);
			Document doc = SMessageUtil.createERPXmlDocument("Parts_PMS_Received", "WMSStockoutInfo");
			Element header = doc.getDocument().getRootElement().getChild("Header");
			Element sitename = new Element("SITENAME");
			sitename.setText(siteName);
			header.addContent(sitename);
			try {
				String nodePath = "//Message/Body";
				Element parentElement = JdomUtils.getNode(doc, nodePath);
				for (int i = 0; i < sqlResult.size(); i++) {
					Element childElemrnt = new Element("item");
					parentElement.addContent(childElemrnt);
					SMessageUtil.createElement(nodePath, childElemrnt, "SITENAME", siteName);
					SMessageUtil.createElement(nodePath, childElemrnt, "MATERIALPACKINGNAME",
							sqlResult.get(i).get("MATERIALPACKINGNAME").toString());
					SMessageUtil.createElement(nodePath, childElemrnt, "MATERIALSPECNAME",
							sqlResult.get(i).get("MATERIALSPECNAME").toString());
					SMessageUtil.createElement(nodePath, childElemrnt, "MATERIALQTY",
							sqlResult.get(i).get("MATERIALQTY").toString());
					SMessageUtil.createElement(nodePath, childElemrnt, "UNIT",
							sqlResult.get(i).get("UNIT") == null ? "" : sqlResult.get(i).get("UNIT").toString());
					SMessageUtil.createElement(nodePath, childElemrnt, "RECEIVEACTNO",
							sqlResult.get(i).get("RECEIVEACTNO") == null ? ""
									: sqlResult.get(i).get("RECEIVEACTNO").toString());
					SMessageUtil.createElement(nodePath, childElemrnt, "STOCKOUTTIME",
							sqlResult.get(i).get("STOCKOUTTIME").toString());
					SMessageUtil.createElement(nodePath, childElemrnt, "SHIPREQUESTNAME",
							sqlResult.get(i).get("SHIPREQUESTNAME").toString());
					SMessageUtil.createElement(nodePath, childElemrnt, "SUPPLIERNO",
							sqlResult.get(i).get("SUPPLIERNO").toString());
					SMessageUtil.createElement(nodePath, childElemrnt, "SUPPLIERNAME",
							sqlResult.get(i).get("SUPPLIERNAME").toString());
					SMessageUtil.createElement(nodePath, childElemrnt, "MAKEDATE",
							sqlResult.get(i).get("MAKEDATE").toString());
					SMessageUtil.createElement(nodePath, childElemrnt, "EXPIRATIONDAY",
							sqlResult.get(i).get("EXPIRATIONDAY") == null ? ""
									: sqlResult.get(i).get("EXPIRATIONDAY").toString());
					SMessageUtil.createElement(nodePath, childElemrnt, "USERID", sqlResult.get(i).get("USERID").toString());
					SMessageUtil.createElement(nodePath, childElemrnt, "COSTUSERID",
							sqlResult.get(i).get("COSTUSERID") == null ? ""
									: sqlResult.get(i).get("COSTUSERID").toString());
					SMessageUtil.createElement(nodePath, childElemrnt, "COSTCENTER",
							sqlResult.get(i).get("COSTCENTER") == null ? ""
									: sqlResult.get(i).get("COSTCENTER").toString());
					SMessageUtil.createElement(nodePath, childElemrnt, "REPAIRFLAG", "");// 用不到 但是非要发RepairFlag
					SMessageUtil.createElement(nodePath, childElemrnt, "REPAIRDATE", "");
					SMessageUtil.createElement(nodePath, childElemrnt, "UNDOFLAG", "");
					SMessageUtil.createElement(nodePath, childElemrnt, "RECEIVEDFLAG", "");
					SMessageUtil.createElement(nodePath, childElemrnt, "RECEIVEDTIME", "");
					SMessageUtil.createElement(nodePath, childElemrnt, "RECEIVEDUSER", "");
					SMessageUtil.createElement(nodePath, childElemrnt, "SHIPREQUESTDETAILNAME",
							sqlResult.get(i).get("SHIPREQUESTDETAILNAME") == null ? ""
									: sqlResult.get(i).get("SHIPREQUESTDETAILNAME").toString());
					SMessageUtil.createElement(nodePath, childElemrnt, "CHARGE",
							sqlResult.get(i).get("CHARGE") == null ? "" : sqlResult.get(i).get("CHARGE").toString());
					SMessageUtil.createElement(nodePath, childElemrnt, "RECEIVEREQUESTNAME",
							sqlResult.get(i).get("RECEIVEREQUESTNAME") == null ? ""
									: sqlResult.get(i).get("RECEIVEREQUESTNAME").toString());
					SMessageUtil.createElement(nodePath, childElemrnt, "BWTAR",
							sqlResult.get(i).get("BWTAR") == null ? "" : sqlResult.get(i).get("BWTAR").toString());
					SMessageUtil.createElement(nodePath, childElemrnt, "ERPFACTORY",
							sqlResult.get(i).get("ERPFACTORY") == null ? "" : sqlResult.get(i).get("ERPFACTORY").toString());
					SMessageUtil.createElement(nodePath, childElemrnt, "REMARK", "");// 用不到																	// 但是非要发ciao
				}
				String replyMSG = JdomUtils.toString(doc);
				log.info(replyMSG);

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			return doc;
		}

	//备件出库，发消息到PMS系统，组装消息
		public Document createMessageForPMS(String siteName,
				List<String> materialPackingKeyList){
			
			Document doc = SMessageUtil.createERPXmlDocument("Parts_PMS_Received", "WMSStockoutInfo");
			Element header=doc.getDocument().getRootElement().getChild("Header");
			Element sitename=new Element("SITENAME");
			sitename.setText(siteName);
			header.addContent(sitename);
			try {
				
				String nodePath = "//Message/Body";
				Element parentElement = JdomUtils.getNode(doc, nodePath);
				for (int i = 0; i < materialPackingKeyList.size(); i++) {						
					Element childElemrnt = new Element("item");
					parentElement.addContent(childElemrnt);
					SMessageUtil.createElement(nodePath, childElemrnt, "SITENAME",
							siteName);
					SMessageUtil.createElement(nodePath, childElemrnt, "MATERIALPACKINGNAME",
							materialPackingKeyList.get(i).toString());
				}
				String replyMSG = JdomUtils.toString(doc);
				log.info(replyMSG);
				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			return doc;
		}
	public void  CreateSMTBoxInfo(EventInfo eventInfo, Document message) throws Exception {
	
		Element headElement = message.getRootElement().getChild("Header");
		Element bodyElement = message.getRootElement().getChild("Body");
		String materialPackingName = bodyElement.getChildText("MATERIALPACKINGNAME");
		String materialSpecName = bodyElement.getChildText("MATERIALSPECNAME");
		String materialQuantity = bodyElement.getChildText("MATERIALQUANTITY");
		String supplierNo = bodyElement.getChildText("SUPPLIERNO");
		String makeDate = bodyElement.getChildText("MAKEDATE");
		String endDate = bodyElement.getChildText("ENDDATE");
		String siteName = bodyElement.getChildText("SITENAME");
		String materialType = bodyElement.getChildText("MATERIALTYPE");
		String LotNo = bodyElement.getChildText("LOTNO");
		String transactionID=headElement.getChildText("TRANSACTIONID");
		String receiveActNo=bodyElement.getChildText("RECEIVEACTNO");
		
		String BOEFactory=System.getProperty("factory");
		if(BOEFactory.equals("B5")){
			//B5/tm1的SMT在sitename按照SMTsitename+-+B5/TM1
			String [] sitelist=siteName.split("\\-");
			siteName = sitelist[0];
			BOEFactory = sitelist[1];
		}

		String[] materialPackingNameList = materialPackingName.split("\\|");
		String[] materialSpecNameList = materialSpecName.split("\\|");
		String[] materialQuantityList = materialQuantity.split("\\|");
		String[] supplierNoList = supplierNo.split("\\|");
		String[] makeDateList = makeDate.split("\\|");
		String[] endDateList = endDate.split("\\|");
		String[] LotNoList = LotNo.split("\\|");

		String exceptionContent="";
		try{
		int packingNamelength=materialPackingNameList.length;
		if(packingNamelength!=materialSpecNameList.length||packingNamelength!=materialQuantityList.length||packingNamelength!=supplierNoList.length
				||packingNamelength!=makeDateList.length||packingNamelength!=endDateList.length){
			log.info("消息中对应BOX数量和料号、数量、供应商代码、生产日期、到期日个数不一致！");
			exceptionContent="消息中对应BOX数量和料号、数量、供应商代码、生产日期、到期日个数不一致！";
			throw new Exception(exceptionContent);
		}
		
		//增加ERPlocation、ERP工厂插入
		String eRPLocation="";
		String ERPFactory = "";
		String sqlERPLocation="SELECT ERPRECEIVELOCATION,ERPFACTORYNAME FROM MATERIALSHIPREQUEST WHERE SITENAME=:SITENAME AND SHIPREQUESTNAME=:SHIPREQUESTNAME ";
		Map<String, String> bindMaperplocation = new HashMap<String, String>();
		bindMaperplocation.put("SITENAME", System.getProperty("factory"));
		bindMaperplocation.put("SHIPREQUESTNAME", receiveActNo);
		List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
				.getSqlTemplate()
				.queryForList(sqlERPLocation, bindMaperplocation);
		if(sqlResult.size()>0){
			eRPLocation=sqlResult.get(0).get("ERPRECEIVELOCATION").toString();
			ERPFactory=sqlResult.get(0).get("ERPFACTORYNAME").toString();
		}

		for (int i = 0; i < materialPackingNameList.length; i++) {

			exceptionContent=materialPackingNameList[i]+"|请检查该BOX！！";
			String sqlCreat = "INSERT INTO MATERIALPACKINGSMT  "
					+ "("
					+ "SITENAME                    "
					+ ",MATERIALPACKINGNAME        "
					+ ",MATERIALPACKINGTYPE        "
					+ ",CONTENTMATERIALTYPE        "
					+ ",MATERIALTYPE               "
					+ ",MATERIALSPECNAME           "
					+ ",SUPERMATERIALPACKINGNAME   "
					+ ",PACKINGGRADE               "
					+ ",SUBPACKINGQUANTITY         "
					+ ",MATERIALCREATEQUANTITY     "
					+ ",MATERIALQUANTITY           "
					+ ",PACKINGSTATE               "
					+ ",OLDPACKINGSTATE            "
					+ ",STOCKSTATE                 "
					+ ",OLDSTOCKSTATE              "
					+ ",HOLDSTATE                  "
					+ ",AREANAME                   "
					+ ",LOCATIONNAME               "
					+ ",DURABLENAME                "
					+ ",MATERIALPROCESSGROUPNAME   "
					+ ",LASTEVENTNAME              "
					+ ",LASTEVENTTIMEKEY           "
					+ ",LASTEVENTTIME              "
					+ ",LASTEVENTUSER              "
					+ ",LASTEVENTCOMMENT           "
					+ ",CREATETIME                 "
					+ ",CREATEUSER                 "
					+ ",RECEIVEREQUESTNAME         "
					+ ",RECEIVEREQUESTDETAILNAME   "
					+ ",MAKEDATE                   "
					+ ",RECEIVEACTNO               "
					+ ",RECEIVETIME                "
					+ ",RECEIVEUSER                "
					+ ",SHIPREQUESTNAME            "
					+ ",SHIPREQUESTDETAILNAME      "
					+ ",SHIPTIME                   "
					+ ",SHIPUSER                   "
					+ ",REASONCODETYPE             "
					+ ",REASONCODE                 "
					+ ",ERPLOCATION                "
					+ ",ETCSTATE                   "
					+ ",ERPFACTORY                 "
					+ ",STOCKINTYPE                "
					+ ",OQARESULTSTATE             "
					+ ",OQARESULT                  "
					+ ",CHARGE                     "
					+ ",SUPPLIERNAME               "
					+ ",UNDOID                     "
					+ ",UNDODETAILNAME             "
					+ ",ERPEVENTTIME               "
					+ ",NPFLAG                     "
					+ ",MESSAGEID                  "
					+ ",ERPSTATE                   "
					+ ",SAVEREASON                 "
					+ ",ENDDATE                    "
					+ ",LOTNO                      "
					+ ",TRANSACTIONID          "
					+ ",BOESITENAME                "
					//+ ",RECEIVEREQUESTNAME     "
					+ ")"
					+ " VALUES ("
					+ " :SITENAME                   "
					+ ",:MATERIALPACKINGNAME        "
					+ ",:MATERIALPACKINGTYPE        "
					+ ",:CONTENTMATERIALTYPE        "
					+ ",:MATERIALTYPE               "
					+ ",:MATERIALSPECNAME           "
					+ ",:SUPERMATERIALPACKINGNAME   "
					+ ",:PACKINGGRADE               "
					+ ",:SUBPACKINGQUANTITY         "
					+ ",:MATERIALCREATEQUANTITY     "
					+ ",:MATERIALQUANTITY           "
					+ ",:PACKINGSTATE               "
					+ ",:OLDPACKINGSTATE            "
					+ ",:STOCKSTATE                 "
					+ ",:OLDSTOCKSTATE              "
					+ ",:HOLDSTATE                  "
					+ ",:AREANAME                   "
					+ ",:LOCATIONNAME               "
					+ ",:DURABLENAME                "
					+ ",:MATERIALPROCESSGROUPNAME   "
					+ ",:LASTEVENTNAME              "
					+ ",:LASTEVENTTIMEKEY           "
					+ " ,SYSDATE "
					+ ",:LASTEVENTUSER              "
					+ ",:LASTEVENTCOMMENT           "
					+ " ,SYSDATE " + ",:CREATEUSER   "
					+ ",:RECEIVEREQUESTNAME         "
					+ ",:RECEIVEREQUESTDETAILNAME   "
					+ ",TO_DATE(:MAKEDATE ,'YYYY-MM-DD')  "
					+ ",:RECEIVEACTNO               "
					+ ",:RECEIVETIME                "
					+ ",:RECEIVEUSER                "
					+ ",:SHIPREQUESTNAME            "
					+ ",:SHIPREQUESTDETAILNAME      "
					+ ",:SHIPTIME                   "
					+ ",:SHIPUSER                   "
					+ ",:REASONCODETYPE             "
					+ ",:REASONCODE                 "
					+ ",:ERPLOCATION                "
					+ ",:ETCSTATE                   "
					+ ",:ERPFACTORY                 "
					+ ",:STOCKINTYPE                "
					+ ",:OQARESULTSTATE             "
					+ ",:OQARESULT                  "
					+ ",:CHARGE                     "
					+ ",:SUPPLIERNAME               "
					+ ",:UNDOID                     "
					+ ",:UNDODETAILNAME             "
					+ ",:ERPEVENTTIME               "
					+ ",:NPFLAG                     "
					+ ",:MESSAGEID                  "
					+ ",:ERPSTATE                   "
					+ ",:SAVEREASON                 "
					+ ",TO_DATE(:ENDDATE ,'YYYY-MM-DD')  "
					+ ",:LOTNO  "
					+ ",:TRANSACTIONID          "
					+ ",:BOESITENAME            "
					//+ ",:RECEIVEREQUESTNAME     " 
					+ ")";
	
	
	Map<String, String> bindMap = new HashMap<String, String>();
	        bindMap.put("SITENAME",siteName);
			bindMap.put("MATERIALPACKINGNAME",materialPackingNameList[i]);
			bindMap.put("MATERIALPACKINGTYPE","");
			bindMap.put("CONTENTMATERIALTYPE","");
			bindMap.put("MATERIALTYPE",materialType);
			bindMap.put("MATERIALSPECNAME",materialSpecNameList[i]);
			bindMap.put("SUPERMATERIALPACKINGNAME","");
			bindMap.put("PACKINGGRADE","");
			bindMap.put("SUBPACKINGQUANTITY","");
			bindMap.put("MATERIALCREATEQUANTITY",materialQuantityList[i]);
			bindMap.put("MATERIALQUANTITY",materialQuantityList[i]);
			bindMap.put("PACKINGSTATE","Released");
			bindMap.put("OLDPACKINGSTATE","");
			bindMap.put("STOCKSTATE","Stocked");
			bindMap.put("OLDSTOCKSTATE","");
			bindMap.put("HOLDSTATE","");
			bindMap.put("AREANAME","");
			bindMap.put("LOCATIONNAME","");
			bindMap.put("DURABLENAME","");
			bindMap.put("MATERIALPROCESSGROUPNAME","");
			bindMap.put("LASTEVENTNAME",eventInfo.getEventName());
			bindMap.put("LASTEVENTTIMEKEY",TimeStampUtil.getCurrentEventTimeKey());
			bindMap.put("LASTEVENTUSER",eventInfo.getEventUser());
			bindMap.put("LASTEVENTCOMMENT",eventInfo.getEventComment());
			bindMap.put("CREATEUSER",eventInfo.getEventUser());
			bindMap.put("RECEIVEREQUESTNAME","");
			bindMap.put("RECEIVEREQUESTDETAILNAME","");
			bindMap.put("MAKEDATE",makeDateList[i]);
			bindMap.put("RECEIVEACTNO",receiveActNo);
			bindMap.put("RECEIVETIME","");
			bindMap.put("RECEIVEUSER","");
			bindMap.put("SHIPREQUESTNAME","");
			bindMap.put("SHIPREQUESTDETAILNAME","");
			bindMap.put("SHIPTIME","");
			bindMap.put("SHIPUSER","");
			bindMap.put("REASONCODETYPE","");
			bindMap.put("REASONCODE","");
			bindMap.put("ERPLOCATION",eRPLocation);
			bindMap.put("ETCSTATE","");
			bindMap.put("ERPFACTORY",ERPFactory);//插入ERP工厂
			bindMap.put("STOCKINTYPE","");
			bindMap.put("OQARESULTSTATE","");
			bindMap.put("OQARESULT","OK");
			bindMap.put("CHARGE","");
			bindMap.put("SUPPLIERNAME",supplierNoList[i].length()==7?"000"+supplierNoList[i]:supplierNoList[i]);
			bindMap.put("UNDOID","");
			bindMap.put("UNDODETAILNAME","");
			bindMap.put("ERPEVENTTIME","");
			bindMap.put("NPFLAG","");
			bindMap.put("MESSAGEID","");
			bindMap.put("ERPSTATE","");
			bindMap.put("SAVEREASON","");
			bindMap.put("ENDDATE",endDateList[i]);
			bindMap.put("TRANSACTIONID", transactionID);
			bindMap.put("BOESITENAME", BOEFactory);          //增加厂内的SITENAME
			//bindMap.put("RECEIVEREQUESTNAME", receiveRequestName);
			if(LotNo.length()==0){
				bindMap.put("LOTNO", "");
			}
			else{
				bindMap.put("LOTNO", LotNoList[i]);
			}
	
		IDMFrameServiceProxy.getSqlTemplate().update(sqlCreat, bindMap);
		CreateBoxHistorySMT(materialPackingNameList[i],siteName,BOEFactory);
		log.info(materialPackingNameList[i] +" is created !");
				
     }
		
		String Undoid="JumpERP";
		String Undoiddetailname="";
		UpdateMaterialPackingSMTERPInfo(transactionID, siteName, Undoid, Undoiddetailname);
		UpdateMaterialpackingSMTHistory(transactionID, siteName, Undoid, Undoiddetailname);
		}
		catch(Exception e)
		{
			e.getMessage();
			throw new Exception(exceptionContent);
			//throw e;
		}
		
	}
public String getSMTSourceInfo(String sourceMaterialPackingName,String siteName, Document message) throws Exception{

	Element headElem = message.getRootElement().getChild("Header");
	String transactionID=headElem.getChildText("TRANSACTIONID");
	String eventTime=headElem.getChildText("EVENTTIME");
	String eventUser=headElem.getChildText("EVENTUSER");
	String messageName=headElem.getChildText("MESSAGENAME");
	//String siteName=headElem.getChildText("SITENAME");
	Element bodyElem = message.getRootElement().getChild("Body");
	String materialType=bodyElem.getChildText("MATERIALTYPE");
	//String sourceMaterialPackingName=bodyElem.getChildText("MATERIALPACKINGNAME");
	
	String BOEFactory=System.getProperty("factory");
	if(BOEFactory.equals("B5")){
		//B5/tm1的SMT在sitename按照SMTsitename+-+B5/TM1
		String [] sitelist=siteName.split("\\-");
		siteName = sitelist[0];
		BOEFactory = sitelist[1];
	}
	
	String eventName=messageName;
	//Document转成String
	Format format = Format.getPrettyFormat();  
    format.setEncoding("UTF-8");// 设置xml文件的字符为UTF-8，解决中文问题  
    XMLOutputter xmlout = new XMLOutputter(format);  
    ByteArrayOutputStream bo = new ByteArrayOutputStream();  
	xmlout.output(message, bo);
    String messageLog=bo.toString();
	//Document转成String
	insertSMTMessageLogUtil(transactionID,
			eventTime,eventName, eventUser,
			siteName, messageLog, messageName,
			materialType);										//存入SMT消息
	
		String checkresultSplit="";
		String checkname="";
		String checkcode="";
		String usrsqla = "SELECT MATERIALQUANTITY,OQARESULT FROM MATERIALPACKINGSMT " +
				" WHERE SITENAME=:SITENAME "
				+ "AND MATERIALPACKINGNAME=:MATERIALPACKINGNAME "
				+ "AND BOESITENAME=:BOESITENAME "
				+ "AND STOCKSTATE='Stocked' " ;
		/*Map<String, Object> bindMap1 = new HashMap<String, Object>();
		bindMap1.put("SITENAME", siteName);
		bindMap1.put("MATERIALPACKINGNAME", sourceMaterialPackingName);*/
		Map<String, String> bindMap = new HashMap<String, String>();
        bindMap.put("SITENAME",siteName);
		bindMap.put("MATERIALPACKINGNAME",sourceMaterialPackingName);
		bindMap.put("BOESITENAME", BOEFactory);
		
		
		List<Map<String, Object>> sqlResult
		= IDMFrameServiceProxy.getSqlTemplate().queryForList(usrsqla, bindMap);
		if(sqlResult.size()<=0){
			checkname="不存在符合条件的原Box信息，请检查";
			checkcode="ERROR";
			checkresultSplit=checkname+"|"+checkcode;
		}
		else{
			
			String checkString = sqlResult.get(0).get("MATERIALQUANTITY").toString();
			String oqaResult = sqlResult.get(0).get("OQARESULT").toString();
			if(checkString.equals("0")||checkString.equals("")){
				checkname="原Box数量为0，请检查";
				checkcode="ERROR";
				checkresultSplit=checkname+"|"+checkcode;
			}
			else if(oqaResult.equals("NG")){
				checkname="原Box状态为NG状态，请修改为OK后再拆分！";
				checkcode="ERROR";
				checkresultSplit=checkname+"|"+checkcode;
			}
			else{
				checkname="OK";
				checkcode="0";
				checkresultSplit=checkname+"|"+checkcode;
			}
		}
		
		return checkresultSplit;	
	}

//插入SMT过账消息
	public static void insertSMTMessageLogUtil(String transactionID,
			String eventTime, String eventName, String eventUser,
			String siteName, String messageLog, String messageName,
			String materialType) {
		try {
			String sql = "INSERT INTO SMT_MESSAGELOG(TRANSACTIONID, EVENTTIME, EVENTNAME, EVENTUSER, SITENAME,MESSAGELOG,MESSAGENAME,MATERIALTYPE) "
					+ " VALUES(:transactionID, :eventTime, :eventName, :eventUser,:siteName, :messageLog, :messageName,:materialType )";
			Map<String, Object> bindMap = new HashMap<String, Object>();
			bindMap.put("transactionID", transactionID);
			bindMap.put("eventTime", eventTime);
			bindMap.put("eventName", eventName);
			bindMap.put("eventUser", eventUser);
			bindMap.put("siteName", siteName);
			bindMap.put("messageLog", messageLog);
			bindMap.put("messageName", messageName);
			bindMap.put("materialType", materialType);

			IDMFrameServiceProxy.getSqlTemplate()
					.update(sql, bindMap);
		} catch (DataAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw e;
		}
	}
	
	//调料入库核对数量是否与发出数量一致-add by wsq 19/1/10
	public String SMTTLcheck(EventInfo eventInfo, Document message) throws Exception {
		Element bodyElem = message.getRootElement().getChild("Body");
		String ReceiveRequestName=bodyElem.getChildText("RECEIVEREQUESTNAME");
		String materialPackingName=bodyElem.getChildText("MATERIALPACKINGNAME");
		String materialQuantity=bodyElem.getChildText("MATERIALQUANTITY");

		String fromsite=ReceiveRequestName.trim().substring(4, 6);
		String[] materialPackingNameList = materialPackingName.split("\\|");
		String[] materialQuantityList = materialQuantity.split("\\|");

		int a=materialPackingNameList.length;
		String checkresult="OK|0";
		for(int i=0;1<a;i++){
			String sqlcheck="SELECT * FROM MATERIALPACKINGSMT WHERE MATERIALPACKINGNAME=:MATERIALPACKINGNAME "
					+ "AND SITENAME=:SITENAME "
					+ "AND RECEIVEREQUESTNAME=:RECEIVEREQUESTNAME "
					+ "AND MATERIALQUANTITY=:MATERIALQUANTITY";
			Map<String, Object> bindMap = new HashMap<String, Object>();
			bindMap.put("SITENAME", fromsite);
			bindMap.put("RECEIVEREQUESTNAME", ReceiveRequestName);
			bindMap.put("MATERIALPACKINGNAME",materialPackingNameList[i]);
			bindMap.put("MATERIALQUANTITY", materialQuantityList[i]);
			List<Map<String, Object>> sqlResult
			= IDMFrameServiceProxy.getSqlTemplate().queryForList(sqlcheck, bindMap);
			if(sqlResult.size()==0){
				checkresult=materialPackingNameList[i]+"与发出方不一致！"+"|"+"ERROR";
				break;
			}
			
		}
		
		
		return checkresult;
	}
	/*
	 * 2019.1.11
	 * WSQ
	 * SMTcheck BOX状态是否为Stocked
	 * */
	public String CheckSMTSite(EventInfo eventInfo, Document message) throws Exception{
		Element bodyElem = message.getRootElement().getChild("Body");
		String siteName=bodyElem.getChildText("SITENAME");
		String materialPackingName=bodyElem.getChildText("MATERIALPACKINGNAME");
		String materialType = bodyElem.getChildText("MATERIALTYPE");
		String[] materialPackingNameList = materialPackingName.split("\\|");
		int a=materialPackingNameList.length;
		
		String BOEFactory=System.getProperty("factory");
		if(BOEFactory.equals("B5")){
			//B5/tm1的SMT在sitename按照SMTsitename+-+B5/TM1
			String [] sitelist=siteName.split("\\-");
			siteName = sitelist[0];
			BOEFactory = sitelist[1];
		}
		
		String checkresult="OK|0";
		
		String checksmtSite="SELECT ENUMVALUE FROM ENUMDEFVALUE WHERE ENUMNAME='SMTFab' AND DESCRIPTION=:DESCRIPTION ";
		Map<String, String> bindMap = new HashMap<String, String>();
		bindMap.put("DESCRIPTION", siteName);
		List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
				.getSqlTemplate()
				.queryForList(checksmtSite, bindMap);
		if(sqlResult.size()==0){
			checkresult="请联系BOE CIM确认SMT SITENAME信息！"+"|"+"ERROR";
			return checkresult;
		}
		//产线退料原材入库不做该校验（其他SMT调料出库的BOX在别家SMT正常入库不可操作）
		if(!materialType.equals("产线退料原材"))
		{
		//for(int i=0;i<a;i++){
			String checkstate="SELECT MATERIALPACKINGNAME FROM MATERIALPACKINGSMT WHERE SITENAME<>:SITENAME "
					+ " AND MATERIALPACKINGNAME IN (select regexp_substr(id, '[^|]+' ,1 ,rownum) id from (select  :MATERIALPACKINGNAME id from dual) a "
					+ " connect by rownum- 1 <= length(regexp_replace(id, '[^|]+'))) "
					+ " AND BOESITENAME=:BOESITENAME "
					+ " AND RECEIVEREQUESTNAME IS NOT NULL ";
			Map<String, String> bindMapa = new HashMap<String, String>();
			bindMapa.put("SITENAME", siteName);
			bindMapa.put("MATERIALPACKINGNAME", materialPackingName);
			bindMapa.put("BOESITENAME", BOEFactory);
			
			List<Map<String, Object>> sqlResulta
			= IDMFrameServiceProxy.getSqlTemplate().queryForList(checkstate, bindMapa);
			if(sqlResulta.size()>0){
				checkresult="请检查入库BOX是否为调料box!|ERROR";
				//break;
			}
		}
		//}
		
		return checkresult;
		
	}
	//检查入库Box是否为调料出库的Box
	public String CheckStockInBoxState(EventInfo eventInfo, Document message) throws Exception{
		Element bodyElem = message.getRootElement().getChild("Body");
		String siteName=bodyElem.getChildText("SITENAME");
		String materialPackingName=bodyElem.getChildText("MATERIALPACKINGNAME");
		String[] materialPackingNameList = materialPackingName.split("\\|");
		int a=materialPackingNameList.length;
		String checkresult="OK|0";
		
		for(int i=0;i<a;i++){
			String checksmtSite="SELECT * FROM MATERIALPACKINGSMT WHERE SITENAME<>:SITENAME "
					+ " AND MATERIALPACKINGNAME=:MATERIALPACKINGNAME "
					+ " AND RECEIVEREQUESTNAME IS NOT NULL ";
			Map<String, String> bindMap = new HashMap<String, String>();
			bindMap.put("SITENAME", siteName);
			bindMap.put("MATERIALPACKINGNAME", materialPackingNameList[i]);
			List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
					.getSqlTemplate()
					.queryForList(checksmtSite, bindMap);
			if(sqlResult.size()>0){
				checkresult="该BOX是否为调料box!|ERROR";
				break;
			}
		}
		return checkresult;
		
		
	}
	/**
	 * smt收货
	 * @param eventInfo
	 * @param siteName
	 * @param receiveActNo
	 * @param receiveRequestName
	 * @param materialPackingName
	 * @param materialSpecName
	 * @param makeDate
	 * @param receiveQuantity
	 * @param erpLocation
	 * @param supplierName
	 * @param NPFlag
	 * @param endDate
	 * @param charge
	 * @param erpFactory
	 * @param message
	 * @throws Exception
	 */
	public void PDACreateBoxByLabelForPCBA(EventInfo eventInfo, String siteName,
			String receiveActNo, String receiveRequestName,
			String materialPackingName, String materialSpecName, String makeDate,
			String receiveQuantity, String erpLocation,
			String supplierName, String NPFlag,String endDate,String charge,String erpFactory,Document message) throws Exception {
		try{
		// 获取MaterialSpec信息
		Element bodyElem = message.getRootElement().getChild("Body");
		String poDetailName=bodyElem.getChildText("RECEIVEREQUESTDETAILNAME");
		String moveType=bodyElem.getChildText("MOVETYPE");
		MaterialSpec materialSpec = new MaterialSpec();
		MaterialSpecKey materialSpecKey = new MaterialSpecKey();
		materialSpecKey.setMaterialSpecName(materialSpecName);
		materialSpecKey.setSiteName(siteName);
		//materialSpecKey.setErpFactoryName();
		materialSpec = MaterialServiceProxy.getMaterialSpecService()
				.selectByKey(materialSpecKey);

		/*MaterialReceiveRequestDetail materialReceiveRequestDetail = new MaterialReceiveRequestDetail();
		MaterialReceiveRequestDetailKey matetialReceiveRequestDetailKey = new MaterialReceiveRequestDetailKey();
		matetialReceiveRequestDetailKey
				.setReceiveRequestName(receiveRequestName);
		matetialReceiveRequestDetailKey.setSiteName(siteName);
		matetialReceiveRequestDetailKey
				.setReceiveRequestDetailName(poDetailName);

		materialReceiveRequestDetail = ReceiveRequestDetailServiceProxy
				.getReceiveRequestDetailService().selectByKey(
						matetialReceiveRequestDetailKey);*/
		if(!materialSpec.getExpirationDateFlag().equals("Y"))
		{
			charge="";
		}
		
		/**
		 * SMT入库的Box允许已经出库的相同料号的Box重复入库---wsq 2020.10.29
		 */
		String checkSql="SELECT STOCKSTATE,MATERIALSPECNAME  FROM MATERIALPACKING "
				+ " WHERE SITENAME=:SITENAME "
				+ " AND MATERIALPACKINGNAME=:MATERIALPACKINGNAME ";
		Map<String, String> bindMapQueryState = new HashMap<String, String>();
		bindMapQueryState.put("SITENAME", siteName);
		bindMapQueryState.put("MATERIALPACKINGNAME", materialPackingName);
		List<Map<String, Object>> materialPackingDetail = IDMFrameServiceProxy
				.getSqlTemplate()
				.queryForList(checkSql, bindMapQueryState);
		
		if(materialPackingDetail.size() > 0){
			if(materialPackingDetail.get(0).get("STOCKSTATE").equals("StockOut")
					&&materialPackingDetail.get(0).get("MATERIALSPECNAME").equals(materialSpecName)){
				MaterialPackingKey mpKey = new MaterialPackingKey();
				mpKey.setMaterialPackingName(materialPackingName);
				mpKey.setSiteName(siteName);
				MaterialPackingServiceProxy.getMaterialPackingService().delete(mpKey);
				log.info("Materialpacking:  " + materialPackingName + "  deleted for SMT Box ReStockIn");
			}
		}

		// 创建Box
		CreateInfo materialPacking = new CreateInfo();
		materialPacking.setMaterialPackingName(materialPackingName);
		materialPacking.setSiteName(siteName);
		materialPacking.setContentMaterialType("");
		materialPacking.setMaterialPackingType("Box");

		Map<String, Object> bindMap = new HashMap<String, Object>();
		bindMap.put("receiveActNo", receiveActNo);
		bindMap.put("receiveRequestName", receiveRequestName);
		bindMap.put("receiveRequestDetailName", poDetailName);

		bindMap.put("materialQuantity", receiveQuantity);
		bindMap.put("materialCreateQuantity", receiveQuantity);
		bindMap.put("packingState", "Created");// 标记Box是刚创建的

		bindMap.put("materialType", materialSpec.getMaterialType());
		bindMap.put("materialSpecName", materialSpecName);
		bindMap.put("stockState", "");
		bindMap.put("holdState", "N");
		bindMap.put("areaName", "");
		bindMap.put("createUser", eventInfo.getEventUser());
		bindMap.put("createTime", eventInfo.getEventTime());
		bindMap.put("makeDate", Timestamp.valueOf(makeDate));
		bindMap.put("expiringDate", Timestamp.valueOf(endDate));
		bindMap.put("erpLocation",erpLocation);
		bindMap.put("erpFactory", erpFactory);
		
		bindMap.put("stockInType", "Normal:"+moveType);
		bindMap.put("charge", charge);
		bindMap.put("supplierName", supplierName);
 		bindMap.put("npFlag", NPFlag);
		bindMap.put("reasonCodeType", moveType);
		bindMap.put("reasonCode", "0001");

		materialPacking.setUserColumns(bindMap);

		MaterialPackingServiceProxy.getMaterialPackingService().create(
				eventInfo, materialPacking);
		
		
		//update SMT NPFLAG
		/*String sqlUpdate="UPDATE MATERIALPACKINGSMT  "
				+" SET NPFLAG='Y' "
				+" ,LASTEVENTNAME=:LASTEVENTNAME"
				+" ,LASTEVENTTIMEKEY=:LASTEVENTTIMEKEY"
				+" ,LASTEVENTTIME=sysdate"
				+" ,LASTEVENTUSER=:LASTEVENTUSER"
				+" ,LASTEVENTCOMMENT=:LASTEVENTCOMMENT"
				+" WHERE MATERIALPACKINGNAME=:MATERIALPACKINGNAME "
				+" AND SUPPLIERNAME=:SUPPLIERNAME ";

		Map<String, String> bindMapSmt = new HashMap<String, String>();
		//bindMapSmt.put("AREANAME",bodyElem.getChildText("AREANAME"));
		bindMapSmt.put("MATERIALPACKINGNAME",materialPackingName);
		bindMapSmt.put("LASTEVENTNAME","BOECreate");
		bindMapSmt.put("LASTEVENTTIMEKEY",TimeStampUtil.getCurrentEventTimeKey());
		bindMapSmt.put("LASTEVENTUSER","BOE");
		bindMapSmt.put("LASTEVENTCOMMENT",eventInfo.getEventComment());
				
		bindMapSmt.put("SUPPLIERNAME",supplierName);
				//IDMFrameServiceProxy.getTransactionManager().beginTransaction();
				IDMFrameServiceProxy.getSqlTemplate().update(sqlUpdate, bindMapSmt);
				//IDMFrameServiceProxy.getTransactionManager().commitTransaction();
				//CreateBoxHistorySMT(materialPackingName);
				log.info(materialPackingName);*/
				
				MakeDetailIncreaseReceivedInfo makeDetailIncreaseReceivedInfo = new MakeDetailIncreaseReceivedInfo();
				MaterialReceiveRequestDetailKey matetialShipRequestDetailKey = new MaterialReceiveRequestDetailKey();
				matetialShipRequestDetailKey
						.setReceiveRequestName(receiveRequestName);
				matetialShipRequestDetailKey.setSiteName(siteName);
				matetialShipRequestDetailKey
						.setReceiveRequestDetailName(poDetailName);
				makeDetailIncreaseReceivedInfo.setIncreaseQuantity(Double
						.parseDouble(receiveQuantity));
				//IDMFrameServiceProxy.getTransactionManager().beginTransaction();
				ReceiveRequestDetailServiceProxy.getReceiveRequestDetailService()
						.increaseReceivedQuantity(matetialShipRequestDetailKey,eventInfo, makeDetailIncreaseReceivedInfo);
				//IDMFrameServiceProxy.getTransactionManager().commitTransaction();
				log.info("流水单号："+receiveRequestName+"行项目号："+poDetailName+"修改完成");
		}
		catch(Exception e)
		{
			e.getMessage();
			throw e;
		}
		

	}
	public static String generateSMTShipRequestName(String siteName, String SMTsiteName)
			throws Throwable {
		List<String> args = new ArrayList<String>();
		// 获取系统当前时间
		// java.util.Calendar c=java.util.Calendar.getInstance();
		// java.text.SimpleDateFormat f=new
		// java.text.SimpleDateFormat("yyyyMMdd");

		Date dt=new Date();
		
	    SimpleDateFormat matter1=new SimpleDateFormat("yyyyMMdd");
	    	   
		String time = matter1.format(dt);
		
		
		args.add(time);

		String virtualOQAid;

		virtualOQAid = NameServiceProxy.getNameRuleDefService()
				.generateName("ShipRequestName", args, 1).get(0);
		String shipRequestName=siteName+"C"+SMTsiteName+virtualOQAid;
		try {
			return shipRequestName;
		} catch (Throwable e) {
			
			throw e;
		}
	}
	//检查Transaction ID是否唯一
	public String CheckTransactionID_SMT(EventInfo eventInfo, Document message) throws Exception {
		Element headElem = message.getRootElement().getChild("Header");
		String transactionID=headElem.getChildText("TRANSACTIONID");
		String checkresultTransact="OK|0";
		String sqla="SELECT * FROM MATERIALPACKINGSMT WHERE TRANSACTIONID=:TRANSACTIONID";
		Map<String, Object> bindMap = new HashMap<String, Object>();
		bindMap.put("TRANSACTIONID", transactionID);
		
		List<Map<String, Object>> sqlResult
		= IDMFrameServiceProxy.getSqlTemplate().queryForList(sqla, bindMap);
		if(sqlResult.size()>0){
			checkresultTransact="TransactionID不唯一！|ERROR";
			return checkresultTransact;
		}
		return checkresultTransact;
	}
	//检查BOX ID是否已经存在
	public String CheckBoxID_SMT(EventInfo eventInfo, Document message) throws Exception {
		Element bodyElem = message.getRootElement().getChild("Body");
		String siteName=bodyElem.getChildText("SITENAME");
		String materialPackingName=bodyElem.getChildText("MATERIALPACKINGNAME");
		String materialType = bodyElem.getChildText("MATERIALTYPE");
		String materialSpecName=bodyElem.getChildText("MATERIALSPECNAME");
		String supplierNoName=bodyElem.getChildText("SUPPLIERNO");
		String materialQuantity=bodyElem.getChildText("MATERIALQUANTITY");
		String[] materialPackingNameList = materialPackingName.split("\\|");
		String[] materialSpecNameList = materialSpecName.split("\\|");
		String BOEFactory=System.getProperty("factory");
		
		if(BOEFactory.equals("B5")){
			//B5/tm1的SMT在sitename按照SMTsitename+-+B5/TM1
			String [] sitelist=siteName.split("\\-");
			siteName = sitelist[0];
			BOEFactory = sitelist[1];
		}
		
		
		int a=materialPackingNameList.length;
		String checkresultBox="OK|0";
		//校验消息中供应商代码是否都是数字代码
		log.info("supplierName:---"+supplierNoName);
		String supplierName=supplierNoName.replace("|", "");
			Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
			if(!pattern.matcher(supplierName).matches()){
				checkresultBox="供应商代码未正确填写，请填写数字代码！|ERROR";
				return checkresultBox;
			}
			
		
		//消息中重复BOXID校验
		String checkPackingNum=" (select DISTINCT regexp_substr(id, '[^|]+' ,1 ,rownum) id from (select  :MATERIALPACKINGNAME id from dual) a "
				+ " connect by rownum- 1 <= length(regexp_replace(id, '[^|]+'))) ";
		Map<String, String> bindMapPackingNum = new HashMap<String, String>();
		bindMapPackingNum.put("MATERIALPACKINGNAME", materialPackingName);
		List<Map<String, Object>> sqlResultforPackingNum = IDMFrameServiceProxy
				.getSqlTemplate()
				.queryForList(checkPackingNum, bindMapPackingNum);
		if(sqlResultforPackingNum.size()<materialPackingNameList.length){
			checkresultBox="消息中包含重复BOXID，请检查！|ERROR";
			return checkresultBox;
		}
		
		//检查是否为当前工厂的物料号
		String checkSpecNum=" (select DISTINCT regexp_substr(id, '[^|]+' ,1 ,rownum) id from (select  :MATERIALSPECNAME id from dual) a "
				+ " connect by rownum- 1 <= length(regexp_replace(id, '[^|]+'))) ";
		Map<String, String> bindMapSpecNum = new HashMap<String, String>();
		bindMapSpecNum.put("MATERIALSPECNAME", materialSpecName);
		List<Map<String, Object>> sqlResultforSpecNum = IDMFrameServiceProxy
				.getSqlTemplate()
				.queryForList(checkSpecNum, bindMapSpecNum);
		
		String checkMaterialSpecName="SELECT MATERIALSPECNAME FROM MATERIALSPEC WHERE SITENAME=:SITENAME "
				+ " AND MATERIALSPECNAME IN (select regexp_substr(id, '[^|]+' ,1 ,rownum) id from (select  :MATERIALSPECNAME id from dual) a "
				+ " connect by rownum- 1 <= length(regexp_replace(id, '[^|]+'))) ";
		Map<String, String> bindMapSpec = new HashMap<String, String>();
		bindMapSpec.put("SITENAME",BOEFactory );
		bindMapSpec.put("MATERIALSPECNAME", materialSpecName);
		List<Map<String, Object>> sqlResultforSpec = IDMFrameServiceProxy
				.getSqlTemplate()
				.queryForList(checkMaterialSpecName, bindMapSpec);
		
		if(sqlResultforSpec.size()!=sqlResultforSpecNum.size()){
			String notRegistedSpec="";
			for(int i=0;i<materialSpecNameList.length;i++){
				String sqlCheckSpec="SELECT MATERIALSPECNAME FROM MATERIALSPEC WHERE SITENAME=:SITENAME "
						+ " AND MATERIALSPECNAME=:MATERIALSPECNAME";
				Map<String, String> bindMapspec1 = new HashMap<String, String>();
				bindMapspec1.put("SITENAME", BOEFactory);
				bindMapspec1.put("MATERIALSPECNAME", materialSpecNameList[i]);
				List<Map<String, Object>> sqlResultforSpec1 = IDMFrameServiceProxy
						.getSqlTemplate()
						.queryForList(sqlCheckSpec, bindMapspec1);
				if(sqlResultforSpec1.size()==0){
					notRegistedSpec=notRegistedSpec+"/"+materialSpecNameList[i];
				}
				
			}
			checkresultBox=notRegistedSpec+"物料号在"+BOEFactory+"未注册，请检查！|ERROR";
			return checkresultBox;
			
		}
		
		if(materialType.equals("产线退料原材")||materialType.equals("成品返退")||materialType.equals("产线重工成品")
				||materialType.equals("正常原材")||materialType.startsWith("调料原材"))
		{
				//BOE过账失败的BOX暂时不可使用,状态为Stocked的BOX不可重复使用
				String checksmtSite="SELECT MATERIALPACKINGNAME FROM MATERIALPACKINGSMT WHERE SITENAME=:SITENAME "
						+ " AND MATERIALPACKINGNAME IN (select regexp_substr(id, '[^|]+' ,1 ,rownum) id from (select  :MATERIALPACKINGNAME id from dual) a "
						+ " connect by rownum- 1 <= length(regexp_replace(id, '[^|]+'))) "
						+ " AND ( UNDOID='ERPFailed' OR STOCKSTATE='Stocked' ) "
						+ " AND BOESITENAME=:BOESITENAME ";
				Map<String, String> bindMap = new HashMap<String, String>();
				bindMap.put("SITENAME", siteName);
				bindMap.put("MATERIALPACKINGNAME", materialPackingName);
				bindMap.put("BOESITENAME", BOEFactory);
				List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
						.getSqlTemplate()
						.queryForList(checksmtSite, bindMap);
				if(sqlResult.size()>0){
					String existedBox="";
					for(int i=0;i<sqlResult.size();i++){
						existedBox=existedBox+"/"+sqlResult.get(i).get("MATERIALPACKINGNAME");
					}
					checkresultBox=existedBox+"在BOE内部账务未处理完成或者当前为在库状态，不可使用，请更换BOXID!|ERROR";
				}
		}
		else{
				String checksmtSite="SELECT MATERIALPACKINGNAME FROM MATERIALPACKINGSMT WHERE SITENAME=:SITENAME "
						+ " AND BOESITENAME=:BOESITENAME "
						+ " AND MATERIALPACKINGNAME IN (select regexp_substr(id, '[^|]+' ,1 ,rownum) id from (select  :MATERIALPACKINGNAME id from dual) a "
						+ " connect by rownum- 1 <= length(regexp_replace(id, '[^|]+'))) ";
				Map<String, String> bindMap = new HashMap<String, String>();
				bindMap.put("SITENAME", siteName);
				bindMap.put("MATERIALPACKINGNAME", materialPackingName);
				bindMap.put("BOESITENAME", BOEFactory);
				List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
						.getSqlTemplate()
						.queryForList(checksmtSite, bindMap);
				if(sqlResult.size()>0){
					String existedBox="";
					for(int i=0;i<sqlResult.size();i++){
						existedBox=existedBox+"/"+sqlResult.get(i).get("MATERIALPACKINGNAME");
					}
					checkresultBox=existedBox+"已存在，请更换BOXID!|ERROR";
				}

		}
		
		//check boxID对应的数量是不是0
		String sqlQTYnot0=" SELECT * FROM ( "
				+ " (select DISTINCT regexp_substr(id, '[^|]+' ,1 ,rownum) id from (select  :MATERIALQUANTITY id from dual) a "
				+ " 				 connect by rownum- 1 <= length(regexp_replace(id, '[^|]+')))) "
				+ " 				 WHERE ID='0' ";
		Map<String, String> bindMapQTYnot0 = new HashMap<String, String>();
		bindMapQTYnot0.put("MATERIALQUANTITY", materialQuantity);
		List<Map<String, Object>> sqlResultQTYnot0 = IDMFrameServiceProxy
				.getSqlTemplate()
				.queryForList(sqlQTYnot0, bindMapQTYnot0);
		
		if(sqlResultQTYnot0.size()>0){
			checkresultBox="消息中包含数量为0的BOX，请检查后重新发送！！|ERROR";
			return checkresultBox;
		}
		
		
		return checkresultBox;
	}
//smt报表消息 WIP信息和 MES组件使用信息
	public void  CreateSMTReportInfo(EventInfo eventInfo, Document message) throws Exception {
		Element headElem = message.getRootElement().getChild("Header");
		String materialType=headElem.getChildText("MATERIALTYPE");
		String siteName = headElem.getChildText("SITENAME");
		String eventTime=headElem.getChildText("EVENTTIME");
		String exceptionContent = "";
		String BOEFactory=System.getProperty("factory");
		if(BOEFactory.equals("B5")){
			//B5/tm1的SMT在sitename按照SMTsitename+-+B5/TM1
			String [] sitelist=siteName.split("\\-");
			siteName = sitelist[0];
			BOEFactory = sitelist[1];
		}
		
		try{
		Element bodyElement = message.getRootElement().getChild("Body");
		Map<String, String> bindMap = new HashMap<String, String>();
	   if(materialType.startsWith("WIP"))
	   {
		   String lineNo = bodyElement.getChildText("LINENO");
		   String makeDate = bodyElement.getChildText("MAKEDATE");
		   String WO = bodyElement.getChildText("WO");
		   String inputQuantity = bodyElement.getChildText("INPUTQUANTITY");
		   String outputQuantity = bodyElement.getChildText("OUTPUTQUANTITY");
		   String ipopRatio = bodyElement.getChildText("IPOPRATIO");
		   String materialspecName = bodyElement.getChildText("MATERIALSPECNAME");
		   String productSize = bodyElement.getChildText("PRODUCTSIZE");
		   String printQuantity = bodyElement.getChildText("PRINTQUANTITY");
		   String patchQuantity = bodyElement.getChildText("PATCHQUANTITY");
		   String weldQuantity = bodyElement.getChildText("WELDQUANTITY");
		   String aoicheckQuantity = bodyElement.getChildText("AOICHECKQUANTITY");
		   String ictQuantity = bodyElement.getChildText("ICTQUANTITY");
		   String prePress = bodyElement.getChildText("PREPRESS");
		   String actualPress = bodyElement.getChildText("ACTUALPRESS");
		   String toolingTest = bodyElement.getChildText("TOOLINGTEST");
		   String visualCheck = bodyElement.getChildText("VISUALCHECK");
		   String fqcCheck = bodyElement.getChildText("FQCCHECK");
		   String packing = bodyElement.getChildText("PACKING");
		   String repaired = bodyElement.getChildText("REPAIRED");
		   String other = bodyElement.getChildText("OTHER");
		   String total = bodyElement.getChildText("TOTAL");
		   
		   String[] lineNoList = lineNo.split("\\|");
		   String[] makeDateList = makeDate.split("\\|");
		   String[] WOList = WO.split("\\|");
		   String[] inputQuantityList = inputQuantity.split("\\|");
		   String[] outputQuantityList = outputQuantity.split("\\|");
		   String[] ipopRatioList = ipopRatio.split("\\|");
		   String[] materialspecNameList = materialspecName.split("\\|");
		   String[] productSizeList = productSize.split("\\|");
		   String[] printQuantityList = printQuantity.split("\\|");
		   String[] patchQuantityList = patchQuantity.split("\\|");
		   String[] weldQuantityList = weldQuantity.split("\\|");
		   String[] aoicheckQuantityList = aoicheckQuantity.split("\\|");
		   String[] ictQuantityList = ictQuantity.split("\\|");
		   String[] prePressList = prePress.split("\\|");
		   String[] actualPressList = actualPress.split("\\|");
		   String[] toolingTestList = toolingTest.split("\\|");
		   String[] visualCheckList = visualCheck.split("\\|");
		   String[] fqcCheckList = fqcCheck.split("\\|");
		   String[] packingList = packing.split("\\|");
		   String[] repairedList = repaired.split("\\|");
		   String[] otherList = other.split("\\|");
		   String[] totalList = total.split("\\|");
		   
			
			for (int i = 0; i < lineNoList.length; i++) 
			{
				
				String sqlWIPCreat = "INSERT INTO SMT_WIPINFO  "
						+ "("
						+ "SITENAME                "
						+ ",LINENO                 "
						+ ",MAKEDATE               "
						+ ",WO                     "
						+ ",INPUTQUANTITY          "
						+ ",OUTPUTQUANTITY         "
						+ ",IPOPRATIO              "
						+ ",MATERIALSPECNAME       "
						+ ",PRODUCTSIZE            "
						+ ",PRINTQUANTITY          "
						+ ",PATCHQUANTITY          "
						+ ",WELDQUANTITY           "
						+ ",AOICHECKQUANTITY       "
						+ ",ICTQUANTITY            "
						+ ",PREPRESS               "
						+ ",ACTUALPRESS            "
						+ ",TOOLINGTEST            "
						+ ",VISUALCHECK            "
						+ ",FQCCHECK               "
						+ ",PACKING                "
						+ ",REPAIRED               "
						+ ",OTHER                  "
						+ ",TOTAL                  "
						+ ",EVENTTIME              "
						+ ",BOESITENAME            "
						+ ")"
						+ " VALUES (               "
						+ " :SITENAME              "
						+ ",:LINENO                "
						+ ",to_date(:MAKEDATE,'yyyy-MM-dd')  "
						+ ",:WO                    "
						+ ",:INPUTQUANTITY         "
						+ ",:OUTPUTQUANTITY        "
						+ ",:IPOPRATIO             "
						+ ",:MATERIALSPECNAME      "
						+ ",:PRODUCTSIZE           "
						+ ",:PRINTQUANTITY         "
						+ ",:PATCHQUANTITY         "
						+ ",:WELDQUANTITY          "
						+ ",:AOICHECKQUANTITY      "
						+ ",:ICTQUANTITY           "
						+ ",:PREPRESS              "
						+ ",:ACTUALPRESS           "
						+ ",:TOOLINGTEST           "
						+ ",:VISUALCHECK           "
						+ ",:FQCCHECK              "
						+ ",:PACKING               "
						+ ",:REPAIRED              "
						+ ",:OTHER                 "
						+ ",:TOTAL                 "
						+ ",to_date(:EVENTTIME,'yyyy-MM-dd HH24:mi:ss')  "
						+ ",:BOESITENAME               "
						+ ")";
					    
				
		        bindMap.put("SITENAME",siteName);
				bindMap.put("LINENO",lineNoList[i]);
				bindMap.put("MAKEDATE",makeDateList[i]);
				bindMap.put("WO",WOList[i]);
				bindMap.put("INPUTQUANTITY",inputQuantityList[i]);
				bindMap.put("OUTPUTQUANTITY",outputQuantityList[i]);
				bindMap.put("IPOPRATIO",ipopRatioList[i]);
				bindMap.put("MATERIALSPECNAME",materialspecNameList[i]);
				bindMap.put("PRODUCTSIZE",productSizeList[i]);
				bindMap.put("PRINTQUANTITY",printQuantityList[i]);
				bindMap.put("PATCHQUANTITY",patchQuantityList[i]);
				bindMap.put("WELDQUANTITY",weldQuantityList[i]);
				bindMap.put("AOICHECKQUANTITY",aoicheckQuantityList[i]);
				bindMap.put("ICTQUANTITY",ictQuantityList[i]);
				bindMap.put("PREPRESS",prePressList[i]);
				bindMap.put("ACTUALPRESS",actualPressList[i]);
				bindMap.put("TOOLINGTEST",toolingTestList[i]);
				bindMap.put("VISUALCHECK",visualCheckList[i]);
				bindMap.put("FQCCHECK",fqcCheckList[i]);
				bindMap.put("PACKING",packingList[i]);
				bindMap.put("REPAIRED",repairedList[i]);
				bindMap.put("OTHER",otherList[i]);
				bindMap.put("TOTAL",totalList[i]);
				bindMap.put("EVENTTIME",eventTime);
				bindMap.put("BOESITENAME", BOEFactory);
				
				IDMFrameServiceProxy.getSqlTemplate().update(sqlWIPCreat, bindMap);
				log.info(WOList[i]+" WIP INFO is created !");
			}
			
	     }else if(materialType.startsWith("MES"))
	     {

			   String materialpackingName = headElem.getChildText("MATERIALPACKINGNAME");
			   String materialQuantity = headElem.getChildText("MATERIALQUANTITY");
			   String packingTime = headElem.getChildText("PACKINGTIME");
			   String materialsepcName = headElem.getChildText("MATERIALSPECNAME");
			   String wo = headElem.getChildText("WO");
			   String flag = headElem.getChildText("FLAG");
			   
			   String componentName = bodyElement.getChildText("COMPONENTNAME");
			   String supplierNo = bodyElement.getChildText("SUPPLIERNO");
			   String componentCharge = bodyElement.getChildText("COMPONENTCHARGE");
			   String componentQuantity = bodyElement.getChildText("COMPONENTQUANTITY");
			   String addition = bodyElement.getChildText("ADDITION");
		
			   String[] componentNameList = componentName.split("\\|");
			   String[] supplierNoList = supplierNo.split("\\|");
			   String[] componentChargeList = componentCharge.split("\\|");
			   String[] componentQuantityList = componentQuantity.split("\\|");
			   String[] additionList = addition.split("\\|");
			   
			   if(componentName.length()==0||supplierNo.length()==0
					   ||componentQuantity.length()==0||addition.length()==0){
				   log.info("消息中对应组件名、组件供应商代码、数量、BOM外投料为必填项！");
					exceptionContent="消息中对应组件名、组件供应商代码、数量、BOM外投料为必填项！";
					throw new Exception(exceptionContent);
			   }
			   
			   int componentNamelength=componentNameList.length;
			   
			   if(componentCharge.length()==0){
				   //charge全部传空
				   if(componentNamelength!=supplierNoList.length||componentNamelength!=componentQuantityList.length
							||componentNamelength!=additionList.length){
						log.info("消息中对应组件名、组件供应商代码、数量、BOM外投料个数不一致！");
						exceptionContent="消息中对应组件名、组件供应商代码、数量、BOM外投料个数不一致！";
						throw new Exception(exceptionContent);
					}
			   }
			   else{
				 //charge不传空
				   if(componentNamelength!=supplierNoList.length||componentNamelength!=componentQuantityList.length
							||componentNamelength!=additionList.length||componentNamelength!=componentChargeList.length){
						log.info("消息中对应组件名、组件供应商代码、组件批次、数量、BOM外投料个数不一致！");
						exceptionContent="消息中对应组件名、组件供应商代码、组件批次、数量、BOM外投料个数不一致！";
						throw new Exception(exceptionContent);
					}
			   }
			   
			   	//批量处理update数据，避免BOX较多时候for循环耗时较多
				log.info("组件料号数量："+additionList.length+"------"+addition);
				double a= additionList.length;
				int length4Split=30;
				double b=Math.ceil(a/length4Split);
				int circleTime =(int)b;
				log.info("additionList.length>>>>>>: " + a+" Circle Times>>>:"+circleTime);
				//将additionList按照30个一循环，循环批量处理，避免SQL过长
				for(int i=0;i<circleTime;i++){
					String AdditionComponentList="";
					if(i==circleTime-1){
						for(int j=0;j<(a-length4Split*(b-1));j++){
							String AdditionComponentLista=additionList[i*length4Split+j]+"|";
							AdditionComponentList=AdditionComponentList+AdditionComponentLista;
						}
					}
					else{
						for(int j=0;j<length4Split;j++){
							String AdditionComponentLista=additionList[i*length4Split+j]+"|";
							AdditionComponentList=AdditionComponentList+AdditionComponentLista;
						}
					}
					AdditionComponentList=AdditionComponentList.substring(0,AdditionComponentList.length()-1);
					
					 String sqlCheckComponent = " SELECT MATERIALSPECNAME FROM MATERIALSPEC WHERE SITENAME=:SITENAME AND MATERIALSPECNAME IN "
						   		+ " (select regexp_substr(id, '[^|]+' ,1 ,rownum) id from (select  :MATERIALSPECNAME id from dual) a connect by rownum- 1 <= length(regexp_replace(id, '[^|]+'))) ";
						   Map<String, String> bindMap4CheckComponent = new HashMap<String, String>();
						   bindMap4CheckComponent.put("SITENAME", BOEFactory);
						   bindMap4CheckComponent.put("MATERIALSPECNAME", AdditionComponentList);
						   
						   List<Map<String, Object>> sqlResult4CheckComponent = IDMFrameServiceProxy
									.getSqlTemplate()
									.queryForList(sqlCheckComponent, bindMap4CheckComponent);
						   
						   String sqlCheckComponenta = " select distinct regexp_substr(id, '[^|]+' ,1 ,rownum) id from (select  :MATERIALSPECNAME id from dual) a connect by rownum- 1 <= length(regexp_replace(id, '[^|]+')) ";
							   Map<String, String> bindMap4CheckComponenta = new HashMap<String, String>();
							   bindMap4CheckComponenta.put("MATERIALSPECNAME", AdditionComponentList);
							   
							   List<Map<String, Object>> sqlResult4CheckComponenta = IDMFrameServiceProxy
										.getSqlTemplate()
										.queryForList(sqlCheckComponenta, bindMap4CheckComponenta);
						   
							if(sqlResult4CheckComponent.size()!=sqlResult4CheckComponenta.size()){
								//addition中存在不在主数据表中的料号
								String[] additionList4Split = AdditionComponentList.split("\\|");
								String notExistComponent ="";
								for(int j=0 ; j<additionList4Split.length ;j++){
									String sqlCheckComponentb = " SELECT MATERIALSPECNAME FROM MATERIALSPEC WHERE SITENAME=:SITENAME AND MATERIALSPECNAME =:MATERIALSPECNAME ";
									   Map<String, String> bindMap4CheckComponentb = new HashMap<String, String>();
									   bindMap4CheckComponentb.put("SITENAME", BOEFactory);
									   bindMap4CheckComponentb.put("MATERIALSPECNAME", additionList4Split[j]);
									   
									   List<Map<String, Object>> sqlResult4CheckComponentb = IDMFrameServiceProxy
												.getSqlTemplate()
												.queryForList(sqlCheckComponentb, bindMap4CheckComponentb);
									   if(sqlResult4CheckComponentb.size()==0){
										   notExistComponent+="/"+additionList4Split[j];
									   }
								}
								
								exceptionContent=notExistComponent+"该部分组件料号在BOE不存在，请检查！！";
								throw new Exception(exceptionContent);
							}
				}
			   
			  
			   
			   String sqlcheck = " SELECT MATERIALPACKINGNAME FROM SMT_COMPONENTUSEINFO "
					   +" WHERE SITENAME=:SITENAME "
					   +" AND BOESITENAME=:BOESITENAME "
					   +" AND MATERIALPACKINGNAME=:MATERIALPACKINGNAME "
					   +" AND WO=:WO ";
			   Map<String, String> bindMap4Check = new HashMap<String, String>();
			   bindMap4Check.put("SITENAME", siteName);
			   bindMap4Check.put("BOESITENAME", BOEFactory);
			   bindMap4Check.put("MATERIALPACKINGNAME", materialpackingName);
			   bindMap4Check.put("WO", wo);
				List<Map<String, Object>> sqlResult4Check = IDMFrameServiceProxy
						.getSqlTemplate()
						.queryForList(sqlcheck, bindMap4Check);
			   
			   if(flag.equals("0")){
				   //新增组件使用信息
				   if(sqlResult4Check.size()>0){
					   exceptionContent="该工单下BOX组件使用信息已经存在，不可重复创建！！";
					   throw new Exception(exceptionContent);
				   }
				   else{
					   for (int i = 0; i < componentNameList.length; i++) 
						{
						   if(componentQuantityList[i]==null){
							   exceptionContent=componentNameList[i]+"组件使用量不可为空";
							   throw new Exception(exceptionContent);
						   }
						   String sqlMESCreat = "INSERT INTO SMT_COMPONENTUSEINFO  "
									+ "("
									+ "SITENAME                "
									+ ",MATERIALPACKINGNAME    "
									+ ",MATERIALQUANTITY       "
									+ ",PACKINGTIME            "
									+ ",MATERIALSPECNAME       "
									+ ",WO                     "
									+ ",COMPONENTNAME          "
									+ ",SUPPLIERNO             "
									+ ",COMPONENTCHARGE        "
									+ ",COMPONENTQUANTITY      "
									+ ",ADDITION               "
									+ ",EVENTTIME              "
									+ ",BOESITENAME            "
									+ ",COMPONENTUNIT          "				
									+ ")"
									+ " VALUES (               "
									+ " :SITENAME              "
									+ ",:MATERIALPACKINGNAME   "
									+ ",:MATERIALQUANTITY      "
									+ ",to_date(:PACKINGTIME,'yyyy-MM-dd HH24:mi:ss')   "
									+ ",:MATERIALSPECNAME      "
									+ ",:WO                    "
									+ ",:COMPONENTNAME         "
									+ ",:SUPPLIERNO            "
									+ ",:COMPONENTCHARGE       "
									+ ",:COMPONENTQUANTITY     "
									+ ",:ADDITION              "
									+ ",to_date(:EVENTTIME,'yyyy-MM-dd HH24:mi:ss')      "
									+ ",:BOESITENAME           "
									+ ",(SELECT DISTINCT MATERIALUNIT FROM MATERIALSPEC WHERE SITENAME=:BOESITENAME AND MATERIALSPECNAME=:ADDITION) "
									+ ")";
								    
							
					        bindMap.put("SITENAME",siteName);
							bindMap.put("MATERIALPACKINGNAME",materialpackingName);
							bindMap.put("MATERIALQUANTITY", materialQuantity);
							bindMap.put("PACKINGTIME",packingTime);
							bindMap.put("MATERIALSPECNAME",materialsepcName);
							bindMap.put("WO",wo);
							bindMap.put("COMPONENTNAME",componentNameList[i]);
							bindMap.put("SUPPLIERNO",supplierNoList[i].length()==7?"000"+supplierNoList[i]:supplierNoList[i]);//供应商代码7位补全10位
							bindMap.put("COMPONENTCHARGE",componentCharge.length()==0?"":componentChargeList[i]);//charge字段全部为空时，直接使用空值
							bindMap.put("COMPONENTQUANTITY",componentQuantityList[i]);
							bindMap.put("ADDITION",additionList[i]);
							bindMap.put("EVENTTIME",eventTime);
							bindMap.put("BOESITENAME", BOEFactory);
							
							IDMFrameServiceProxy.getSqlTemplate().update(sqlMESCreat, bindMap);
							log.info(sqlMESCreat);
							log.info(materialpackingName+" COMPONENT INFO is created !");
						}
				   }   
			   }
			   else if(flag.equals("1")){
				   //update组件使用信息时，校验是否存在可update的组件使用信息
				   if(sqlResult4Check.size()<0){
					   exceptionContent="该工单下BOX组件使用信息不存在，无法进行更新！！";
					   throw new Exception(exceptionContent);
				   }
				   else{
					   
					   String delete_Sql = "DELETE FROM SMT_COMPONENTUSEINFO WHERE "
					   		+ " SITENAME=:SITENAME  "
					   		+ " AND BOESITENAME=:BOESITENAME "
					   		+ " AND MATERIALPACKINGNAME=:MATERIALPACKINGNAME "
					   		+ " AND WO=:WO ";
					   Map<String, String> bindMap_DEL = new HashMap<String, String>();
					   bindMap_DEL.put("SITENAME", siteName);
					   bindMap_DEL.put("BOESITENAME", BOEFactory);
					   bindMap_DEL.put("MATERIALPACKINGNAME", materialpackingName);
					   bindMap_DEL.put("WO", wo);
					   IDMFrameServiceProxy.getSqlTemplate().update(delete_Sql, bindMap_DEL);
						log.info(delete_Sql);
						log.info(materialpackingName+"  WO:"+wo+" COMPONENT INFO is deleted !");
					  //先删除后再重新插入新的 
					   for (int i = 0; i < componentNameList.length; i++) 
						{
						   if(componentQuantityList[i]==null){
							   exceptionContent=componentNameList[i]+"组件使用量不可为空";
							   throw new Exception(exceptionContent);
						   }
						   String sqlMESCreat = "INSERT INTO SMT_COMPONENTUSEINFO  "
									+ "("
									+ "SITENAME                "
									+ ",MATERIALPACKINGNAME    "
									+ ",MATERIALQUANTITY       "
									+ ",PACKINGTIME            "
									+ ",MATERIALSPECNAME       "
									+ ",WO                     "
									+ ",COMPONENTNAME          "
									+ ",SUPPLIERNO             "
									+ ",COMPONENTCHARGE        "
									+ ",COMPONENTQUANTITY      "
									+ ",ADDITION               "
									+ ",EVENTTIME              "
									+ ",BOESITENAME            "
									+ ",COMPONENTUNIT          "				
									+ ")"
									+ " VALUES (               "
									+ " :SITENAME              "
									+ ",:MATERIALPACKINGNAME   "
									+ ",:MATERIALQUANTITY      "
									+ ",to_date(:PACKINGTIME,'yyyy-MM-dd HH24:mi:ss')   "
									+ ",:MATERIALSPECNAME      "
									+ ",:WO                    "
									+ ",:COMPONENTNAME         "
									+ ",:SUPPLIERNO            "
									+ ",:COMPONENTCHARGE       "
									+ ",:COMPONENTQUANTITY     "
									+ ",:ADDITION              "
									+ ",to_date(:EVENTTIME,'yyyy-MM-dd HH24:mi:ss')      "
									+ ",:BOESITENAME           "
									+ ",(SELECT DISTINCT MATERIALUNIT FROM MATERIALSPEC WHERE SITENAME=:BOESITENAME AND MATERIALSPECNAME=:ADDITION) "
									+ ")";
								    
							
					        bindMap.put("SITENAME",siteName);
							bindMap.put("MATERIALPACKINGNAME",materialpackingName);
							bindMap.put("MATERIALQUANTITY", materialQuantity);
							bindMap.put("PACKINGTIME",packingTime);
							bindMap.put("MATERIALSPECNAME",materialsepcName);
							bindMap.put("WO",wo);
							bindMap.put("COMPONENTNAME",componentNameList[i]);
							bindMap.put("SUPPLIERNO",supplierNoList[i].length()==7?"000"+supplierNoList[i]:supplierNoList[i]);//供应商代码7位补全10位
							bindMap.put("COMPONENTCHARGE",componentCharge.length()==0?"":componentChargeList[i]);//charge字段全部为空时，直接使用空值
							bindMap.put("COMPONENTQUANTITY",componentQuantityList[i]);
							bindMap.put("ADDITION",additionList[i]);
							bindMap.put("EVENTTIME",eventTime);
							bindMap.put("BOESITENAME", BOEFactory);
							
							IDMFrameServiceProxy.getSqlTemplate().update(sqlMESCreat, bindMap);
							log.info(sqlMESCreat);
							log.info(materialpackingName+" COMPONENT INFO is created !");
						}
				   }
				   
			   }
			   else{
				   exceptionContent="FLAG字段传输错误，仅可传输0或1！！";
				   throw new Exception(exceptionContent);
			   }
			   

		    }
	     else{
	    	 exceptionContent="消息中MATERIALTYPE填写不符合要求！！！";
	    	 throw new Exception(exceptionContent);
	     }
		}
		catch(Exception e)
		{
			e.getMessage();
			throw new Exception(exceptionContent);
			//throw e;
		}
	
	}//报表
	
 //成品发货的物料号，流水单号，数量写入到materialreceiverequestdetail表中，便于收货比较
	//2019.2.26wsq修改，判定流水单号是否已经存在，如已存在更新receiverequestdetail中详细行项目
	//2019.3.8iqcflag写为X，发送TQMS
	public void CreateReceiveRequest(EventInfo eventInfo,Document message)
	{
		Element bodyElem = message.getRootElement().getChild("Body");
		String siteName=bodyElem.getChildText("SITENAME");
		String shipRequestDetailName=bodyElem.getChildText("SHIPREQUESTDETAILNAME");
		String materialspecName="";//物料号
		String requestQuantity="";//单个物料数量
		String supplierNO="SMTtoBOE";//供应商代码
		
		String BOEFactory=System.getProperty("factory");
		if(BOEFactory.equals("B5")){
			//B5/tm1的SMT在sitename按照SMTsitename+-+B5/TM1
			String [] sitelist=siteName.split("\\-");
			siteName = sitelist[0];
			BOEFactory = sitelist[1];
		}
		
		//获取流水号下物料号，数量

		String stockOutInfo="SELECT MATERIALSPECNAME,SUM(MATERIALQUANTITY) AS REQUESTQUANTITY "
							//+ ",SUPPLIERNAME " //group by条件中去掉供应商名称，只按照物料号分行项目
							+ " FROM   MATERIALPACKINGSMT " 
                            +"WHERE SITENAME=:SITENAME "
                            + " AND SHIPREQUESTDETAILNAME=:SHIPREQUESTDETAILNAME "
                            + " AND STOCKSTATE='StockOut' "
                            + " AND BOESITENAME=:BOESITENAME "
                            +" GROUP BY MATERIALSPECNAME"
                            //+ ",SUPPLIERNAME "//group by条件中去掉供应商名称，按照物料号分行项目
                            + " ORDER BY MATERIALSPECNAME DESC";
		
		
		Map<String, String> bindMap = new HashMap<String, String>();
		bindMap.put("SITENAME",siteName);
		bindMap.put("SHIPREQUESTDETAILNAME",shipRequestDetailName);
		bindMap.put("BOESITENAME", BOEFactory);
		List<Map<String, Object>> stockOutList =IDMFrameServiceProxy.getSqlTemplate().queryForList(stockOutInfo, bindMap);
		
		//supplierNO=stockOutList.get(0).get("SUPPLIERNAME").toString();

		//插入materialreceiverequest和 detail表中
		//String factory =System.getProperty("factory");
		String WERKS = "";
		if(BOEFactory.equals("B4")) {
			WERKS = "1200";
		}
		else if(BOEFactory.equals("B3")){
			WERKS = "1100";
		 }
		else if(BOEFactory.equals("B5")){
			WERKS = "1300";
		 }
		else if(BOEFactory.equals("B8")) {
			 WERKS = "1800";
		 }
		else if(BOEFactory.equals("B10")) {
			 WERKS = "3020";
		 }
		else if(BOEFactory.equals("B9")){
			WERKS = "3010";
		}
		else if(BOEFactory.equals("TM1")){
			WERKS = "1310";
		}
		else{
			String sql4WERKS = "SELECT DISTINCT ERPFACTORYNAME FROM BS_ERPLOCATION WHERE TYPE='Valued' and SITENAME=:SITENAME";
			Map<String, String> bindMap4WERKS = new HashMap<String, String>();	
			bindMap4WERKS.put("SITENAME", BOEFactory);
			List<Map<String, Object>> sqlResult4WERKS
	  			= IDMFrameServiceProxy.getSqlTemplate().queryForList(sql4WERKS, bindMap4WERKS);
			WERKS = sqlResult4WERKS.get(0).get("ERPFACTORYNAME").toString();
		}
		
		//查询SHIPREQUESTDETAILNAME是否已存在
		String sqla="SELECT * FROM MATERIALRECEIVEREQUEST WHERE RECEIVEREQUESTNAME=:RECEIVEREQUESTNAME "
				+ "AND SITENAME=:SITENAME";
		Map<String, Object> bindMapship = new HashMap<String, Object>();
		bindMapship.put("RECEIVEREQUESTNAME", shipRequestDetailName);
		bindMapship.put("SITENAME", BOEFactory);
		
		List<Map<String, Object>> sqlResult
		= IDMFrameServiceProxy.getSqlTemplate().queryForList(sqla, bindMapship);
		
		//SHIPREQUESTDETAILNAME不存在，直接新建
		if(sqlResult.size()==0){
			CreateReceiveRequestInfo createInfo = new CreateReceiveRequestInfo();
			createInfo.setSiteName(BOEFactory);
			createInfo.setReceiveRequestName(shipRequestDetailName);
			createInfo.setReceiveRequestState("Created");
			createInfo.setSupplierNO(supplierNO);
			createInfo.setSystemType("OIC_SMT");
			createInfo.setReceiveRequestType(siteName);
			eventInfo.setEventName("WMSCreate");
			MaterialReceiveRequestServiceProxy.getMaterialReceiveRequestService().create(eventInfo, createInfo);
			
			for(int i=0;i<stockOutList.size();i++)
			{
				materialspecName=stockOutList.get(i).get("MATERIALSPECNAME").toString();
				requestQuantity=stockOutList.get(i).get("REQUESTQUANTITY").toString();
				MaterialReceiveRequestDetail mrd =new MaterialReceiveRequestDetail();
				MaterialReceiveRequestDetailKey mrdk=new MaterialReceiveRequestDetailKey();
				mrdk.setSiteName(BOEFactory);
				mrdk.setReceiveRequestName(shipRequestDetailName);
				mrdk.setReceiveRequestDetailName(String.valueOf(i+1));
				mrd.setKey(mrdk);					
				mrd.setReceiveRequestDetailType("0");
				mrd.setMaterialSpecName(materialspecName);
				mrd.setLastEventTime(eventInfo.getEventTime());
				mrd.setErpFactory(WERKS);//单据详情中增加ERP工厂
				mrd.setIqcFlag("X");//iqcflag置为X，发送tqms
				if(!requestQuantity.isEmpty())
					mrd.setRequestQuantity(Double.valueOf(requestQuantity));
				mrd.setReceivedQuantity(0);
				//新的单号，插入detail内容
				ReceiveRequestDetailServiceProxy.getReceiveRequestDetailService().insert(mrd);
				
			}
		}
		//SHIPREQUESTDETAILNAME存在，update
		else{
			//MaterialReceiveRequest updateInfo = new MaterialReceiveRequest();
			//updateInfo.setLastEventTime(eventInfo.getEventTime());
			//MaterialReceiveRequestServiceProxy.getMaterialReceiveRequestService().update(updateInfo);
			//判断已有行项目与已传过来的行项是否一致
			String sqldetail="SELECT MATERIALSPECNAME,REQUESTQUANTITY  FROM MATERIALRECEIVEREQUESTDETAIL "
					+ " WHERE RECEIVEREQUESTNAME=:RECEIVEREQUESTNAME "
					+ " ORDER BY MATERIALSPECNAME DESC";
			Map<String, Object> bindMapdetail = new HashMap<String, Object>();
			bindMapdetail.put("RECEIVEREQUESTNAME", shipRequestDetailName);
			
			List<Map<String, Object>> sqlResultdetail
			= IDMFrameServiceProxy.getSqlTemplate().queryForList(sqldetail, bindMapdetail);
			int a=stockOutList.size()-sqlResultdetail.size();
			//行项数量相同，update全部行项
			if(a==0){
				
				for(int i=0;i<stockOutList.size();i++)
				{
					materialspecName=stockOutList.get(i).get("MATERIALSPECNAME").toString();
					requestQuantity=stockOutList.get(i).get("REQUESTQUANTITY").toString();
					MaterialReceiveRequestDetail mrd =new MaterialReceiveRequestDetail();
					MaterialReceiveRequestDetailKey mrdk=new MaterialReceiveRequestDetailKey();
					mrdk.setSiteName(BOEFactory);
					mrdk.setReceiveRequestName(shipRequestDetailName);
					mrdk.setReceiveRequestDetailName(String.valueOf(i+1));
					mrd.setKey(mrdk);					
					mrd.setReceiveRequestDetailType("0");
					mrd.setMaterialSpecName(materialspecName);
					mrd.setLastEventTime(eventInfo.getEventTime());
					mrd.setErpFactory(WERKS);//单据详情中增加ERP工厂
					mrd.setIqcFlag("X");
					if(!requestQuantity.isEmpty())
						mrd.setRequestQuantity(Double.valueOf(requestQuantity));
					mrd.setReceivedQuantity(0);
					
					//已存在单号时且行项目与已有完全一样时，update receiverequestdetail内容
					ReceiveRequestDetailServiceProxy.getReceiveRequestDetailService().update(mrd);
				}
				
				
			}
			else{
				//行项数量不一样，update一样的行项目，新的行项目insert
				for(int i=0;i<sqlResultdetail.size();i++)
				{
					materialspecName=stockOutList.get(i).get("MATERIALSPECNAME").toString();
					requestQuantity=stockOutList.get(i).get("REQUESTQUANTITY").toString();
					MaterialReceiveRequestDetail mrd =new MaterialReceiveRequestDetail();
					MaterialReceiveRequestDetailKey mrdk=new MaterialReceiveRequestDetailKey();
					mrdk.setSiteName(BOEFactory);
					mrdk.setReceiveRequestName(shipRequestDetailName);
					mrdk.setReceiveRequestDetailName(String.valueOf(i+1));
					mrd.setKey(mrdk);					
					mrd.setReceiveRequestDetailType("0");
					mrd.setMaterialSpecName(materialspecName);
					mrd.setLastEventTime(eventInfo.getEventTime());
					mrd.setErpFactory(WERKS);//单据详情中增加ERP工厂
					mrd.setIqcFlag("X");
					if(!requestQuantity.isEmpty())
						mrd.setRequestQuantity(Double.valueOf(requestQuantity));
					mrd.setReceivedQuantity(0);
					
					//已存在单号时但是本次有新加行项目时，update receiverequestdetail中前一部分行项目内容
					ReceiveRequestDetailServiceProxy.getReceiveRequestDetailService().update(mrd);
				}
				
				for(int i=sqlResultdetail.size();i<stockOutList.size();i++)
				{
					materialspecName=stockOutList.get(i).get("MATERIALSPECNAME").toString();
					requestQuantity=stockOutList.get(i).get("REQUESTQUANTITY").toString();
					MaterialReceiveRequestDetail mrd =new MaterialReceiveRequestDetail();
					MaterialReceiveRequestDetailKey mrdk=new MaterialReceiveRequestDetailKey();
					mrdk.setSiteName(BOEFactory);
					mrdk.setReceiveRequestName(shipRequestDetailName);
					mrdk.setReceiveRequestDetailName(String.valueOf(i+1));
					mrd.setKey(mrdk);					
					mrd.setReceiveRequestDetailType("0");
					mrd.setMaterialSpecName(materialspecName);
					mrd.setLastEventTime(eventInfo.getEventTime());
					mrd.setErpFactory(WERKS);//单据详情中增加ERP工厂
					mrd.setIqcFlag("X");
					if(!requestQuantity.isEmpty())
						mrd.setRequestQuantity(Double.valueOf(requestQuantity));
					mrd.setReceivedQuantity(0);
					
					//已存在单号时但是本次有新加行项目时，update receiverequestdetail中前一部分行项目内容
					ReceiveRequestDetailServiceProxy.getReceiveRequestDetailService().insert(mrd);
				}
				
			}
		}
		
		
	}
	//获取PCBA行项目
	public String getPCBADetail(String receiveRequestName,String materialSpecName,String materialQuantity) throws CustomException 
	{
		String poDetailName="";
		
		String sql = "SELECT a.RECEIVEREQUESTDETAILNAME, a.REQUESTQUANTITY-a.RECEIVEDQUANTITY as QUANTITY FROM MATERIALRECEIVEREQUESTDETAIL a WHERE RECEIVEREQUESTNAME=:receiveRequestName and MATERIALSPECNAME=:materialSpecName ";
		Map<String, String> bindMap = new HashMap<String, String>();
		bindMap.put("receiveRequestName", receiveRequestName);
		bindMap.put("materialSpecName", materialSpecName);
		List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
				.getSqlTemplate()
				.queryForList(sql, bindMap);
		
		for (int i = 0; i < sqlResult.size(); i++) 
		{
			if((Double.parseDouble(sqlResult.get(i).get("QUANTITY").toString())-(Double.parseDouble(materialQuantity))>=0))
			{
				poDetailName= sqlResult.get(i).get("RECEIVEREQUESTDETAILNAME").toString();
				break;
			}else{
				throw new CustomException(materialSpecName+"行项目收货数量不足");
			}
		}
		
		return poDetailName;

	}
	/**
	 * PDA PCBA创建box
	 * @param eventInfo
	 * @param siteName
	 * @param receiveActNo
	 * @param receiveRequestName
	 * @param materialPackingName
	 * @param poDetailName
	 * @param makeDate
	 * @param receiveQuantity
	 * @param materialSpecName
	 * @param supplierName
	 * @param NPFlag
	 * @param palletID
	 * @param EXPIRINGDATE
	 * @param erpFactory
	 * @param erpLocation
	 * @param moveType
	 * @throws Exception
	 */
	public void PCBACreateBoxByLabel(EventInfo eventInfo, String siteName,
			String receiveActNo, String receiveRequestName,
			String materialPackingName, String poDetailName, String makeDate,
			String receiveQuantity, String materialSpecName,
			String supplierName, String NPFlag,String palletID,String EXPIRINGDATE,String erpFactory,String erpLocation,String moveType) throws Exception {
		
		try {
			if(poDetailName.equals(""))
			{
				throw new CustomException("FindDetailError","","");
			}
			
			MaterialSpec materialSpec = new MaterialSpec();
			MaterialSpecKey materialSpecKey = new MaterialSpecKey();
			materialSpecKey.setMaterialSpecName(materialSpecName);
			materialSpecKey.setSiteName(siteName);
			materialSpec = MaterialServiceProxy.getMaterialSpecService()
					.selectByKey(materialSpecKey);

			MaterialReceiveRequestDetail materialReceiveRequestDetail = new MaterialReceiveRequestDetail();
			MaterialReceiveRequestDetailKey matetialReceiveRequestDetailKey = new MaterialReceiveRequestDetailKey();
			matetialReceiveRequestDetailKey
					.setReceiveRequestName(receiveRequestName);
			matetialReceiveRequestDetailKey.setSiteName(siteName);
			matetialReceiveRequestDetailKey
					.setReceiveRequestDetailName(poDetailName);

			materialReceiveRequestDetail = ReceiveRequestDetailServiceProxy
					.getReceiveRequestDetailService().selectByKey(
							matetialReceiveRequestDetailKey);
			// 创建Pallet信息
			if(!(palletID==null||palletID.equals("")))
			{
				String sql="SELECT MATERIALPACKINGNAME,MATERIALSPECNAME,to_char(EXPIRINGDATE,'yyyy-MM-dd') EXPIRINGDATE,MATERIALQUANTITY  FROM MATERIALPACKING WHERE MATERIALPACKINGNAME=:materialPackingName AND SITENAME=:siteName AND PACKINGSTATE='Created' ";
				Map<String, Object> bindMap1 = new HashMap<String, Object>();
				bindMap1.put("materialPackingName", palletID);
				bindMap1.put("siteName", siteName);
				List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
						.getSqlTemplate()
						.queryForList(sql, bindMap1);	
				if(sqlResult.size()==0)
				{
					CreateInfo materialPacking = new CreateInfo();
					materialPacking.setMaterialPackingName(palletID);
					materialPacking.setSiteName(siteName);
					materialPacking.setContentMaterialType("MaterialPacking");
					materialPacking.setMaterialPackingType("Pallet");
					Map<String, Object> bindMap = new HashMap<String, Object>();
					//bindMap.put("receiveActNo", receiveActNo);
					bindMap.put("receiveRequestName", receiveRequestName);
					bindMap.put("receiveRequestDetailName", poDetailName);
					bindMap.put("packingState", "Created");// 标记Box是刚创建的
					bindMap.put("materialQuantity", receiveQuantity);
					bindMap.put("materialSpecName", materialSpecName);
					bindMap.put("erpLocation",
							erpLocation);
					bindMap.put("erpFactory", erpFactory);
					bindMap.put("stockInType", "Normal");
					bindMap.put("supplierName", supplierName);
					bindMap.put("superMaterialPackingName", palletID);
					bindMap.put("expiringDate", Timestamp.valueOf(EXPIRINGDATE+" 00:00:00"));
					bindMap.put("makeDate", Timestamp.valueOf(makeDate+" 00:00:00"));
					bindMap.put("supplierName", supplierName);
					bindMap.put("createUser", eventInfo.getEventUser());
					bindMap.put("createTime", eventInfo.getEventTime());
					bindMap.put("holdState", "N");
					bindMap.put("packingState", "Created");// 标记Box是刚创建的
					materialPacking.setUserColumns(bindMap);
					MaterialPackingServiceProxy.getMaterialPackingService().create(
							eventInfo, materialPacking);
				}
				else
				{
					if(sqlResult.get(0).get("MATERIALSPECNAME").toString().equals(materialSpecName))
					{
						MaterialPacking  pallet=new MaterialPacking();
						MaterialPackingKey key =new MaterialPackingKey();
						key.setMaterialPackingName(palletID);
						key.setSiteName(siteName);
						Map<String, Object> bindMap = new HashMap<String, Object>();
						if(sqlResult.get(0).get("EXPIRINGDATE").toString().compareTo(EXPIRINGDATE)>0)
						{
							bindMap.put("expiringDate", Timestamp.valueOf(EXPIRINGDATE+" 00:00:00"));
						}
						bindMap.put("materialQuantity",String.valueOf(Double.valueOf(receiveQuantity)+ Double.valueOf(sqlResult.get(0).get("MATERIALQUANTITY").toString())));
						bindMap.put("erpLocation",
								erpLocation);
						bindMap.put("erpFactory", erpFactory);
						SetEventInfo setEventInfo=new SetEventInfo();
						setEventInfo.setUserColumns(bindMap);
						pallet=MaterialPackingServiceProxy.getMaterialPackingService().setEvent(key, eventInfo, setEventInfo);
					}
					else 
						throw new CustomException("FindDetailError","","");
				}
			}
			
			/**
			 * SMT入库的Box允许已经出库的相同料号的Box重复入库---wsq 2020.10.29
			 */
			String checkSql="SELECT STOCKSTATE,MATERIALSPECNAME  FROM MATERIALPACKING "
					+ " WHERE SITENAME=:SITENAME "
					+ " AND MATERIALPACKINGNAME=:MATERIALPACKINGNAME ";
			Map<String, String> bindMapQueryState = new HashMap<String, String>();
			bindMapQueryState.put("SITENAME", siteName);
			bindMapQueryState.put("MATERIALPACKINGNAME", materialPackingName);
			List<Map<String, Object>> materialPackingDetail = IDMFrameServiceProxy
					.getSqlTemplate()
					.queryForList(checkSql, bindMapQueryState);
			
			if(materialPackingDetail.size() > 0){
				if(materialPackingDetail.get(0).get("STOCKSTATE").equals("StockOut")
						&&materialPackingDetail.get(0).get("MATERIALSPECNAME").equals(materialSpecName)){
					MaterialPackingKey mpKey = new MaterialPackingKey();
					mpKey.setMaterialPackingName(materialPackingName);
					mpKey.setSiteName(siteName);
					MaterialPackingServiceProxy.getMaterialPackingService().delete(mpKey);
					log.info("Materialpacking:  " + materialPackingName + "  deleted for SMT Box ReStockIn");
				}
			}
			
			CreateInfo materialPacking = new CreateInfo();
			materialPacking.setMaterialPackingName(materialPackingName);
			materialPacking.setSiteName(siteName);
			materialPacking.setContentMaterialType("");
			materialPacking.setMaterialPackingType("Box");

			Map<String, Object> bindMap = new HashMap<String, Object>();
			bindMap.put("receiveActNo", receiveActNo);
			bindMap.put("receiveRequestName", receiveRequestName);
			bindMap.put("receiveRequestDetailName", poDetailName);

			bindMap.put("materialQuantity", receiveQuantity);
			bindMap.put("materialCreateQuantity", receiveQuantity);
			bindMap.put("packingState", "Created");// 标记Box是刚创建的
			EXPIRINGDATE=EXPIRINGDATE+" 00:00:00";
			bindMap.put("materialType", materialSpec.getMaterialType());
			bindMap.put("materialSpecName", materialSpecName);
			bindMap.put("stockState", "");
			bindMap.put("holdState", "N");
			bindMap.put("areaName", "");
			bindMap.put("createUser", eventInfo.getEventUser());
			bindMap.put("createTime", eventInfo.getEventTime());
			makeDate=makeDate+" 00:00:00";
			bindMap.put("makeDate", Timestamp.valueOf(makeDate));
			bindMap.put("erpLocation",
					erpLocation);
			bindMap.put("erpFactory", erpFactory);
			bindMap.put("stockInType", "Normal:"+moveType);
			bindMap.put("charge", materialReceiveRequestDetail.getCharge());//默认为空
			bindMap.put("supplierName", supplierName);
			bindMap.put("npFlag", NPFlag);
			bindMap.put("superMaterialPackingName", palletID);
			bindMap.put("expiringDate", Timestamp.valueOf(EXPIRINGDATE));

			materialPacking.setUserColumns(bindMap);
			eventInfo.setReasonCode("0001");
			eventInfo.setReasonCodeType(moveType);
			MaterialPackingServiceProxy.getMaterialPackingService().create(
					eventInfo, materialPacking);

			// 创建抬头

			CreateActDetailInfo createActDetailInfo = new CreateActDetailInfo();

			MaterialReceiveActDetailKey materialReceiveActDetailKey = new MaterialReceiveActDetailKey();
			materialReceiveActDetailKey.setSiteName(siteName);
			materialReceiveActDetailKey.setReceiveRequestName(receiveRequestName);
			materialReceiveActDetailKey.setReceiveRequestDetailName(poDetailName);
			materialReceiveActDetailKey.setReceiveActNO(receiveActNo);
			materialReceiveActDetailKey.setMakeDate(Timestamp.valueOf(makeDate));

			String sql = "SELECT * FROM materialreceiveactdetail "
					+ "WHERE sitename = :sitename AND receiveRequestName = :receiveRequestName and ReceiveRequestDetailName=:ReceiveRequestDetailName and receiveActNo=:receiveActNo"
					+ " and makeDate=:makeDate ";

			Map<String, Object> bindMap1 = new HashMap<String, Object>();
			bindMap1.put("sitename", siteName);
			bindMap1.put("receiveRequestName", receiveRequestName);
			bindMap1.put("ReceiveRequestDetailName", poDetailName);
			bindMap1.put("receiveActNo", receiveActNo);
			bindMap1.put("makeDate", Timestamp.valueOf(makeDate));

			List<Map<String, Object>> queryResult = IDMFrameServiceProxy
					.getSqlTemplate()
					.queryForList(sql, bindMap1);

			if (queryResult.size() == 0) {
				createActDetailInfo.setReceiveActNO(receiveActNo);
				createActDetailInfo.setReceiveRequestName(receiveRequestName);
				createActDetailInfo.setReceiveRequestDetailName(poDetailName);
				createActDetailInfo.setSiteName(siteName);

				// Date date1 = new Date();//获取当前时间
				// SimpleDateFormat sdf = new
				// SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				// String str = sdf.format(date1);//时间存储为字符串
				// System.out.println(str);
				createActDetailInfo.setMakeDate(Timestamp.valueOf(makeDate));
				createActDetailInfo.setReceiveQuantity(Double
						.parseDouble(receiveQuantity));
				Map<String, Object> bindMap3 = new HashMap<String, Object>();
				bindMap3.put("receiveActState", "Created");
				// bindMap3.put("receiveQuantity",
				// Double.parseDouble(receiveQuantity));
				createActDetailInfo.setUserColumns(bindMap3);

				MaterialReceiveRequestActDetailServiceProxy
						.getMaterialReceiveRequestActDetailService().create(
								eventInfo, createActDetailInfo);
			} else {
				ActDetailIncreaseInfo actDetailIncreaseInfo = new ActDetailIncreaseInfo();
				actDetailIncreaseInfo.setReceiveQuantity(Double
						.parseDouble(receiveQuantity));

				MaterialReceiveRequestActDetailServiceProxy
						.getMaterialReceiveRequestActDetailService()
						.increaseReceivedQuantity(materialReceiveActDetailKey,
								eventInfo, actDetailIncreaseInfo);
			}

			MakeDetailIncreaseReceivedInfo makeDetailIncreaseReceivedInfo = new MakeDetailIncreaseReceivedInfo();
			MaterialReceiveRequestDetailKey materialReceiveRequestDetailKey = new MaterialReceiveRequestDetailKey();
			materialReceiveRequestDetailKey
					.setReceiveRequestName(receiveRequestName);
			materialReceiveRequestDetailKey.setSiteName(siteName);
			materialReceiveRequestDetailKey
					.setReceiveRequestDetailName(poDetailName);

			makeDetailIncreaseReceivedInfo.setIncreaseQuantity(Double
					.parseDouble(receiveQuantity));

			ReceiveRequestDetailServiceProxy.getReceiveRequestDetailService()
					.increaseReceivedQuantity(materialReceiveRequestDetailKey,
							eventInfo, makeDetailIncreaseReceivedInfo);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			
			e.printStackTrace();
			throw e;
		}

	}
	
	//检查MessageName是否正确
		public String CheckMessageName_SMT(EventInfo eventInfo, Document message) throws Exception {
			Element headElem = message.getRootElement().getChild("Header");
			String MessageName=headElem.getChildText("MESSAGENAME");
			String checkresult="OK|0";

			if(MessageName.equals("SMTStockIn")){
				checkresult="messagename不正确！|ERROR";
				return checkresult;
			}
			return checkresult;
		}
		
		//检查shipRequestDetailName是否已收货
				public String CheckshipRequestDetail_SMT(EventInfo eventInfo, Document message) throws Exception {
					Element BodyElem = message.getRootElement().getChild("Body");
					String shipRequestDetailName=BodyElem.getChildText("SHIPREQUESTDETAILNAME");
					String siteName = BodyElem.getChildText("SITENAME");
					String areaname = BodyElem.getChildText("AREANAME");
					String checkresultShiprequest="OK|0";
					if(shipRequestDetailName.length()==0){
						checkresultShiprequest="出货流水号SHIPREQUESTDETAILNAME不可为空！|ERROR";
						return checkresultShiprequest;
					}
					
					String BOEFactory=System.getProperty("factory");
					if(BOEFactory.equals("B5")){
						//B5/tm1的SMT在sitename按照SMTsitename+-+B5/TM1
						String [] sitelist=siteName.split("\\-");
						siteName = sitelist[0];
						BOEFactory = sitelist[1];
					}
					
					String sqla="SELECT * FROM MATERIALRECEIVEREQUESTDETAIL "
							+ " WHERE SITENAME=:SITENAME "
							+ " AND RECEIVEREQUESTNAME=:RECEIVEREQUESTNAME "
							+ " AND RECEIVEDQUANTITY<>0";
					Map<String, Object> bindMap = new HashMap<String, Object>();
					bindMap.put("RECEIVEREQUESTNAME", shipRequestDetailName);
					bindMap.put("SITENAME", BOEFactory);
					log.info(sqla+"Parameter:"+shipRequestDetailName+"SITENAME:"+BOEFactory);
					
					List<Map<String, Object>> sqlResult
					= IDMFrameServiceProxy.getSqlTemplate().queryForList(sqla, bindMap);
					log.info("SQL查询结果包含内容数量："+sqlResult.size());
					if(sqlResult.size()>0){
						checkresultShiprequest="出货流水号:"+shipRequestDetailName+"BOE已收货，不可继续使用！|ERROR";
						return checkresultShiprequest;
					}
					
					if(BOEFactory.equals("B17")&&areaname.contains("成品")){
						String materialPackingName = BodyElem.getChildText("MATERIALPACKINGNAME");
						String[] materialPackingNameList = materialPackingName.split("\\|");
						String sqlCheckTray = "SELECT DISTINCT MATERIALPACKINGNAME FROM DURABLE "
								+ " WHERE SITENAME=:SITENAME "
								+ " AND MATERIALPACKINGNAME IN  (select regexp_substr(id, '[^|]+' ,1 ,rownum) id from (select  :MATERIALPACKINGNAME id from dual) a "
								+ "  connect by rownum- 1 <= length(regexp_replace(id, '[^|]+'))) ";
						Map<String, Object> bindMapCheckTray = new HashMap<String, Object>();
						bindMapCheckTray.put("MATERIALPACKINGNAME", materialPackingName);
						bindMapCheckTray.put("SITENAME", BOEFactory);
						log.info(sqlCheckTray+">>>>>>Parameter:"+materialPackingName+"SITENAME:"+BOEFactory);
						
						List<Map<String, Object>> sqlResultCheckTray
						= IDMFrameServiceProxy.getSqlTemplate().queryForList(sqlCheckTray, bindMapCheckTray); 
						if(sqlResultCheckTray.size()!=materialPackingNameList.length){
							String noTrayBox = "";
							for(int i=0;i<materialPackingNameList.length;i++){
								String sqlNoTrayBox = "SELECT DISTINCT MATERIALPACKINGNAME FROM DURABLE "
										+ " WHERE SITENAME=:SITENAME "
										+ " AND MATERIALPACKINGNAME = :MATERIALPACKINGNAME ";
								Map<String, Object> bindMapNoTrayBox = new HashMap<String, Object>();
								bindMapNoTrayBox.put("MATERIALPACKINGNAME", materialPackingNameList[i]);
								bindMapNoTrayBox.put("SITENAME", BOEFactory);
								List<Map<String, Object>> sqlResultNoTrayBox
								=IDMFrameServiceProxy.getSqlTemplate().queryForList(sqlNoTrayBox, bindMapNoTrayBox); 
								if(sqlResultNoTrayBox.size()==0){
									noTrayBox = noTrayBox+"/"+materialPackingNameList[i];
								}
								checkresultShiprequest=noTrayBox+">>该部分box尚未传输Tray使用信息！|ERROR";
							}
							
						}
						
					}
					return checkresultShiprequest;
				}
				//确认SMT使用的userID是否厂内已注册
			public String VerifySMTUser(Document message) throws Exception
			{
				String checkresultuser="OK|0";
				Element HeadElem = message.getRootElement().getChild("Header");
				String Userid=HeadElem.getChildText("EVENTUSER");
				String SiteName=HeadElem.getChildText("SITENAME");
				if(System.getProperty("factory").equals("B5")){
					//B5/tm1的SMT在sitename按照SMTsitename+-+B5/TM1
					String [] sitelist=SiteName.split("\\-");
					SiteName = sitelist[0];
				}
				
				String sqla="SELECT * FROM USERINFO WHERE SITENAME=:SITENAME "
						+ " AND USERID=:USERID ";
				Map<String, Object> bindMap = new HashMap<String, Object>();
				bindMap.put("SITENAME", SiteName);
				bindMap.put("USERID", Userid);
				
				List<Map<String, Object>> sqlResult
				= IDMFrameServiceProxy.getSqlTemplate().queryForList(sqla, bindMap);
				if(sqlResult.size()==0){
					checkresultuser="EVENTUSER未注册！|ERROR";
					return checkresultuser;
				}
				
				return checkresultuser;
			}
			
			public String checkSMTReceiveNo(Document message) throws Exception
			{
				String checkresultReceive="OK|0";
				Element BodyElem = message.getRootElement().getChild("Body");
				String SiteName=BodyElem.getChildText("SITENAME");
				String ReceiveNo=BodyElem.getChildText("RECEIVEACTNO");
				
				if(System.getProperty("factory").equals("B5")){
					//B5/tm1的SMT在sitename按照SMTsitename+-+B5/TM1
					String [] sitelist=SiteName.split("\\-");
					SiteName = sitelist[0];
				}
				
				
				String sqla="SELECT * FROM MATERIALSHIPREQUEST WHERE SYSTEMTYPE='OIC_SMT' AND CUSTOMERNO=:CUSTOMERNO AND SHIPREQUESTNAME=:SHIPREQUESTNAME ";
				Map<String, Object> bindMap = new HashMap<String, Object>();
				bindMap.put("CUSTOMERNO", SiteName);
				bindMap.put("SHIPREQUESTNAME", ReceiveNo);
				
				List<Map<String, Object>> sqlResult
				= IDMFrameServiceProxy.getSqlTemplate().queryForList(sqla, bindMap);
				if(sqlResult.size()==0){
					checkresultReceive="收货单据错误，请联系BOE人员！|ERROR";
					return checkresultReceive;
				}
				
				return checkresultReceive;
			}
			
			public String checkFlagForSMT(Document message) throws Exception
			{
				Element BodyElem = message.getRootElement().getChild("Body");
				String SMTFlag=BodyElem.getChildText("OTHER");
				String Flag = "Create";
				if(SMTFlag.equals("Delete")){
					Flag="Delete";
				}
				return Flag;
				
			}
			
			//smt收货删除Box
			public void PDADeleteBoxByLabelForPCBA(EventInfo eventInfo, String siteName,
					 String receiveRequestName,
					String materialPackingName, String materialSpecName,Document message) throws Exception {
				// 获取MaterialSpec信息
				Element bodyElem = message.getRootElement().getChild("Body");
				String poDetailName=bodyElem.getChildText("RECEIVEREQUESTDETAILNAME");
				String decreaseQuantity=bodyElem.getChildText("MATERIALQUANTITY");
				
				MaterialPackingKey deleteKeyInfoKey=new MaterialPackingKey();
				deleteKeyInfoKey.setMaterialPackingName(materialPackingName);
				deleteKeyInfoKey.setSiteName(siteName);
				IDMFrameServiceProxy.getTransactionManager().beginTransaction();
				MaterialPackingServiceProxy.getMaterialPackingService().delete(deleteKeyInfoKey);
				IDMFrameServiceProxy.getTransactionManager().commitTransaction();
				log.info(materialPackingName+" Deleted");
				
				
						//MakeDetailIncreaseReceivedInfo makeDetailIncreaseReceivedInfo = new MakeDetailIncreaseReceivedInfo();
						MakeDetailDecreaseReceivedInfo makeDetailDecreaseReceivedInfo=new MakeDetailDecreaseReceivedInfo();
						MaterialReceiveRequestDetailKey matetialShipRequestDetailKey = new MaterialReceiveRequestDetailKey();
						matetialShipRequestDetailKey
								.setReceiveRequestName(receiveRequestName);
						matetialShipRequestDetailKey.setSiteName(siteName);
						matetialShipRequestDetailKey
								.setReceiveRequestDetailName(poDetailName);
						//makeDetailIncreaseReceivedInfo.setIncreaseQuantity(Double
								//.parseDouble(receiveQuantity));
						makeDetailDecreaseReceivedInfo.setDecreaseQuantity(Double.parseDouble(decreaseQuantity));
						//ReceiveRequestDetailServiceProxy.getReceiveRequestDetailService()
							//	.increaseReceivedQuantity(matetialShipRequestDetailKey,eventInfo, makeDetailIncreaseReceivedInfo);
						IDMFrameServiceProxy.getTransactionManager().beginTransaction();
						ReceiveRequestDetailServiceProxy.getReceiveRequestDetailService()
						.decreaseReceivedQuantity(matetialShipRequestDetailKey, eventInfo, makeDetailDecreaseReceivedInfo);
						IDMFrameServiceProxy.getTransactionManager().commitTransaction();
						log.info("流水号："+receiveRequestName+"行项目："+poDetailName+"已接收数量修改完成");
				

			}
			
			public void UpdateMaterialPackingSMTERPInfo(String transactionID,String siteName,String Undoid,String Undoiddetailname) throws Exception{
				try{
					log.info("Start Update MATERIALPACKINGSMT WHERE transactionID IS :"+transactionID);
					String sqlUpdateSMT=" UPDATE MATERIALPACKINGSMT SET UNDOID=:UNDOID "
							+ " ,UNDODETAILNAME=:UNDODETAILNAME "
							+ " WHERE TRANSACTIONID=:TRANSACTIONID  "
							+ " AND SITENAME=:SITENAME ";
							//+ " AND MATERIALSPECNAME=:MATERIALSPECNAME";
					Map<String, String> bindMapmessage = new HashMap<String, String>();
					bindMapmessage.put("TRANSACTIONID", transactionID);
					bindMapmessage.put("SITENAME", siteName);
					bindMapmessage.put("UNDOID", Undoid);
					bindMapmessage.put("UNDODETAILNAME", Undoiddetailname);
					//bindMapmessage.put("MATERIALSPECNAME", newUnDoMaterialSpecName.get(i));
					//IDMFrameServiceProxy.getTransactionManager().beginTransaction();
					IDMFrameServiceProxy.getSqlTemplate().update(sqlUpdateSMT, bindMapmessage);
					//IDMFrameServiceProxy.getTransactionManager().commitTransaction();
					log.info("Update MATERIALPACKINGSMT WHERE transactionID IS :"+transactionID+"  Successful!");
				}
				catch(Exception e)
				{
					e.getMessage();
					throw e;
				}
				
			}
			
			public void UpdateMaterialpackingSMTHistory(String transactionID,String siteName,String Undoid,String Undoiddetailname) throws Exception{
				try{
					log.info("Start Update MATERIALPACKINGSMTHISTORY WHERE transactionID IS :"+transactionID);
					String sqlUpdateSMT=" UPDATE MATERIALPACKINGSMTHISTORY SET UNDOID=:UNDOID "
							+ " ,UNDODETAILNAME=:UNDODETAILNAME "
							+ " WHERE TRANSACTIONID=:TRANSACTIONID  "
							+ " AND SITENAME=:SITENAME ";
							//+ " AND MATERIALSPECNAME=:MATERIALSPECNAME";
					Map<String, String> bindMapmessage = new HashMap<String, String>();
					bindMapmessage.put("TRANSACTIONID", transactionID);
					bindMapmessage.put("SITENAME", siteName);
					bindMapmessage.put("UNDOID", Undoid);
					bindMapmessage.put("UNDODETAILNAME", Undoiddetailname);
					//bindMapmessage.put("MATERIALSPECNAME", newUnDoMaterialSpecName.get(i));
					//IDMFrameServiceProxy.getTransactionManager().beginTransaction();
					IDMFrameServiceProxy.getSqlTemplate().update(sqlUpdateSMT, bindMapmessage);
					//IDMFrameServiceProxy.getTransactionManager().commitTransaction();
					log.info("Update MATERIALPACKINGSMTHISTORY WHERE transactionID IS :"+transactionID+"  Successful!");
					
				}
				catch(Exception e)
				{
					e.getMessage();
					throw e;
				}
			}
	
			//SMT出库MesReceiveFlag直接置为Y，避免影响MES出库视图， added by wsq 19.3.11
			public void updateMaterialPackingStockOutForSMT(EventInfo eventInfo,
					String siteName, List<String> materialPackingKeyList,
					String stockState, String erpEventTime, String eventUser,
					String eventComment, String receiveActNo) throws Exception {
				try {
					String lastEventTimeKey = TimeStampUtil.getCurrentEventTimeKey();
					List<MaterialPackingKey> packingKeyList = new ArrayList<MaterialPackingKey>();
					Timestamp lastEventTime = new Timestamp(System.currentTimeMillis());
					SetEventInfo setEventInfo = new SetEventInfo();

					Map<String, Object> bindMap = new HashMap<String, Object>();
					CommonValidation cv = new CommonValidation();
					SimpleDateFormat wad = new SimpleDateFormat("yyyy-MM-dd");
					// Date erpTime= wad.parse(erpEventTime);
					erpEventTime = cv.getDate(erpEventTime) + " 00:00:00";
					Date date = new Date();
					date = wad.parse(cv.getDate(erpEventTime));

					bindMap.put("stockState", stockState);
					bindMap.put("erpEventTime", date);
					bindMap.put("shipTime", lastEventTime);
					bindMap.put("receiveActNo", receiveActNo);
					bindMap.put("locationName", "");
					bindMap.put("oldStockState", "Stocked");
					// bindMap.setLocationName("");

					setEventInfo.setUserColumns(bindMap);

					for (int i = 0; i < materialPackingKeyList.size(); i++) {

						MaterialPackingKey keyInfo = new MaterialPackingKey();
						keyInfo.setSiteName(siteName);
						keyInfo.setMaterialPackingName((String) materialPackingKeyList
								.get(i));
						MaterialPacking dataInfo = selectByKey(keyInfo);
//		                if(eventInfo.getEventName().equalsIgnoreCase("CompleteNPShipRequest"))
//		                {
//						  dataInfo.setStockState(stockState);
//		                }
						dataInfo.setShipTime(lastEventTime);
						dataInfo.setReceiveActNo(receiveActNo);
						dataInfo.setLocationName("");
						dataInfo.setErpEventTime(Timestamp.valueOf(erpEventTime));
						dataInfo.setLastEventName(eventInfo.getEventName());
						dataInfo.setLastEventComment(eventInfo.getEventComment());
						dataInfo.setLastEventTimeKey(lastEventTimeKey);
						dataInfo.setLastEventUser(eventInfo.getEventUser());
						dataInfo.setLastEventTime(eventInfo.getEventTime());
						dataInfo.setReasonCodeType(eventInfo.getReasonCodeType());
						dataInfo.setReasonCode(eventInfo.getReasonCode());
						dataInfo.setMesReceiveFlag("Y");
				        //dataInfo.setReceiptor(receiptor);
						MaterialPackingServiceProxy.getMaterialPackingService().update(
								dataInfo);

						// packingKeyList.add(keyInfo);

					}
					// 20160525，马兴华注释，保证出库只留一条历史记录，才用上面的Update方法
					// MaterialPackingServiceProxy.getMaterialPackingService().setEvent(packingKeyList,
					// eventInfo, setEventInfo);
				} catch (IDMFrameDBErrorSignal e) {
					e.printStackTrace();
				}
			}
			
			/*
			 * 新增方法-wsq2019.3.20
			 * */
			public void CreateBoxHistorySMTbatch(String boxName,String BOEFactory,String siteName) throws Exception {

				String sql=" INSERT INTO MATERIALPACKINGSMTHISTORY   "
						+" ( SITENAME                              "
						+" ,MATERIALPACKINGNAME                    "
						+" ,TIMEKEY                                "
						+" ,REASONCODETYPE                         "
						+" ,REASONCODE                             "
						+" ,MATERIALPACKINGTYPE                    "
						+" ,CONTENTMATERIALTYPE                    "
						+" ,MATERIALTYPE                           "
						+" ,MATERIALSPECNAME                       "
						+" ,SUPERMATERIALPACKINGNAME               "
						+" ,MAKEDATE                               "
						+" ,PACKINGGRADE                           "
						+" ,SUBPACKINGQUANTITY                     "
						+" ,MATERIALCREATEQUANTITY                 "
						+" ,MATERIALQUANTITY                       "
						+" ,OLDPACKINGSTATE                        "
						+" ,PACKINGSTATE                           "
						+" ,STOCKSTATE                             "
						+" ,OLDSTOCKSTATE                          "
						+" ,HOLDSTATE                              "
						+" ,AREANAME                               "
						+" ,LOCATIONNAME                           "
						+" ,DURABLENAME                            "
						+" ,MATERIALPROCESSGROUPNAME               "
						+" ,CREATETIME                             "
						+" ,CREATEUSER                             "
						+" ,RECEIVEREQUESTNAME                     "
						+" ,RECEIVEREQUESTDETAILNAME               "
						+" ,RECEIVEACTNO                           "
						+" ,RECEIVETIME                            "
						+" ,RECEIVEUSER                            "
						+" ,SHIPREQUESTNAME                        "
						+" ,SHIPREQUESTDETAILNAME                  "
						+" ,SHIPTIME                               "
						+" ,SHIPUSER                               "
						+" ,ERPLOCATION                            "
						+" ,ETCSTATE                               "
						+" ,ERPFACTORY                             "
						+" ,STOCKINTYPE                            "
						+" ,OQARESULTSTATE                         "
						+" ,OQARESULT                              "
						+" ,UNDOID                                 "
						+" ,SUPPLIERNAME                           "
						+" ,CHARGE                                 "
						+" ,UNDODETAILNAME                         "
						+" ,ERPEVENTTIME                           "
						+" ,EVENTNAME                              "
						+" ,EVENTTIME                              "
						+" ,EVENTUSER                              "
						+" ,EVENTCOMMENT                           "
						+" ,NPFLAG                                 "
						+" ,MESSAGEID                              "
						+" ,ERPSTATE                               "
						+" ,SAVEREASON                             "
						+" ,ENDDATE                                "
						+" ,SMTEVENTTIME                           "
						+ " ,TRANSACTIONID                      "
						+ " ,BOESITENAME                        "
						+ " )            "
						+" SELECT SITENAME                         "
						+" ,MATERIALPACKINGNAME                    "
						+" ,LASTEVENTTIMEKEY            "// 修改回原来的LASTEVENTTIMEKEY
						+" ,REASONCODETYPE                         "
						+" ,REASONCODE                             "
						+" ,MATERIALPACKINGTYPE                    "
						+" ,CONTENTMATERIALTYPE                    "
						+" ,MATERIALTYPE                           "
						+" ,MATERIALSPECNAME                       "
						+" ,SUPERMATERIALPACKINGNAME               "
						+" ,MAKEDATE                               "
						+" ,PACKINGGRADE                           "
						+" ,SUBPACKINGQUANTITY                     "
						+" ,MATERIALCREATEQUANTITY                 "
						+" ,MATERIALQUANTITY                       "
						+" ,OLDPACKINGSTATE                        "
						+" ,PACKINGSTATE                           "
						+" ,STOCKSTATE                             "
						+" ,OLDSTOCKSTATE                          "
						+" ,HOLDSTATE                              "
						+" ,AREANAME                               "
						+" ,LOCATIONNAME                           "
						+" ,DURABLENAME                            "
						+" ,MATERIALPROCESSGROUPNAME               "
						+" ,CREATETIME                             "
						+" ,CREATEUSER                             "
						+" ,RECEIVEREQUESTNAME                     "
						+" ,RECEIVEREQUESTDETAILNAME               "
						+" ,RECEIVEACTNO                           "
						+" ,RECEIVETIME                            "
						+" ,RECEIVEUSER                            "
						+" ,SHIPREQUESTNAME                        "
						+" ,SHIPREQUESTDETAILNAME                  "
						+" ,SHIPTIME                               "
						+" ,SHIPUSER                               "
						+" ,ERPLOCATION                            "
						+" ,ETCSTATE                               "
						+" ,ERPFACTORY                             "
						+" ,STOCKINTYPE                            "
						+" ,OQARESULTSTATE                         "
						+" ,OQARESULT                              "
						+" ,UNDOID                                 "
						+" ,SUPPLIERNAME                           "
						+" ,CHARGE                                 "
						+" ,UNDODETAILNAME                         "
						+" ,ERPEVENTTIME                           "
						+" ,LASTEVENTNAME                          "
						+" ,LASTEVENTTIME                          "
						+" ,LASTEVENTUSER                          "
						+" ,LASTEVENTCOMMENT                       "
						+" ,NPFLAG                                 "
						+" ,MESSAGEID                              "
						+" ,ERPSTATE                               "
						+" ,SAVEREASON                             "
						+" ,ENDDATE                                "
						+" ,SMTEVENTTIME                           "
						+ " ,TRANSACTIONID                         "
						+ ",BOESITENAME                            "
						+" FROM MATERIALPACKINGSMT                 "
						+" WHERE MATERIALPACKINGNAME  IN(select regexp_substr(id, '[^|]+' ,1 ,rownum) id from (select  :MATERIALPACKINGNAME id from dual) a  "
						+ " connect by rownum- 1 <= length(regexp_replace(id, '[^|]+'))) "
						+"  AND LASTEVENTTIMEKEY=(SELECT MAX(LASTEVENTTIMEKEY) FROM MATERIALPACKINGSMT  "
						+"  WHERE MATERIALPACKINGNAME IN(select regexp_substr(id, '[^|]+' ,1 ,rownum) id from (select  :MATERIALPACKINGNAME id from dual) a "
						+ " connect by rownum- 1 <= length(regexp_replace(id, '[^|]+'))) "
						+ " AND BOESITENAME=:BOESITENAME "
						+ " AND SITENAME=:SITENAME "
						+ " ) "
						+ " AND BOESITENAME=:BOESITENAME "
						+ " AND SITENAME=:SITENAME ";     
			
				Map<String, String> bindMap = new HashMap<String, String>();
				bindMap.put("MATERIALPACKINGNAME", boxName);
				bindMap.put("BOESITENAME", BOEFactory);
				bindMap.put("SITENAME", siteName);
				IDMFrameServiceProxy.getSqlTemplate().update(sql, bindMap);
			}
			
			//检查调料类型是否符合标准
			public String CheckTLType_SMT(EventInfo eventInfo, Document message) throws Exception {
				Element bodyElem = message.getRootElement().getChild("Body");
				Element headerElem = message.getRootElement().getChild("Header");
				String areaName=bodyElem.getChildText("AREANAME");
				String materialTypea=bodyElem.getChildText("MATERIALTYPE");
				String siteName=headerElem.getChildText("SITENAME");
				String materialType="";
				if(materialTypea==null){
					materialType=areaName;
				}
				else{
					materialType=materialTypea;
				}
				
				String BOEFactory=System.getProperty("factory");
				if(BOEFactory.equals("B5")){
					//B5/tm1的SMT在sitename按照SMTsitename+-+B5/TM1
					String [] sitelist=siteName.split("\\-");
					siteName = sitelist[0];
					BOEFactory = sitelist[1];
				}
				
				String checkresultTLType="OK|0";
				String sql="SELECT MATERIALTYPE FROM BS_SMT_ENUMDEF WHERE SITENAME=:SITENAME AND MATERIALTYPE=:MATERIALTYPE "
						+ " AND BOESITENAME=:BOESITENAME";
				Map<String, Object> bindMap = new HashMap<String, Object>();
				bindMap.put("SITENAME", siteName);
				bindMap.put("MATERIALTYPE", materialType);
				bindMap.put("BOESITENAME", BOEFactory);
				
				
				List<Map<String, Object>> sqlResult
				= IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, bindMap);
				if(sqlResult.size()==0){
					checkresultTLType="调料业务类型错误，请按照要求填写！|ERROR";
					return checkresultTLType;
				}
				return checkresultTLType;
			}
			
			//校验SMT调料入库单据
			public String CheckReceiveRequestSMTTLIN(EventInfo eventInfo,Document message){
				Element bodyElem = message.getRootElement().getChild("Body");
				String siteName=bodyElem.getChildText("SITENAME");
				String receiveRequestName=bodyElem.getChildText("RECEIVEREQUESTNAME");
				String materialSpecName = bodyElem.getChildText("MATERIALSPECNAME");
				String materialQuantity = bodyElem.getChildText("MATERIALQUANTITY");
				String[] materialSpecNameList = materialSpecName.split("\\|");
				String checkresultReceiverequest="OK|0";
				

				String BOEFactory=System.getProperty("factory");
				if(BOEFactory.equals("B5")){
					//B5/tm1的SMT在sitename按照SMTsitename+-+B5/TM1
					String [] sitelist=siteName.split("\\-");
					siteName = sitelist[0];
					BOEFactory = sitelist[1];
				}
				
				String sqlRequest=" SELECT RECEIVEREQUESTNAME FROM MATERIALRECEIVEREQUEST "
						+ " WHERE SITENAME=:SITENAME "
						+ " AND RECEIVEREQUESTNAME=:RECEIVEREQUESTNAME "
						+ " AND PURCHASEORDERGROUP=:PURCHASEORDERGROUP";
				Map<String, Object> bindMapRequest=new HashMap<String, Object>();
				bindMapRequest.put("SITENAME", BOEFactory);
				bindMapRequest.put("RECEIVEREQUESTNAME", receiveRequestName);
				bindMapRequest.put("PURCHASEORDERGROUP", siteName);
				List<Map<String, Object>> sqlResultRequest
				= IDMFrameServiceProxy.getSqlTemplate().queryForList(sqlRequest, bindMapRequest);
				log.info("单据查询结果："+sqlResultRequest.size());
				if(sqlResultRequest.size()==0){
					checkresultReceiverequest="该调料单号在调料到"+siteName+"的单号中不存在，请检查！！|ERROR";
					return checkresultReceiverequest;
				}
				
				//校验物料号是否都是可收货的物料号
				String checkSpecNum=" (select DISTINCT regexp_substr(id, '[^|]+' ,1 ,rownum) id from (select  :MATERIALSPECNAME id from dual) a "
						+ " connect by rownum- 1 <= length(regexp_replace(id, '[^|]+'))) ";
				Map<String, Object> bindMapSpec=new HashMap<String, Object>();
				bindMapSpec.put("MATERIALSPECNAME", materialSpecName);
				List<Map<String, Object>> sqlResultSpec
				= IDMFrameServiceProxy.getSqlTemplate().queryForList(checkSpecNum, bindMapSpec);
				log.info("物料号数量："+sqlResultSpec.size());
				
				String sqla="SELECT * FROM MATERIALRECEIVEREQUESTDETAIL WHERE SITENAME=:SITENAME "
						+ " AND RECEIVEREQUESTNAME=:RECEIVEREQUESTNAME "
						+ " AND MATERIALSPECNAME IN (select regexp_substr(id, '[^|]+' ,1 ,rownum) id from (select  :MATERIALSPECNAME id from dual) a  "
						+ "				 connect by rownum- 1 <= length(regexp_replace(id, '[^|]+'))) "
						+ "AND REQUESTQUANTITY>RECEIVEDQUANTITY ";
				Map<String, Object> bindMap = new HashMap<String, Object>();
				bindMap.put("RECEIVEREQUESTNAME", receiveRequestName);
				bindMap.put("SITENAME", BOEFactory);
				bindMap.put("MATERIALSPECNAME", materialSpecName);
				log.info(sqla+receiveRequestName+"SITENAME:"+BOEFactory+receiveRequestName+materialSpecName);
				
				List<Map<String, Object>> sqlResult
				= IDMFrameServiceProxy.getSqlTemplate().queryForList(sqla, bindMap);
				if(sqlResultSpec.size()!=sqlResult.size()){
					String receivedSpecName="";
					String notExitSpecName="";
					String checknotExitSpec="";
					for(int i=0;i<materialSpecNameList.length;i++){
						String sqlreceivedSpec="SELECT * FROM MATERIALRECEIVEREQUESTDETAIL WHERE SITENAME=:SITENAME "
								+ " AND RECEIVEREQUESTNAME=:RECEIVEREQUESTNAME "
								+ " AND MATERIALSPECNAME =:MATERIALSPECNAME "
								+ "AND REQUESTQUANTITY=RECEIVEDQUANTITY ";
						Map<String, Object> bindMapReceived = new HashMap<String, Object>();
						bindMapReceived.put("RECEIVEREQUESTNAME", receiveRequestName);
						bindMapReceived.put("SITENAME", BOEFactory);
						bindMapReceived.put("MATERIALSPECNAME", materialSpecNameList[i]);
						log.info(sqlreceivedSpec+"SITENAME"+BOEFactory+receiveRequestName+materialSpecNameList[i]);
						
						List<Map<String, Object>> sqlResultReceived
						= IDMFrameServiceProxy.getSqlTemplate().queryForList(sqlreceivedSpec, bindMapReceived);
						if(sqlResultReceived.size()>0){
							receivedSpecName=receivedSpecName+"/"+materialSpecNameList[i];
						}
						else{
							String sqlnotExitSpec="SELECT * FROM MATERIALRECEIVEREQUESTDETAIL WHERE SITENAME=:SITENAME "
									+ " AND RECEIVEREQUESTNAME=:RECEIVEREQUESTNAME "
									+ " AND MATERIALSPECNAME =:MATERIALSPECNAME ";
							Map<String, Object> bindMapnotExitSpec = new HashMap<String, Object>();
							bindMapnotExitSpec.put("RECEIVEREQUESTNAME", receiveRequestName);
							bindMapnotExitSpec.put("SITENAME", BOEFactory);
							bindMapnotExitSpec.put("MATERIALSPECNAME", materialSpecNameList[i]);
							log.info(sqlreceivedSpec+"SITENAME"+BOEFactory+receiveRequestName+materialSpecNameList[i]);
							
							List<Map<String, Object>> sqlResultnotExitSpec
							= IDMFrameServiceProxy.getSqlTemplate().queryForList(sqlnotExitSpec, bindMapnotExitSpec);
							if(sqlResultnotExitSpec.size()==0){
								notExitSpecName=notExitSpecName+"/"+materialSpecNameList[i];
							}
						}
						
					}
					checknotExitSpec=notExitSpecName+" >>>左侧料号不在调料单中！";
					checkresultReceiverequest=receivedSpecName+"/>>>左边物料号在该调料单中已全部收货，请检查调料单据！"+checknotExitSpec+"|ERROR";
					return checkresultReceiverequest;
				}
				
				//校验收货数量
				String sqlcheckReceiveSpec=" SELECT receivetemp.MATERIALSPECNAME,receivetemp.QTY,RECEIVEDETAIL.SITENAME,RECEIVEDETAIL.REQUESTQUANTITY,RECEIVEDETAIL.RECEIVEDQUANTITY FROM "
						+ " ((SELECT 	MATERIALSPECNAME,SUM(MATERIALQUANTITY) QTY FROM ( "
						+ " select A.MATERIALSPECNAME,B.MATERIALQUANTITY from "
						+ " (select DISTINCT regexp_substr(spec, '[^|]+' ,1 ,rownum) MATERIALSPECNAME,rownum as num from (select  :MATERIALSPECNAME spec from dual) "
						+ " 						 connect by rownum- 1 <= length(regexp_replace(spec, '[^|]+')))  a left JOIN "
						+ " (select DISTINCT regexp_substr(qty, '[^|]+' ,1 ,rownum) MATERIALQUANTITY,rownum as num from (select  :MATERIALQUANTITY qty from dual) "
						+ " 						 connect by rownum- 1 <= length(regexp_replace(qty, '[^|]+')))  b   ON  a.num=b.num) GROUP BY MATERIALSPECNAME) receivetemp LEFT JOIN "
						+ " (SELECT * FROM MATERIALRECEIVEREQUESTDETAIL WHERE RECEIVEREQUESTNAME=:RECEIVEREQUESTNAME AND SITENAME=:SITENAME) RECEIVEDETAIL ON receivetemp.MATERIALSPECNAME=RECEIVEDETAIL.MATERIALSPECNAME) ";
				Map<String, Object> bindMapReceiveSpec=new HashMap<String, Object>();
				bindMapReceiveSpec.put("SITENAME", BOEFactory);
				bindMapReceiveSpec.put("MATERIALSPECNAME", materialSpecName);
				bindMapReceiveSpec.put("MATERIALQUANTITY", materialQuantity);
				bindMapReceiveSpec.put("RECEIVEREQUESTNAME", receiveRequestName);
				log.info(sqlcheckReceiveSpec+">>>SITENAME:"+ BOEFactory+"MATERIALSPECNAME:"+materialSpecName+"MATERIALQUANTITY:"+materialQuantity+"RECEIVEREQUESTNAME:"+ receiveRequestName);
				List<Map<String, Object>> sqlResultReceiveSpec
				= IDMFrameServiceProxy.getSqlTemplate().queryForList(sqlcheckReceiveSpec, bindMapReceiveSpec);
				String SMTReceiveQty="";
				String requestQty="";
				String receivedQty="";
				for(int i=0;i<sqlResultReceiveSpec.size();i++){
					SMTReceiveQty=sqlResultReceiveSpec.get(i).get("QTY").toString();
					receivedQty=sqlResultReceiveSpec.get(i).get("RECEIVEDQUANTITY").toString();
					requestQty=sqlResultReceiveSpec.get(i).get("REQUESTQUANTITY").toString();
					if(Double.parseDouble(SMTReceiveQty)+Double.parseDouble(receivedQty)>Double.parseDouble(requestQty)){
						checkresultReceiverequest=sqlResultReceiveSpec.get(i).get("MATERIALSPECNAME").toString()+"料号收货数量超出可收货数量，请检查！！可收货总数量："+requestQty+"已收货数量："+receivedQty+"本次计划收货数量："+SMTReceiveQty+"|ERROR";
						return checkresultReceiverequest;
					}
				}
				
				return checkresultReceiverequest;
			}
			
			//校验SMT出库调料单据
			public String CheckReceiveRequestSMTTLOUT(EventInfo eventInfo,Document message){
				Element bodyElem = message.getRootElement().getChild("Body");
				String siteName=bodyElem.getChildText("SITENAME");
				String receiveRequestName=bodyElem.getChildText("RECEIVEREQUESTNAME");
				
				String BOEFactory=System.getProperty("factory");
				if(BOEFactory.equals("B5")){
					//B5/tm1的SMT在sitename按照SMTsitename+-+B5/TM1
					String [] sitelist=siteName.split("\\-");
					siteName = sitelist[0];
					BOEFactory = sitelist[1];
				}
				
				String checkresultReceiverequest="OK|0";
				if(receiveRequestName.length()==0){
					checkresultReceiverequest="出货调料单号RECEIVEREQUESTNAME不可为空！|ERROR";
					return checkresultReceiverequest;
				}
				if(!receiveRequestName.substring(0, 2).equals(siteName)){
					checkresultReceiverequest="调料单号第1~2位请正确填写调料发出SMT！！|ERROR";
					return checkresultReceiverequest;
				}
				
				String sqlSite="SELECT DESCRIPTION FROM SITE "
						+ " WHERE SITENAME=:SITENAME ";
				Map<String, Object> bindMapSite = new HashMap<String, Object>();
				bindMapSite.put("SITENAME", receiveRequestName.substring(4, 6));
				log.info(sqlSite+"RECEIVE SITENAME:"+receiveRequestName.substring(4, 6));
				List<Map<String, Object>> sqlResultSite
				= IDMFrameServiceProxy.getSqlTemplate().queryForList(sqlSite, bindMapSite);
				log.info("SQL查询结果包含内容数量："+sqlResultSite.size());
				if(sqlResultSite.size()==0){
					checkresultReceiverequest="调料单号第5~6位请正确填写调料目的SMT！！|ERROR";
					return checkresultReceiverequest;
				}
				
				String sqla="SELECT * FROM MATERIALRECEIVEREQUESTDETAIL "
						+ " WHERE SITENAME=:SITENAME "
						+ " AND RECEIVEREQUESTNAME=:RECEIVEREQUESTNAME "
						+ " AND RECEIVEDQUANTITY<>0";
				Map<String, Object> bindMap = new HashMap<String, Object>();
				bindMap.put("RECEIVEREQUESTNAME", receiveRequestName);
				bindMap.put("SITENAME", BOEFactory);
				log.info(sqla+">>>>"+receiveRequestName+"SITENAME:"+BOEFactory);
				
				List<Map<String, Object>> sqlResult
				= IDMFrameServiceProxy.getSqlTemplate().queryForList(sqla, bindMap);
				log.info("SQL查询结果包含内容数量："+sqlResult.size());
				if(sqlResult.size()>0){
					checkresultReceiverequest="调料单号:"+receiveRequestName+"已收货，不可继续使用！|ERROR";
					return checkresultReceiverequest;
				}
				return checkresultReceiverequest;
				
			}
			
			//SMT调料发货的物料号，流水单号，数量写入到materialreceiverequestdetail表中，便于收货比较
			public void CreateReceiveRequestforSMTTL(EventInfo eventInfo,Document message)
			{
				Element bodyElem = message.getRootElement().getChild("Body");
				String siteName=bodyElem.getChildText("SITENAME");
				String receiveRequestName=bodyElem.getChildText("RECEIVEREQUESTNAME");
				String materialspecName="";//物料号
				String requestQuantity="";//单个物料数量
				String supplierNO="";//供应商代码
				
				String BOEFactory=System.getProperty("factory");
				if(BOEFactory.equals("B5")){
					//B5/tm1的SMT在sitename按照SMTsitename+-+B5/TM1
					String [] sitelist=siteName.split("\\-");
					siteName = sitelist[0];
					BOEFactory = sitelist[1];
				}
				
				//获取流水号下物料号，数量
				String stockOutInfo="SELECT MATERIALSPECNAME,SUM(MATERIALQUANTITY) AS REQUESTQUANTITY  FROM   MATERIALPACKINGSMT " 
		                            +"WHERE SITENAME=:SITENAME AND RECEIVEREQUESTNAME=:RECEIVEREQUESTNAME AND STOCKSTATE='StockOut' "
		                            +" GROUP BY MATERIALSPECNAME "
		                            + " ORDER BY MATERIALSPECNAME DESC";
				
				Map<String, String> bindMap = new HashMap<String, String>();
				bindMap.put("SITENAME",siteName);
				bindMap.put("RECEIVEREQUESTNAME",receiveRequestName);
				List<Map<String, Object>> stockOutList =IDMFrameServiceProxy.getSqlTemplate().queryForList(stockOutInfo, bindMap);
				
				supplierNO="SMTTL";
				//插入materialreceiverequest和 detail表中
				//String factory =System.getProperty("factory");
				String WERKS = "";
				if(BOEFactory.equals("B4")) {
					WERKS = "1200";
				}
				else if(BOEFactory.equals("B3")){
					WERKS = "1100";
				 }
				else if(BOEFactory.equals("B5")){
					WERKS = "1300";
				 }
				else if(BOEFactory.equals("B8")) {
					 WERKS = "1800";
				 }
				else if(BOEFactory.equals("B10")) {
					 WERKS = "3020";
				 }
				else if(BOEFactory.equals("B9")){
					WERKS = "3010";
				}
				else if(BOEFactory.equals("TM1")) {
					WERKS = "1310";
				}
				else{
					
				}
				
				//查询SHIPREQUESTDETAILNAME是否已存在
				String sqla="SELECT * FROM MATERIALRECEIVEREQUEST WHERE RECEIVEREQUESTNAME=:RECEIVEREQUESTNAME "
						+ " AND SITENAME=:SITENAME";
				Map<String, Object> bindMapship = new HashMap<String, Object>();
				bindMapship.put("RECEIVEREQUESTNAME", receiveRequestName);
				bindMapship.put("SITENAME", BOEFactory);
				
				List<Map<String, Object>> sqlResult
				= IDMFrameServiceProxy.getSqlTemplate().queryForList(sqla, bindMapship);
				
				//receiveRequestName不存在，直接新建
				if(sqlResult.size()==0){
					CreateReceiveRequestInfo createInfo = new CreateReceiveRequestInfo();
					createInfo.setSiteName(BOEFactory);
					createInfo.setReceiveRequestName(receiveRequestName);
					createInfo.setReceiveRequestState("Created");
					createInfo.setSupplierNO(supplierNO);
					createInfo.setSystemType("OIC_SMT");
					createInfo.setReceiveRequestType(siteName);
					createInfo.setPurchaseOrderGroup(receiveRequestName.substring(4, 6));
					eventInfo.setEventName("WMSCreate");
					MaterialReceiveRequestServiceProxy.getMaterialReceiveRequestService().create(eventInfo, createInfo);
					
					for(int i=0;i<stockOutList.size();i++)
					{
						materialspecName=stockOutList.get(i).get("MATERIALSPECNAME").toString();
						requestQuantity=stockOutList.get(i).get("REQUESTQUANTITY").toString();
						MaterialReceiveRequestDetail mrd =new MaterialReceiveRequestDetail();
						MaterialReceiveRequestDetailKey mrdk=new MaterialReceiveRequestDetailKey();
						mrdk.setSiteName(BOEFactory);
						mrdk.setReceiveRequestName(receiveRequestName);
						mrdk.setReceiveRequestDetailName(String.valueOf(i+1));
						mrd.setKey(mrdk);					
						mrd.setReceiveRequestDetailType("0");
						mrd.setMaterialSpecName(materialspecName);
						mrd.setLastEventTime(eventInfo.getEventTime());
						mrd.setErpFactory(WERKS);//单据详情中增加ERP工厂
						mrd.setIqcFlag("X");//iqcflag置为X，发送tqms
						if(!requestQuantity.isEmpty())
							mrd.setRequestQuantity(Double.valueOf(requestQuantity));
						mrd.setReceivedQuantity(0);
						//新的单号，插入detail内容
						ReceiveRequestDetailServiceProxy.getReceiveRequestDetailService().insert(mrd);
						
					}
				}
				//SHIPREQUESTDETAILNAME存在，update
				else{
					//MaterialReceiveRequest updateInfo = new MaterialReceiveRequest();
					//updateInfo.setLastEventTime(eventInfo.getEventTime());
					//MaterialReceiveRequestServiceProxy.getMaterialReceiveRequestService().update(updateInfo);
					//判断已有行项目与已传过来的行项是否一致
					String sqldetail="SELECT MATERIALSPECNAME,REQUESTQUANTITY  FROM MATERIALRECEIVEREQUESTDETAIL "
							+ " WHERE RECEIVEREQUESTNAME=:RECEIVEREQUESTNAME "
							+ " ORDER BY MATERIALSPECNAME DESC";
					Map<String, Object> bindMapdetail = new HashMap<String, Object>();
					bindMapdetail.put("RECEIVEREQUESTNAME", receiveRequestName);
					
					List<Map<String, Object>> sqlResultdetail
					= IDMFrameServiceProxy.getSqlTemplate().queryForList(sqldetail, bindMapdetail);
					int a=stockOutList.size()-sqlResultdetail.size();
					//行项数量相同，update全部行项
					if(a==0){
						
						for(int i=0;i<stockOutList.size();i++)
						{
							materialspecName=stockOutList.get(i).get("MATERIALSPECNAME").toString();
							requestQuantity=stockOutList.get(i).get("REQUESTQUANTITY").toString();
							MaterialReceiveRequestDetail mrd =new MaterialReceiveRequestDetail();
							MaterialReceiveRequestDetailKey mrdk=new MaterialReceiveRequestDetailKey();
							mrdk.setSiteName(BOEFactory);
							mrdk.setReceiveRequestName(receiveRequestName);
							mrdk.setReceiveRequestDetailName(String.valueOf(i+1));
							mrd.setKey(mrdk);					
							mrd.setReceiveRequestDetailType("0");
							mrd.setMaterialSpecName(materialspecName);
							mrd.setLastEventTime(eventInfo.getEventTime());
							mrd.setErpFactory(WERKS);//单据详情中增加ERP工厂
							mrd.setIqcFlag("X");
							if(!requestQuantity.isEmpty())
								mrd.setRequestQuantity(Double.valueOf(requestQuantity));
							mrd.setReceivedQuantity(0);
							
							//已存在单号时且行项目与已有完全一样时，update receiverequestdetail内容
							ReceiveRequestDetailServiceProxy.getReceiveRequestDetailService().update(mrd);
						}
						
						
					}
					else{
						//行项数量不一样，update一样的行项目，新的行项目insert
						for(int i=0;i<sqlResultdetail.size();i++)
						{
							materialspecName=stockOutList.get(i).get("MATERIALSPECNAME").toString();
							requestQuantity=stockOutList.get(i).get("REQUESTQUANTITY").toString();
							MaterialReceiveRequestDetail mrd =new MaterialReceiveRequestDetail();
							MaterialReceiveRequestDetailKey mrdk=new MaterialReceiveRequestDetailKey();
							mrdk.setSiteName(BOEFactory);
							mrdk.setReceiveRequestName(receiveRequestName);
							mrdk.setReceiveRequestDetailName(String.valueOf(i+1));
							mrd.setKey(mrdk);					
							mrd.setReceiveRequestDetailType("0");
							mrd.setMaterialSpecName(materialspecName);
							mrd.setLastEventTime(eventInfo.getEventTime());
							mrd.setErpFactory(WERKS);//单据详情中增加ERP工厂
							mrd.setIqcFlag("X");
							if(!requestQuantity.isEmpty())
								mrd.setRequestQuantity(Double.valueOf(requestQuantity));
							mrd.setReceivedQuantity(0);
							
							//已存在单号时但是本次有新加行项目时，update receiverequestdetail中前一部分行项目内容
							ReceiveRequestDetailServiceProxy.getReceiveRequestDetailService().update(mrd);
						}
						
						for(int i=sqlResultdetail.size();i<stockOutList.size();i++)
						{
							materialspecName=stockOutList.get(i).get("MATERIALSPECNAME").toString();
							requestQuantity=stockOutList.get(i).get("REQUESTQUANTITY").toString();
							MaterialReceiveRequestDetail mrd =new MaterialReceiveRequestDetail();
							MaterialReceiveRequestDetailKey mrdk=new MaterialReceiveRequestDetailKey();
							mrdk.setSiteName(BOEFactory);
							mrdk.setReceiveRequestName(receiveRequestName);
							mrdk.setReceiveRequestDetailName(String.valueOf(i+1));
							mrd.setKey(mrdk);					
							mrd.setReceiveRequestDetailType("0");
							mrd.setMaterialSpecName(materialspecName);
							mrd.setLastEventTime(eventInfo.getEventTime());
							mrd.setErpFactory(WERKS);//单据详情中增加ERP工厂
							mrd.setIqcFlag("X");
							if(!requestQuantity.isEmpty())
								mrd.setRequestQuantity(Double.valueOf(requestQuantity));
							mrd.setReceivedQuantity(0);
							
							//已存在单号时但是本次有新加行项目时，update receiverequestdetail中前一部分行项目内容
							ReceiveRequestDetailServiceProxy.getReceiveRequestDetailService().insert(mrd);
						}
						
					}
				}
				
				
			}
			
			public void IncreaseSMTTLRequest(EventInfo eventInfo, Document message) throws Exception{
				
				Element bodyElement = message.getRootElement().getChild("Body");
				Element headElement = message.getRootElement().getChild("Header");
				String siteName=headElement.getChildText("SITENAME");
				String transactionID=headElement.getChildText("TRANSACTIONID");
				String receiveRequestName=bodyElement.getChildText("RECEIVEREQUESTNAME");
				String exceptionContent="调料单据操作异常，请联系BOE CIM人员查看处理！";
				
				String BOEFactory=System.getProperty("factory");
				if(BOEFactory.equals("B5")){
					//B5/tm1的SMT在sitename按照SMTsitename+-+B5/TM1
					String [] sitelist=siteName.split("\\-");
					siteName = sitelist[0];
					BOEFactory = sitelist[1];
				}
				
				try{
					String sql="SELECT MATERIALSPECNAME,RECEIVEREQUESTNAME,SUM(MATERIALQUANTITY) QUANTITY  "
							+ " FROM MATERIALPACKINGSMTHISTORY "
							+ " WHERE SITENAME=:SITENAME "
							+ " AND TRANSACTIONID=:TRANSACTIONID "
							+ " AND RECEIVEREQUESTNAME=:RECEIVEREQUESTNAME "
							+ " AND BOESITENAME=:BOESITENAME "
							+ " GROUP BY MATERIALSPECNAME,RECEIVEREQUESTNAME ";
					Map<String, Object> bindMap = new HashMap<String, Object>();
					bindMap.put("SITENAME", siteName);
					bindMap.put("TRANSACTIONID", transactionID);
					bindMap.put("RECEIVEREQUESTNAME", receiveRequestName);
					bindMap.put("BOESITENAME", BOEFactory);
					List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
							.getSqlTemplate()
							.queryForList(sql, bindMap);
					if(sqlResult.size()>0){
						for(int i=0;i<sqlResult.size();i++){
							
							String receiveQuantity=sqlResult.get(i).get("QUANTITY").toString();
							String sqla="SELECT RECEIVEREQUESTDETAILNAME FROM MATERIALRECEIVEREQUESTDETAIL "
									+ " WHERE RECEIVEREQUESTNAME=:RECEIVEREQUESTNAME "
									+ " AND MATERIALSPECNAME=:MATERIALSPECNAME "
									+ " AND SITENAME=:SITENAME ";
							Map<String, Object> bindMapa = new HashMap<String, Object>();
							bindMapa.put("SITENAME", BOEFactory);
							bindMapa.put("MATERIALSPECNAME", sqlResult.get(i).get("MATERIALSPECNAME"));
							bindMapa.put("RECEIVEREQUESTNAME", receiveRequestName);
							List<Map<String, Object>> sqlResulta = IDMFrameServiceProxy
									.getSqlTemplate()
									.queryForList(sqla, bindMapa);
							String poDetailName=sqlResulta.get(0).get("RECEIVEREQUESTDETAILNAME").toString();
							
							MakeDetailIncreaseReceivedInfo makeDetailIncreaseReceivedInfo = new MakeDetailIncreaseReceivedInfo();
							MaterialReceiveRequestDetailKey materialReceiveRequestDetailKey = new MaterialReceiveRequestDetailKey();
							materialReceiveRequestDetailKey
									.setReceiveRequestName(receiveRequestName);
							materialReceiveRequestDetailKey.setSiteName(BOEFactory);
							materialReceiveRequestDetailKey
									.setReceiveRequestDetailName(poDetailName);
				
							makeDetailIncreaseReceivedInfo.setIncreaseQuantity(Double
									.parseDouble(receiveQuantity));
				
							ReceiveRequestDetailServiceProxy.getReceiveRequestDetailService()
									.increaseReceivedQuantity(materialReceiveRequestDetailKey,
											eventInfo, makeDetailIncreaseReceivedInfo);
						}
					
					}
					else{
						throw new Exception(exceptionContent);
					}
				}
				catch(Exception e)
				{
					e.getMessage();
					throw new Exception(exceptionContent);
					//throw e;
				}			
				
				
			}
			
			//SMT仓库物料库存报表
			public void  CreateSMTWarehouseInventoryInfo(EventInfo eventInfo, Document message) throws Exception {
				Element headElem = message.getRootElement().getChild("Header");
				String siteName = headElem.getChildText("SITENAME");
				String eventTime=headElem.getChildText("EVENTTIME");
				String bOEOwner=headElem.getChildText("BOEOWNER");
				
				String BOEFactory=System.getProperty("factory");
				if(BOEFactory.equals("B5")){
					//B5/tm1的SMT在sitename按照SMTsitename+-+B5/TM1
					String [] sitelist=siteName.split("\\-");
					siteName = sitelist[0];
					BOEFactory = sitelist[1];
				}
				
				Element bodyElement = message.getRootElement().getChild("Body");
				String materialSpecName = bodyElement.getChildText("MATERIALSPECNAME");
				String materialQty = bodyElement.getChildText("MATERIALQUANTITY");
				String[] materialSpecNamelist = materialSpecName.split("\\|");
				String[] materialQtylist = materialQty.split("\\|");
				Map<String, String> bindMap = new HashMap<String, String>();
				
				for(int i=0;i<materialSpecNamelist.length;i++){
					String sqlInventoryCreat = "INSERT INTO SMT_WAREHOUSEINVENTORY  "
							+ "("
							+ "SITENAME                "
							+ ",MATERIALSPECNAME                 "
							+ ",MATERIALQUANTITY               "
							+ ",EVENTTIME                     "
							+ ",LASTEVENTTIME          "
							+ ",BOESITENAME         "
							+ ",BOEOWNER    "
							+ ")"
							+ " VALUES (               "
							+ " :SITENAME              "
							+ ",:MATERIALSPECNAME                "
							+ ",:MATERIALQUANTITY"
							+ ",to_date(:EVENTTIME,'yyyy-MM-dd HH24:mi:ss')  "
							+ ",SYSDATE                    "
							+ ",:BOESITENAME         "
							+ ",:BOEOWNER   "
							+ ")";
						    
					
			        bindMap.put("SITENAME",siteName);
					bindMap.put("MATERIALSPECNAME",materialSpecNamelist[i]);
					bindMap.put("MATERIALQUANTITY",materialQtylist[i]);
					bindMap.put("EVENTTIME",eventTime);
					bindMap.put("BOESITENAME",BOEFactory);
					bindMap.put("BOEOWNER", bOEOwner);
					
					IDMFrameServiceProxy.getSqlTemplate().update(sqlInventoryCreat, bindMap);
					log.info(materialSpecNamelist[i]+"Inventory INFO is created !");
				}
				
			}
			
			//SMT仓库物料库存报表校验物料号
			public String  CheckSMTWarehouseInventoryInfo(EventInfo eventInfo, Document message) throws Exception {
				Element headElem = message.getRootElement().getChild("Header");
				String siteName = headElem.getChildText("SITENAME");
				String eventTime=headElem.getChildText("EVENTTIME");
				String checkresultSpec="OK|0";
				String BOEFactory=System.getProperty("factory");
				if(BOEFactory.equals("B5")){
					//B5/tm1的SMT在sitename按照SMTsitename+-+B5/TM1
					String [] sitelist=siteName.split("\\-");
					siteName = sitelist[0];
					BOEFactory = sitelist[1];
				}
				
				Element bodyElement = message.getRootElement().getChild("Body");
				String materialSpecName = bodyElement.getChildText("MATERIALSPECNAME");
				String materialQty = bodyElement.getChildText("MATERIALQUANTITY");
				String[] materialSpecNamelist = materialSpecName.split("\\|");
				
				//消息中重复BOXID校验
				String checkSpecNum=" (select DISTINCT regexp_substr(id, '[^|]+' ,1 ,rownum) id from (select  :MATERIALSPECNAME id from dual) a "
						+ " connect by rownum- 1 <= length(regexp_replace(id, '[^|]+'))) ";
				Map<String, String> bindMapSpecNum = new HashMap<String, String>();
				bindMapSpecNum.put("MATERIALSPECNAME", materialSpecName);
				List<Map<String, Object>> sqlResultforSpecNum = IDMFrameServiceProxy
						.getSqlTemplate()
						.queryForList(checkSpecNum, bindMapSpecNum);
				if(sqlResultforSpecNum.size()<materialSpecNamelist.length){
					checkresultSpec="包含重复物料号，请检查后重新发送！|ERROR";
					return checkresultSpec;
				}
				
				//校验是否会存在主键冲突
				String checkPK="SELECT MATERIALSPECNAME FROM SMT_WAREHOUSEINVENTORY "
						+ " WHERE SITENAME=:SITENAME "
						+ " AND BOESITENAME=:BOESITENAME "
						+ " AND EVENTTIME=to_date(:EVENTTIME,'yyyy-MM-dd HH24:mi:ss') "
						+ " AND MATERIALSPECNAME IN (select regexp_substr(id, '[^|]+' ,1 ,rownum) id from (select  :MATERIALSPECNAME id from dual) a "
						+ "  connect by rownum- 1 <= length(regexp_replace(id, '[^|]+'))) ";
				Map<String, String> bindMapPK = new HashMap<String, String>();
				bindMapPK.put("MATERIALSPECNAME", materialSpecName);
				bindMapPK.put("SITENAME", siteName);
				bindMapPK.put("BOESITENAME", BOEFactory);
				bindMapPK.put("EVENTTIME", eventTime);
				List<Map<String, Object>> sqlResultforPK = IDMFrameServiceProxy
						.getSqlTemplate()
						.queryForList(checkPK, bindMapPK);
				if(sqlResultforPK.size()>0){
					String conflictedSpec="";
					for(int i=0;i<sqlResultforPK.size();i++){
						conflictedSpec=conflictedSpec+"/"+sqlResultforPK.get(i).get("MATERIALSPECNAME").toString();
					}
					checkresultSpec=conflictedSpec+"该部分物料号在报表时间："+eventTime+"中已传输，请检查后发送！|ERROR";
				}
				
				return checkresultSpec;
				
			}
			
			/***
			 * 校验Tray信息
			 * @param message
			 * @return
			 * @throws Exception
			 */
			public String checkSMTTray(Document message) throws Exception
			{
				Element headElem = message.getRootElement().getChild("Header");
				String siteName = headElem.getChildText("SITENAME");
				String eventTime=headElem.getChildText("EVENTTIME");
				Element body = message.getRootElement().getChild("Body");
				String trayName = body.getChildText("TRAYNAME");
				String[] trayList = trayName.split("\\|");
				String checkresultTray="OK|0";
				
				String BOEFactory=System.getProperty("factory");
				if(BOEFactory.equals("B5")){
					//B5/tm1的SMT在sitename按照SMTsitename+-+B5/TM1
					String [] sitelist=siteName.split("\\-");
					siteName = sitelist[0];
					BOEFactory = sitelist[1];
				}
				
				//消息中重复TrayID校验
				String checkTrayNum=" (select DISTINCT regexp_substr(id, '[^|]+' ,1 ,rownum) id from (select  :TRAYNAME id from dual) a "
						+ " connect by rownum- 1 <= length(regexp_replace(id, '[^|]+'))) ";
				Map<String, String> bindMapSpecNum = new HashMap<String, String>();
				bindMapSpecNum.put("TRAYNAME", trayName);
				List<Map<String, Object>> sqlResult1 = IDMFrameServiceProxy
						.getSqlTemplate()
						.queryForList(checkTrayNum, bindMapSpecNum);
				if(sqlResult1.size()<trayList.length){
					checkresultTray="包含重复TrayID，请检查后重新发送！|ERROR";
					return checkresultTray;
				}
				//检查是否存在boe不存在的TrayID
				String checkExitTray="SELECT DURABLENAME FROM DURABLE "
						+ " WHERE DURABLESPECNAME='PCBA' "
						+ " AND SITENAME = :SITENAME "
						+ " AND RECEIVESTATE = 'BOE' "
						+ " AND DURABLENAME IN (select regexp_substr(id, '[^|]+' ,1 ,rownum) id from (select  :TRAYNAME id from dual) a "
						+ "  connect by rownum- 1 <= length(regexp_replace(id, '[^|]+'))) ";
				Map<String, Object> bindMap = new HashMap<String, Object>();
				bindMap.put("TRAYNAME", trayName);
				bindMap.put("SITENAME", BOEFactory);
				List<Map<String, Object>> sqlResult2
				= IDMFrameServiceProxy.getSqlTemplate().queryForList(checkExitTray, bindMap);
				if(sqlResult2.size()<trayList.length){
					String notExitTray = "";
					String stateErrorTray = "";
					for(int i=0;i<trayList.length;i++){
						String checkNotExitTray="SELECT DURABLENAME FROM DURABLE "
								+ " WHERE DURABLESPECNAME='PCBA' "
								+ " AND SITENAME = :SITENAME "
								+ " AND DURABLENAME = :TRAYNAME  ";
						String checkStateErrorTray="SELECT DURABLENAME FROM DURABLE "
								+ " WHERE DURABLESPECNAME='PCBA' "
								+ " AND RECEIVESTATE = 'BOE' "
								+ " AND SITENAME = :SITENAME "
								+ " AND DURABLENAME = :TRAYNAME  ";
						Map<String, Object> bindMapNotExitTray = new HashMap<String, Object>();
						bindMapNotExitTray.put("TRAYNAME", trayList[i]);
						bindMapNotExitTray.put("SITENAME", BOEFactory);
						List<Map<String, Object>> sqlResultNotExitTray
						= IDMFrameServiceProxy.getSqlTemplate().queryForList(checkNotExitTray, bindMapNotExitTray);
						
						if(sqlResultNotExitTray.size()==0){
							notExitTray = notExitTray+"/"+trayList[i];
						}
						else{
							List<Map<String, Object>> sqlResultStateErrorTray
							= IDMFrameServiceProxy.getSqlTemplate().queryForList(checkStateErrorTray, bindMapNotExitTray);
							if(sqlResultStateErrorTray.size()==0){
								stateErrorTray = stateErrorTray+"/"+trayList[i];
							}
						}
						
					}
					notExitTray = notExitTray.length()==0 ? notExitTray : notExitTray.substring(1)+"为非BOE Tray，请联系BOE人员！";
					stateErrorTray = stateErrorTray.length()==0 ? stateErrorTray : stateErrorTray.substring(1)+"Tray已与其他未出货BOX绑定，请检查更换Tray！";
					checkresultTray=notExitTray+stateErrorTray+"|ERROR";
					return checkresultTray;
				}
				
				return checkresultTray;
			}
			
			/***
			 * 更新Durable中PCBA Tray
			 * @param eventInfo
			 * @param message
			 * @throws Exception
			 */
			public void updateDrablePCBATray(EventInfo eventInfo, Document message) throws Exception {
				String exceptionContent = "";
				try{
					Element headElement = message.getRootElement().getChild("Header");
					Element bodyElement = message.getRootElement().getChild("Body");
					String materialPackingName=headElement.getChildText("MATERIALPACKINGNAME");				
					String siteName = headElement.getChildText("SITENAME");
					String flag = headElement.getChildText("FLAG");
					String trayName = bodyElement.getChildText("TRAYNAME");
					String lastEventName = eventInfo.getEventComment();
					String lastEventUser = eventInfo.getEventUser();
					
					String BOEFactory=System.getProperty("factory");
					if(BOEFactory.equals("B5")){
						//B5/tm1的SMT在sitename按照SMTsitename+-+B5/TM1
						String [] sitelist=siteName.split("\\-");
						siteName = sitelist[0];
						BOEFactory = sitelist[1];
					}
					
					String sqlCheck = "SELECT DURABLENAME FROM DURABLE "
							+ " WHERE SITENAME=:SITENAME "
							+ " AND MATERIALPACKINGNAME=:MATERIALPACKINGNAME ";
					Map<String, String> bindMapCheck = new HashMap<String, String>();
					bindMapCheck.put("SITENAME", BOEFactory);
					bindMapCheck.put("MATERIALPACKINGNAME", materialPackingName);
					List<Map<String, Object>> sqlResult4Check = IDMFrameServiceProxy
							.getSqlTemplate()
							.queryForList(sqlCheck, bindMapCheck);
					
					//创建新的Tray信息
					if(flag.equals("0")){
						if(sqlResult4Check.size()>0){
							exceptionContent="该BOX Tray使用信息已经存在，不可重复创建！！";
							throw new Exception(exceptionContent);
						}
						else{
							String updatesql=" UPDATE DURABLE SET "
									+ " RECEIVESTATE=:RECEIVESTATE, "
									+ " LASTEVENTNAME=:LASTEVENTNAME, "
									+ " LASTEVENTTIME=SYSDATE, "
									+ " LASTEVENTUSER=:LASTEVENTUSER, "
									+ " MATERIALPACKINGNAME=:MATERIALPACKINGNAME"
									+ " WHERE SITENAME=:SITENAME "
									+ " AND DURABLENAME IN (select DISTINCT regexp_substr(id, '[^|]+' ,1 ,rownum) id from (select  :TRAYNAME id from dual) a "
									+ "  connect by rownum- 1 <= length(regexp_replace(id, '[^|]+'))) ";
							
							Map<String, String> bindMap = new HashMap<String, String>();
							bindMap.put("RECEIVESTATE", "SMTTOBOE");
							bindMap.put("LASTEVENTNAME", lastEventName);
							bindMap.put("LASTEVENTUSER", lastEventUser);
							bindMap.put("MATERIALPACKINGNAME", materialPackingName);
							bindMap.put("SITENAME", BOEFactory);
							bindMap.put("TRAYNAME", trayName);
							log.info("Finished>>>>>"+updatesql+"RECEIVESTATE:SMTTOBOE "+"MATERIALPACKINGNAME:  "+materialPackingName+"TRAYNAME"+trayName);
							
							IDMFrameServiceProxy.getSqlTemplate().update(updatesql, bindMap);
						}
					}
					else if(flag.equals("1")){
						if(sqlResult4Check.size()==0){
							exceptionContent="该BOX Tray使用信息尚未创建，请创建后修改！！";
							throw new Exception(exceptionContent);
						}
						else{
							String sqlClear = " UPDATE DURABLE SET "
									+ " RECEIVESTATE='BOE' "
									+ " ,MATERIALPACKINGNAME=''"
									+ " WHERE SITENAME=:SITENAME "
									+ " AND MATERIALPACKINGNAME=:MATERIALPACKINGNAME ";
							Map<String, String> bindMapClear = new HashMap<String, String>();
							bindMapClear.put("SITENAME", BOEFactory);
							bindMapClear.put("MATERIALPACKINGNAME", materialPackingName);
							IDMFrameServiceProxy.getSqlTemplate().update(sqlClear, bindMapClear);
							log.info("Cleared>>>>>"+"RECEIVESTATE:BOE "+"MATERIALPACKINGNAME:  "+materialPackingName);
							
							String updatesql=" UPDATE DURABLE SET "
									+ " RECEIVESTATE=:RECEIVESTATE, "
									+ " LASTEVENTNAME=:LASTEVENTNAME, "
									+ " LASTEVENTTIME=SYSDATE, "
									+ " LASTEVENTUSER=:LASTEVENTUSER, "
									+ " MATERIALPACKINGNAME=:MATERIALPACKINGNAME"
									+ " WHERE SITENAME=:SITENAME "
									+ " AND DURABLENAME IN (select DISTINCT regexp_substr(id, '[^|]+' ,1 ,rownum) id from (select  :TRAYNAME id from dual) a "
									+ "  connect by rownum- 1 <= length(regexp_replace(id, '[^|]+'))) ";
							
							Map<String, String> bindMap = new HashMap<String, String>();
							bindMap.put("RECEIVESTATE", "SMTTOBOE");
							bindMap.put("LASTEVENTNAME", lastEventName);
							bindMap.put("LASTEVENTUSER", lastEventUser);
							bindMap.put("MATERIALPACKINGNAME", materialPackingName);
							bindMap.put("SITENAME", BOEFactory);
							bindMap.put("TRAYNAME", trayName);
							log.info("Finished>>>>>"+updatesql+"RECEIVESTATE:SMTTOBOE "+"MATERIALPACKINGNAME:  "+materialPackingName);
							
							IDMFrameServiceProxy.getSqlTemplate().update(updatesql, bindMap);
						}
					}
					
				}
				catch(Exception e)
				{
					e.getMessage();
					throw new Exception(exceptionContent);
					//throw e;
				}
				
				
			}
			//校验SMT成品入库是否已有组件核销信息
			public String  CheckSMTComponentUsedInfo(EventInfo eventInfo, Document message) throws Exception {
				Element headElem = message.getRootElement().getChild("Header");
				String siteName = headElem.getChildText("SITENAME");
				String checkresultComponent="OK|0";
				String BOEFactory=System.getProperty("factory");
				if(BOEFactory.equals("B5")){
					//B5/tm1的SMT在sitename按照SMTsitename+-+B5/TM1
					String [] sitelist=siteName.split("\\-");
					siteName = sitelist[0];
					BOEFactory = sitelist[1];
				}
				
				Element bodyElement = message.getRootElement().getChild("Body");
				String materialPackingName=bodyElement.getChildText("MATERIALPACKINGNAME");
				String materialSpecName=bodyElement.getChildText("MATERIALSPECNAME");
				String[] materialPackingNameList = materialPackingName.split("\\|");
				
				//消息中重复BOXID校验
				String checkBoxNum=" SELECT DISTINCT MATERIALPACKINGNAME "
						+ " FROM SMT_COMPONENTUSEINFO "
						+ " WHERE SITENAME=:SITENAME "
						+ " AND BOESITENAME=:BOESITENAME "
						+ " AND MATERIALPACKINGNAME IN  (select DISTINCT regexp_substr(id, '[^|]+' ,1 ,rownum) id from (select  :MATERIALPACKINGNAME id from dual) a "
						+ "  connect by rownum- 1 <= length(regexp_replace(id, '[^|]+'))) "
						+ " AND MATERIALSPECNAME IN (select DISTINCT regexp_substr(id, '[^|]+' ,1 ,rownum) id from (select  :MATERIALSPECNAME id from dual) a "
						+ "  connect by rownum- 1 <= length(regexp_replace(id, '[^|]+'))) "
						+ " AND (VERIFICATIONFLAG <> 'used' OR VERIFICATIONFLAG IS NULL)  ";
				
				Map<String, String> bindMapBoxNum = new HashMap<String, String>();
				bindMapBoxNum.put("MATERIALPACKINGNAME", materialPackingName);
				bindMapBoxNum.put("SITENAME", siteName);
				bindMapBoxNum.put("BOESITENAME", BOEFactory);
				bindMapBoxNum.put("MATERIALSPECNAME", materialSpecName);
				
				log.info(checkBoxNum+siteName+BOEFactory+materialPackingName+materialSpecName);
				
				List<Map<String, Object>> sqlResultforBoxNum = IDMFrameServiceProxy
						.getSqlTemplate()
						.queryForList(checkBoxNum, bindMapBoxNum);
				
				if(sqlResultforBoxNum.size()<materialPackingNameList.length){
					
					String noUseInfoBox="";
					
					for(int i=0;i<materialPackingNameList.length;i++){
						String checkBoxNuma=" SELECT DISTINCT MATERIALPACKINGNAME "
								+ " FROM SMT_COMPONENTUSEINFO "
								+ " WHERE SITENAME=:SITENAME "
								+ " AND BOESITENAME=:BOESITENAME "
								+ " AND MATERIALPACKINGNAME=:MATERIALPACKINGNAME ";
						
						Map<String, String> bindMapBoxNuma = new HashMap<String, String>();
						bindMapBoxNuma.put("MATERIALPACKINGNAME", materialPackingNameList[i]);
						bindMapBoxNuma.put("SITENAME", siteName);
						bindMapBoxNuma.put("BOESITENAME", BOEFactory);
						
						List<Map<String, Object>> sqlResultforBoxNuma = IDMFrameServiceProxy
								.getSqlTemplate()
								.queryForList(checkBoxNuma, bindMapBoxNuma);
						
						if(sqlResultforBoxNuma.size()==0){
							noUseInfoBox=noUseInfoBox+"/"+materialPackingNameList[i];
						}
						
					}
					checkresultComponent=noUseInfoBox+"该部分box未传输组件使用情况！"+"|ERROR";
					return checkresultComponent;
					
				}
				
				return checkresultComponent;
				
			}
			
			//校验SMT成品入库类型
			public String  CheckSMTPCBAintype(EventInfo eventInfo, Document message) throws Exception {
				Element bodyElement = message.getRootElement().getChild("Body");
				String materialType=bodyElement.getChildText("MATERIALTYPE");
				String materialTypeforPCBA="";
				if(materialType.equals("成品返退")){
					materialTypeforPCBA="ReturnPcbaInfromBOE";
				}
				else if(materialType.equals("产线重工成品")){
					materialTypeforPCBA="ReturnPcbaInfromSMT";
				}
				else if(materialType.equals("正常成品")){
					materialTypeforPCBA="NormalPcbaIn";
				}
				else if(materialType.equals("1")){
					materialTypeforPCBA="NormalPcbaIn";
				}
				else{
					materialTypeforPCBA="MATERIALTYPE字段值为： "+materialType+"  传输错误！|ERROR";
				}
				return materialTypeforPCBA;
				
			}
	
			//需要核销部分的组件使用情况表中插入transactionID和核销flag
			public void updateComponentInfo(EventInfo eventInfo, Document message,String verificationFlag) throws Exception {
				Element bodyElement = message.getRootElement().getChild("Body");
				Element headElem = message.getRootElement().getChild("Header");
				String materialPackingName=bodyElement.getChildText("MATERIALPACKINGNAME");				
				String siteName = headElem.getChildText("SITENAME");
				String transactionid = headElem.getChildText("TRANSACTIONID");
				String BOEFactory=System.getProperty("factory");
				if(BOEFactory.equals("B5")){
					//B5/tm1的SMT在sitename按照SMTsitename+-+B5/TM1
					String [] sitelist=siteName.split("\\-");
					siteName = sitelist[0];
					BOEFactory = sitelist[1];
				}
				
				String updatesql=" UPDATE SMT_COMPONENTUSEINFO SET "
						+ " TRANSACTIONID=:TRANSACTIONID, "
						+ " VERIFICATIONFLAG=:VERIFICATIONFLAG  "
						+ " WHERE SITENAME=:SITENAME "
						+ " AND BOESITENAME=:BOESITENAME "
						+ " AND MATERIALPACKINGNAME IN (select DISTINCT regexp_substr(id, '[^|]+' ,1 ,rownum) id from (select  :MATERIALPACKINGNAME id from dual) a "
						+ "  connect by rownum- 1 <= length(regexp_replace(id, '[^|]+'))) "
						+ " AND TRANSACTIONID IS NULL ";
				if(verificationFlag.equals("used")){
					updatesql=" UPDATE SMT_COMPONENTUSEINFO SET "
							+ " TRANSACTIONID=:TRANSACTIONID, "
							+ " VERIFICATIONFLAG=:VERIFICATIONFLAG  "
							+ " WHERE SITENAME=:SITENAME "
							+ " AND BOESITENAME=:BOESITENAME "
							+ " AND MATERIALPACKINGNAME IN (select DISTINCT regexp_substr(id, '[^|]+' ,1 ,rownum) id from (select  :MATERIALPACKINGNAME id from dual) a "
							+ "  connect by rownum- 1 <= length(regexp_replace(id, '[^|]+'))) "
							+ " AND TRANSACTIONID = :TRANSACTIONID ";
				}
				
				Map<String, String> bindMap = new HashMap<String, String>();
				bindMap.put("SITENAME", siteName);
				bindMap.put("BOESITENAME", BOEFactory);
				bindMap.put("MATERIALPACKINGNAME", materialPackingName);
				bindMap.put("TRANSACTIONID", transactionid);
				bindMap.put("VERIFICATIONFLAG", verificationFlag);
				log.info(updatesql+"materialPackingName: "+materialPackingName+"transactionid:  "+transactionid+"verificationFlag: "+verificationFlag+"SMT: "+siteName+"BOE: "+BOEFactory);
				
				IDMFrameServiceProxy.getSqlTemplate().update(updatesql, bindMap);
				
			}
			
			//将物料号组成消息，后面按照PCBA物料号做循环
			public Document GenerateSMTPCBASpecmsg(EventInfo eventInfo, Document message) throws Exception {
				Element bodyElement = message.getRootElement().getChild("Body");
				Element headElem = message.getRootElement().getChild("Header");
				String materialSpecName = bodyElement.getChildText("MATERIALSPECNAME");
				
				String checkSpecNum=" (select DISTINCT regexp_substr(id, '[^|]+' ,1 ,rownum) id from (select  :MATERIALSPECNAME id from dual) a "
						+ " connect by rownum- 1 <= length(regexp_replace(id, '[^|]+'))) ";
				Map<String, String> bindMapSpecNum = new HashMap<String, String>();
				bindMapSpecNum.put("MATERIALSPECNAME", materialSpecName);
				List<Map<String, Object>> sqlResultforSpecNum = IDMFrameServiceProxy
						.getSqlTemplate()
						.queryForList(checkSpecNum, bindMapSpecNum);
				
				Document materialspecMessage = SMessageUtil.createERPXmlDocument("MATERIALSPECLIST","");
				String nodePath = "//Message/Body";
				Element parentElement = JdomUtils.getNode(materialspecMessage, nodePath);
				
				for(int i=0;i<sqlResultforSpecNum.size();i++){
					Element childElement=new Element("item");
					parentElement.addContent(childElement);
					SMessageUtil.createElement(nodePath, childElement, "MATERIALSPECNAME", sqlResultforSpecNum.get(i).get("ID").toString());
				}

				String replyMSG = JdomUtils.toString(materialspecMessage);
				log.info("materialspeclist:>>"+replyMSG);
				return materialspecMessage;
				
			}
			
			//B17 MDL MES接收载具后更新durable表
			public void saveMDLReceivedCarrierInfo(EventInfo eventInfo,String siteName,String durableName,String durableState,String shiprequestName){
				String lastEventName = eventInfo.getEventComment();
				String lastEventUser = eventInfo.getEventUser();
				
					String updatesql = "UPDATE DURABLE SET "
							+ " DURABLESTATE=:DURABLESTATE, "
							+ " LASTEVENTNAME=:LASTEVENTNAME, "
							+ " LASTEVENTTIME=SYSDATE, "
							+ " LASTEVENTUSER=:LASTEVENTUSER "
							+ " WHERE SITENAME=:SITENAME "
							+ " AND DURABLENAME=:DURABLENAME ";
					
					MaterialShipRequestKey keyInfo=new MaterialShipRequestKey(siteName, shiprequestName);
					//MaterialShipRequest selectByKey = selectByKey(keyInfo);
					
					MaterialShipRequestSetEventInfo setEventInfo= new MaterialShipRequestSetEventInfo();
					
					Map<String, Object> bindMap1 = new HashMap<String, Object>();
					bindMap1.put("mesReceiveFlag", "Y");
					setEventInfo.setUserColumns(bindMap1);
					
					//selectByKey.setLastEventTime(eventTime);
					MaterialShipRequestServiceProxy.getMaterialShipRequestService().setEvent(keyInfo, eventInfo, setEventInfo);
					
					Map<String, String> bindMap = new HashMap<String, String>();
					bindMap.put("SITENAME", siteName);
					bindMap.put("DURABLENAME", durableName);
					bindMap.put("DURABLESTATE", durableState);
					bindMap.put("LASTEVENTNAME", lastEventName);
					bindMap.put("LASTEVENTUSER", lastEventUser);
				if(!shiprequestName.startsWith("L")){
					IDMFrameServiceProxy.getSqlTemplate().update(updatesql, bindMap);
				}
				
			}
			
			//B17取消出货发送消息
			public Document GenerateCarrierIDmsg(String siteName,String requestName) throws Exception {

				String sql=" SELECT DURABLENAME FROM DURABLE WHERE SITENAME=:SITENAME AND SHIPREQUESTNAME=:SHIPREQUESTNAME ";
				Map<String, String> bindMap = new HashMap<String, String>();
				bindMap.put("SITENAME", siteName);
				bindMap.put("SHIPREQUESTNAME", requestName);
				List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
						.getSqlTemplate()
						.queryForList(sql, bindMap);
				
				Document message = SMessageUtil.createERPXmlDocument("CancelShipToMDLMaterialReport","");
				String nodePath = "//Message/Body";
				Element parentElement = JdomUtils.getNode(message, nodePath);
				for(int i=0;i<sqlResult.size();i++){
					Element childElement=new Element("CARRIERLIST");
					parentElement.addContent(childElement);
					SMessageUtil.createElement(nodePath, childElement, "CARRIERID", sqlResult.get(i).get("DURABLENAME").toString());
				}

				String replyMSG = JdomUtils.toString(message);
				log.info("toMESCancelMessage:>>"+replyMSG);
				return message;
				
			}
			//20190625-hf
			public void updateMaterialPackingForErplocationChanged(List<MaterialUnDoinfo> materialUnDoinfoList,
					EventInfo eventInfo,String receiveActNo,String shiprequestName,String erpEventTime) throws Exception {
				
				

				try {
					String locationSql="select distinct ERPRECEIVELOCATION from materialshiprequest where SHIPREQUESTNAME=:shiprequestName  ";
					String sql_sel = "SELECT MATERIALPACKINGNAME,SITENAME FROM MATERIALPACKING  where UNDODETAILNAME=:seq and RECEIVEACTNO = :receiveActNo";
				
					String sql2 = insertUnDOMaterialPackingInfo_v3
							+ "select P.SITENAME,P.MATERIALPACKINGNAME,P.LASTEVENTTIMEKEY FROM MATERIALPACKING P WHERE P.UNDODETAILNAME=:seq and P.RECEIVEACTNO = :receiveActNo )	";
					Map<String, Object> bmap = new HashMap<String, Object>();
					bmap.put("shiprequestName", shiprequestName);
					List<Map<String, Object>> locationResult = IDMFrameServiceProxy
							.getSqlTemplate()
							.queryForList(locationSql, bmap);
					String erpreceiveLocation=locationResult.get(0).get("ERPRECEIVELOCATION").toString();//移库目的库位
					String seq="";
					CommonValidation cv = new CommonValidation();
					SimpleDateFormat wad = new SimpleDateFormat("yyyy-MM-dd");
					erpEventTime = cv.getDate(erpEventTime) + " 00:00:00";
					Date date = new Date();
					date = wad.parse(cv.getDate(erpEventTime));
					for (int i = 0; i < materialUnDoinfoList.size(); i++) {
						Map<String, Object> bindMap = new HashMap<String, Object>();
						Map<String, Object> bindMap1 = new HashMap<String, Object>();
						if(materialUnDoinfoList.get(i).getUnDoID().equalsIgnoreCase("0000")||materialUnDoinfoList.get(i).getUnDoID().equalsIgnoreCase("0000")){
							continue;
						}
						if(materialUnDoinfoList.get(i).getSeq().length()>15)
						{
							seq=materialUnDoinfoList.get(i).getSeq().substring(15);
							bindMap1.put("seq", seq);
						}
						else
						{
							seq=materialUnDoinfoList.get(i).getSeq();
							bindMap1.put("seq", seq);
						}
						
						bindMap1.put("receiveActNo", receiveActNo);
						log.info("seq:"+seq+" receiveActNo:"+receiveActNo);
						List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
								.getSqlTemplate()
								.queryForList(sql_sel, bindMap1);
						List<MaterialPackingKey> materialPackingKeyList = new ArrayList<MaterialPackingKey>();
						for (int j = 0; j < sqlResult.size(); j++) {
							MaterialPackingKey keyInfo = new MaterialPackingKey();
							keyInfo.setMaterialPackingName(sqlResult.get(j)
									.get("MATERIALPACKINGNAME").toString());
							keyInfo.setSiteName(sqlResult.get(j).get("SITENAME")
									.toString());
							materialPackingKeyList.add(keyInfo);
						}
						SetEventInfo setEventInfo = new SetEventInfo();
						Map<String, Object> bindMap2 = new HashMap<String, Object>();
						bindMap2.put("unDoDetailName", materialUnDoinfoList.get(i)
								.getUnDoDetailName());
						bindMap2.put("unDoID", materialUnDoinfoList.get(i).getUnDoID());
						bindMap2.put("erpState", "SUCCESS");
						bindMap2.put("erpLocation", erpreceiveLocation);
						bindMap2.put("LASTEVENTNAME", eventInfo.getEventName());
						bindMap2.put("LASTEVENTCOMMENT", eventInfo.getEventComment());
						bindMap2.put("LASTEVENTUSER", eventInfo.getEventUser());
						bindMap2.put("LASTEVENTTIMEKEY", eventInfo.getEventTime());
						bindMap2.put("LASTEVENTTIME", date);
						bindMap2.put("REASONCODE", eventInfo.getReasonCode());
						bindMap2.put("REASONCODETYPE", eventInfo.getReasonCodeType());
						bindMap2.put("SHIPREQUESTNAME", "");
						bindMap2.put("SHIPREQUESTDETAILNAME", "");
						setEventInfo.setUserColumns(bindMap2);
						
						bindMap.put("unDoDetailName", materialUnDoinfoList.get(i)
								.getUnDoDetailName());
						bindMap.put("unDoID", materialUnDoinfoList.get(i).getUnDoID());
						if(materialUnDoinfoList.get(i).getSeq().length()>15)
						{
							bindMap.put("seq", materialUnDoinfoList.get(i).getSeq().substring(15));
						}
						else
						{
							bindMap.put("seq", materialUnDoinfoList.get(i).getSeq());
						}
						bindMap.put("UNDOIDDATE", materialUnDoinfoList.get(i)
								.getUnDoIdDate());
						bindMap.put("receiveActNo", receiveActNo);
						bindMap.put("LASTEVENTNAME", eventInfo.getEventName());
						bindMap.put("LASTEVENTCOMMENT", eventInfo.getEventComment());
						
						
						int count=IDMFrameServiceProxy.getSqlTemplate()
								.update(sql2, bindMap);
						MaterialPackingServiceProxy.getMaterialPackingService()
								.setEvent(materialPackingKeyList, eventInfo,
										setEventInfo);
					}
					
				} catch (IDMFrameDBErrorSignal ex) {
					log.error(ex, ex);
					throw ex;
				} catch (NotFoundSignal ex) {
					log.error(ex, ex);
					throw ex;
				}
			}	
			
			//生成发送ship to mes消息
			public Document GenerateShipToMESmsg(String siteName,String shipRequestName,String replySubJectName) throws Exception {
				
				String sql=" SELECT DISTINCT DURABLENAME FROM MATERIALPACKING "
						+ " WHERE SITENAME=:SITENAME AND SHIPREQUESTNAME=:SHIPREQUESTNAME ";
				Map<String, String> bindMap = new HashMap<String, String>();
				bindMap.put("SITENAME", siteName);
				bindMap.put("SHIPREQUESTNAME", shipRequestName);
				
				List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
						.getSqlTemplate()
						.queryForList(sql, bindMap);
				
				Document shiptoMESMessage = SMessageUtil.createMESXmlDocument("ShipToMDLMaterialReport",replySubJectName);
				String nodePath = "//Message/Body";
				Element parentElement = JdomUtils.getNode(shiptoMESMessage, nodePath);
				SMessageUtil.createElement(nodePath,parentElement, "INVOICENO", shipRequestName);
				Element childElementA=new Element("CARRIERLIST");
				parentElement.addContent(childElementA);
				for(int i=0;i<sqlResult.size();i++){
					Element childElement=new Element("CARRIER");
					childElementA.addContent(childElement);
					SMessageUtil.createElement(nodePath, childElement, "CARRIERID", sqlResult.get(i).get("DURABLENAME").toString());
				}

				String replyMSG = JdomUtils.toString(shiptoMESMessage);
				log.info("shiptoMESMessage:>>"+replyMSG);
				return shiptoMESMessage;
				
			}
			
			//生成发送ship to mes消息 For B20
			public Document GenerateShipToMESMsgForB20(String siteName,String shipRequestName,String replySubJectName) throws Exception {
				
				String sql="SELECT m.MATERIALPACKINGNAME, m.MATERIALSPECNAME, m.MATERIALQUANTITY, m.MAKEDATE, m.CHARGE, m.EXPIRINGDATE FROM MATERIALPACKING m "
						+ "WHERE m.SITENAME = :SITENAME AND m.SHIPREQUESTNAME = :SHIPREQUESTNAME";
				Map<String, String> bindMap = new HashMap<String, String>();
				bindMap.put("SITENAME", siteName);
				bindMap.put("SHIPREQUESTNAME", shipRequestName);
				
				List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
						.getSqlTemplate()
						.queryForList(sql, bindMap);
				
				Document shiptoMESMessage = SMessageUtil.createMESXmlDocument("CallMaterialSend",replySubJectName);
				String nodePath = "//Message/Body";
				Element parentElement = JdomUtils.getNode(shiptoMESMessage, nodePath);
				SMessageUtil.createElement(nodePath,parentElement, "SHIPREQUESTNAME", shipRequestName);
				SMessageUtil.createElement(nodePath,parentElement, "COMMENT", "");
				Element childElementA=new Element("CONSUMABLELIST");
				parentElement.addContent(childElementA);
				
				SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
				
				for(int i=0;i<sqlResult.size();i++){
					
					Date makeDate = sdf.parse(sqlResult.get(i).get("MAKEDATE").toString());
					String makeDateStr = sdf.format(makeDate) + "000000";
					
					Date expiringDate = sdf.parse(sqlResult.get(i).get("EXPIRINGDATE").toString());
					String expringDateStr = sdf.format(expiringDate) + "000000";
					
					Element childElement=new Element("CONSUMABLE");
					childElementA.addContent(childElement);
					SMessageUtil.createElement(nodePath, childElement, "CONSUMABLENAME", sqlResult.get(i).get("MATERIALPACKINGNAME").toString());
					SMessageUtil.createElement(nodePath, childElement, "CONSUMABLESPECNAME", sqlResult.get(i).get("MATERIALSPECNAME").toString());
					SMessageUtil.createElement(nodePath, childElement, "QUANTITY", sqlResult.get(i).get("MATERIALQUANTITY").toString());
					SMessageUtil.createElement(nodePath, childElement, "MAKEDATE", makeDateStr);
					SMessageUtil.createElement(nodePath, childElement, "BATCHNUMBER", sqlResult.get(i).get("CHARGE") == null ? "" : sqlResult.get(i).get("CHARGE").toString());
					SMessageUtil.createElement(nodePath, childElement, "DUEDATE", expringDateStr);
				}

				String replyMSG = JdomUtils.toString(shiptoMESMessage);
				log.info("shiptoMESMessage:>>"+replyMSG);
				return shiptoMESMessage;
				
			}
			
			//生成发送ship to FAB mes消息
			public Document GenerateShipToFABMESmsg(String siteName,String shipRequestName,String replySubJectName) throws Exception {
				
				String sql=" SELECT B.SHIPREQUESTDETAILNAME, "
						+ "    B.MATERIALSPECNAME, "
						+ "    B.REQUESTQUANTITY, "
						+ "    B.ASSIGNEDQUANTITY, "
						+ "    A.RECEIVER "
						+ "    FROM MATERIALSHIPREQUEST A,MATERIALSHIPREQUESTDETAIL B "
						+ "    WHERE A.SITENAME=:SITENAME "
						+ "        AND A.SHIPREQUESTNAME=:SHIPREQUESTNAME "
						+ "        AND A.SHIPREQUESTNAME=B.SHIPREQUESTNAME ";
				Map<String, String> bindMap = new HashMap<String, String>();
				bindMap.put("SITENAME", siteName);
				bindMap.put("SHIPREQUESTNAME", shipRequestName);
				
				List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
						.getSqlTemplate()
						.queryForList(sql, bindMap);
				
				Document shiptoMESMessage = SMessageUtil.createMESXmlDocument("CallMaterialReceived",replySubJectName);
				String nodePath = "//Message/Body";
				Element parentElement = JdomUtils.getNode(shiptoMESMessage, nodePath);
				SMessageUtil.createElement(nodePath,parentElement, "SHIPREQUESTNAME", shipRequestName);
				Element childElementA=new Element("MATERIALLIST");
				parentElement.addContent(childElementA);
				for(int i=0;i<sqlResult.size();i++){
					SMessageUtil.createElement(nodePath, childElementA, "SHIPREQUESTDETAIL", sqlResult.get(i).get("SHIPREQUESTDETAILNAME").toString());
					SMessageUtil.createElement(nodePath, childElementA, "MATERIALSPEC", sqlResult.get(i).get("MATERIALSPECNAME").toString());
					SMessageUtil.createElement(nodePath, childElementA, "REQUESTQUANTITY", sqlResult.get(i).get("REQUESTQUANTITY").toString());
					SMessageUtil.createElement(nodePath, childElementA, "RECEIVEQUANTITY", sqlResult.get(i).get("ASSIGNEDQUANTITY").toString());
					SMessageUtil.createElement(nodePath, childElementA, "RECEIVER", sqlResult.get(i).get("RECEIVER").toString());
				}

				String replyMSG = JdomUtils.toString(shiptoMESMessage);
				log.info("shiptoMESMessage:>>"+replyMSG);
				return shiptoMESMessage;
				
			}
			
			public void updateSMTPackingCancel(EventInfo eventinfo,String siteName,String receiveRequestType,String receiveRequestName)throws Exception {
				String sqlupdatePacking=" UPDATE MATERIALPACKINGSMT SET "
						+ " STOCKSTATE='Stocked',SHIPREQUESTDETAILNAME='',LASTEVENTNAME=:EVENTNAME "
						+ " WHERE SITENAME=:SITENAME "
						+ " AND BOESITENAME=:BOESITENAME "
						+ " AND SHIPREQUESTDETAILNAME=:SHIPREQUESTDETAILNAME "
						+ " AND STOCKSTATE='StockOut' ";
				String sqlupdateHistory=" UPDATE MATERIALPACKINGSMTHISTORY SET "
						+ " STOCKSTATE='Stocked',SHIPREQUESTDETAILNAME='',EVENTNAME=:EVENTNAME "
						+ " WHERE SITENAME=:SITENAME "
						+ " AND BOESITENAME=:BOESITENAME "
						+ " AND SHIPREQUESTDETAILNAME=:SHIPREQUESTDETAILNAME "
						+ " AND STOCKSTATE='StockOut' ";
				Map<String, String> bindMap = new HashMap<String, String>();
				bindMap.put("SITENAME", receiveRequestType);
				bindMap.put("BOESITENAME", siteName);
				bindMap.put("SHIPREQUESTDETAILNAME", receiveRequestName);
				bindMap.put("EVENTNAME", eventinfo.getEventName());
				IDMFrameServiceProxy.getSqlTemplate().update(sqlupdatePacking, bindMap);
				IDMFrameServiceProxy.getSqlTemplate().update(sqlupdateHistory, bindMap);
				log.info("materialpackingsmt&materialpackingsmthistory Updated Successful!!");
				
			}
			
			public void deleteSMTReceiveRequest(EventInfo eventInfo,String siteName,String receiveRequestType,String receiveRequestName) throws Exception{
				MaterialReceiveRequestKey key = new MaterialReceiveRequestKey();

				key.setSiteName(siteName);
				key.setReceiveRequestName(receiveRequestName);

				RemoveReceiveRequestInfo info = new RemoveReceiveRequestInfo();

				MaterialReceiveRequestServiceProxy.getMaterialReceiveRequestService()
						.remove(key, eventInfo, info);
				
				String sql=" SELECT RECEIVEREQUESTDETAILNAME FROM materialreceiverequestdetail"
						+ " WHERE SITENAME=:SITENAME AND RECEIVEREQUESTNAME=:RECEIVEREQUESTNAME ";
				Map<String, String> bindMap = new HashMap<String, String>();
				bindMap.put("SITENAME", siteName);
				bindMap.put("RECEIVEREQUESTNAME", receiveRequestName);
				
				List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
						.getSqlTemplate()
						.queryForList(sql, bindMap);
				for(int i=0;i<sqlResult.size();i++){
					
					MaterialReceiveRequestDetailKey detailKey = new MaterialReceiveRequestDetailKey();
					
					detailKey.setSiteName(siteName);
					detailKey.setReceiveRequestName(receiveRequestName);
					detailKey.setReceiveRequestDetailName(sqlResult.get(i).get("RECEIVEREQUESTDETAILNAME").toString());
					
					RemoveRequestDetailInfo detailInfo = new RemoveRequestDetailInfo();
					
					ReceiveRequestDetailServiceProxy.getReceiveRequestDetailService().remove(detailKey, eventInfo, detailInfo);
				}
				
			}
			
	//校验物料是否拒收		
	public void checkLimitedSpec(EventInfo eventInfo, String siteName,
			String receiveQty, String receiveRequestName,
			String receiveRequestDetailName,String shipRequestName, String shipRequestDetailName, String materialSpecName, String receiveActno,String flag) throws Throwable
	{

		boolean limitFlag=false;
		String createSql="select * from MATERIALLIMITSPEC where SITENAME=:SITENAME and  MATERIALSPECNAME=:MATERIALSPECNAME ";
		Map<String, Object> createMap = new HashMap<String, Object>();
		createMap.put("SITENAME", siteName);
		createMap.put("MATERIALSPECNAME", materialSpecName);
		
		List<Map<String, Object>> checkResult
		= IDMFrameServiceProxy.getSqlTemplate().queryForList(createSql, createMap);
		if(checkResult.size()>0)limitFlag=true;
		if (!receiveRequestName.equals("")
				&& !receiveRequestDetailName.equals("")&&limitFlag) {
			String sql="select LIMITEDQUANTITY-RECEIVEDQUANTITY AS leftQty from MATERIALLIMITSPEC where SITENAME=:SITENAME and  MATERIALSPECNAME=:MATERIALSPECNAME ";
			Map<String, Object> bindMap = new HashMap<String, Object>();
			bindMap.put("SITENAME", siteName);
			bindMap.put("MATERIALSPECNAME", materialSpecName);
			
			List<Map<String, Object>> sqlResult
			= IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, bindMap);
			Double leftQty=Double.parseDouble(sqlResult.get(0).get("leftQty").toString());
			Double receivedQty=Double.parseDouble(receiveQty);
			if(receivedQty>leftQty)
			{
				//oic端创建box会先生成抬头行项目和接收数量绑定，不创建box需要还原
				if("delete".equals(flag)){
				MakeDetailDecreaseReceivedInfo makeDetailDecreaseReceivedInfo = new MakeDetailDecreaseReceivedInfo();
			MaterialReceiveRequestDetailKey materialReceiveRequestDetailKey = new MaterialReceiveRequestDetailKey();
			materialReceiveRequestDetailKey
					.setReceiveRequestName(receiveRequestName);
			materialReceiveRequestDetailKey.setSiteName(siteName);
			materialReceiveRequestDetailKey
					.setReceiveRequestDetailName(receiveRequestDetailName);

			makeDetailDecreaseReceivedInfo.setDecreaseQuantity(receivedQty);

			ReceiveRequestDetailServiceProxy.getReceiveRequestDetailService()
					.decreaseReceivedQuantity(materialReceiveRequestDetailKey,
							eventInfo, makeDetailDecreaseReceivedInfo);
			
			   //删除行项目抬头
				String deleteDetailSql="delete materialreceiveactDETAIL WHERE receiverequestname=:receiverequestname and receiverequestdetailname=:receiverequestdetailname "
                +" and SITENAME=:siteName and RECEIVEACTNO=:receiveActno";
				Map<String, Object> deleteMap = new HashMap<String, Object>();
				deleteMap.put("receiverequestname", receiveRequestName);
				deleteMap.put("receiverequestdetailname", receiveRequestDetailName);
				deleteMap.put("siteName", siteName);
				deleteMap.put("receiveActno", receiveActno);
			IDMFrameServiceProxy.getSqlTemplate().update(deleteDetailSql, deleteMap);
				}
				throw new CustomException("ReceivedQuantityError","");
				
			}else{
				bindMap.put("receivedQty", receiveQty);
				String updateSql="update MATERIALLIMITSPEC set RECEIVEDQUANTITY=RECEIVEDQUANTITY+:receivedQty where SITENAME=:SITENAME and  MATERIALSPECNAME=:MATERIALSPECNAME ";
				
				IDMFrameServiceProxy.getSqlTemplate().update(updateSql, bindMap);
			}	
			
			
		} else if (!shipRequestName.equals("")&& !shipRequestDetailName.equals("")&&limitFlag) {
		       try{
		    	   String usrSql = "SELECT queryString FROM BS_CustomQuery WHERE queryId = ? and version = ? ";
					String[] args = new String[] { "CheckDetailType", "00001" };
								
					List<Map<String, Object>> resultList = IDMFrameServiceProxy.getSqlTemplate().queryForList(
					usrSql, args);
					
					Map<String, Object> queryMap = resultList.get(0);
					String dbSql = queryMap.get("queryString").toString();
					dbSql = dbSql.replaceFirst(";\\s*$", "");
					
					Map<String, Object> bindMap1 = new HashMap<String, Object>();
					bindMap1.put("SITENAME", siteName);
					bindMap1.put("SHIPREQUESTNAME", shipRequestName);
					
					List<Map<String, Object>> sqlR
					= IDMFrameServiceProxy.getSqlTemplate().queryForList(dbSql, bindMap1);
					//需要限制收货数量
		    	  if(sqlR.size()>0){
		    		  
		    		  String sql="select LIMITEDQUANTITY-RECEIVEDQUANTITY AS leftQty from MATERIALLIMITSPEC where SITENAME=:SITENAME and  MATERIALSPECNAME=:MATERIALSPECNAME ";
		  			Map<String, Object> bindMap = new HashMap<String, Object>();
		  			bindMap.put("SITENAME", siteName);
		  			bindMap.put("MATERIALSPECNAME", materialSpecName);
		  			
		  			List<Map<String, Object>> sqlResult
		  			= IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, bindMap);
		  			Double leftQty=Double.parseDouble(sqlResult.get(0).get("leftQty").toString());
		  			Double receivedQty=Double.parseDouble(receiveQty);
		  			if(receivedQty>leftQty)
		  			{
		  			//oic端创建box会先生成抬头行项目和接收数量绑定，不创建box需要还原
					 if("delete".equals(flag)){
		  				//删除行项目已经接收的数量
		  				MakeShipDetailDecreaseAssignedInfo makeShipDetailDecreaseAssignedInfo = new MakeShipDetailDecreaseAssignedInfo();
		  				MaterialShipRequestDetailKey materialShipRequestDetailKey = new MaterialShipRequestDetailKey();
		  				materialShipRequestDetailKey.setShipRequestName(shipRequestName);
		  				materialShipRequestDetailKey.setSiteName(siteName);
		  				materialShipRequestDetailKey
		  						.setShipRequestDetailName(shipRequestDetailName);
		  				makeShipDetailDecreaseAssignedInfo
		  						.setAssignedQuantity(receivedQty);
		  				MaterialShipRequestDetailServiceProxy
  						.getMaterialShipRequestDetailService().decreaseAssignedQuantity(materialShipRequestDetailKey, makeShipDetailDecreaseAssignedInfo);
		  				//删除行项目抬头
		  				String deleteDetailSql="delete materialreceiveactDETAIL WHERE receiverequestname=:receiverequestname and receiverequestdetailname=:receiverequestdetailname "
                            +" and SITENAME=:siteName and RECEIVEACTNO=:receiveActno";
		  				Map<String, Object> deleteMap = new HashMap<String, Object>();
		  				deleteMap.put("receiverequestname", shipRequestName);
		  				deleteMap.put("receiverequestdetailname", shipRequestDetailName);
		  				deleteMap.put("siteName", siteName);
		  				deleteMap.put("receiveActno", receiveActno);
						IDMFrameServiceProxy.getSqlTemplate().update(deleteDetailSql, deleteMap);
						}
		  				throw new CustomException("ReceivedQuantityError","");
		  			}else{
		  				bindMap.put("receivedQty", receiveQty);
						String updateSql="update MATERIALLIMITSPEC set RECEIVEDQUANTITY=RECEIVEDQUANTITY+:receivedQty where SITENAME=:SITENAME and  MATERIALSPECNAME=:MATERIALSPECNAME ";
						
						IDMFrameServiceProxy.getSqlTemplate().update(updateSql, bindMap);
					}		
		    		  
		    	  } 
		    } catch(Throwable e) {
					
					throw e;
			}
		}
	  }		
	
public void SMTChangeQualityStatus( EventInfo eventInfo,String materialPackingName,
		String sqeComment,String siteName,Document message) 
				throws Exception {
		
		try {

			Element headElem = message.getRootElement().getChild("Header");
			String transactionID=headElem.getChildText("TRANSACTIONID");
			String eventTime=headElem.getChildText("EVENTTIME");
			
			String BOEFactory=System.getProperty("factory");
			if(BOEFactory.equals("B5")){
				//B5/tm1的SMT在sitename按照SMTsitename+-+B5/TM1
				String [] sitelist=siteName.split("\\-");
				siteName = sitelist[0];
				BOEFactory = sitelist[1];
			}
			
			String update_Sql = " UPDATE MATERIALPACKINGSMT SET LASTEVENTNAME=:LASTEVENTNAME "
					+ " ,LASTEVENTTIMEKEY=:LASTEVENTTIMEKEY "
					+ " ,LASTEVENTCOMMENT=:LASTEVENTCOMMENT "
					+ " ,LASTEVENTUSER=:LASTEVENTUSER "
					+ " ,LASTEVENTTIME=sysdate "
					+ " ,OQARESULT=:OQARESULT "
					+ " ,SMTEVENTTIME=:SMTEVENTTIME "
					+ " ,TRANSACTIONID=:TRANSACTIONID "
					+ " WHERE SITENAME=:SITENAME "
					+ " AND BOESITENAME=:BOESITENAME "
					+ " AND MATERIALPACKINGNAME IN (select regexp_substr(id, '[^|]+' ,1 ,rownum) id from (select  :MATERIALPACKINGNAME id from dual) a  "
					+ " 	 connect by rownum- 1 <= length(regexp_replace(id, '[^|]+'))) "
					+ " AND OQARESULT=:OLDOQARESULT  ";
			
			Map<String, String> bindMap = new HashMap<String, String>();
	        bindMap.put("LASTEVENTNAME",eventInfo.getEventName());
			bindMap.put("MATERIALPACKINGNAME",materialPackingName);
			bindMap.put("LASTEVENTTIMEKEY",TimeStampUtil.getCurrentEventTimeKey());
			bindMap.put("SMTEVENTTIME",eventTime);                                      //smt实际操作时间
			bindMap.put("LASTEVENTUSER",eventInfo.getEventUser());
			bindMap.put("LASTEVENTCOMMENT",eventInfo.getEventComment());
			bindMap.put("TRANSACTIONID", transactionID);
			bindMap.put("SITENAME",siteName);
			bindMap.put("BOESITENAME", BOEFactory);
			bindMap.put("OQARESULT", sqeComment.substring(4));
			bindMap.put("OLDOQARESULT", sqeComment.substring(0,2));
			
			log.info(sqeComment.substring(0,2)+">>>"+sqeComment.substring(4));

			IDMFrameServiceProxy.getSqlTemplate().update(update_Sql,bindMap);
			CreateBoxHistorySMTbatch(materialPackingName,BOEFactory,siteName);
			
			
		} 
		catch(Exception e)
		{
			e.getMessage();
			throw e;
		}
	}

	public String checkStorageStatus (EventInfo eventInfo,String materialPackingName,
			String sqeComment,String siteName,String materialSpecName)
					throws Exception{
		
		String checkResult="";
		String [] materialPackingNameList = materialPackingName.split("\\|"); 
		String [] materialSpecNameList = materialSpecName.split("\\|");
		
		if(materialPackingNameList.length>50){
			checkResult="一次修改BOX状态数量请不要超过50个|ERROR";
			return checkResult;
		}
		
		if(materialSpecNameList.length != materialPackingNameList.length){
			checkResult="物料号数量与BoxID数量不符！！|ERROR";
			return checkResult;
		}
		
		
		String BOEFactory=System.getProperty("factory");
		if(BOEFactory.equals("B5")){
			//B5/tm1的SMT在sitename按照SMTsitename+-+B5/TM1
			String [] sitelist=siteName.split("\\-");
			siteName = sitelist[0];
			BOEFactory = sitelist[1];
		}
		

		String check_Sql = " SELECT MATERIALPACKINGNAME FROM MATERIALPACKINGSMT WHERE SITENAME=:SITENAME "
				+ " AND BOESITENAME=:BOESITENAME "
				+ " AND STOCKSTATE='Stocked' "
				+ " AND OQARESULT=:OQARESULT "
				+ " AND MATERIALPACKINGNAME IN (select regexp_substr(id, '[^|]+' ,1 ,rownum) id from (select  :MATERIALPACKINGNAME id from dual) a "
				+ "	 connect by rownum- 1 <= length(regexp_replace(id, '[^|]+'))) "
				+ " AND MATERIALSPECNAME IN  (select regexp_substr(id, '[^|]+' ,1 ,rownum) id from (select  :MATERIALSPECNAME id from dual) a "
				+ "	 connect by rownum- 1 <= length(regexp_replace(id, '[^|]+'))) ";
		Map<String, String> bindMap = new HashMap<String, String>();
		bindMap.put("SITENAME", siteName);
		bindMap.put("BOESITENAME", BOEFactory);
		bindMap.put("MATERIALPACKINGNAME", materialPackingName);
		bindMap.put("MATERIALSPECNAME", materialSpecName);
		if(sqeComment.equals("OKToNG")){
			bindMap.put("OQARESULT", "OK");
		}
		else{
			bindMap.put("OQARESULT", "NG");
		}
		
		List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
				.getSqlTemplate()
				.queryForList(check_Sql, bindMap);
		if(sqlResult.size()>0 && sqlResult.size()==materialPackingNameList.length){
			checkResult="OK|0";
		}
		else if(sqlResult.size()>0 && sqlResult.size()!=materialPackingNameList.length){
			
			String errorBox = "";
			for(int i=0;i<materialPackingNameList.length;i++){
				
				String check_Sql1 = " SELECT MATERIALPACKINGNAME FROM MATERIALPACKINGSMT WHERE SITENAME=:SITENAME "
						+ " AND BOESITENAME=:BOESITENAME "
						+ " AND STOCKSTATE='Stocked' "
						+ " AND OQARESULT=:OQARESULT "
						+ " AND MATERIALPACKINGNAME=:MATERIALPACKINGNAME "
						+ " AND MATERIALSPECNAME=:MATERIALSPECNAME ";
				Map<String, String> bindMap1 = new HashMap<String, String>();
				bindMap1.put("SITENAME", siteName);
				bindMap1.put("BOESITENAME", BOEFactory);
				bindMap1.put("MATERIALPACKINGNAME", materialPackingNameList[i]);
				bindMap1.put("MATERIALSPECNAME", materialSpecNameList[i]);
				if(sqeComment.equals("OKToNG")){
					bindMap1.put("OQARESULT", "OK");
				}
				else{
					bindMap1.put("OQARESULT", "NG");
				}
				
				List<Map<String, Object>> sqlResult1 = IDMFrameServiceProxy
						.getSqlTemplate()
						.queryForList(check_Sql1, bindMap1);
				if(sqlResult1.size()==0){
					errorBox+="/"+errorBox;
				}
			}
			checkResult=errorBox+"该部分box未找到符合需要修改状态的库存，请检查！|ERROR";
		}
		else{
			checkResult="该部分box均为找到，请检查需要修改的状态是否正确！|ERROR";
		}

		return checkResult;
	}

	/*
	 * Name : updateERPLocationForB2 Desc : This function is updateERPLocationForB2 Author : boe cim
	 * dev. Date : 2019.08.21
	 */
	public static void updateERPLocationForB2(String erpLocation,String erpPoName,String receiveRequestDetailname,String siteName) throws CustomException {
		
		String erpLocationname = erpLocation==null?"":erpLocation;	
		String receiveRequestdetail = receiveRequestDetailname ==null?"":receiveRequestDetailname;
		String receiveRequestName = erpPoName ==null?"":erpPoName;
		String sitename = siteName==null?"":siteName;
		String sql = "UPDATE materialreceiverequestdetail a set a.ERPLOCATION=:erpLocationname where a.RECEIVEREQUESTNAME =:receiveRequestName and a.RECEIVEREQUESTDETAILNAME=:receiveRequestdetailname and a.SITENAME=:siteName";

		Map<String, Object> bindMap = new HashMap<String, Object>();
		bindMap.put("erpLocationname", erpLocationname);
		bindMap.put("receiveRequestdetailname", receiveRequestdetail);
		bindMap.put("siteName", sitename);
		bindMap.put("receiveRequestName",receiveRequestName);
		IDMFrameServiceProxy.getSqlTemplate()
				.update(sql, bindMap);
	}
	
	public void SetCheckStockOutFlag(EventInfo eventInfo,
			String siteName, String materialPackingNameList,String eventUser){
	  try {

			SetEventInfo setEventInfo = new SetEventInfo();
			Map<String, Object> bindMap = new HashMap<String, Object>();
            MaterialPackingKey packingInfo = new MaterialPackingKey();
            packingInfo.setSiteName(siteName);
            packingInfo.setMaterialPackingName(materialPackingNameList);
			bindMap.put("shipUser", eventUser);
            setEventInfo.setUserColumns(bindMap);
			MaterialPackingServiceProxy.getMaterialPackingService().setEvent(packingInfo, eventInfo, setEventInfo);
		} catch (IDMFrameDBErrorSignal e) {
			e.printStackTrace();
			throw e;
		}
	}
	
	public void PDADeassignBoxCarrier()throws Exception{
		
	}
	
	/***
	 * 
	 * PCBACheckHistory wsq-2019-12-4  for B17
	 * @param eventInfo
	 * @param siteName
	 * @param materialSpecName
	 * @param materialPackingName
	 * @param PCBAName
	 * @throws Exception
	 */
	public void PCBACheckHistory(EventInfo eventInfo,String siteName,String materialSpecName,
			String materialPackingName,String PCBAName)throws Exception{
		String sql = "INSERT INTO MATERIALPCBACHECKHISTORY "
				+ " ( "
				+ " SITENAME "
				+ " ,MATERIALSPECNAME "
				+ " ,MATERIALPACKINGNAME "
				+ " ,PCBANAME "
				+ " ,EVENTNAME "
				+ " ,EVENTUSER "
				+ " ,EVENTTIMEKEY "
				+ " ,EVENTTIME "
				+ " ) "
				+ " VALUES ( "
				+ " :SITENAME "
				+ ",:MATERIALSPECNAME "
				+ ",:MATERIALPACKINGNAME "
				+ ",:PCBANAME "
				+ ",:EVENTNAME "
				+ ",:EVENTUSER "
				+ ",:EVENTTIMEKEY "
				+ ",SYSDATE "
				+ " ) ";
		Map<String, String> bindMap = new HashMap<String, String>();
		bindMap.put("SITENAME", siteName);
		bindMap.put("MATERIALSPECNAME", materialSpecName);
		bindMap.put("MATERIALPACKINGNAME", materialPackingName);
		bindMap.put("PCBANAME", PCBAName);
		bindMap.put("EVENTNAME", eventInfo.getEventName());
		bindMap.put("EVENTUSER", eventInfo.getEventUser());
		bindMap.put("EVENTTIMEKEY", TimeStampUtil.getCurrentEventTimeKey());
		log.info(TimeStampUtil.getCurrentEventTimeKey());
		IDMFrameServiceProxy.getSqlTemplate().update(sql, bindMap);
	}
	
	public void updateTrayInfo(EventInfo eventInfo,String siteName,
			String materialPackingName,String flag)throws Exception{
		String sql = "";
		if(flag.equals("Create")){
			sql = " SELECT DISTINCT MATERIALSPECNAME,COUNT(MATERIALSPECNAME) AS QTY FROM DURABLE "
					+ " WHERE MATERIALPACKINGNAME=:MATERIALPACKINGNAME "
					+ " AND SITENAME=:SITENAME "
					+ " AND RECEIVESTATE='SMTTOBOE' "
					+ " group by MATERIALSPECNAME ";
		}
		else{
			sql = " SELECT DISTINCT MATERIALSPECNAME,COUNT(MATERIALSPECNAME) AS QTY FROM DURABLE "
					+ " WHERE MATERIALPACKINGNAME=:MATERIALPACKINGNAME "
					+ " AND SITENAME=:SITENAME "
					+ " AND RECEIVESTATE='BOE' "
					+ " group by MATERIALSPECNAME ";
		}
		
		Map<String, String> bindMap = new HashMap<String, String>();
		bindMap.put("SITENAME", siteName);
		bindMap.put("MATERIALPACKINGNAME", materialPackingName);
		
		List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
				.getSqlTemplate()
				.queryForList(sql, bindMap);
		for(int i=0;i<sqlResult.size();i++){
			String sqlUpdate = "";
			String sqlDurable = "UPDATE DURABLE SET RECEIVESTATE =:RECEIVESTATE "
					+ " WHERE MATERIALPACKINGNAME=:MATERIALPACKINGNAME "
					+ " AND SITENAME=:SITENAME ";
			String timeKey = TimeStampUtil.getCurrentEventTimeKey();
			Map<String, String> bindMapUpdate = new HashMap<String, String>();
			bindMapUpdate.put("SITENAME", siteName);
			bindMapUpdate.put("MATERIALSPECNAME", sqlResult.get(i).get("MATERIALSPECNAME").toString());
			bindMapUpdate.put("QTY", sqlResult.get(i).get("QTY").toString());
			bindMapUpdate.put("LASTEVENTNAME", eventInfo.getEventName());
			bindMapUpdate.put("LASTEVENTTIMEKEY", timeKey);
			bindMapUpdate.put("MATERIALPACKINGNAME", materialPackingName);
			
			if(flag.equals("Create")){
				sqlUpdate = "UPDATE DURABLESMT "
						+ " SET QTY = QTY+TO_NUMBER(:QTY) "
						+ " ,SMTQTY = SMTQTY-TO_NUMBER(:QTY) "
						+ " ,CHANGEQTY = :QTY "
						+ " ,LASTEVENTNAME = :LASTEVENTNAME "
						+ " ,LASTEVENTTIMEKEY = :LASTEVENTTIMEKEY "
						+ " ,LASTEVENTTIME = SYSDATE "
						+ " ,LASTEVENTCOMMENT = :LASTEVENTCOMMENT "
						+ " WHERE SITENAME = :SITENAME "
						+ " AND MATERIALSPECNAME = :MATERIALSPECNAME ";
				bindMapUpdate.put("LASTEVENTCOMMENT", "CreateReceivePCBABox");
				bindMapUpdate.put("RECEIVESTATE", "BOE");
				IDMFrameServiceProxy.getSqlTemplate().update(sqlUpdate, bindMapUpdate);
				
			}
			else{
				sqlUpdate = "UPDATE DURABLESMT "
						+ " SET QTY = QTY-TO_NUMBER(:QTY) "
						+ " ,SMTQTY = SMTQTY+TO_NUMBER(:QTY) "
						+ " ,CHANGEQTY = :QTY "
						+ " ,LASTEVENTNAME = :LASTEVENTNAME "
						+ " ,LASTEVENTTIMEKEY = :LASTEVENTTIMEKEY "
						+ " ,LASTEVENTTIME = SYSDATE "
						+ " ,LASTEVENTCOMMENT = :LASTEVENTCOMMENT "
						+ " WHERE SITENAME = :SITENAME "
						+ " AND MATERIALSPECNAME = :MATERIALSPECNAME ";
				bindMapUpdate.put("LASTEVENTCOMMENT", "DeleteReceivePCBABox");
				bindMapUpdate.put("RECEIVESTATE", "SMTTOBOE");
				IDMFrameServiceProxy.getSqlTemplate().update(sqlUpdate, bindMapUpdate);
			}
			String sqlUpdateHistory = "INSERT INTO DURABLESMTHISTORY "
					+ " ( SITENAME "
					+ " ,MATERIALSPECNAME "
					+ " ,QTY "
					+ " ,SMTQTY "
					+ " ,MDLQTY "
					+ " ,CHANGEQTY "
					+ " ,EVENTNAME "
					+ " ,EVENTTIMEKEY "
					+ " ,EVENTTIME "
					+ " ,EVENTUSER "
					+ " ,EVENTCOMMENT "
					+ " ) "
					+ " SELECT "
					+ " SITENAME "
					+ " ,MATERIALSPECNAME "
					+ " ,QTY "
					+ " ,SMTQTY "
					+ " ,MDLQTY "
					+ " ,CHANGEQTY "
					+ " ,LASTEVENTNAME "
					+ " ,LASTEVENTTIMEKEY "
					+ " ,LASTEVENTTIME "
					+ " ,LASTEVENTUSER "
					+ " ,LASTEVENTCOMMENT "
					+ " FROM DURABLESMT "
					+ " WHERE SITENAME = :SITENAME "
					+ " AND MATERIALSPECNAME = :MATERIALSPECNAME ";
			IDMFrameServiceProxy.getSqlTemplate().update(sqlUpdateHistory, bindMapUpdate);
			IDMFrameServiceProxy.getSqlTemplate().update(sqlDurable, bindMapUpdate);
		}
		
	}
	
	public String getPartsQTYToPMS(String siteName,String materialSpec){
		
		String sql = "select sum(materialquantity) from materialpacking where sitename=:siteName and materialspecname=:materialspecname  and materialpackingtype='Box' and STOCKSTATE='Stocked' and packinggrade='OK' and materialtype='ERSA' ";

		Map<String, Object> bindMap = new HashMap<String, Object>();
		bindMap.put("materialspecname", materialSpec);
		bindMap.put("siteName", siteName);
	
		int quantity=IDMFrameServiceProxy.getSqlTemplate().queryForInt(sql, bindMap);
		return String.valueOf(quantity);
	}


	/**
	 * Assign Box update fifoflag
	 * @param eventInfo
	 * @param siteName
	 * @param materialPackingNameList
	 * @param fifoFlagList
	 */
	public void updateAssignFifoFlag(EventInfo eventInfo,
			String siteName, List<Element> materialPackingNameList,
			List<Element> fifoFlagList ){
		
		List<MaterialPackingKey> packingList = new ArrayList<MaterialPackingKey>();
		for (Element materialPackingName : materialPackingNameList) {
			MaterialPackingKey keyInfo = new MaterialPackingKey();
			keyInfo.setSiteName(siteName);
			keyInfo.setMaterialPackingName(materialPackingName
					.getTextTrim());
			packingList.add(keyInfo);
		}
		
		List<SetEventInfo> setEventInfoList = new ArrayList<SetEventInfo>();
		
		for (Element fifoFlag : fifoFlagList) {
			
			SetEventInfo setEventInfo = new SetEventInfo();
			Map<String, Object> bindmpMap = new HashMap<String, Object>();
			bindmpMap.put("fifoFlag",fifoFlag.getTextTrim());
			setEventInfo.setUserColumns(bindmpMap);
			setEventInfoList.add(setEventInfo);
		}
		
		eventInfo.setEventName("updateAssignedFIFOFlag");
		eventInfo.setEventComment("updateAssignedFIFOFlag");
		
		MaterialPackingServiceProxy.getMaterialPackingService().setEvent(packingList, eventInfo, setEventInfoList);
		
	}
	
	/***
	 * Deassign Box update fifoflag
	 * @param eventInfo
	 * @param siteName
	 * @param materialPackingNameList
	 */
	public void updateDeassignFifoFlag(EventInfo eventInfo,
			String siteName, List<Element> materialPackingNameList ){
		
		List<MaterialPackingKey> packingList = new ArrayList<MaterialPackingKey>();
		List<SetEventInfo> setEventInfoList = new ArrayList<SetEventInfo>();
		
		for (Element materialPackingName : materialPackingNameList) {
			MaterialPackingKey keyInfo = new MaterialPackingKey();
			keyInfo.setSiteName(siteName);
			keyInfo.setMaterialPackingName(materialPackingName
					.getTextTrim());
			packingList.add(keyInfo);
			SetEventInfo setEventInfo = new SetEventInfo();
			Map<String, Object> bindmpMap = new HashMap<String, Object>();
			bindmpMap.put("fifoFlag","");
			setEventInfo.setUserColumns(bindmpMap);
			setEventInfoList.add(setEventInfo);
		}
		
		
		
		eventInfo.setEventName("updateDeassignedFIFOFlag");
		eventInfo.setEventComment("updateDeassignedFIFOFlag");
		
		MaterialPackingServiceProxy.getMaterialPackingService().setEvent(packingList, eventInfo, setEventInfoList);
		
	}
	
	/***
	 * update PDA Assign Box info
	 * @param eventInfo
	 * @param siteName
	 * @param materialPackingName
	 */
	public void updatePDAAssignFifoFlag(EventInfo eventInfo,
			String siteName, String materialPackingName ){
		
		MaterialPackingKey key = new MaterialPackingKey();
		key.setMaterialPackingName(materialPackingName);
		key.setSiteName(siteName);
		
		SetEventInfo setEventInfo = new SetEventInfo();
		Map<String, Object> bindmpMap = new HashMap<String, Object>();
		bindmpMap.put("fifoFlag","Y");
		setEventInfo.setUserColumns(bindmpMap);
		
		eventInfo.setEventName("updatePDAAssignedFIFOFlag");
		eventInfo.setEventComment("updatePDAAssignedFIFOFlag");
		
		MaterialPackingServiceProxy.getMaterialPackingService().setEvent(key, eventInfo, setEventInfo);
		
	}
	
	/***
	 * 
	 * @param eventInfo
	 * @param siteName
	 * @param materialPackingName
	 */
	public void updatePDADeassignFifoFlag(EventInfo eventInfo,
			String siteName, String materialPackingName, String receiveActNo ){
		
		//boxid不为空，更新单个box
		if(!materialPackingName.equals("")){
			
			MaterialPackingKey key = new MaterialPackingKey();
			key.setMaterialPackingName(materialPackingName);
			key.setSiteName(siteName);
			
			SetEventInfo setEventInfo = new SetEventInfo();
			Map<String, Object> bindmpMap = new HashMap<String, Object>();
			bindmpMap.put("fifoFlag","");
			setEventInfo.setUserColumns(bindmpMap);
			
			eventInfo.setEventName("updatePDADeassignFifoFlag");
			eventInfo.setEventComment("updatePDADeassignFifoFlag");
			
			MaterialPackingServiceProxy.getMaterialPackingService().setEvent(key, eventInfo, setEventInfo);
		}
		
		//boxid为空时，更新整个抬头下面的box
		else{
			String condition=" WHERE SITENAME = ? AND RECEIVEACTNO = ? AND SHIPREQUESTNAME IS NOT NULL ";
			Object[] bind={siteName,receiveActNo};
			List<MaterialPacking> mpList=MaterialPackingServiceProxy.getMaterialPackingService().select(condition, bind);
			
			for (MaterialPacking materialPacking : mpList){
				materialPacking.setFifoFlag("");
				materialPacking.setLastEventTime(eventInfo.getEventTime());
				materialPacking.setLastEventUser(eventInfo.getEventUser());
				materialPacking.setLastEventName("updatePDADeassignFifoFlag");
				materialPacking.setLastEventComment("updatePDADeassignFifoFlag");
			}
			
			MaterialPackingServiceProxy.getMaterialPackingService().update(mpList);			
		}

		
	}
	
	/**
	 * pda初始化库存信息
	 * @param siteName
	 * @param materialpackingname
	 * @param materialspecname
	 * @param materialquantity
	 * @param makeDate
	 * @param supplierNo
	 * @param expiringdate
	 * @return
	 */
	public String OnlineStockImportPDA(String siteName,String materialpackingname,
			String materialspecname,String materialquantity,String makeDate,String supplierNo,String expiringdate) {
		
		StringBuffer sql = new StringBuffer();
		sql.append(" ");
		sql.append("MERGE INTO MATERIALPACKING T ");
		sql.append("USING (SELECT :SITENAME SITENAME, :MATERIALPACKINGNAME MATERIALPACKINGNAME FROM DUAL) M ");
		sql.append("ON (T.SITENAME = M.SITENAME AND T.MATERIALPACKINGNAME = M.MATERIALPACKINGNAME) ");
		sql.append("WHEN NOT MATCHED THEN ");
		sql.append("INSERT ");
		sql.append("(T.SITENAME, ");
		sql.append("MATERIALPACKINGNAME, ");
		sql.append("MATERIALSPECNAME, ");
		sql.append("MATERIALQUANTITY, ");
		sql.append("MAKEDATE, ");
		sql.append("T.SUPPLIERNAME, ");
		sql.append("EXPIRINGDATE, ");
		sql.append("MATERIALPACKINGTYPE, ");
		sql.append("CONTENTMATERIALTYPE, ");
		sql.append("PACKINGGRADE, ");
		sql.append("MATERIALCREATEQUANTITY, ");
		sql.append("PACKINGSTATE, ");
		sql.append("STOCKSTATE, ");
		sql.append("HOLDSTATE, ");
		sql.append("LASTEVENTTIMEKEY, ");
		sql.append("LASTEVENTUSER, ");
		sql.append("STOCKINTYPE, ");
		sql.append("OQARESULTSTATE, ");
		sql.append("OQARESULT, ");
		sql.append("ERPSTATE, ");
		sql.append("NPFLAG,CREATETIME) ");
		sql.append("VALUES ");
		sql.append("(:SITENAME, ");
		sql.append(":MATERIALPACKINGNAME, ");
		sql.append(":MATERIALSPECNAME, ");
		sql.append(":MATERIALQUANTITY, ");
		sql.append("TO_DATE(:MAKEDATE,'YYYY-MM-DD'), ");
		sql.append(":SUPPLIERNO, ");
		sql.append("TO_DATE(:EXPIRINGDATE,'YYYY-MM-DD'), ");
		sql.append("'Box', ");
		sql.append("'MaterialPacking', ");
		sql.append("'OK', ");
		sql.append(":MATERIALQUANTITY, ");
		sql.append("'Released', ");
		sql.append("'Stocked', ");
		sql.append("'N', ");
		sql.append("'202106171314', ");
		sql.append("'admin', ");
		sql.append("'Normal', ");
		sql.append("'END', ");
		sql.append("'OK', ");
		sql.append("'SUCCESS', ");
		sql.append("'N',SYSDATE) ");
		    
		    
		  Map<String, String> palletMap = new HashMap<String,String>();
		  palletMap.put("SITENAME", siteName);
		  palletMap.put("MATERIALPACKINGNAME", materialpackingname);
		  palletMap.put("MATERIALSPECNAME", materialspecname);
		  palletMap.put("MATERIALQUANTITY", materialquantity);
		  palletMap.put("MAKEDATE", makeDate);
		  palletMap.put("SUPPLIERNO", supplierNo);
		  palletMap.put("EXPIRINGDATE", expiringdate);
		  int update = IDMFrameServiceProxy.getSqlTemplate().update(sql.toString(), palletMap);
		  if (update >= 1) {
			  return "1";
		  }
		  return "0";

		
	}
	
	
	/**
	 * PC端接收初始化库存
	 * @param siteName
	 * @param materialpackingname
	 * @param materialspecname
	 * @param materialquantity
	 * @param makeDate
	 * @param supplierNo
	 * @param expiringdate
	 * @param lastUser
	 * @return
	 */
	public String OnlineStockImportByPC(String siteName,String materialpackingname,
			String materialspecname,String materialquantity,String makeDate,String supplierNo,String expiringdate,String lastUser,org.jdom.Document doc) {
		
		Element rootElement = doc.getDocument().getRootElement();
		Element element = rootElement.getChild("Body").getChild("MATERIALPACKINGLIST");
		int update = 0;
		for (Iterator<?> iterator = element.getChildren().iterator(); iterator
				.hasNext();) {

			Element mpE = (Element) iterator.next();

			if (mpE.getName().equals("MATERIALPACKING")) {
				Map<String, String> palletMap = new HashMap<String,String>();
				palletMap.put("SITENAME", mpE.getChild("SITENAME").getText());
				palletMap.put("MATERIALPACKINGNAME", mpE.getChild("MATERIALPACKINGNAME").getText());
				palletMap.put("MATERIALSPECNAME", mpE.getChild("MATERIALSPECNAME").getText());
				palletMap.put("MATERIALQUANTITY", mpE.getChild("MATERIALQUANTITY").getText());
				palletMap.put("MAKEDATE", mpE.getChild("MAKEDATE").getText());
				palletMap.put("SUPPLIERNO", mpE.getChild("SUPPLIERNO").getText());
				palletMap.put("EXPIRINGDATE", mpE.getChild("EXPIRINGDATE").getText());
				palletMap.put("LASTUSER", mpE.getChild("LASTEVENTNAME").getText());
				StringBuffer sql = new StringBuffer();
				sql.append(" ");
				sql.append("MERGE INTO MATERIALPACKING T ");
				sql.append("USING (SELECT :SITENAME SITENAME, :MATERIALPACKINGNAME MATERIALPACKINGNAME FROM DUAL) M ");
				sql.append("ON (T.SITENAME = M.SITENAME AND T.MATERIALPACKINGNAME = M.MATERIALPACKINGNAME) ");
				sql.append("WHEN NOT MATCHED THEN ");
				sql.append("INSERT ");
				sql.append("(T.SITENAME, ");
				sql.append("MATERIALPACKINGNAME, ");
				sql.append("MATERIALSPECNAME, ");
				sql.append("MATERIALQUANTITY, ");
				sql.append("MAKEDATE, ");
				sql.append("T.SUPPLIERNAME, ");
				sql.append("EXPIRINGDATE, ");
				sql.append("MATERIALPACKINGTYPE, ");
				sql.append("CONTENTMATERIALTYPE, ");
				sql.append("PACKINGGRADE, ");
				sql.append("MATERIALCREATEQUANTITY, ");
				sql.append("PACKINGSTATE, ");
				sql.append("STOCKSTATE, ");
				sql.append("HOLDSTATE, ");
				sql.append("LASTEVENTTIMEKEY, ");
				sql.append("LASTEVENTUSER, ");
				sql.append("STOCKINTYPE, ");
				sql.append("OQARESULTSTATE, ");
				sql.append("OQARESULT, ");
				sql.append("ERPSTATE, ");
				sql.append("NPFLAG,CREATETIME) ");
				sql.append("VALUES ");
				sql.append("(:SITENAME, ");
				sql.append(":MATERIALPACKINGNAME, ");
				sql.append(":MATERIALSPECNAME, ");
				sql.append(":MATERIALQUANTITY, ");
				sql.append("TO_DATE(:MAKEDATE,'YYYY-MM-DD'), ");
				sql.append(":SUPPLIERNO, ");
				sql.append("TO_DATE(:EXPIRINGDATE,'YYYY-MM-DD'), ");
				sql.append("'Box', ");
				sql.append("'MaterialPacking', ");
				sql.append("'OK', ");
				sql.append(":MATERIALQUANTITY, ");
				sql.append("'Released', ");
				sql.append("'Stocked', ");
				sql.append("'N', ");
				sql.append("'202106171314', ");
				sql.append(":LASTUSER, ");
				sql.append("'Normal', ");
				sql.append("'END', ");
				sql.append("'OK', ");
				sql.append("'SUCCESS', ");
				sql.append("'N',SYSDATE) ");
				    
				    
			update = IDMFrameServiceProxy.getSqlTemplate().update(sql.toString(), palletMap);
			}
		}
		
		
		  if (update >= 1) {
			  return "1";
		  }
		  return "0";

		
	}
	
	/**
	 * 将K类库存更新为N
	 * @param eventInfo
	 * @param siteName
	 * @param materialPackingKeyList
	 * @param stockState
	 * @param erpEventTime
	 * @param eventUser
	 * @param eventComment
	 * @param receiveActNo
	 * @param kMaterialList
	 * @throws Exception
	 */
	public void updateKMaterialPacking(EventInfo eventInfo,
			String siteName, List<String> materialPackingKeyList,
			String stockState, String erpEventTime, String eventUser,
			String eventComment, String receiveActNo, List<MaterialUnDoinfo> kMaterialList, String shiprequestname) throws Exception {
		try {
			if( kMaterialList.size() > 0 ){
				String lastEventTimeKey = TimeStampUtil.getCurrentEventTimeKey();
				List<MaterialPackingKey> packingKeyList = new ArrayList<MaterialPackingKey>();
				Timestamp lastEventTime = new Timestamp(System.currentTimeMillis());
				SetEventInfo setEventInfo = new SetEventInfo();

				Map<String, Object> bindMap = new HashMap<String, Object>();
				CommonValidation cv = new CommonValidation();
				SimpleDateFormat wad = new SimpleDateFormat("yyyy-MM-dd");
				erpEventTime = cv.getDate(erpEventTime) + " 00:00:00";
				Date date = new Date();
				date = wad.parse(cv.getDate(erpEventTime));

				bindMap.put("erpEventTime", date);

				setEventInfo.setUserColumns(bindMap);
				
				String EventComment = eventInfo.getEventComment();
				String EventName = eventInfo.getEventName();
				String ReasonCode = eventInfo.getReasonCode();
				String ReasonCodeType = eventInfo.getReasonCodeType();
	
				
				eventInfo.setEventComment("ChangeKToN");
				eventInfo.setEventName("ChangeKToN");
				eventInfo.setReasonCode("0001");
				eventInfo.setReasonCodeType("411");

				for (int i = 0; i < materialPackingKeyList.size(); i++) {
					MaterialPackingKey keyInfo = new MaterialPackingKey();
					SetEventInfo eventInfo1 = new SetEventInfo();
					Map<String, Object> bindMap1 = new HashMap<String, Object>();
					keyInfo.setSiteName(siteName);
					keyInfo.setMaterialPackingName(materialPackingKeyList.get(i));
					MaterialPacking dataInfo = selectByKey(keyInfo);
					dataInfo.setErpEventTime(Timestamp.valueOf(erpEventTime));
					dataInfo.setLastEventName("ChangeKToN");
					dataInfo.setLastEventComment("ChangeKToN");
					dataInfo.setLastEventTimeKey(lastEventTimeKey);
					dataInfo.setLastEventUser(eventInfo.getEventUser());
					dataInfo.setLastEventTime(eventInfo.getEventTime());
					dataInfo.setReasonCodeType("411");
					dataInfo.setReasonCode("0001");
					dataInfo.setReceiveActNo(receiveActNo);
					MaterialPackingServiceProxy.getMaterialPackingService().update(dataInfo);
					//bindMap1.put("erpEventTime", Timestamp.valueOf(erpEventTime));
					//bindMap1.put("lastEventName", "ChangeKToN");
					//bindMap1.put("lastEventComment", "ChangeKToN");
					//bindMap1.put("specialFlag", "N");
					//bindMap1.put("lastEventTimeKey", lastEventTimeKey);
					//bindMap1.put("lastEventUser", eventInfo.getEventUser());
					//bindMap1.put("lastEventTime", eventInfo.getEventTime());
					//bindMap1.put("reasonCodeType", "411");
					//bindMap1.put("reasonCode", "0001");
					//bindMap1.put("receiveActNo", receiveActNo);
					//eventInfo1.setUserColumns(bindMap1);
					//MaterialPackingServiceProxy.getMaterialPackingService().setEvent(keyInfo, eventInfo, eventInfo1);
				}
				
				
				//插入bs_materialpackingundobiao 
				String sql_sel = "SELECT MATERIALPACKINGNAME,SITENAME FROM MATERIALPACKING  where UNDODETAILNAME=:seq and RECEIVEACTNO = :receiveActNo "
							+" AND MATERIALPACKINGNAME IN (SELECT REGEXP_SUBSTR(:materialPackingKeyList, '[^,]+', 1, ROWNUM) AS MATERIALPACKINGNAME FROM DUAL CONNECT BY ROWNUM - 1 <= LENGTH(REGEXP_REPLACE(:materialPackingKeyList, '[^,]+')))";
				String sql2 = insertUnDOMaterialPackingInfo_v3
						+ "select P.SITENAME,P.MATERIALPACKINGNAME,P.LASTEVENTTIMEKEY FROM MATERIALPACKING P WHERE P.UNDODETAILNAME=:seq and P.RECEIVEACTNO = :receiveActNo "
						+" AND MATERIALPACKINGNAME IN (SELECT REGEXP_SUBSTR(:materialPackingKeyList, '[^,]+', 1, ROWNUM) AS MATERIALPACKINGNAME FROM DUAL CONNECT BY ROWNUM - 1 <= LENGTH(REGEXP_REPLACE(:materialPackingKeyList, '[^,]+'))))";
				String seq="";
				for (int i = 0; i < kMaterialList.size(); i++) {
					Map<String, Object> bindMap4 = new HashMap<String, Object>();
					Map<String, Object> bindMap5 = new HashMap<String, Object>();
					if(kMaterialList.get(i).getUnDoID().equalsIgnoreCase("0000")||kMaterialList.get(i).getUnDoID().equalsIgnoreCase("0000")){
						continue;
					}
					if(kMaterialList.get(i).getSeq().length()>15)
					{
						seq=kMaterialList.get(i).getSeq().substring(15);
						bindMap5.put("seq", seq);
					}
					else
					{
						seq=kMaterialList.get(i).getSeq();
						bindMap5.put("seq", seq);
					}
					
					bindMap5.put("receiveActNo", receiveActNo);
					String materialList = StringUtils.join(materialPackingKeyList,",");
					bindMap5.put("materialPackingKeyList", materialList);
					log.info("seq:"+seq+" receiveActNo:"+receiveActNo +" materialpackingnameList:"+ materialList);
					List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
							.getSqlTemplate()
							.queryForList(sql_sel, bindMap5);
					List<MaterialPackingKey> materialPackingKeyList1 = new ArrayList<MaterialPackingKey>();
					for (int j = 0; j < sqlResult.size(); j++) {
						MaterialPackingKey keyInfo = new MaterialPackingKey();
						keyInfo.setMaterialPackingName(sqlResult.get(j)
								.get("MATERIALPACKINGNAME").toString());
						keyInfo.setSiteName(sqlResult.get(j).get("SITENAME")
								.toString());
						// materialPackingInfo.setKey(keyInfo);
						materialPackingKeyList1.add(keyInfo);
					}
					SetEventInfo setEventInfo1 = new SetEventInfo();
					Map<String, Object> bindMap2 = new HashMap<String, Object>();
					bindMap2.put("unDoDetailName", kMaterialList.get(i)
							.getUnDoDetailName());
					bindMap2.put("unDoID", kMaterialList.get(i).getUnDoID());
					bindMap2.put("erpState", "SUCCESS");
					//bindMap2.put("stockState", "StockOut");
					bindMap2.put("oldStockState", "Stocked");
					setEventInfo1.setUserColumns(bindMap2);
					bindMap4.put("unDoDetailName", kMaterialList.get(i)
							.getUnDoDetailName());
					bindMap4.put("unDoID", kMaterialList.get(i).getUnDoID());
					if(kMaterialList.get(i).getSeq().length()>15)
					{
						bindMap4.put("seq", kMaterialList.get(i).getSeq().substring(15));
					}
					else
					{
						bindMap4.put("seq", kMaterialList.get(i).getSeq());
					}
					//bindMap.put("seq", materialUnDoinfoList.get(i).getSeq().substring(15));
					bindMap4.put("UNDOIDDATE", kMaterialList.get(i)
							.getUnDoIdDate());
					bindMap4.put("receiveActNo", receiveActNo);
					bindMap4.put("LASTEVENTNAME", eventInfo.getEventName());
					bindMap4.put("LASTEVENTCOMMENT", eventInfo.getEventComment());
					bindMap4.put("materialPackingKeyList", materialList);
					// IDMFrameServiceProxy.getSqlTemplate().getSimpleJdbcTemplate().update(sql2,
					// bindMap1);
					//IDMFrameServiceProxy.getSqlTemplate().getSimpleJdbcTemplate().update(update, bindMap5);
					int count=IDMFrameServiceProxy.getSqlTemplate().update(sql2, bindMap4);
					MaterialPackingServiceProxy.getMaterialPackingService()
							.setEvent(materialPackingKeyList1, eventInfo,
									setEventInfo1);
				}
				eventInfo.setEventComment(EventComment);
				eventInfo.setEventName(EventName);
				eventInfo.setReasonCode(ReasonCode);
				eventInfo.setReasonCodeType(ReasonCodeType);
			}
		} 
		catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
	}
	
	
	public Document setOQAResult(Document message,EventInfo eventInfo) throws Exception
	{
		//reply message
		Element returnmessage = new Element(SMessageUtil.Message_Tag);
		Element returnbody = new Element("Body");
		Document replyDoc = new Document();
		String setmessage="";
		String setflag="";
		String seq="";
		Element root = message.getDocument().getRootElement();	 			
		Element bodyElement = root.getChild("Body");
		Element itemList = bodyElement.getChild("item");
		seq=itemList.getChildText("SEQ");	
		String erpfactory = "";
		erpfactory = itemList.getChildText("WERKS");
		List<SetEventInfo> setlist = new ArrayList<SetEventInfo>();
		Date date = new Date();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String systemdate = df.format(date);
        List<MaterialPackingKey> mpklist = new ArrayList<MaterialPackingKey>();
        
        Element header = new Element("Header");
		Element idelement = new Element("MESSAGENAME");
		idelement.setText("14330");
		header.addContent(idelement);
		
		Element comment = new Element("EVENTCOMMENT");
		comment.setText("PDABoxPreScrap");
		header.addContent(comment);
		
		Element interelement = new Element("INTERFACEID");
		interelement.setText("14330");
		header.addContent(interelement);
		
		Element transelement = new Element("TRANSID");
		transelement.setText(root.getChild("Header").getChildText("TRANSID"));
		header.addContent(transelement);
		
		Element messageelement = new Element("MESSAGEID");
		transelement.setText(root.getChild("Header").getChildText("messageID"));
		header.addContent(messageelement);
		
		returnmessage.addContent(header);
		
		try{
			//header				
			String oqaResult = "";
			String WMS_INSMK = "";
			String boxID="";
			String oqaResultState = "";
			String holdState = "N";

			String sql_ist ="SELECT * FROM MATERIALPACKING WHERE MATERIALPACKINGNAME = :MATERIALPACKINGNAME AND ERPFACTORY = :ERPFACTORY";	
			MaterialPacking mp=new MaterialPacking();
			MaterialPackingKey mpk=new MaterialPackingKey();		
			
			for(Iterator<?> iterator = itemList.getChildren().iterator();iterator.hasNext();){
				Element mpelement = (Element)iterator.next();
				boxID=mpelement.getChildText("ZF_NEWBOXID")==null?mpelement.getChildText("ZF_BOXID"):mpelement.getChildText("ZF_NEWBOXID");
				if(boxID!=null){
					WMS_INSMK = mpelement.getChildText("WMS_INSMK");
					if(WMS_INSMK.equals("F"))
					{
						oqaResult = "OK";
						oqaResultState = "END";
					}
					else if(WMS_INSMK.equals("Q"))
					{
						oqaResult = "";
						oqaResultState = "PREOQA";
					}
					else if(WMS_INSMK.equals("S"))
					{
						oqaResult = "NG";
						oqaResultState = "END";
					}
					else if(WMS_INSMK.equals("H"))
					{
						oqaResult = "";
						oqaResultState = "PREOQA";
						holdState = "Y";
					}
					Map<String, Object> bm_ist=new HashMap<String, Object>();
					bm_ist.put("MATERIALPACKINGNAME", boxID);
					bm_ist.put("ERPFACTORY", erpfactory);
					List<Map<String, Object>> sqlresult=IDMFrameServiceProxy.getSqlTemplate().queryForList(sql_ist, bm_ist);
					if(sqlresult.size()>0)
					{
						for(int i=0;i<sqlresult.size();i++)	
						{ 					
						//根据主键选择BOX，保存BOX的质检状态和新增字段值
						mpk.setMaterialPackingName(sqlresult.get(i).get("MATERIALPACKINGNAME")==null?"":sqlresult.get(i).get("MATERIALPACKINGNAME").toString());
						mpk.setSiteName(sqlresult.get(i).get("SITENAME").toString());							
						mp=MaterialPackingServiceProxy.getMaterialPackingService().selectByKey(mpk);
						//质检时判断当前BOX是否已存在质检结果
						if(mp!=null)
						{
							if(!mp.getStockState().equalsIgnoreCase("Stocked")){
								throw new CustomException("BOX{0}当前为非在库状态！",boxID);
							}
						}
						mp.setMaterialProcessGroupName(boxID);						
						mp.setOqaResult(oqaResult);
						mp.setOqaResultState(oqaResultState);
						mp.setPackingGrade(oqaResult);
						mp.setHoldState(holdState);
						mp.setLastEventName("UpdateOQAResutBy14330");	
						mp.setLastEventUser("14330");						
						mp.setLastEventTime(TimeStampUtil.getCurrentTimestamp());						
						mp.setLastEventTimeKey(TimeStampUtil.getCurrentEventTimeKey());
										
						MaterialPackingServiceProxy.getMaterialPackingService().update(mp);	

						//insertMaterialpackingHistory(boxID);//add by wx 20240821
						}
					}
					else
					{
						throw new CustomException("BOX{0}不存在！",boxID);
					}
				}
			}

			// Body Element
			setmessage="序列号:"+seq+"创建成功！";
			setflag="S";
			Element itemelement = new Element("item"); 
			
			Element seqelement = new Element("SEQ");
			seqelement.setText(seq);
			itemelement.addContent(seqelement);
			
			Element zfelement = new Element("ZF_QNUM");
			zfelement.setText(itemList.getChildText("ZF_QNUM"));
			itemelement.addContent(zfelement);
			
			Element msgtyelement = new Element("MSGTY");
			msgtyelement.setText(setflag);
			itemelement.addContent(msgtyelement);
			
			Element msgelement = new Element("MESSAGE");
			msgelement.setText(setmessage);
			itemelement.addContent(msgelement);

			returnbody.addContent(itemelement);
						
		} catch (Exception e) {
			setmessage="序列号:"+seq+"创建失败！";
			setflag="E";
			
			Element itemelement = new Element("item"); 
			
			Element seqelement = new Element("SEQ");
			seqelement.setText(seq);
			itemelement.addContent(seqelement);
			
			Element zfelement = new Element("ZF_QNUM");
			zfelement.setText(itemList.getChildText("ZF_QNUM"));
			itemelement.addContent(zfelement);
			
			Element msgtyelement = new Element("MSGTY");
			msgtyelement.setText(setflag);
			itemelement.addContent(msgtyelement);
			
			Element msgelement = new Element("MESSAGE");
			msgelement.setText(setmessage);
			itemelement.addContent(msgelement);
			
			
			returnbody.addContent(itemelement);			
		}
		if (setflag.equals("S")) {
			Element returnCode = new Element("RESULTTYPE");
			returnCode.setText("S");
			header.addContent(returnCode);

			Element returnMessage = new Element("RESULTMESSAGE");
			returnCode.setText("成功");
			header.addContent(returnMessage);
		}else {
			Element returnCode = new Element("RESULTTYPE");
			returnCode.setText("E");
			header.addContent(returnCode);

			Element returnMessage = new Element("RESULTMESSAGE");
			returnMessage.setText("失败");
			header.addContent(returnMessage);
		}
		
		returnmessage.addContent(returnbody);
		replyDoc = new Document(returnmessage);

		log.info("returnMessage=" + JdomUtils.toString(returnmessage));
		return replyDoc;
	}
	
	// for GERP 20241009
	/**
	 * 出库备件信息请求PMS
	 * 
	 * @param siteName              工厂
	 * @param shiprequestName       PO
	 * @param transactionId 行项目
	 * @return
	 */
	public Document PartsPMSRequest(String siteName, String shiprequestName, String transactionId,
			String originalSourceSubjectName, String sourceSubjectName, String targetSubjectName, String eventUser,
			String eventComment) {
		String Interface = GenericServiceProxy.getConstantMap().New_PartsStockInOutRequest;
		
		Document doc = SMessageUtil.createPMSMessageDocument(Interface, siteName, "MWMS", "", transactionId,
				originalSourceSubjectName, sourceSubjectName, targetSubjectName, eventUser, eventComment);
		/**
		 * Element header=doc.getDocument().getRootElement().getChild("Header"); Element
		 * sitename=new Element("SITENAME"); sitename.setText(siteName);
		 * header.addContent(sitename);
		 **/
		try {
			String nodePath = "//Message/Body";
			Element parentElement = JdomUtils.getNode(doc, nodePath);
			String selectMaterialShipRequestDetailSql = " SELECT SHIPREQUESTDETAILNAME FROM MATERIALSHIPREQUESTDETAIL WHERE SITENAME = :SITENAME AND SHIPREQUESTNAME = :SHIPREQUESTNAME ";
			Map<String, Object> selectMaterialShipRequestDetailMap = new HashMap<String, Object>();
			selectMaterialShipRequestDetailMap.put("SITENAME", siteName);
			selectMaterialShipRequestDetailMap.put("SHIPREQUESTNAME", shiprequestName);
			List<Map<String, Object>> resultMaterialShipRequestDetailList = IDMFrameServiceProxy.getSqlTemplate()
					.queryForList(selectMaterialShipRequestDetailSql, selectMaterialShipRequestDetailMap);
			for (int i = 0; i < resultMaterialShipRequestDetailList.size(); i++) {
				Element childElemrnt = new Element("item");
				parentElement.addContent(childElemrnt);
				SMessageUtil.createElement(nodePath, childElemrnt, "SITENAME", siteName);
				SMessageUtil.createElement(nodePath, childElemrnt, "SHIPREQUESTNAME", shiprequestName);
				SMessageUtil.createElement(nodePath, childElemrnt, "SHIPREQUESTDETAILNAME",
						resultMaterialShipRequestDetailList.get(i).get("SHIPREQUESTDETAILNAME").toString());
			}
			String replyMSG = JdomUtils.toString(doc);
			log.info(replyMSG);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return doc;
	}
	
	public String sendRequestBySenderWithSReply(Document doc, String senderName,String subjectName) {
	    Document msg = new Document();
	    String mm="";
	    String sendMsg = JdomUtils.toString(doc);
	    log.info("send started!");  
	    try {
	    mm=GenericServiceProxy.getGenericSender(senderName).sendRequest(sendMsg,2000).toString();
//	    msg = (Document)GenericServiceProxy.getGenericSender(senderName).sendRequest(sendMsg,2000);
//	    		.sendRequest(sendMsg);
//	    log.info(" SEND : Sender=" + senderName);
//	    loggingSend(sendMsg);
//	    log.info("receive:---------"+msg+"--------");
//	    log.info(" Receive : Reply=" + msg.toString());
//	    loggingSend(msg.toString());
        int start = mm.indexOf("<Body>") + "<Body>".length();
        int end = mm.indexOf("</Body>");
        String bodyContent = mm.substring(start, end).trim();
        String[] items = bodyContent.split("<\\/ITEM>\\s*<ITEM>");
         log.info("Found " + items + " ITEM elements.");
        if(null != items && items.length > 0) {
        	// 遍历每个 <ITEM> 元素
            for (String item : items) {
           	 if (!item.trim().isEmpty()) {
           		// 在这里处理每个 ITEM 元素的内容
                    String siteName = extractElementValue(item, "SITENAME");
                    String partsPackingName = extractElementValue(item, "PARTSPACKINGNAME");
                    String partsSpecName = extractElementValue(item, "PARTSSPECNAME");
                    String quantity = extractElementValue(item, "QUANTITY");
                    String stockState = extractElementValue(item, "STOCKSTATE");
                    String shipRequestName = "";
                    String packingType = extractElementValue(item, "PACKINGTYPE");
                    String avaliableState = extractElementValue(item, "AVAILABLESTATE");
                    String serialNumber = extractElementValue(item, "SERIALNUMBER");
                    String repairState = extractElementValue(item, "REPAIRSTATE");
                    String useCount = extractElementValue(item, "USECOUNT");
                    String locationName = extractElementValue(item, "LOCATIONNAME");
                    String unit = extractElementValue(item, "UNIT");
                    String returnType = extractElementValue(item, "RETURNTYPE");
                    String charge = extractElementValue(item, "CHARGE");
                    String judgeFlag = extractElementValue(item, "JUDGEFLAG");
                    String ponumber = extractElementValue(item, "PONUMBER");
                    String costCenter = extractElementValue(item, "COSTCENTER");
                    String erpFactory = extractElementValue(item, "ERPFACTORY");
                    String shipRequestDetailName = "";
                    String repairFlag = extractElementValue(item, "REPAIRFLAG");
                    //不同的业务，发送报文的字段不同
                    if(extractElementValue(item, "STOCKOUTSHIPREQUESTNAME").isEmpty()) {
                    	shipRequestName = extractElementValue(item, "SHIPREQUESTNAME");
                    	shipRequestDetailName = extractElementValue(item, "SHIPREQUESTDETAILNAME");
                    }else {
                    	shipRequestName = extractElementValue(item, "STOCKOUTSHIPREQUESTNAME");
                        shipRequestDetailName = extractElementValue(item, "STOCKOUTSHIPREQUESTDETAILNAME");
                    }
                    String queryPMSPreMaterialPackingByKeySql = "SELECT SITENAME,PARTSPACKINGNAME,PARTSSPECNAME,STOCKSTATE,AVALIABLESTATE,SHIPREQUESTNAME,SHIPREQUESTDETAILNAME,SERIALNUMBER,REPAIRSTATE,USECOUNT,LOCATION,QUANTITY,UNIT,RETURNCODE,CHARGE,BWTAR,RECEIVEREQUESTNAME,RECEIVEFLAG FROM PMSPREMATERIALPACKING " + "WHERE SITENAME = :siteName and PARTSPACKINGNAME = :partsPackingName and SHIPREQUESTNAME = :shipRequestName and SHIPREQUESTDETAILNAME = :shipRequestDetailName ";
            		Map<String, String> queryPMSPreMaterialPackingByKeyMap = new HashMap<String, String>();
            		queryPMSPreMaterialPackingByKeyMap.put("siteName", siteName);
            		queryPMSPreMaterialPackingByKeyMap.put("partsPackingName", partsPackingName);
            		queryPMSPreMaterialPackingByKeyMap.put("shipRequestName", shipRequestName);
            		queryPMSPreMaterialPackingByKeyMap.put("shipRequestDetailName", shipRequestDetailName);
            		String insetPMSPreMaterialPackingSql = 
            				" insert into PMSPREMATERIALPACKING (SITENAME,PARTSPACKINGNAME,PARTSSPECNAME,STOCKSTATE,AVALIABLESTATE,SHIPREQUESTNAME,SHIPREQUESTDETAILNAME,SERIALNUMBER,REPAIRSTATE,USECOUNT,LOCATION,QUANTITY,UNIT,RETURNCODE,CHARGE,BWTAR,RECEIVEREQUESTNAME,REPAIRFLAG) "
            				+ " VALUES (:SITENAME,:PARTSPACKINGNAME,:PARTSSPECNAME,:STOCKSTATE,:AVALIABLESTATE,:SHIPREQUESTNAME,:SHIPREQUESTDETAILNAME,:SERIALNUMBER,:REPAIRSTATE,:USECOUNT,:LOCATION,:QUANTITY,:UNIT,:RETURNCODE,:CHARGE,:BWTAR,:RECEIVEREQUESTNAME,:REPAIRFLAG) ";
            		//Double zfMengSumDouble =  Double.parseDouble(zfMengSum);
            		Map<String, Object> insetPMSPreMaterialPackingMap = new HashMap<String, Object>();
            		List<Map<String, Object>> queryResult = IDMFrameServiceProxy.getSqlTemplate().queryForList(queryPMSPreMaterialPackingByKeySql, queryPMSPreMaterialPackingByKeyMap);
            		if (queryResult == null || queryResult.isEmpty()) {
            			// Create
            			insetPMSPreMaterialPackingMap.put("SITENAME", siteName);
            			insetPMSPreMaterialPackingMap.put("PARTSPACKINGNAME", partsPackingName);
            			insetPMSPreMaterialPackingMap.put("PARTSSPECNAME", partsSpecName);
            			insetPMSPreMaterialPackingMap.put("STOCKSTATE", stockState);
            			insetPMSPreMaterialPackingMap.put("AVALIABLESTATE", avaliableState);
            			insetPMSPreMaterialPackingMap.put("SHIPREQUESTNAME", shipRequestName);
            			insetPMSPreMaterialPackingMap.put("SHIPREQUESTDETAILNAME", shipRequestDetailName);
            			insetPMSPreMaterialPackingMap.put("SERIALNUMBER", serialNumber);
            			insetPMSPreMaterialPackingMap.put("REPAIRSTATE", repairState);
            			insetPMSPreMaterialPackingMap.put("USECOUNT", useCount);
            			insetPMSPreMaterialPackingMap.put("LOCATION", locationName);
            			insetPMSPreMaterialPackingMap.put("QUANTITY", quantity);
            			insetPMSPreMaterialPackingMap.put("UNIT", unit);
            			insetPMSPreMaterialPackingMap.put("RETURNCODE", returnType);
            			insetPMSPreMaterialPackingMap.put("CHARGE", charge);
            			insetPMSPreMaterialPackingMap.put("BWTAR", judgeFlag);
            			insetPMSPreMaterialPackingMap.put("RECEIVEREQUESTNAME", ponumber);                			                			
            			//insetPMSPreMaterialPackingMap.put("RECEIVEFLAG", "");
            			insetPMSPreMaterialPackingMap.put("REPAIRFLAG", repairFlag);
            			IDMFrameServiceProxy.getSqlTemplate().update(insetPMSPreMaterialPackingSql, insetPMSPreMaterialPackingMap);
            		}
           	 }
            }
        } 
	    } catch (Exception e) {
            log.error("Failed to parse XML response.", e);
        } 
	    log.info("receive:---------"+mm+"--------");
	    return mm;
	    //	    return msg;
	}

	
	private String extractElementValue(String item, String elementName) {
        String pattern = "<" + elementName + ">[^<]*</" + elementName + ">";
        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(item);
        if (m.find()) {
            String match = m.group();
            int start = match.indexOf('>') + 1;
            int end = match.lastIndexOf('<');
            return match.substring(start, end).trim();
        }
        return "";
    }
	
	public void CreateBoxByLabelPMS(EventInfo eventInfo, String siteName, String receiveActNo, String shipRequestName,
			String materialPackingName, String poDetailName, String makeDate, String receiveQuantity,
			String materialSpecName, String supplierName, String NPFlag, String expiringDate, String erpLocation)
			throws Exception {
		// 获取MaterialSpec信息
		MaterialSpec materialSpec = new MaterialSpec();
		MaterialSpecKey materialSpecKey = new MaterialSpecKey();
		materialSpecKey.setMaterialSpecName(materialSpecName);
		materialSpecKey.setSiteName(siteName);
		materialSpec = MaterialServiceProxy.getMaterialSpecService().selectByKey(materialSpecKey);
		/**
		 * MaterialReceiveRequestDetail materialReceiveRequestDetail = new
		 * MaterialReceiveRequestDetail(); MaterialReceiveRequestDetailKey
		 * matetialReceiveRequestDetailKey = new MaterialReceiveRequestDetailKey();
		 * matetialReceiveRequestDetailKey.setReceiveRequestName(receiveRequestName);
		 * matetialReceiveRequestDetailKey.setSiteName(siteName);
		 * matetialReceiveRequestDetailKey.setReceiveRequestDetailName(poDetailName);
		 * 
		 * materialReceiveRequestDetail = ReceiveRequestDetailServiceProxy
		 * .getReceiveRequestDetailService().selectByKey(matetialReceiveRequestDetailKey);
		 **/
		MaterialShipRequestDetail materialShipRequestDetail = new MaterialShipRequestDetail();
		MaterialShipRequestDetailKey matetialShipRequestDetailKey = new MaterialShipRequestDetailKey();
		matetialShipRequestDetailKey.setShipRequestName(shipRequestName);
		matetialShipRequestDetailKey.setSiteName(siteName);
		matetialShipRequestDetailKey.setShipRequestDetailName(poDetailName);

		materialShipRequestDetail = MaterialShipRequestDetailServiceProxy.getMaterialShipRequestDetailService()
				.selectByKey(matetialShipRequestDetailKey);
		
		materialShipRequestDetail.setAssignedQuantity(Double.parseDouble(receiveQuantity));
		MaterialShipRequestDetailServiceProxy.getMaterialShipRequestDetailService().update(materialShipRequestDetail);
		
		String sql2 = "SELECT * FROM MATERIALPACKING WHERE MATERIALPACKINGNAME=:materialPackingNmae AND STOCKSTATE='StockOut' AND SITENAME=:siteName";
		Map<String, Object> bindMap2 = new HashMap<String, Object>();
		bindMap2.put("materialPackingNmae", materialPackingName);
		bindMap2.put("siteName", siteName);
		List<Map<String, Object>> sqlResult = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql2, bindMap2);

		if (!(sqlResult.size() == 0 || sqlResult.get(0).get("MATERIALPACKINGNAME").toString().equals(""))) {
			MaterialPackingKey materialPackingKey = new MaterialPackingKey();
			materialPackingKey.setMaterialPackingName(materialPackingName);
			materialPackingKey.setSiteName(siteName);
			MaterialPacking mp = MaterialPackingServiceProxy.getMaterialPackingService()
					.selectByKey(materialPackingKey);
			String charge;
			if (materialShipRequestDetail.getErpLocation().equals("2001")) {
				charge = "E0000001";
			} else {
				charge = materialShipRequestDetail.getCharge();
			}
			Map<String, Object> bindMap = new HashMap<String, Object>();
			bindMap.put("receiveActNo", receiveActNo);
			bindMap.put("shipRequestName", shipRequestName);
			bindMap.put("shipRequestDetailName", poDetailName);
			bindMap.put("receiveRequestName", shipRequestName);
			bindMap.put("receiveRequestDetailName", poDetailName);
			bindMap.put("materialQuantity", receiveQuantity);
			bindMap.put("materialCreateQuantity", receiveQuantity);
			bindMap.put("packingState", "Created");// 标记Box是刚创建的
			bindMap.put("materialType", materialSpec.getMaterialType());
			bindMap.put("materialSpecName", materialSpecName);
			bindMap.put("stockState", "");
			bindMap.put("holdState", "N");
			bindMap.put("areaName", "");
			bindMap.put("createUser", eventInfo.getEventUser());
			bindMap.put("createTime", eventInfo.getEventTime());
			// makeDate=makeDate+" 00:00:00";
			bindMap.put("makeDate", makeDate);
			bindMap.put("expiringDate", expiringDate);
//							if(materialReceiveRequestDetail.getErpLocation().toString()!=erpLocation){
//								bindMap.put("erpLocation", erpLocation);
//							}else{
//								bindMap.put("erpLocation",materialReceiveRequestDetail.getErpLocation());
//							}
			bindMap.put("erpLocation", erpLocation);
			if (materialShipRequestDetail.getErpLocation() == null
					|| materialShipRequestDetail.getErpLocation().equals("")) {
				throw new CustomException("ERPLOCATIONLOSS", "", "");
			}
			bindMap.put("erpFactoryName", materialShipRequestDetail.getErpFactoryName());
			bindMap.put("stockInType", "");
			bindMap.put("charge", charge);
			bindMap.put("supplierName", supplierName);
			bindMap.put("npFlag", NPFlag);
			if (siteName.equals("B9")) {
				bindMap.put("locationName", "9-C1-02-C");
			}
//							bindMap.put("reasonCodeType", eventInfo.getReasonCodeType());
//							bindMap.put("reasonCode", eventInfo.getReasonCode());
			eventInfo.setReasonCode("0001");
			eventInfo.setReasonCodeType("101");

			SetEventInfo setEventInfo = new SetEventInfo();
			setEventInfo.setUserColumns(bindMap);
			MaterialPackingServiceProxy.getMaterialPackingService().setEvent(materialPackingKey, eventInfo,
					setEventInfo);
		} else {
			// 创建Box
			CreateInfo materialPacking = new CreateInfo();
			materialPacking.setMaterialPackingName(materialPackingName);
			materialPacking.setSiteName(siteName);
			materialPacking.setContentMaterialType("");
			materialPacking.setMaterialPackingType("Box");
			String charge;
			if (materialShipRequestDetail.getErpFactoryName().equals("2001")) {
				charge = "E0000001";
			} else {
				charge = materialShipRequestDetail.getCharge();
			}
			Map<String, Object> bindMap = new HashMap<String, Object>();
			bindMap.put("receiveActNo", receiveActNo);
			bindMap.put("shipRequestName", shipRequestName);
			bindMap.put("shipRequestDetailName", poDetailName);
			bindMap.put("receiveRequestName", shipRequestName);
			bindMap.put("receiveRequestDetailName", poDetailName);
			bindMap.put("materialQuantity", receiveQuantity);
			bindMap.put("materialCreateQuantity", receiveQuantity);
			bindMap.put("packingState", "Created");// 标记Box是刚创建的
			bindMap.put("materialType", materialSpec.getMaterialType());
			bindMap.put("materialSpecName", materialSpecName);
			bindMap.put("stockState", "");
			bindMap.put("holdState", "N");
			bindMap.put("areaName", "");
			bindMap.put("createUser", eventInfo.getEventUser());
			bindMap.put("createTime", eventInfo.getEventTime());
			// makeDate=makeDate+" 00:00:00";
			bindMap.put("makeDate", makeDate);
			bindMap.put("expiringDate", expiringDate);
			if (siteName.equals("B9")) {
				bindMap.put("locationName", "9-C1-02-C");
			}
//							if(materialReceiveRequestDetail.getErpLocation().toString()!=erpLocation){
//								bindMap.put("erpLocation", erpLocation);
//							}else{
//								bindMap.put("erpLocation",materialReceiveRequestDetail.getErpLocation());
//							}
			bindMap.put("erpLocation", erpLocation);
			if (materialShipRequestDetail.getErpLocation() == null
					|| materialShipRequestDetail.getErpLocation().equals("")) {
				throw new CustomException("ERPLOCATIONLOSS", "", "");
			}
			bindMap.put("erpFactory", materialShipRequestDetail.getErpFactoryName());
			bindMap.put("stockInType", "");
			bindMap.put("charge", charge);
			bindMap.put("supplierName", supplierName);
			bindMap.put("npFlag", NPFlag);
//							bindMap.put("reasonCodeType", eventInfo.getReasonCodeType());
//							bindMap.put("reasonCode", eventInfo.getReasonCode());

			materialPacking.setUserColumns(bindMap);
			eventInfo.setReasonCode("0001");
			eventInfo.setReasonCodeType("101");
			MaterialPackingServiceProxy.getMaterialPackingService().create(eventInfo, materialPacking);
		}

		// 创建批次

		CreateActDetailInfo createActDetailInfo = new CreateActDetailInfo();

		MaterialReceiveActDetailKey materialReceiveActDetailKey = new MaterialReceiveActDetailKey();
		materialReceiveActDetailKey.setSiteName(siteName);
		materialReceiveActDetailKey.setReceiveRequestName(shipRequestName);
		materialReceiveActDetailKey.setReceiveRequestDetailName(poDetailName);
		materialReceiveActDetailKey.setReceiveActNO(receiveActNo);
		materialReceiveActDetailKey.setMakeDate(Timestamp.valueOf(makeDate));
		String sql = "SELECT * FROM materialreceiveactdetail "
				+ "WHERE sitename = :sitename AND receiveRequestName = :receiveRequestName and ReceiveRequestDetailName=:ReceiveRequestDetailName and receiveActNo=:receiveActNo"
				+ " and makeDate=:makeDate ";

		Map<String, Object> bindMap1 = new HashMap<String, Object>();
		bindMap1.put("sitename", siteName);
		bindMap1.put("receiveRequestName", shipRequestName);
		bindMap1.put("ReceiveRequestDetailName", poDetailName);
		bindMap1.put("receiveActNo", receiveActNo);
		bindMap1.put("makeDate", Timestamp.valueOf(makeDate));
		List<Map<String, Object>> queryResult = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, bindMap1);
		if (queryResult.size() == 0) {
			createActDetailInfo.setReceiveActNO(receiveActNo);
			createActDetailInfo.setReceiveRequestName(shipRequestName);
			createActDetailInfo.setReceiveRequestDetailName(poDetailName);
			createActDetailInfo.setSiteName(siteName);

			// Date date1 = new Date();//获取当前时间
			// SimpleDateFormat sdf = new
			// SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			// String str = sdf.format(date1);//时间存储为字符串
			// System.out.println(str);
			createActDetailInfo.setMakeDate(Timestamp.valueOf(makeDate));
			createActDetailInfo.setReceiveQuantity(Double.parseDouble(receiveQuantity));
			Map<String, Object> bindMap3 = new HashMap<String, Object>();
			bindMap3.put("receiveActState", "Created");
			// bindMap3.put("receiveQuantity",
			// Double.parseDouble(receiveQuantity));
			createActDetailInfo.setUserColumns(bindMap3);

			MaterialReceiveRequestActDetailServiceProxy.getMaterialReceiveRequestActDetailService().create(eventInfo,
					createActDetailInfo);
		} else {
			ActDetailIncreaseInfo actDetailIncreaseInfo = new ActDetailIncreaseInfo();
			actDetailIncreaseInfo.setReceiveQuantity(Double.parseDouble(receiveQuantity));

			MaterialReceiveRequestActDetailServiceProxy.getMaterialReceiveRequestActDetailService()
					.increaseReceivedQuantity(materialReceiveActDetailKey, eventInfo, actDetailIncreaseInfo);
		}
		/**
		 * MakeDetailIncreaseReceivedInfo makeDetailIncreaseReceivedInfo = new
		 * MakeDetailIncreaseReceivedInfo(); MaterialReceiveRequestDetailKey
		 * materialReceiveRequestDetailKey = new MaterialReceiveRequestDetailKey();
		 * materialReceiveRequestDetailKey.setReceiveRequestName(shipRequestName);
		 * materialReceiveRequestDetailKey.setSiteName(siteName);
		 * materialReceiveRequestDetailKey.setReceiveRequestDetailName(poDetailName);
		 * makeDetailIncreaseReceivedInfo.setIncreaseQuantity(Double.parseDouble(receiveQuantity));
		 * ReceiveRequestDetailServiceProxy.getReceiveRequestDetailService()
		 * .increaseReceivedQuantity(materialReceiveRequestDetailKey, eventInfo,
		 * makeDetailIncreaseReceivedInfo);
		 **/
	}
	
	// FORGERP
	public Document PartsPMSReceived(List<MaterialStockInClass> mplist, String siteName, String shiprequestName,EventInfo eventInfo) {
		String Interface = GenericServiceProxy.getConstantMap().New_PartsStockInOutReceived;
		Document doc = SMessageUtil.createERPXmlDocument(Interface, "");
		// Element header=doc.getDocument().getRootElement().getChild("Header");
		try {
			String nodePath = "//Message/Body";
			Element parentElement = JdomUtils.getNode(doc, nodePath);
			for (int i = 0; i < mplist.size(); i++) {
				MaterialStockInClass msa = mplist.get(i);
				Element childElemrnt = new Element("item");
				parentElement.addContent(childElemrnt);
				List<MaterialPacking> materialpackinglist = new MaterialPackingStockInUtil().GetBackStockInList(msa);
				SMessageUtil.createElement(nodePath, childElemrnt, "SITENAME", siteName);
				
				if (null != materialpackinglist && materialpackinglist.size() > 0) {
					for (MaterialPacking mp : materialpackinglist) {
						SMessageUtil.createElement(nodePath, childElemrnt, "BOXID",
								mp.getKey().getMaterialPackingName());
						SMessageUtil.createElement(nodePath, childElemrnt, "RECEIVEDTIME", eventInfo.getEventTime().toString());
						SMessageUtil.createElement(nodePath, childElemrnt, "RECEIVEDUSER", eventInfo.getEventName());
					}
				}
			}
			String replyMSG = JdomUtils.toString(doc);
			log.info(replyMSG);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return doc;
	}
	
	public List<MaterialPacking> updateMaterialPackingStockStateList(String siteName,
			List<MaterialPacking> materialPackingList, EventInfo eventInfo) throws Exception {
		if (materialPackingList.size() == 0) {
			throw new CustomException("PK-0001", "", "");
		}
		try {				
			String erpEventTime1 = eventInfo.getEventTime().toString();
			List<MaterialPacking> mpList = new ArrayList<MaterialPacking>();
			for (int i = 0; i < materialPackingList.size(); i++) {	
					MaterialPacking materialPacking = new MaterialPacking();
					MaterialPackingKey keyInfo = materialPackingList.get(i).getKey();
					materialPacking = MaterialPackingServiceProxy.getMaterialPackingService().selectByKey(keyInfo);
					materialPacking.setUnDoDetailName(Integer.toString(i + 1));
					//materialPacking.setPackingState("Scrapped");
					materialPacking.setStockState("StockOut");
					materialPacking.setLastEventName("ScrapManualStockOut");
					// materialPacking.setLastEventTimeKey(eventInfo.getEventTimeKey());
					materialPacking.setLastEventTime(eventInfo.getEventTime());
					materialPacking.setLastEventUser(eventInfo.getEventUser());
					materialPacking.setLastEventComment( materialPackingList.get(i).getLastEventComment());
					materialPacking.setErpEventTime(Timestamp.valueOf(erpEventTime1));
					materialPacking.setReasonCode(eventInfo.getReasonCode());
					materialPacking.setReasonCodeType(eventInfo.getReasonCodeType());
					mpList.add(materialPacking);
			}
			if (mpList.size() > 0) {
				MaterialPackingServiceProxy.getMaterialPackingService().update(mpList);
			}
			/**
			MaterialReceiveActKey receiveActKey = new MaterialReceiveActKey(siteName, receiveRequestName, receiveActNo);
			Map<String, Object> bindMap1 = new HashMap<String, Object>();
			bindMap1.put("receiveActState", "Completed");
			com.cim.idm.wmspackage.materialreceiverequestact.management.info.SetEventInfo setEventInfo = new com.cim.idm.wmspackage.materialreceiverequestact.management.info.SetEventInfo();
			setEventInfo.setUserColumns(bindMap1);
			MaterialReceiveRequestActServiceProxy.getReceiveRequestBatchService().setEvent(receiveActKey, eventInfo,
					setEventInfo);
			**/
			return mpList;
		} catch (IDMFrameDBErrorSignal ex) {
			log.error(ex, ex);
			throw ex;
		} catch (NotFoundSignal ex) {
			log.error(ex, ex);
			throw ex;
		}
	}
	
	public String getMaterialSpecaMaterialTypeIfPMSByReceiveactno(EventInfo eventInfo, String siteName, String receiveActno) {
		String materialType = "";
		String queryMaterialSpecSql = "SELECT ms.MATERIALTYPE FROM	MATERIALPACKING mq,	MATERIALSPEC ms WHERE " + 
				"	mq.SITENAME = :SITENAME " + 
				"	AND mq.RECEIVEACTNO = :RECEIVEACTNO " + 
				"	AND mq.SITENAME = ms.SITENAME " + 
				"	AND mq.MATERIALSPECNAME = ms.MATERIALSPECNAME ";
		Map<String, Object> queryMaterialSpecMap = new HashMap<String, Object>();
		queryMaterialSpecMap.put("SITENAME", siteName);
		queryMaterialSpecMap.put("RECEIVEACTNO", receiveActno);
		List<Map<String, Object>> sqlResult = IDMFrameServiceProxy.getSqlTemplate().queryForList(queryMaterialSpecSql,
				queryMaterialSpecMap);
		if (null != sqlResult && sqlResult.size() > 0) {
			materialType = sqlResult.get(0).get("MATERIALTYPE").toString();
		}
		return materialType;
	}
	
	//插入出库信息
	public void insertStockOutInfoPreStocked(List<MaterialUnDoinfo> materialUnDoinfoList, EventInfo eventInfo,
			String receiveActNo,String stockState) throws Exception {
		// List<MaterialUnDoinfo> materialUnDoinfoList=new
		// ERPInterfaceServiceImpl().erpInterface_WMS19(shipType,requestDetailName,eventInfo);

		if (materialUnDoinfoList.size() == 0) {
			throw new CustomException("PK-0001", "", "");
		}

		try {
			String sql_sel = "SELECT MATERIALPACKINGNAME,SITENAME FROM MATERIALPACKING  where  RECEIVEACTNO = :receiveActNo";
			String update = "UPDATE MATERIALPACKING SET STOCKSTATE= :STOCKSTATE where  RECEIVEACTNO = :receiveActNo";
			// String sql_sel2 = "SELECT MATERIALPACKINGNAME,SITENAME ，LASTEVENTTIMEKEY FROM
			// MATERIALPACKING where UNDODETAILNAME=:seq";
			// String
			// sql="update MATERIALPACKING set UNDODETAILNAME=:unDoDetailName,UNDOID=:unDoID
			// where UNDODETAILNAME=:seq";
			String sql2 = insertUnDOMaterialPackingInfo_v3
					+ "select P.SITENAME,P.MATERIALPACKINGNAME,P.LASTEVENTTIMEKEY FROM MATERIALPACKING P WHERE  P.RECEIVEACTNO = :receiveActNo )	";
			String upACT = "UPDATE MATERIALRECEIVEACT T SET T.RECEIVEACTSTATE = 'Received' WHERE T.RECEIVEACTNO = :receiveActNo";// 更新抬头文本
																																	// 20230216
			for (int i = 0; i < materialUnDoinfoList.size(); i++) {
				Map<String, Object> bindMap = new HashMap<String, Object>();
				Map<String, Object> bindMap1 = new HashMap<String, Object>();
//						if(materialUnDoinfoList.get(i).getUnDoID().equalsIgnoreCase("0000")||materialUnDoinfoList.get(i).getUnDoID().equalsIgnoreCase("0000")){
//							continue;
//						}
				if (materialUnDoinfoList.get(i).getSeq().length() > 15) {
					bindMap1.put("seq", materialUnDoinfoList.get(i).getSeq().substring(15));
				} else {
					bindMap1.put("seq", materialUnDoinfoList.get(i).getSeq());
				}

				bindMap1.put("receiveActNo", receiveActNo);
				
				List<Map<String, Object>> sqlResult = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql_sel,
						bindMap1);
				List<MaterialPackingKey> materialPackingKeyList = new ArrayList<MaterialPackingKey>();
				for (int j = 0; j < sqlResult.size(); j++) {
					MaterialPackingKey keyInfo = new MaterialPackingKey();
					keyInfo.setMaterialPackingName(sqlResult.get(j).get("MATERIALPACKINGNAME").toString());
					keyInfo.setSiteName(sqlResult.get(j).get("SITENAME").toString());
					// materialPackingInfo.setKey(keyInfo);
					materialPackingKeyList.add(keyInfo);
				}
				SetEventInfo setEventInfo = new SetEventInfo();
				Map<String, Object> bindMap2 = new HashMap<String, Object>();
				bindMap2.put("unDoDetailName", materialUnDoinfoList.get(i).getUnDoDetailName());
				bindMap2.put("unDoID", materialUnDoinfoList.get(i).getUnDoID());
				bindMap2.put("erpState", "SUCCESS");
				bindMap2.put("oldStockState", "Stocked");
				setEventInfo.setUserColumns(bindMap2);
				bindMap.put("unDoDetailName", materialUnDoinfoList.get(i).getUnDoDetailName());
				bindMap.put("unDoID", materialUnDoinfoList.get(i).getUnDoID());
				if (materialUnDoinfoList.get(i).getSeq().length() > 15) {
					bindMap.put("seq", materialUnDoinfoList.get(i).getSeq().substring(15));
				} else {
					bindMap.put("seq", materialUnDoinfoList.get(i).getSeq());
				}
				// bindMap.put("seq", materialUnDoinfoList.get(i).getSeq().substring(15));
				bindMap.put("UNDOIDDATE", materialUnDoinfoList.get(i).getUnDoIdDate());
				bindMap.put("receiveActNo", receiveActNo);
				bindMap.put("LASTEVENTNAME", eventInfo.getEventName());
				bindMap.put("LASTEVENTCOMMENT", eventInfo.getEventComment());
				// IDMFrameServiceProxy.getSqlTemplate().update(sql2,
				// bindMap1);
				/**
				bindMap1.put("STOCKSTATE", stockState);//PreStocked
				IDMFrameServiceProxy.getSqlTemplate().update(update, bindMap1);
				**/
				IDMFrameServiceProxy.getSqlTemplate().update(upACT, bindMap1);
				if (i == 0) {
					int count = IDMFrameServiceProxy.getSqlTemplate().update(sql2, bindMap);
				}

				MaterialPackingServiceProxy.getMaterialPackingService().setEvent(materialPackingKeyList, eventInfo,
						setEventInfo);
			}
			// MaterialPackingServiceProxy.getMaterialPackingService().makeScrapped(materialPackingKey,
			// eventInfo, makeScrappedInfo);
		} catch (IDMFrameDBErrorSignal ex) {
			log.error(ex, ex);
			throw ex;
		} catch (NotFoundSignal ex) {
			log.error(ex, ex);
			throw ex;
		}
	}
	
	public String getMaterialSpecaByMaterialTypeIfPMS(EventInfo eventInfo, String siteName, String receiveActno) {
		String materialType = "";
		String queryMaterialSpecSql = "SELECT ms.MATERIALTYPE FROM "
				+ "	 MATERIALRECEIVEACT me,MATERIALSHIPREQUESTDETAIL mq,MATERIALSPEC ms " + "WHERE "
				+ "	me.SITENAME =:SITENAME " + "	AND me.RECEIVEACTNO = :SHIPREQUESTNAME "
				+ "	AND me.SITENAME = mq.SITENAME " + "	AND me.RECEIVEREQUESTNAME = mq.SHIPREQUESTNAME "
				+ "	AND mq.SITENAME = mq.SITENAME " + "	AND mq.MATERIALSPECNAME = ms.MATERIALSPECNAME ";
		Map<String, Object> queryMaterialSpecMap = new HashMap<String, Object>();
		queryMaterialSpecMap.put("SITENAME", siteName);
		queryMaterialSpecMap.put("SHIPREQUESTNAME", receiveActno);
		List<Map<String, Object>> sqlResult = IDMFrameServiceProxy.getSqlTemplate().queryForList(queryMaterialSpecSql,
				queryMaterialSpecMap);
		if (null != sqlResult && sqlResult.size() > 0) {
			materialType = sqlResult.get(0).get("MATERIALTYPE").toString();
		}
		return materialType;
	}

	
	// 校验物料是否拒收
		public void checkLimitedSpecByShipRequest(EventInfo eventInfo, String siteName, String receiveQty,
				String receiveRequestName, String receiveRequestDetailName, String shipRequestName,
				String shipRequestDetailName, String materialSpecName, String receiveActno, String flag) throws Throwable {

			boolean limitFlag = false;
			String createSql = "select * from MATERIALLIMITSPEC where SITENAME=:SITENAME and  MATERIALSPECNAME=:MATERIALSPECNAME ";
			Map<String, Object> createMap = new HashMap<String, Object>();
			createMap.put("SITENAME", siteName);
			createMap.put("MATERIALSPECNAME", materialSpecName);

			List<Map<String, Object>> checkResult = IDMFrameServiceProxy.getSqlTemplate().queryForList(createSql,
					createMap);
			if (checkResult.size() > 0)
				limitFlag = true;
			if (!receiveRequestName.equals("") && !receiveRequestDetailName.equals("") && limitFlag) {
				String sql = "select LIMITEDQUANTITY-RECEIVEDQUANTITY AS leftQty from MATERIALLIMITSPEC where SITENAME=:SITENAME and  MATERIALSPECNAME=:MATERIALSPECNAME ";
				Map<String, Object> bindMap = new HashMap<String, Object>();
				bindMap.put("SITENAME", siteName);
				bindMap.put("MATERIALSPECNAME", materialSpecName);

				List<Map<String, Object>> sqlResult = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, bindMap);
				Double leftQty = Double.parseDouble(sqlResult.get(0).get("leftQty").toString());
				Double receivedQty = Double.parseDouble(receiveQty);
				if (receivedQty > leftQty) {
					// oic端创建box会先生成抬头行项目和接收数量绑定，不创建box需要还原
					if ("delete".equals(flag)) {
						MakeDetailDecreaseReceivedInfo makeDetailDecreaseReceivedInfo = new MakeDetailDecreaseReceivedInfo();
						MaterialReceiveRequestDetailKey materialReceiveRequestDetailKey = new MaterialReceiveRequestDetailKey();
						materialReceiveRequestDetailKey.setReceiveRequestName(receiveRequestName);
						materialReceiveRequestDetailKey.setSiteName(siteName);
						materialReceiveRequestDetailKey.setReceiveRequestDetailName(receiveRequestDetailName);

						makeDetailDecreaseReceivedInfo.setDecreaseQuantity(receivedQty);

						ReceiveRequestDetailServiceProxy.getReceiveRequestDetailService().decreaseReceivedQuantity(
								materialReceiveRequestDetailKey, eventInfo, makeDetailDecreaseReceivedInfo);

						// 删除行项目抬头
						String deleteDetailSql = "delete materialreceiveactDETAIL WHERE receiverequestname=:receiverequestname and receiverequestdetailname=:receiverequestdetailname "
								+ " and SITENAME=:siteName and RECEIVEACTNO=:receiveActno";
						Map<String, Object> deleteMap = new HashMap<String, Object>();
						deleteMap.put("receiverequestname", receiveRequestName);
						deleteMap.put("receiverequestdetailname", receiveRequestDetailName);
						deleteMap.put("siteName", siteName);
						deleteMap.put("receiveActno", receiveActno);
						IDMFrameServiceProxy.getSqlTemplate().update(deleteDetailSql, deleteMap);
					}
					throw new CustomException("ReceivedQuantityError", "");

				} else {
					bindMap.put("receivedQty", receiveQty);
					String updateSql = "update MATERIALLIMITSPEC set RECEIVEDQUANTITY=RECEIVEDQUANTITY+:receivedQty where SITENAME=:SITENAME and  MATERIALSPECNAME=:MATERIALSPECNAME ";

					IDMFrameServiceProxy.getSqlTemplate().update(updateSql, bindMap);
				}

			} else if (!shipRequestName.equals("") && !shipRequestDetailName.equals("") && limitFlag) {
				try {
					String usrSql = "SELECT queryString FROM BS_CustomQuery WHERE queryId = ? and version = ? ";
					String[] args = new String[] { "CheckDetailType", "00001" };

					List<Map<String, Object>> resultList = IDMFrameServiceProxy.getSqlTemplate().queryForList(usrSql, args);

					Map<String, Object> queryMap = resultList.get(0);
					String dbSql = queryMap.get("queryString").toString();
					dbSql = dbSql.replaceFirst(";\\s*$", "");

					Map<String, Object> bindMap1 = new HashMap<String, Object>();
					bindMap1.put("SITENAME", siteName);
					bindMap1.put("SHIPREQUESTNAME", shipRequestName);

					List<Map<String, Object>> sqlR = IDMFrameServiceProxy.getSqlTemplate().queryForList(dbSql, bindMap1);
					// 需要限制收货数量
					if (sqlR.size() > 0) {

						String sql = "select LIMITEDQUANTITY-RECEIVEDQUANTITY AS leftQty from MATERIALLIMITSPEC where SITENAME=:SITENAME and  MATERIALSPECNAME=:MATERIALSPECNAME ";
						Map<String, Object> bindMap = new HashMap<String, Object>();
						bindMap.put("SITENAME", siteName);
						bindMap.put("MATERIALSPECNAME", materialSpecName);

						List<Map<String, Object>> sqlResult = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql,
								bindMap);
						Double leftQty = Double.parseDouble(sqlResult.get(0).get("leftQty").toString());
						Double receivedQty = Double.parseDouble(receiveQty);
						if (receivedQty > leftQty) {
							// oic端创建box会先生成抬头行项目和接收数量绑定，不创建box需要还原
							if ("delete".equals(flag)) {
								// 删除行项目已经接收的数量
								MakeShipDetailDecreaseAssignedInfo makeShipDetailDecreaseAssignedInfo = new MakeShipDetailDecreaseAssignedInfo();
								MaterialShipRequestDetailKey materialShipRequestDetailKey = new MaterialShipRequestDetailKey();
								materialShipRequestDetailKey.setShipRequestName(shipRequestName);
								materialShipRequestDetailKey.setSiteName(siteName);
								materialShipRequestDetailKey.setShipRequestDetailName(shipRequestDetailName);
								makeShipDetailDecreaseAssignedInfo.setAssignedQuantity(receivedQty);
								MaterialShipRequestDetailServiceProxy.getMaterialShipRequestDetailService()
										.decreaseAssignedQuantity(materialShipRequestDetailKey,
												makeShipDetailDecreaseAssignedInfo);
								// 删除行项目抬头
								String deleteDetailSql = "delete materialreceiveactDETAIL WHERE receiverequestname=:receiverequestname and receiverequestdetailname=:receiverequestdetailname "
										+ " and SITENAME=:siteName and RECEIVEACTNO=:receiveActno";
								Map<String, Object> deleteMap = new HashMap<String, Object>();
								deleteMap.put("receiverequestname", shipRequestName);
								deleteMap.put("receiverequestdetailname", shipRequestDetailName);
								deleteMap.put("siteName", siteName);
								deleteMap.put("receiveActno", receiveActno);
								IDMFrameServiceProxy.getSqlTemplate().update(deleteDetailSql, deleteMap);
							}
							throw new CustomException("ReceivedQuantityError", "");
						} else {
							bindMap.put("receivedQty", receiveQty);
							String updateSql = "update MATERIALLIMITSPEC set RECEIVEDQUANTITY=RECEIVEDQUANTITY+:receivedQty where SITENAME=:SITENAME and  MATERIALSPECNAME=:MATERIALSPECNAME ";

							IDMFrameServiceProxy.getSqlTemplate().update(updateSql, bindMap);
						}

					}
				} catch (Throwable e) {

					throw e;
				}
			}
		}
		
		
		public void checkMaterialShipRequestState(String receiveActNo, String shipRequestName) throws Exception {
			try {
				String sql2 = "SELECT * FROM materialpacking "
						+ "WHERE  receiveActNo=:receiveActNo and erpstate='ERPSUCCESS' ";


				Map<String, Object> bindMap3 = new HashMap<String, Object>();
				bindMap3.put("receiveActNo", receiveActNo);

				List<Map<String, Object>> queryResult2 = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql2, bindMap3);
				if (queryResult2.size() > 0) {
					throw new CustomException("AccoutTimeOut", "", "");
				}
				String sql = "SELECT SHIPREQUESTSTATE FROM MATERIALSHIPREQUEST WHERE SHIPREQUESTNAME=:SHIPREQUESTNAME FOR UPDATE";
				Map<String, Object> bindMap1 = new HashMap<String, Object>();
				bindMap1.put("SHIPREQUESTNAME", shipRequestName);
				List<Map<String, Object>> sqlResult = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, bindMap1);
				if (sqlResult.size() == 0) {
					throw new CustomException("ACTSTATEERROR", "", "");
				}
			} catch (Exception ex) {
				ex.printStackTrace();
				throw ex;
			}
		}

		

}


 
