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

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import 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.Content;
import org.jdom.Document;
import org.jdom.Element;

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.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.util.CommonValidation;
import com.cim.idm.wmsextend.generic.util.SMessageUtil;
import com.cim.idm.mwmsextend.materialpacking.service.MaterialPackingServiceImpl;
import com.cim.idm.mwmsextend.materialreceiverequest.service.MaterialReceiveRequestServiceImpl;
import com.cim.idm.wmsextend.generic.wmsmail.MailUtil;
import com.cim.idm.wmspackage.inbounddeliveryorder.data.InnerRequestDetailInfo;
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.SetEventInfo;
import com.cim.idm.wmspackage.materialprocessgroup.MaterialProcessGroupServiceProxy;
import com.cim.idm.wmspackage.materialprocessgroup.management.info.MaterialProcessGroupCreateInfo;
import com.cim.idm.wmspackage.materialreceiverequestact.MaterialReceiveRequestActServiceProxy;
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.MaterialShipRequestSetEventInfo;
import com.cim.idm.wmspackage.materialshiprequestdetail.MaterialShipRequestDetailServiceProxy;
import com.cim.idm.wmspackage.materialshiprequestdetail.management.data.MaterialShipRequestDetailKey;
import com.cim.idm.wmspackage.materialshiprequestdetail.management.info.MakeShipDetailIncreaseAssignedInfo;
import com.cim.idm.wmspackage.materialundo.info.MaterialUnDoinfo;
import com.cim.idm.wmspackage.name.NameServiceProxy;
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.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;


public class MaterialPackingStockInImpl {
	private static Log log = LogFactory.getLog(ERPInterfaceServiceImpl.class);
	static String factory = System.getProperty("factory");
	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,NPFLAG)"
			+ "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,NPFLAG"
			+ " from MATERIALPACKING  "
			+ " where UNDOID=:unDoID and UNDODETAILNAME=:UNDODETAILNAME";

	

    // （2）MaterialPackingStockInImpl.java文件中增加sendSplitBoxToTQMS方法
	public void SaveUnDoInfo(String receiveActNO, String undodate, String undoid) {

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

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

	}

	public void SaveUnDoInfoWO(String receiveActNO, String undodate,
			String undoid, String undoIDDetail) {

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

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

	}

	public void SaveOQAUnDoInfo(String undodate, String undoid) throws Exception {

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

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

	}

	public void SaveNoOQANormalStockInInfo(String receiveRequestName,
			String receiveRequestDetailName, String receiveActNo,
			String siteName, EventInfo eventinfo) {

		List<MaterialPacking> mp = new MaterialPackingStockInUtil()
				.GetOQAGroupList(receiveRequestName, receiveRequestDetailName,
						receiveActNo);
		for (MaterialPacking p : mp) {
			p.setMaterialProcessGroupName("NoOQA");
			p.setPackingState("Released");
			// p.setOqaResultState(GenericServiceProxy.getConstantMap().OQA_State_Pre);
		}
		MaterialPackingServiceProxy.getMaterialPackingService().update(mp);
		// 更改MaterialReceiveRequestAct表中的RECEIVEACTSTATE为received
		// int result2 =
		// MaterialReceiveRequestActProxy.MaterialReceiveRequestAct

		MaterialReceiveActKey key = new MaterialReceiveActKey();
		key.setReceiveactNO(receiveActNo);
		key.setReceiveRequestName(receiveRequestName);
		key.setSiteName(siteName);
		MaterialReceiveRequestActServiceProxy.getReceiveRequestBatchService()
				.makeReceived(key, eventinfo, null);
		// 这个更新状态应该有问题 ！！！
	}

	public Boolean IsOQAMaterial(String receiveRequestName,
			String receiveRequestDetailName, String siteName) {

		boolean isoqa = new MaterialPackingStockInUtil().GetOQAInfo(
				receiveRequestName, receiveRequestDetailName, siteName);
		return isoqa;
	}




	public void SaveDumpStockInList(String acttype, String sitename,
			List<MaterialStockInClass> msilist, EventInfo eventInfo) {
		// 首先从shiprequest表中查找出ERPlocation和移动类型，根据ERPlocation决定OQAResult和oqaresultstate，用以修改box信息
		if (msilist != null) {
			MaterialShipRequestKey mspk = new MaterialShipRequestKey();
			mspk.setSiteName(msilist.get(0).getSiteName());
			mspk.setShipRequestName(msilist.get(0).getReceiveRequestName());
			MaterialShipRequest msp = MaterialShipRequestServiceProxy
					.getMaterialShipRequestService().selectByKey(mspk);
			String toFactory = msp.getErpReceiveFactory();
			String toLocation = msp.getErpReceiveLocation();
			String toSitename = new CommonValidation().getSiteName(toFactory);
			for (int i = 0; i < msilist.size(); i++) {
				MaterialStockInClass msa = msilist.get(i);
				if (msa.getActtype().equals("DUMP")) {

					List<MaterialPacking> mplist = new MaterialPackingStockInUtil()
							.GetDumpStockInList(msa.getSiteName(),
									msa.getReceiveRequestName(),
									msa.getReceiveRequestDetailName());
					if (mplist.size() > 0) {
						Date date = new Date();
						SimpleDateFormat df = new SimpleDateFormat(
								"yyyy-MM-dd HH:mm:ss");
						String receivedate = df.format(date);
						for (MaterialPacking mp : mplist) {
							// MaterialPackingServiceProxy.getMaterialPackingService().delete(mp.getKey());
							MaterialPackingKey mpkey = new MaterialPackingKey();
							mpkey.setSiteName(mp.getKey().getSiteName());
							mpkey.setMaterialPackingName(mp.getKey()
									.getMaterialPackingName());

							String sql1 = " update MaterialPacking set siteName =:sitename where materialPackingName=:materialPackingName and siteName=:oldsitename";
							// String sql2 =
							// " update MaterialPackingHistory set siteName =:sitename where materialPackingName=:materialPackingName and siteName=:oldsitename";
							Map<String, Object> bindMap1 = new HashMap<String, Object>();
							bindMap1.put("sitename", toSitename);
							bindMap1.put("materialPackingName", mp.getKey()
									.getMaterialPackingName());
							bindMap1.put("oldsitename", mp.getKey()
									.getSiteName());
							// bindMap1.put("erpFactory", toFactory);
							// bindMap1.put("erpLocation", toLocation);
							IDMFrameServiceProxy.getSqlTemplate().update(sql1,
									bindMap1);
							// IDMFrameServiceProxy.getSqlTemplate().update(sql2,
							// bindMap1);

							Map<String, Object> bindMap = new HashMap<String, Object>();
							bindMap.put("erpFactory", toFactory);
							bindMap.put("packingState", "Received");
							bindMap.put("stockState", "Stocked");
							bindMap.put("erpLocation", toLocation);
							bindMap.put("receiveUser", eventInfo.getEventUser());
							bindMap.put("receiveTime",
									Timestamp.valueOf(receivedate));
							SetEventInfo setevent = new SetEventInfo();// 以后改成可传参的
							setevent.setUserColumns(bindMap);
							mpkey.setSiteName(toSitename);

							eventInfo.setReasonCode(mp.getReasonCode());
							eventInfo.setReasonCodeType(mp.getReasonCodeType());

							MaterialPackingServiceProxy
									.getMaterialPackingService().setEvent(
											mpkey, eventInfo, setevent);

						}
					}
				}
			}
		}
	}

	public List<MaterialPacking> SaveRefundStockInListForERPAccount(List<MaterialStockInClass> msilist,
			List<MaterialUnDoinfo> undolist, EventInfo eventinfo,String messageID)
			throws Exception {

		if (msilist.size() <= 0 || undolist.size() <= 0) {
			throw (new Exception("ERP返回结果为" + undolist.size()));
		}
		List<MaterialPacking> tqmsList=new ArrayList<MaterialPacking>();
		try {
			
			List<MaterialPackingKey> mpklist = new ArrayList<MaterialPackingKey>();
			List<SetEventInfo> eventlist = new ArrayList<SetEventInfo>();
			CommonValidation cv = new CommonValidation();
			for (int i = 0; i < msilist.size(); i++) {
				MaterialStockInClass msa = msilist.get(i);
				MaterialUnDoinfo undo = null;
				List<MaterialPacking> materialPackingList = new MaterialPackingStockInUtil()
				.GetBackStockInList(msa);
				for (int j = 0; j < undolist.size(); j++) {
					String a = undolist.get(j).getSeq();
					String b = materialPackingList.get(0).getMessageId()+ Integer.toString(i + 1);

					if (a.equals(b)) {
						undo = undolist.get(j);
						break;
					}
				}

				String oqaresult = "";
				// 首先从shiprequest表中查找出ERPlocation和移动类型，根据ERPlocation决定OQAResult和oqaresultstate，用以修改box信息
				if (msa.getActtype().equals("Refund")||msa.getActtype().equals("WO")||msa.getActtype().equals("POOEM")) {
					String grade = new CommonValidation()
							.getGradeByErplocation(msa.getErpfactory(),
									msa.getErplocation());
					if (grade.equals("zp")) {
						oqaresult = "OK";
					} else if (grade == "cs") {
						oqaresult = "OK";
					} else if (grade == "zs") {
						oqaresult = "OK";
					} else {	
						oqaresult = "OK";
					}



					for (MaterialPacking mp : materialPackingList) {
						MaterialPackingKey mpkey = new MaterialPackingKey();
						mpkey.setSiteName(mp.getKey().getSiteName());
						mpkey.setMaterialPackingName(mp.getKey()
								.getMaterialPackingName());
						mpklist.add(mpkey);
						SetEventInfo setevent = new SetEventInfo();
						Map<String, Object> bindMap = new HashMap<String, Object>();
						bindMap.put("packingState", "Released");
						bindMap.put("stockState", "Stocked");
						bindMap.put("charge", msa.getCharge());
						bindMap.put("kostl", msa.getKostl());
						bindMap.put("unDoID", undo.getUnDoID());
						bindMap.put("unDoDetailName", undo.getUnDoDetailName());
						bindMap.put(
								"erpEventTime",
								Timestamp.valueOf(cv.getDate(msa
										.getReceiveTime()) + " 00:00:00"));
						bindMap.put(
								"stockInType",
								msa.getActtype() + ":"
										+ msa.getShipRequestDetailType());
						//BMDT 311移库不需要质检
			            if(mp.getKey().getSiteName()=="BMDT"){
			            	if(mp.getReasonCodeType().equals("311")||mp.getReasonCodeType().equals("926"))
							{
								
								bindMap.put("packingGrade", "OK");
								bindMap.put("oqaResult", "OK");
								bindMap.put("oqaResultState", "END");
							}
							else
							{
								bindMap.put("oqaResult", "");
								bindMap.put("packingGrade", "");
								bindMap.put(
										"oqaResultState",
										GenericServiceProxy.getConstantMap().OQA_State_Pre);
								bindMap.put("materialProcessGroupName",
											"OICOQA");
							}
			            }
						else
						{
						if(mp.getReasonCodeType().equals("503"))
						{
							if(cv.getIQCFlagOfMaterialSpec(msa.getMaterialSpecName(), msa.getErpfactory())){
								bindMap.put("oqaResult", "");
								bindMap.put("packingGrade", "");
								bindMap.put("materialProcessGroupName",
										"OICOQA");
								bindMap.put(
										"oqaResultState",
										GenericServiceProxy.getConstantMap().OQA_State_Pre);
								tqmsList.add(mp);
							}//add by mxh  for b10 new need
							else
							{
								bindMap.put("packingGrade", "OK");
								bindMap.put(
										"oqaResultState",
										GenericServiceProxy.getConstantMap().OQA_State_End);
								bindMap.put("oqaResult","OK");
							}
						}
						else if(mp.getReasonCodeType().equals("505"))
						{
							bindMap.put("packingGrade", "NG");
							bindMap.put(
									"oqaResultState",
									GenericServiceProxy.getConstantMap().OQA_State_End);
							bindMap.put("oqaResult","NG");
						}
						else{
							bindMap.put("packingGrade", "OK");
							bindMap.put("oqaResult", oqaresult);
							bindMap.put("oqaResultState", "END");
						}}
						bindMap.put("messageId", mp.getErpState().equalsIgnoreCase("ERPSUCCESS")?mp.getMessageId():messageID);
						Date date = new Date();
						SimpleDateFormat df = new SimpleDateFormat(
								"yyyy-MM-dd HH:mm:ss");
						String receivedate = df.format(date);
						bindMap.put("receiveTime",
								Timestamp.valueOf(receivedate));
						bindMap.put("receiveUser", eventinfo.getEventUser());
						bindMap.put("erpState", "SUCCESS");
						setevent.setUserColumns(bindMap);
						eventlist.add(setevent);
						eventinfo.setReasonCode(mp.getReasonCode());
						eventinfo.setReasonCodeType(mp.getReasonCodeType());
						eventinfo.setEventName("RefundStockIn");
						eventinfo.setEventComment("RefundStockIn");
						MaterialPackingServiceProxy.getMaterialPackingService()
								.setEvent(mpkey, eventinfo, setevent);
					}
					// MaterialPackingServiceProxy.getMaterialPackingService().setEvent(mpklist,
					// eventinfo, eventlist);

				}else if(msa.getActtype().equals("BMDTOEM")||msa.getActtype().equals("ERPReserve")){
					
					
					List<MaterialPacking> mplist = new MaterialPackingStockInUtil()
					.GetBackStockInList(msa);

					for (MaterialPacking mp : mplist) {
						MaterialPackingKey mpkey = new MaterialPackingKey();
						mpkey.setSiteName(mp.getKey().getSiteName());
						mpkey.setMaterialPackingName(mp.getKey()
								.getMaterialPackingName());
						mpklist.add(mpkey);
						SetEventInfo setevent = new SetEventInfo();
						Map<String, Object> bindMap = new HashMap<String, Object>();
						bindMap.put("packingState", "Released");
						bindMap.put("stockState", "Stocked");
						bindMap.put("oqaResult", "");
						bindMap.put("packingGrade", "");
						bindMap.put("materialProcessGroupName",
									"OICOQA");
						bindMap.put(
									"oqaResultState",
									GenericServiceProxy.getConstantMap().OQA_State_Pre);
							tqmsList.add(mp);
						bindMap.put("charge", msa.getCharge());
						bindMap.put("kostl", msa.getKostl());
						bindMap.put("unDoID", undo.getUnDoID());
						bindMap.put("unDoDetailName", undo.getUnDoDetailName());
						bindMap.put(
								"erpEventTime",
								Timestamp.valueOf(cv.getDate(msa
										.getReceiveTime()) + " 00:00:00"));
						bindMap.put(
								"stockInType",
								msa.getActtype() + ":"
										+ msa.getShipRequestDetailType());
						Date date = new Date();
						SimpleDateFormat df = new SimpleDateFormat(
								"yyyy-MM-dd HH:mm:ss");
						String receivedate = df.format(date);
						bindMap.put("receiveTime",
								Timestamp.valueOf(receivedate));
						bindMap.put("receiveUser", eventinfo.getEventUser());
						bindMap.put("erpState", "SUCCESS");
						setevent.setUserColumns(bindMap);
						eventlist.add(setevent);
						eventinfo.setReasonCode(mp.getReasonCode());
						eventinfo.setReasonCodeType(mp.getReasonCodeType());
						eventinfo.setEventName("BMDTOEMStockIn");
						eventinfo.setEventComment("BMDTOEMStockIn");
						MaterialPackingServiceProxy.getMaterialPackingService()
								.setEvent(mpkey, eventinfo, setevent);
					}
					
				}else {
				
					List<MaterialPacking> mplist = new MaterialPackingStockInUtil()
							.GetBackStockInList(msa);

					for (MaterialPacking mp : mplist) {
						MaterialPackingKey mpkey = new MaterialPackingKey();
						mpkey.setSiteName(mp.getKey().getSiteName());
						mpkey.setMaterialPackingName(mp.getKey()
								.getMaterialPackingName());
						mpklist.add(mpkey);
						SetEventInfo setevent = new SetEventInfo();
						Map<String, Object> bindMap = new HashMap<String, Object>();
						bindMap.put("packingState", "Released");
						bindMap.put("stockState", "Stocked");
						if(mp.getReasonCodeType().equals("503")){
							bindMap.put("packingGrade", "");
							bindMap.put("oqaResult", "");
							bindMap.put("oqaResultState", "PREOQA");
							bindMap.put("materialProcessGroupName",
									"OICOQA");
							tqmsList.add(mp);
						}//add by mxh  for b10 new need
						
						else if(mp.getReasonCodeType().equals("505"))
						{
							bindMap.put("packingGrade", "NG");
							bindMap.put("oqaResult", oqaresult);
							bindMap.put("oqaResultState", "END");
						}else if(mp.getKey().getSiteName().equals("B7")&&mp.getReasonCodeType().equals("Z32"))//B7新增20190415
						{
							bindMap.put("packingGrade", "OK");
							bindMap.put("oqaResult", "OK");
							bindMap.put("oqaResultState", "END");
						}else if(mp.getKey().getSiteName().equals("B11")&&mp.getReasonCodeType().equals("501"))//B11新增20190712
						{
							bindMap.put("packingGrade", "OK");
							bindMap.put("materialProcessGroupName","OICOQA");
							bindMap.put("oqaResult","OK");
							bindMap.put("oqaResultState", "END");
						} else if (mp.getKey().getSiteName().equals("B12")&&mp.getReasonCodeType().equals("501")) {
							bindMap.put("packingGrade", "OK");
							bindMap.put("oqaResult", "OK");
							bindMap.put("oqaResultState", "END");
							bindMap.put("materialProcessGroupName","OICOQA");
						}else{
							bindMap.put("packingGrade", "OK");
							bindMap.put("oqaResult", "OK");
							bindMap.put("oqaResultState", "END");
							bindMap.put("materialProcessGroupName","OICOQA");
						}
						bindMap.put("messageId", mp.getErpState().equalsIgnoreCase("ERPSUCCESS")?mp.getMessageId():messageID);
						bindMap.put("charge", msa.getCharge());
						bindMap.put("kostl", msa.getKostl());
						bindMap.put("unDoID", undo.getUnDoID());
						bindMap.put("unDoDetailName", undo.getUnDoDetailName());
						bindMap.put(
								"erpEventTime",
								Timestamp.valueOf(cv.getDate(msa
										.getReceiveTime()) + " 00:00:00"));
						bindMap.put(
								"stockInType",
								msa.getActtype() + ":"
										+ msa.getShipRequestDetailType());
						Date date = new Date();
						SimpleDateFormat df = new SimpleDateFormat(
								"yyyy-MM-dd HH:mm:ss");
						String receivedate = df.format(date);
						bindMap.put("receiveTime",
								Timestamp.valueOf(receivedate));
						bindMap.put("receiveUser", eventinfo.getEventUser());
						bindMap.put("erpState", "SUCCESS");
						setevent.setUserColumns(bindMap);
						eventlist.add(setevent);
						eventinfo.setReasonCode(mp.getReasonCode());
						eventinfo.setReasonCodeType(mp.getReasonCodeType());
						eventinfo.setEventName("RefundStockIn");
						eventinfo.setEventComment("RefundStockIn");
						MaterialPackingServiceProxy.getMaterialPackingService()
								.setEvent(mpkey, eventinfo, setevent);

					}
					// MaterialPackingServiceProxy.getMaterialPackingService().setEvent(mpklist,
					// eventinfo, eventlist);
				}

				MaterialReceiveActKey mrk = new MaterialReceiveActKey();
				mrk.setSiteName(msa.getSiteName());
				mrk.setReceiveactNO(msa.getReceiveActNo());
				mrk.setReceiveRequestName(msa.getReceiveRequestName());
				com.cim.idm.wmspackage.materialreceiverequestact.management.info.SetEventInfo setevent1 = new 

com.cim.idm.wmspackage.materialreceiverequestact.management.info.SetEventInfo();
				Map<String, Object> bindMap1 = new HashMap<String, Object>();
				bindMap1.put("receiveActState", "Received");
				setevent1.setUserColumns(bindMap1);
				MaterialReceiveRequestActServiceProxy
						.getReceiveRequestBatchService().setEvent(mrk,
								eventinfo, setevent1);

				// 存物料凭证
				// 针对WO中对LCM的领料问题，同一笔过账会出现多个物料凭证号。
				SaveUnDoInfoWO(msilist.get(0).getReceiveActNo(),
						undo.getUnDoIdDate(), undo.getUnDoID(),
						undo.getUnDoDetailName());

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

		return tqmsList;
	}
	
	public List<MaterialPacking> SaveRefundStockInList(List<MaterialStockInClass> msilist,
			List<MaterialUnDoinfo> undolist, EventInfo eventinfo)
			throws Exception {

		if (msilist.size() <= 0 || undolist.size() <= 0) {
			throw (new Exception("ERP返回结果为" + undolist.size()));
		}
		List<MaterialPacking> tqmsList=new ArrayList<MaterialPacking>();
		try {
			List<MaterialPackingKey> mpklist = new ArrayList<MaterialPackingKey>();
			
			List<SetEventInfo> eventlist = new ArrayList<SetEventInfo>();
			CommonValidation cv = new CommonValidation();
			for (int i = 0; i < msilist.size(); i++) {
				MaterialStockInClass msa = msilist.get(i);
				MaterialUnDoinfo undo = null;

				for (int j = 0; j < undolist.size(); j++) {
					String a = undolist.get(j).getSeq();
					String b = Integer.toString(i + 1);

					if (a.equals(b)) {
						undo = undolist.get(j);
						break;
					}
				}

				String oqaresult = "";
				// 首先从shiprequest表中查找出ERPlocation和移动类型，根据ERPlocation决定OQAResult和oqaresultstate，用以修改box信息
				if (msa.getActtype().equals("Refund")) {
					String grade = new CommonValidation()
							.getGradeByErplocation(msa.getErpfactory(),
									msa.getErplocation());
					if (grade.equals("zp")) {
						oqaresult = "OK";
					} else if (grade == "cs") {
						oqaresult = "OK";
					} else if (grade == "zs") {
						oqaresult = "OK";
					} else {	
						oqaresult = "OK";
					}

					List<MaterialPacking> mplist = new MaterialPackingStockInUtil()
							.GetBackStockInList(msa);

					for (MaterialPacking mp : mplist) {
						MaterialPackingKey mpkey = new MaterialPackingKey();
						mpkey.setSiteName(mp.getKey().getSiteName());
						mpkey.setMaterialPackingName(mp.getKey()
								.getMaterialPackingName());
						mpklist.add(mpkey);
						SetEventInfo setevent = new SetEventInfo();
						Map<String, Object> bindMap = new HashMap<String, Object>();
						bindMap.put("packingState", "Released");
						bindMap.put("stockState", "Stocked");
						bindMap.put("charge", msa.getCharge());
						bindMap.put("unDoID", undo.getUnDoID());
						bindMap.put("unDoDetailName", undo.getUnDoDetailName());
						bindMap.put(
								"erpEventTime",
								Timestamp.valueOf(cv.getDate(msa
										.getReceiveTime()) + " 00:00:00"));
						bindMap.put(
								"stockInType",
								msa.getActtype() + ":"
										+ msa.getShipRequestDetailType());
						//B10 503移动类型需要判断是否需要质检
						if(mp.getReasonCodeType().equals("503"))
						{
							if(cv.getIQCFlagOfMaterialSpec(msa.getMaterialSpecName(), msa.getErpfactory())){
								bindMap.put("oqaResult", "");
								bindMap.put("packingGrade", "");
								bindMap.put("materialProcessGroupName",
										"OICOQA");
								bindMap.put(
										"oqaResultState",
										GenericServiceProxy.getConstantMap().OQA_State_Pre);
								tqmsList.add(mp);
							}//add by mxh  for b10 new need
							else
							{
								bindMap.put("packingGrade", "OK");
							}
						}
						if(mp.getReasonCodeType().equals("505"))
						{
							bindMap.put("packingGrade", "NG");
						}
						else{
							bindMap.put("packingGrade", "OK");
							bindMap.put("oqaResult", oqaresult);
							bindMap.put("oqaResultState", "END");
						}
						Date date = new Date();
						SimpleDateFormat df = new SimpleDateFormat(
								"yyyy-MM-dd HH:mm:ss");
						String receivedate = df.format(date);
						bindMap.put("receiveTime",
								Timestamp.valueOf(receivedate));
						bindMap.put("receiveUser", eventinfo.getEventUser());
						bindMap.put("erpState", "SUCCESS");
						setevent.setUserColumns(bindMap);
						eventlist.add(setevent);
						eventinfo.setReasonCode(mp.getReasonCode());
						eventinfo.setReasonCodeType(mp.getReasonCodeType());
						eventinfo.setEventName("RefundStockIn");
						eventinfo.setEventComment("RefundStockIn");
						MaterialPackingServiceProxy.getMaterialPackingService()
								.setEvent(mpkey, eventinfo, setevent);
					}
					// MaterialPackingServiceProxy.getMaterialPackingService().setEvent(mpklist,
					// eventinfo, eventlist);

				}else if(msa.getActtype().equals("BMDTOEM")){
					
					
					List<MaterialPacking> mplist = new MaterialPackingStockInUtil()
					.GetBackStockInList(msa);

					for (MaterialPacking mp : mplist) {
						MaterialPackingKey mpkey = new MaterialPackingKey();
						mpkey.setSiteName(mp.getKey().getSiteName());
						mpkey.setMaterialPackingName(mp.getKey()
								.getMaterialPackingName());
						mpklist.add(mpkey);
						SetEventInfo setevent = new SetEventInfo();
						Map<String, Object> bindMap = new HashMap<String, Object>();
						bindMap.put("packingState", "Released");
						bindMap.put("stockState", "Stocked");
						if(cv.getIQCFlagOfMaterialSpec(msa.getMaterialSpecName(), msa.getErpfactory())){
							bindMap.put("oqaResult", "");
							bindMap.put("packingGrade", "");
							bindMap.put("materialProcessGroupName",
									"OICOQA");
							bindMap.put(
									"oqaResultState",
									GenericServiceProxy.getConstantMap().OQA_State_Pre);
							tqmsList.add(mp);
							
						}//add by mxh  for b10 new need
						else
						{
							bindMap.put("packingGrade", "OK");
						}
						bindMap.put("charge", msa.getCharge());
						bindMap.put("unDoID", undo.getUnDoID());
						bindMap.put("unDoDetailName", undo.getUnDoDetailName());
						bindMap.put(
								"erpEventTime",
								Timestamp.valueOf(cv.getDate(msa
										.getReceiveTime()) + " 00:00:00"));
						bindMap.put(
								"stockInType",
								msa.getActtype() + ":"
										+ msa.getShipRequestDetailType());
						Date date = new Date();
						SimpleDateFormat df = new SimpleDateFormat(
								"yyyy-MM-dd HH:mm:ss");
						String receivedate = df.format(date);
						bindMap.put("receiveTime",
								Timestamp.valueOf(receivedate));
						bindMap.put("receiveUser", eventinfo.getEventUser());
						bindMap.put("erpState", "SUCCESS");
						setevent.setUserColumns(bindMap);
						eventlist.add(setevent);
						eventinfo.setReasonCode(mp.getReasonCode());
						eventinfo.setReasonCodeType(mp.getReasonCodeType());
						eventinfo.setEventName("BMDTOEMStockIn");
						eventinfo.setEventComment("BMDTOEMStockIn");
						MaterialPackingServiceProxy.getMaterialPackingService()
								.setEvent(mpkey, eventinfo, setevent);
					}
					
				}else {
				
					List<MaterialPacking> mplist = new MaterialPackingStockInUtil()
							.GetBackStockInList(msa);

					for (MaterialPacking mp : mplist) {
						MaterialPackingKey mpkey = new MaterialPackingKey();
						mpkey.setSiteName(mp.getKey().getSiteName());
						mpkey.setMaterialPackingName(mp.getKey()
								.getMaterialPackingName());
						mpklist.add(mpkey);
						SetEventInfo setevent = new SetEventInfo();
						Map<String, Object> bindMap = new HashMap<String, Object>();
						bindMap.put("packingState", "Released");
						bindMap.put("stockState", "Stocked");
						if(mp.getReasonCodeType().equals("503")){
							bindMap.put("packingGrade", "");
							bindMap.put("oqaResult", "");
							bindMap.put("oqaResultState", "PREOQA");
							tqmsList.add(mp);
						}//add by mxh  for b10 new need
						else
						{
							bindMap.put("packingGrade", "OK");
						}
						bindMap.put("charge", msa.getCharge());
						bindMap.put("unDoID", undo.getUnDoID());
						bindMap.put("unDoDetailName", undo.getUnDoDetailName());
						bindMap.put(
								"erpEventTime",
								Timestamp.valueOf(cv.getDate(msa
										.getReceiveTime()) + " 00:00:00"));
						bindMap.put(
								"stockInType",
								msa.getActtype() + ":"
										+ msa.getShipRequestDetailType());
						Date date = new Date();
						SimpleDateFormat df = new SimpleDateFormat(
								"yyyy-MM-dd HH:mm:ss");
						String receivedate = df.format(date);
						bindMap.put("receiveTime",
								Timestamp.valueOf(receivedate));
						bindMap.put("receiveUser", eventinfo.getEventUser());
						bindMap.put("erpState", "SUCCESS");
						setevent.setUserColumns(bindMap);
						eventlist.add(setevent);
						eventinfo.setReasonCode(mp.getReasonCode());
						eventinfo.setReasonCodeType(mp.getReasonCodeType());
						eventinfo.setEventName("RefundStockIn");
						eventinfo.setEventComment("RefundStockIn");
						MaterialPackingServiceProxy.getMaterialPackingService()
								.setEvent(mpkey, eventinfo, setevent);

					}
					// MaterialPackingServiceProxy.getMaterialPackingService().setEvent(mpklist,
					// eventinfo, eventlist);
				}

				MaterialReceiveActKey mrk = new MaterialReceiveActKey();
				mrk.setSiteName(msa.getSiteName());
				mrk.setReceiveactNO(msa.getReceiveActNo());
				mrk.setReceiveRequestName(msa.getReceiveRequestName());
				com.cim.idm.wmspackage.materialreceiverequestact.management.info.SetEventInfo setevent1 = new com.cim.idm.wmspackage.materialreceiverequestact.management.info.SetEventInfo();
				Map<String, Object> bindMap1 = new HashMap<String, Object>();
				bindMap1.put("receiveActState", "Received");
				setevent1.setUserColumns(bindMap1);
				MaterialReceiveRequestActServiceProxy
						.getReceiveRequestBatchService().setEvent(mrk,
								eventinfo, setevent1);

				// 存物料凭证
				// 针对WO中对LCM的领料问题，同一笔过账会出现多个物料凭证号。
				SaveUnDoInfoWO(msilist.get(0).getReceiveActNo(),
						undo.getUnDoIdDate(), undo.getUnDoID(),
						undo.getUnDoDetailName());

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

		return tqmsList;
	}
	public List<Map<String,Object>> getOEMPackingList(String siteName,String actNO)
	{
		List<Map<String,Object>> result=new ArrayList<Map<String,Object>>();
		try{
			String querySql="SELECT MP.MATERIALSPECNAME,MP.ERPLOCATION,MP.ERPFACTORY,SUM(MP.MATERIALQUANTITY) AS MATERIALQUANTITY,MP.CHARGE,MP.REASONCODETYPE FROM MATERIALPACKING MP"
							+" WHERE MP.SITENAME=:SITENAME"
							+" AND MP.RECEIVEACTNO=:RECEIVEACTNO"
				            +" AND MP.MATERIALQUANTITY>0"
							+" AND ((MP.MATERIALPACKINGTYPE='Box' AND MP.SUPERMATERIALPACKINGNAME IS NULL) OR MP.MATERIALPACKINGTYPE='Pallet')"
							+" GROUP BY MP.MATERIALSPECNAME,MP.ERPFACTORY,MP.ERPLOCATION,MP.CHARGE,MP.REASONCODETYPE ";	
			Map<String,String> map=new HashMap<String, String>();
			map.put("SITENAME", siteName);
			map.put("RECEIVEACTNO", actNO);
			result = IDMFrameServiceProxy.getSqlTemplate().queryForList(querySql, map);
		}catch(Exception e)
		{
			
		}
		return result;
	}
	public List<Map<String,Object>> getPreStockOutList(String siteName,String actNO)
	{
		List<Map<String,Object>> result=new ArrayList<Map<String,Object>>();
		try{
			//materialpacking中的ERPFACTORY和MATERIALSHIPREQUEST中的ERPFACTORYNAME不一致，以MATERIALSHIPREQUEST为主;MP.ERPFACTORY
			String querySql="SELECT MP.MATERIALSPECNAME,MP.ERPLOCATION,MS.ERPFACTORYNAME AS ERPFACTORY,SUM(MP.MATERIALQUANTITY) AS MATERIALQUANTITY,MP.CHARGE,MP.SHIPREQUESTNAME,MP.SHIPREQUESTDETAILNAME,MS.WORKORDERID,MS.SHIPREQUESTDETAILTYPE FROM MATERIALPACKING MP,MATERIALSHIPREQUEST MS,MATERIALSHIPREQUESTDETAIL MSD"
                             +" WHERE MP.SITENAME=:SITENAME AND MS.SHIPREQUESTNAME=MSD.SHIPREQUESTNAME AND MS.SITENAME=MSD.SITENAME AND MS.SITENAME=MP.SITENAME"
                             +" AND MP.SHIPREQUESTNAME=MS.SHIPREQUESTNAME AND MP.SHIPREQUESTDETAILNAME =MSD.SHIPREQUESTDETAILNAME"
                             +" AND MP.RECEIVEACTNO=:RECEIVEACTNO"   
                             +" AND MP.MATERIALQUANTITY>0"
                             +" GROUP BY MP.MATERIALSPECNAME,MS.ERPFACTORYNAME,MP.ERPFACTORY,MP.ERPLOCATION,MP.CHARGE,MP.SHIPREQUESTNAME,MP.SHIPREQUESTDETAILNAME,MS.WORKORDERID,MS.SHIPREQUESTDETAILTYPE";	
			Map<String,String> map=new HashMap<String, String>();
			map.put("SITENAME", siteName);
			map.put("RECEIVEACTNO", actNO);
			result = IDMFrameServiceProxy.getSqlTemplate().queryForList(querySql, map);
		}catch(Exception e)
		{
			
		}
		return result;
	}
	public List<MaterialPacking> saveOEMStockinInfo(List<Map<String,Object>> stockinList,List<MaterialUnDoinfo> undoList,String siteName,EventInfo eventInfo,String actNo) throws ParseException
	{
		List<MaterialPacking> tqmsList=new ArrayList<MaterialPacking>();
		List<SetEventInfo> eventlist = new ArrayList<SetEventInfo>();
		String receiveRequestName="";
		CommonValidation cv = new CommonValidation();
		for (int i = 0; i < stockinList.size(); i++) 
		{
			List<MaterialPackingKey> mpklist = new ArrayList<MaterialPackingKey>();
			MaterialUnDoinfo undo = null;		
			String condition=" WHERE SITENAME= ? AND MATERIALSPECNAME = ? AND ERPLOCATION= ? AND ERPFACTORY = ? AND RECEIVEACTNO = ?";					
			Object[] bind={siteName,stockinList.get(i).get("MATERIALSPECNAME").toString(),stockinList.get(i).get("ERPLOCATION").toString(),stockinList.get(i).get("ERPFACTORY").toString(),actNo};
			List<MaterialPacking> mpList=MaterialPackingServiceProxy.getMaterialPackingService().select(condition, bind);
			String sql_insertUndoInfo =new MaterialPackingServiceImpl().insertUnDOMaterialPackingInfo_v3
					+ "select P.SITENAME,P.MATERIALPACKINGNAME,P.LASTEVENTTIMEKEY FROM MATERIALPACKING P WHERE P.UNDODETAILNAME=:unDoDetailName AND P.UNDOID=:unDoID )";
			for (int j = 0; j < undoList.size(); j++) {
				String a = undoList.get(j).getSeq();
				String b = mpList.get(0).getMessageId()+ Integer.toString(i + 1);
				if (a.equals(b)) {
					undo = undoList.get(j);
					break;
				}
			}
			for (MaterialPacking materialPacking : mpList) {
				mpklist.add(materialPacking.getKey());
			}			
			SetEventInfo setevent = new SetEventInfo();
			Map<String, Object> bindMap = new HashMap<String, Object>();
			bindMap.put("packingState", "Released");
			bindMap.put("stockState", "Stocked");
			bindMap.put("oqaResult", "");
			bindMap.put("packingGrade", "");
			bindMap.put("materialProcessGroupName", "OICOQA");
			bindMap.put("oqaResultState",GenericServiceProxy.getConstantMap().OQA_State_Pre);
			tqmsList.addAll(mpList);
			bindMap.put("charge", stockinList.get(i).get("CHARGE").toString());
			bindMap.put("unDoID", undo.getUnDoID());
			bindMap.put("unDoDetailName", undo.getUnDoDetailName());			
			bindMap.put("stockInType","POOEM");
			Date date = new Date();
			SimpleDateFormat df = new SimpleDateFormat(
					"yyyy-MM-dd HH:mm:ss");
			String receivedate = df.format(date);
			bindMap.put("receiveTime",
					Timestamp.valueOf(receivedate));
			//过账时间是否从前台获取？
			bindMap.put("erpEventTime",Timestamp.valueOf(receivedate));
			bindMap.put("receiveUser", eventInfo.getEventUser());
			bindMap.put("erpState", "SUCCESS");
			setevent.setUserColumns(bindMap);
			eventlist.add(setevent);
			eventInfo.setReasonCode(mpList.get(0).getReasonCode());
			eventInfo.setReasonCodeType(mpList.get(0).getReasonCodeType());
			eventInfo.setEventName("OEMStockIn");
			eventInfo.setEventComment("OEMStockIn");
			MaterialPackingServiceProxy.getMaterialPackingService()
					.setEvent(mpklist, eventInfo, setevent);		
			bindMap.put("UNDOIDDATE", undo.getUnDoIdDate());
			bindMap.put("LASTEVENTNAME", eventInfo.getEventName());
			bindMap.put("LASTEVENTCOMMENT", eventInfo.getEventComment());
			setevent.setUserColumns(bindMap);
			int count=IDMFrameServiceProxy.getSqlTemplate()
					.update(sql_insertUndoInfo, bindMap);
			receiveRequestName=mpList.get(0).getReceiveRequestName();
		}
		// 存抬头文本信息
		MaterialReceiveActKey mrk = new MaterialReceiveActKey();
		String sql =" SELECT RECEIVEREQUESTNAME FROM MATERIALRECEIVEACT WHERE SITENAME =:SITENAME AND RECEIVEACTNO =:RECEIVEACTNO ";
		Map<String, Object> bindMap1 = new HashMap<String, Object>();
		bindMap1.put("SITENAME", siteName);
		bindMap1.put("RECEIVEACTNO", actNo);
		List<Map<String, Object>> queryResult = IDMFrameServiceProxy
				.getSqlTemplate()
				.queryForList(sql, bindMap1);
		MaterialReceiveActKey actKey=new MaterialReceiveActKey();
		actKey.setSiteName(siteName);
		actKey.setReceiveactNO(actNo);
		actKey.setReceiveRequestName(queryResult.get(0).get("RECEIVEREQUESTNAME").toString());
		MaterialReceiveAct act=  MaterialReceiveRequestActServiceProxy.getReceiveRequestBatchService().selectByKey(actKey);
		act.setReceiveActState("Received");
		MaterialReceiveRequestActServiceProxy.getReceiveRequestBatchService().update(act);
		return tqmsList;
	}
	// 在用
	public List<MaterialStockInClass> GetRefundStockInList(
			org.jdom.Document document) throws Exception {

		List<MaterialStockInClass> mplist = new ArrayList<MaterialStockInClass>();
		Element root = document.getDocument().getRootElement();
		Element bodyElement = root.getChild("Body");
		Element requestlist = bodyElement.getChild("DATALIST");
		CommonValidation cv = new CommonValidation();
		int seqno = 1;
		try {
			if (requestlist != null) {
				for (Iterator<?> iterator = requestlist.getChildren()
						.iterator(); iterator.hasNext();) {
					Element element = (Element) iterator.next();
					String erpfactroty = element.getChild("ERPFACTORYNAME")
							.getText();
					if (erpfactroty.equals("")) {
						throw (new Exception("no erpfactory !"));
					}
					String sitename = element.getChild("SITENAME").getText();
					String materialSpecName = element.getChild(
							"MATERIALSPECNAME").getText();
					String receiveRequestName = element.getChild(
							"RECEIVEREQUESTNAME").getText();
					String receiveRequestDetailName = element.getChild(
							"RECEIVEREQUESTDETAILNAME").getText();
					String receiveActNo = element.getChild("RECEIVEACTNO")
							.getText();
					String makedate = element.getChild("MAKEDATE").getText();
					String erplocation = element.getChild("ERPLOCATION")
							.getText();
					String materialtype = element.getChild("MATERIALTYPE")
							.getText();
					String receiveTime = cv.getDate(element.getChild(
							"RECEIVETIME").getText());
					String receiveQuantity = element
							.getChild("RECEIVEQUANTITY").getText();
					String acttype = element.getChild("ACTTYPE").getText();
					String shiptype = element.getChild("SHIPREQUESTDETAILTYPE")
							.getText();
					String workerorder = element.getChild("WORKORDERID")
							.getText();
					String charge = element.getChild("CHARGE").getText();

					MaterialStockInClass msc = new MaterialStockInClass();
					String ACTTYPE = bodyElement.getChild("ACTTYPE").getText();
					if(ACTTYPE.equals("ReserveManual")||ACTTYPE.equals("POManual")){
						String costcenter = element.getChild("COSTCENTER").getText()==null?"":element.getChild("COSTCENTER").getText();
						String CUSTOMERNO = element.getChild("CUSTOMERNO").getText()==null?"":element.getChild("CUSTOMERNO").getText();
						String CUSTOMSDECLARE = element.getChild("CUSTOMSDECLARE").getText()==null?"":element.getChild("CUSTOMSDECLARE").getText();
						msc.setCostcenter(costcenter);
						msc.setCustomerno(CUSTOMERNO);
						msc.setCustomsdeclare(CUSTOMSDECLARE);
					}
					if(ACTTYPE.equals("NGManual"))
					{
						String CUSTOMERNO = element.getChild("CUSTOMERNO").getText()==null?"":element.getChild("CUSTOMERNO").getText();
						String CUSTOMSDECLARE = element.getChild("CUSTOMSDECLARE").getText()==null?"":element.getChild("CUSTOMSDECLARE").getText();
						String ERPFROMFACTORYNAME = element.getChild("ERPFROMFACTORYNAME").getText()==null?"":element.getChild("ERPFROMFACTORYNAME").getText();
						String ERPFROMLOCATION = element.getChild("ERPFROMLOCATION").getText()==null?"":element.getChild("ERPFROMLOCATION").getText();
						msc.setCustomerno(CUSTOMERNO);
						msc.setCustomsdeclare(CUSTOMSDECLARE);
						msc.setErpfromfactory(ERPFROMFACTORYNAME);
						msc.setErpfromlocation(ERPFROMLOCATION);
					}
					msc.setCharge(charge);
					msc.setErpfactory(erpfactroty);
					msc.setErplocation(erplocation);
					msc.setMaterialSpecName(materialSpecName);
					msc.setMaterialtype(materialtype);
					msc.setMakedate(makedate);
					msc.setReceiveActNo(receiveActNo);
					msc.setReceiveQuantity(receiveQuantity);
					msc.setReceiveRequestDetailName(receiveRequestDetailName);
					msc.setReceiveRequestName(receiveRequestName);
					msc.setReceiveTime(receiveTime);
					msc.setSiteName(sitename);
					msc.setActtype(acttype);
					msc.setSeqno(seqno++);
					msc.setShipRequestDetailType(shiptype);
					if (workerorder != null) {

						msc.setWorkorderid(workerorder);
					}
					
					String kostl = "";
					String sql = "SELECT COSTCENTER FROM MATERIALSHIPREQUEST WHERE SHIPREQUESTNAME = :SHIPREQUESTNAME";
					Map<String, Object> bindMap = new HashMap<String, Object>();
					bindMap.put("SHIPREQUESTNAME", receiveRequestName);
					List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
							.getSqlTemplate()
							.queryForList(sql, bindMap);
					if (sqlResult.size() != 0) {
						if (sqlResult.get(0) != null) {
							if (sqlResult.get(0).get("COSTCENTER") != null) {
								kostl = sqlResult.get(0).get("COSTCENTER").toString();
							}
						}
					}
					msc.setKostl(kostl);

					mplist.add(msc);
				}
			}

		} catch (Exception e) {
			e.getMessage();
			throw e;
		}
		return mplist;
	}
	public List<InnerRequestDetailInfo> GetInnerStockInList(org.jdom.Document document) throws Exception
	{
		List<InnerRequestDetailInfo> innerList=new ArrayList<InnerRequestDetailInfo>();
		Element root=document.getDocument().getRootElement();
		Element bodyElement=root.getChild("Body");
		try
		{
			if(bodyElement!=null)
			{
				for(Iterator<?> i =bodyElement.getChildren().iterator();i.hasNext();)
				{
					Element element=(Element)i.next();
					String siteName=element.getChild("SITENAME").getText();
					String innerRequestName=element.getChild("INNERREQUESTNAME").getText();
					String innerRequestDetailName=element.getChild("INNERREQUESTDETAILNAME").getText();
					String erpFactory=element.getChild("ERPFACTORY").getText();
					String receiveRequestName=element.getChild("RECEIVEREQUESTNAME").getText();
					String receiveRequestDetailName=element.getChild("RECEIVEREQUESTDETAILNAME").getText();
					String materialSpecName=element.getChild("MATERIALSPECNAME").getText();
					String unit=element.getChild("UNIT").getText();
					String materialQuantity=element.getChild("MATERIALQUANTITY").getText();
					String receivedQuantity=element.getChild("RECEIVEDQUANTITY").getText();
					String erpLocation=element.getChild("ERPLOCATION").getText();
					String charge=element.getChild("CHARGE").getText();
					String materialOqaNum=element.getChild("MATERIALOQANUM").getText();
					String oqaFlag=element.getChild("OQAFLAG").getText();
					CommonValidation cv=new CommonValidation();					
					String erpTime=element.getChild("ERPTIME").getText().equals(null)?"":cv.getDate(element.getChild("ERPTIME").getText());
					String receiveActNo=element.getChild("RECEIVEACTNO").getText();
					String iqcFlag=element.getChild("IQCFLAG").getText();
					InnerRequestDetailInfo info=new InnerRequestDetailInfo();
					info.setSiteName(siteName);
					info.setInnerRequestName(innerRequestName);
					info.setInnerRequestDetailName(innerRequestDetailName);
					info.setErpLocation(erpLocation);
					info.setErpFactory(erpFactory);
					info.setReceiveRequestName(receiveRequestName);
					info.setReceiveRequestDetailName(receiveRequestDetailName);
					info.setMaterialSpecName(materialSpecName);
					info.setUnit(unit);
					info.setMaterialQuantity(materialQuantity);
					info.setReceivedQuantity(receivedQuantity);
					info.setCharge(charge);
					info.setMaterialOqaNum(materialOqaNum);
					info.setOqaFlag(oqaFlag);
					//info.setErpTime(Timestamp.valueOf(erpTime));
					info.setReceiveTime(erpTime);
					info.setReceiveActNo(receiveActNo);
					info.setIqcFlag(iqcFlag);
					innerList.add(info);
				}
			}
		}catch(Exception e)
		{
			e.getMessage();
			throw e;
		}
		return innerList;
	}
	public void updateMessageIDToMaterialPackingByInner(List<InnerRequestDetailInfo> msilist,String messageid,EventInfo eventinfo){
		if(msilist.size()>0){
			List<MaterialPackingKey> mpklist = new ArrayList<MaterialPackingKey>();
			for(InnerRequestDetailInfo ms:msilist){
				List<MaterialPacking> mplist = new MaterialPackingStockInUtil().GetOQAGroupList(ms.getReceiveRequestName(),
						ms.getReceiveRequestDetailName(), ms.getReceiveActNo());
				for(MaterialPacking mp:mplist){
					MaterialPackingKey key = new MaterialPackingKey();
					key = mp.getKey();
					mpklist.add(key);					
				}
			}
			MaterialPacking  materialpcking =MaterialPackingServiceProxy.getMaterialPackingService().selectByKey(mpklist.get(0));
			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);
			if(eventinfo.getReasonCode().equals(null)||eventinfo.getReasonCode().equals("")){
				eventinfo.setReasonCode(materialpcking.getReasonCode());
				eventinfo.setReasonCodeType(materialpcking.getReasonCodeType());
			}
			eventinfo.setEventComment("SaveMessageID");
			eventinfo.setEventName("SaveMessageID");
			MaterialPackingServiceProxy.getMaterialPackingService()
			.setEvent(mpklist, eventinfo, setevent);
		}
	}
	
	public List<MaterialStockInClass> GetNormalStockInList(
			org.jdom.Document document) throws Exception {

		List<MaterialStockInClass> mplist = new ArrayList<MaterialStockInClass>();
		Element root = document.getDocument().getRootElement();
		Element bodyElement = root.getChild("Body");
		Element requestlist = bodyElement.getChild("DATALIST");

		try {
			if (requestlist != null) {
				for (Iterator<?> iterator = requestlist.getChildren()
						.iterator(); iterator.hasNext();) {
					Element element = (Element) iterator.next();
					String sitename = element.getChild("SITENAME").getText();
					String erpfactory = element.getChildText("ERPFACTORYNAME");
					String materialSpecName = element.getChild(
							"MATERIALSPECNAME").getText();
					String receiveRequestName = element.getChild(
							"RECEIVEREQUESTNAME").getText();
					String receiveRequestDetailName = element.getChild(
							"RECEIVEREQUESTDETAILNAME").getText();
					String receiveActNo = element.getChild("RECEIVEACTNO")
							.getText();
					String erplocation = element.getChild("ERPLOCATION")
							.getText();
					double materialOQAnum = 0;
					if (element.getChild("MATERIALOQANUM").getText() != null) {
						materialOQAnum = Double.valueOf(element.getChild(
								"MATERIALOQANUM").getText());
					} else {
						materialOQAnum = 0;
					}
					CommonValidation cv = new CommonValidation();
					String receiveTime = cv.getDate(element.getChild(
							"RECEIVETIME").getText());
					String erptime = "";
					if (new CommonValidation().checkTime(receiveTime)) {
						erptime = receiveTime;
					} else {
						throw (new Exception(
								"Server StockInDate more than system Date !"));
					}
					String receiveQuantity = element
							.getChild("RECEIVEQUANTITY").getText();
					String acttype = element.getChild("ACTTYPE").getText();
					String customform = element.getChild("CUSTOMFORM")
							.getText();
//					String customstate = element.getChild("CUSTOMSTATE")
//							.getText();
					String customstate = "";
					// element.getChild("CUSTOMDATE").getText();
					String transportformno = element
							.getChild("TRANSPORTFORMNO").getText();
					String taxid = element.getChild("TAXID").getText();
					// GERP
					String zcino = element.getChild("ZCINO").getText();
					
					String icqflag = element.getChild("IQCFLAG") == null ? ""
							: element.getChild("IQCFLAG").getText();
					String oqaflag = element.getChild("OQAFLAG").getText();
					String charge = element.getChild("CHARGE").getText();
					String remark = element.getChild("REMARK").getText();
					// String inspectp = element.getChild("INSPECTP").getText();
					String suppliername = element.getChild("SUPPLIERNAME").getText();//B2新增
					//GERP
					//String supplierno = element.getChild("SUPPLIERNO").getText();//BADT新增
					String zlshm = element.getChild("ZLSHM").getText();//采购发票
					//String materialtype = element.getChild("MATERIALTYPE").getText();
					MaterialStockInClass msc = new MaterialStockInClass();
					msc.setErplocation(erplocation);
					msc.setMaterialSpecName(materialSpecName);
					msc.setErpfactory(erpfactory);
					msc.setReceiveActNo(receiveActNo);
					msc.setReceiveQuantity(receiveQuantity);
					msc.setMaterialOQAnum(materialOQAnum);
					msc.setReceiveRequestDetailName(receiveRequestDetailName);
					msc.setReceiveRequestName(receiveRequestName);
					msc.setReceiveTime(erptime);
					msc.setSiteName(sitename);
					msc.setActtype(acttype);
					// msc.setCustomdate(customdate);
					msc.setCustomform(customform);
					msc.setCustomformstate(customstate);
					msc.setTaxid(taxid);
					msc.setZcino(zcino);
					msc.setOqaflag(oqaflag);
					msc.setCharge(charge);
					msc.setIcqflag(icqflag);
					msc.setTransportformno(transportformno);
					msc.setRemark(remark);
					msc.setZlshm(zlshm);
                    //msc.setMaterialtype(materialtype);
					mplist.add(msc);
				}
			}

			
		} catch (Exception e) {
			e.getMessage();
			throw e;
		}
		return mplist;
	}
	
	public void updateMessageIDToMaterialPacking(List<MaterialStockInClass> msilist,String messageid,EventInfo eventinfo){
		if(msilist.size()>0){
			List<MaterialPackingKey> mpklist = new ArrayList<MaterialPackingKey>();
			for(MaterialStockInClass ms:msilist){
				List<MaterialPacking> mplist = new MaterialPackingStockInUtil().GetOQAGroupList(ms.getReceiveRequestName(),
						ms.getReceiveRequestDetailName(), ms.getReceiveActNo());
				for(MaterialPacking mp:mplist){
					MaterialPackingKey key = new MaterialPackingKey();
					key = mp.getKey();
					mpklist.add(key);					
				}
			}
			MaterialPacking  materialpcking =MaterialPackingServiceProxy.getMaterialPackingService().selectByKey(mpklist.get(0));
			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);
			if(eventinfo.getReasonCode().equals(null)||eventinfo.getReasonCode().equals("")){
				eventinfo.setReasonCode(materialpcking.getReasonCode());
				eventinfo.setReasonCodeType(materialpcking.getReasonCodeType());
			}
			eventinfo.setEventComment("SaveMessageID");
			eventinfo.setEventName("SaveMessageID");
			MaterialPackingServiceProxy.getMaterialPackingService()
			.setEvent(mpklist, eventinfo, setevent);
		}
	}
	/*
	 * 不完整，所以弃用 public List<MaterialStockInClass>
	 * GetToERPStockInList(List<MaterialStockInClass> msilist,int num){
	 * List<MaterialStockInClass> erplist = new
	 * ArrayList<MaterialStockInClass>(); for(MaterialStockInClass ms:msilist){
	 * if(ms.getInspecta()=="" && ms.getInspectp()=="" && ms.getInspectv()==""){
	 * erplist.addAll(GetOQAGroupList(ms,num)); }else{ erplist.add(ms); } }
	 * 
	 * return erplist; }
	 */
	public List<MaterialStockInClass> GetOQAGroupList(MaterialStockInClass msi,
													  double num, int seqno) throws ParseException {

		// 这里查到的 MaterialStockInClass 的列表要得到所有信息，这个要重新看看怎么写SQL
		List<MaterialStockInClass> oqalist = new MaterialPackingStockInUtil()
				.GetOQAMakedateGroupList(msi.getReceiveRequestName(),
						msi.getReceiveRequestDetailName(),
						msi.getReceiveActNo(), msi.getSiteName());
		List<MaterialStockInClass> oplist = new ArrayList<MaterialStockInClass>();
		// List <MaterialPacking> mp
		for (MaterialStockInClass ms : oqalist) {
			List<MaterialStockInClass> testlist = GroupOQAList2(ms, num, seqno);
			seqno = seqno + testlist.size();// 这里的SEQ号也要随着list变化累加，因为传过来和传过去的是形参，GroupOQAList2方法中SEQ变化后不会反映到这个function中，所以要手动累加一下
			oplist.addAll(testlist);
		}

		return oplist;
	}
	public List<InnerRequestDetailInfo> GetOQAGroupListByInner(InnerRequestDetailInfo msi,
			double num, int seqno) throws ParseException {

		// 这里查到的 MaterialStockInClass 的列表要得到所有信息，这个要重新看看怎么写SQL
		List<InnerRequestDetailInfo> oqalist = new MaterialPackingStockInUtil()
				.GetOQAMakedateGroupListByInner(msi.getReceiveRequestName(),
						msi.getReceiveRequestDetailName(),
						msi.getReceiveActNo(), msi.getSiteName());
		List<InnerRequestDetailInfo> oplist = new ArrayList<InnerRequestDetailInfo>();
		// List <MaterialPacking> mp
		for (InnerRequestDetailInfo ms : oqalist) {
			List<InnerRequestDetailInfo> testlist = GroupOQAListByInner2(ms, num, seqno);
			seqno = seqno + testlist.size();// 这里的SEQ号也要随着list变化累加，因为传过来和传过去的是形参，GroupOQAList2方法中SEQ变化后不会反映到这个function中，所以要手动累加一下
			oplist.addAll(testlist);
		}

		return oplist;
	}
	
public void checkReceiveactState( String receiveActNo)throws Exception {
	try{
	String sql="SELECT RECEIVEACTSTATE FROM MATERIALRECEIVEACT 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);
	//||!sqlResult.get(0).get("RECEIVEACTSTATE").toString().equals("Created")
	if(sqlResult.size()==0)
	{
		throw new CustomException("ACTSTATEERROR","","");
	}
	}catch (Exception ex) {
		 ex.printStackTrace();
		 throw ex;
	}	
}

public void checkBoxState( List<Element> materialPackingNameList,String flag,String siteName)throws Exception {
	try{
		
		List<String> BoxList = new ArrayList<String>();
		for (Element materialPackingName : materialPackingNameList) {
			BoxList.add(materialPackingName
					.getTextTrim());
		}
	String sql="SELECT SHIPREQUESTNAME FROM MATERIALPACKING WHERE MATERIALPACKINGNAME=:MATERIALPACKINGNAME AND SITENAME=:SITENAME ";
	Map<String, Object> bindMap1 = new HashMap<String, Object>();
	bindMap1.put("SITENAME", siteName);
	for(int i=0;i<BoxList.size();i++){
		bindMap1.put("MATERIALPACKINGNAME", BoxList.get(i));
		List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
				.getSqlTemplate()
				.queryForList(sql, bindMap1);
		if(flag.equals("Asign"))
			{
				if(!(sqlResult.get(0).get("SHIPREQUESTNAME")==null))
				{
					throw new CustomException("SignFailed","","");
				}
			}
		if(flag.equals("Design"))
		{
			if(sqlResult.get(0).get("SHIPREQUESTNAME")==null)
			{
				throw new CustomException("SignFailed","","");
			}
		}
		}
	
	
	}catch (Exception ex) {
		 ex.printStackTrace();
		 throw ex;
	}	
}
//防止网络卡顿，出现帮错数量和物料号
public void checkBoxInfo( List<Element> materialPackingNameList,String flag,String siteName,String shipRequestName,String shipRequestDetailName )throws Exception {
	try{
		
		List<String> BoxList = new ArrayList<String>();
		for (Element materialPackingName : materialPackingNameList) {
			BoxList.add(materialPackingName
					.getTextTrim());
		}
	String sql="SELECT A.* FROM MATERIALPACKING A,MaterialShipRequestDetail B WHERE A.MATERIALPACKINGNAME=:MATERIALPACKINGNAME AND A.SITENAME=:SITENAME "
			+" AND A.MATERIALSPECNAME=B.MATERIALSPECNAME AND B.SHIPREQUESTNAME=:SHIPREQUESTNAME AND B.SHIPREQUESTDETAILNAME=:SHIPREQUESTDETAILNAME ";
	Map<String, Object> bindMap1 = new HashMap<String, Object>();
	bindMap1.put("SITENAME", siteName);
	bindMap1.put("SHIPREQUESTNAME", shipRequestName);
	bindMap1.put("SHIPREQUESTDETAILNAME", shipRequestDetailName);
	if(flag.equals("Asign"))
	{
	for(int i=0;i<BoxList.size();i++){
		bindMap1.put("MATERIALPACKINGNAME", BoxList.get(i));
		List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
				.getSqlTemplate()
				.queryForList(sql, bindMap1);
				if(sqlResult.size()==0)
				{
					throw new CustomException("SignFailed","","");
				}
				if(i>0&&BoxList.get(i)==BoxList.get(0)){
					throw new CustomException("SignFailed","重复box错误","");
				}
			}
	}
	}catch (Exception ex) {
		 ex.printStackTrace();
		 throw ex;
	}	
}
public void checkShipRequestState( String shipRequestName)throws Exception {
	try{
	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||sqlResult.get(0).get("shiprequeststate").toString().equals("StockOut")||sqlResult.get(0).get("shiprequeststate").toString().equals("Completed"))
	{
		throw new CustomException("CHECKFAILED","","");
	}
	}catch (Exception ex) {
		 ex.printStackTrace();
		 throw ex;
	}	
}
public void checkETCState( String materialpackingName)throws Exception {
	try{
	String sql="SELECT ETCSTATE FROM MATERIALPACKING WHERE materialpackingName=:materialpackingName and ETCSTATE='EtcOut' for update";
	Map<String, Object> bindMap1 = new HashMap<String, Object>();
	bindMap1.put("materialpackingName", materialpackingName);
	List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
			.getSqlTemplate()
			.queryForList(sql, bindMap1);
	if(sqlResult.size()!=0&&sqlResult.get(0).get("ETCSTATE").toString().equals("EtcOut"))
	{
		throw new CustomException("CHECKFAILED","","");
	}
	}catch (Exception ex) {
		 ex.printStackTrace();
		 throw ex;
	}	
}
	public List<MaterialStockInClass> GroupOQAList2(MaterialStockInClass ms,
													double num, int seqno) {

		List<MaterialPacking> mplist = new MaterialPackingStockInUtil()
				.GetOQADetailGroupList(ms);
		List<MaterialStockInClass> result = new ArrayList<MaterialStockInClass>();

		int first = 0;
		 DecimalFormat df=new DecimalFormat("#.##");
		int end = mplist.size() - 1;// int groupname = seqno;
		if (mplist.get(first).getMaterialQuantity() >= num) {
			for (MaterialPacking p : mplist) {

				MaterialStockInClass mg = new MaterialStockInClass();// ms;
				mg.setCustomdate(ms.getCustomdate());
				mg.setCustomform(ms.getCustomform());
				mg.setReceiveTime(ms.getReceiveTime());
				mg.setCustomformstate(ms.getCustomformstate());
				mg.setMaterialOQAnum(ms.getMaterialOQAnum());
				mg.setTaxid(ms.getTaxid());
				mg.setTransportformno(ms.getTransportformno());
				mg.setErplocation(ms.getErplocation());
				mg.setErpfactory(ms.getErpfactory());
				mg.setMaterialSpecName(ms.getMaterialSpecName());
				mg.setMaterialtype(ms.getMaterialtype());
				mg.setSeqno(seqno);
				mg.setReceiveActNo(ms.getReceiveActNo());
				mg.setReceiveRequestDetailName(ms.getReceiveRequestDetailName());
				mg.setReceiveRequestName(ms.getReceiveRequestName());
				mg.setPreGroupName(Integer.toString(seqno));
				mg.setMakedate(ms.getMakedate());
				mg.setSiteName(ms.getSiteName());
				mg.setIcqflag(ms.getIcqflag());
				mg.setShipRequestDetailType(ms.getShipRequestDetailType());
				mg.setReceiveQuantity(df.format((p.getMaterialQuantity())));
				p.setMaterialProcessGroupName(Integer.toString(seqno));
				result.add(mg);
				seqno++;
			}
			MaterialPackingServiceProxy.getMaterialPackingService().update(
					mplist);
		} else if (mplist.get(first).getMaterialQuantity() < num
				&& mplist.get(end).getMaterialQuantity() >= num) {
			// mplist.get(first).getMaterialQuantity()<num &&
			// mplist.get(end).getMaterialQuantity()>num-mplist.get(first).getMaterialQuantity()
			for (; end > first && mplist.get(end).getMaterialQuantity() >= num; end--) {
				MaterialStockInClass mg = new MaterialStockInClass();// ms;
				mg.setCustomdate(ms.getCustomdate());
				mg.setCustomform(ms.getCustomform());
				mg.setReceiveTime(ms.getReceiveTime());
				mg.setCustomformstate(ms.getCustomformstate());
				mg.setMaterialOQAnum(ms.getMaterialOQAnum());
				mg.setTaxid(ms.getTaxid());
				mg.setTransportformno(ms.getTransportformno());
				mg.setErplocation(ms.getErplocation());
				mg.setErpfactory(ms.getErpfactory());
				mg.setMaterialSpecName(ms.getMaterialSpecName());
				mg.setMaterialtype(ms.getMaterialtype());
				mg.setSeqno(seqno);
				mg.setReceiveActNo(ms.getReceiveActNo());
				mg.setReceiveRequestDetailName(ms.getReceiveRequestDetailName());
				mg.setReceiveRequestName(ms.getReceiveRequestName());
				mg.setPreGroupName(Integer.toString(seqno));
				mg.setMakedate(ms.getMakedate());
				mg.setSiteName(ms.getSiteName());
				mg.setIcqflag(ms.getIcqflag());
				mg.setShipRequestDetailType(ms.getShipRequestDetailType());
				mg.setReceiveQuantity(df.format((mplist.get(end)
						.getMaterialQuantity())));
				mplist.get(end).setMaterialProcessGroupName(
						Integer.toString(seqno));
				result.add(mg);
				seqno++;
			}
			// MaterialPackingServiceProxy.getMaterialPackingService().update(mplist);
			result.addAll(GroupOQA(mplist, ms, first, end, seqno, num));

		} else {
			result.addAll(GroupOQA(mplist, ms, first, end, seqno, num));
		}
		return result;
	}
	public List<InnerRequestDetailInfo> GroupOQAListByInner2(InnerRequestDetailInfo ms,
															 double num, int seqno) {

		List<MaterialPacking> mplist = new MaterialPackingStockInUtil()
				.GetOQADetailGroupListByInner(ms);
		List<InnerRequestDetailInfo> result = new ArrayList<InnerRequestDetailInfo>();

		int first = 0;
		 DecimalFormat df=new DecimalFormat("#.##");
		int end = mplist.size() - 1;// int groupname = seqno;
		if (mplist.get(first).getMaterialQuantity() >= num) {
			for (MaterialPacking p : mplist) {
				InnerRequestDetailInfo mg = new InnerRequestDetailInfo();// ms;
				mg.setErpTime(ms.getErpTime());
				mg.setMaterialOqaNum(ms.getMaterialOqaNum());
				mg.setErpLocation(ms.getErpLocation());
				mg.setErpFactory(ms.getErpFactory());
				mg.setMaterialSpecName(ms.getMaterialSpecName());
				//mg.setMaterialtype(ms.getMaterialtype());
				mg.setSeqNO(Integer.toString(seqno));
				mg.setReceiveActNo(ms.getReceiveActNo());
				mg.setReceiveRequestDetailName(ms.getReceiveRequestDetailName());
				mg.setReceiveRequestName(ms.getReceiveRequestName());
				mg.setPreGroupName(Integer.toString(seqno));
				mg.setMakeDate(ms.getMakeDate());
				mg.setSiteName(ms.getSiteName());
				mg.setIqcFlag(ms.getIqcFlag());
				//mg.setShipRequestDetailType(ms.getShipRequestDetailType());
				mg.setReceivedQuantity(df.format((p.getMaterialQuantity())));
				p.setMaterialProcessGroupName(Integer.toString(seqno));
				result.add(mg);
				seqno++;
			}
			MaterialPackingServiceProxy.getMaterialPackingService().update(
					mplist);
		} else if (mplist.get(first).getMaterialQuantity() < num
				&& mplist.get(end).getMaterialQuantity() >= num) {
			// mplist.get(first).getMaterialQuantity()<num &&
			// mplist.get(end).getMaterialQuantity()>num-mplist.get(first).getMaterialQuantity()
			for (; end > first && mplist.get(end).getMaterialQuantity() >= num; end--) {
				InnerRequestDetailInfo mg = new InnerRequestDetailInfo();// ms;
				//mg.setCustomdate(ms.getCustomdate());
				//mg.setCustomform(ms.getCustomform());
				mg.setErpTime(ms.getErpTime());
				//mg.setCustomformstate(ms.getCustomformstate());
				mg.setMaterialOqaNum(ms.getMaterialOqaNum());
				//mg.setTaxid(ms.getTaxid());
				//mg.setTransportformno(ms.getTransportformno());
				mg.setErpLocation(ms.getErpLocation());
				mg.setErpFactory(ms.getErpFactory());
				mg.setMaterialSpecName(ms.getMaterialSpecName());
				//mg.setMaterialtype(ms.getMaterialtype());
				mg.setSeqNO(Integer.toString(seqno));
				mg.setReceiveActNo(ms.getReceiveActNo());
				mg.setReceiveRequestDetailName(ms.getReceiveRequestDetailName());
				mg.setReceiveRequestName(ms.getReceiveRequestName());
				mg.setPreGroupName(Integer.toString(seqno));
				mg.setMakeDate(ms.getMakeDate());
				mg.setSiteName(ms.getSiteName());
				mg.setIqcFlag(ms.getIqcFlag());
				//mg.setShipRequestDetailType(ms.getShipRequestDetailType());
				mg.setReceivedQuantity(df.format((mplist.get(end)
						.getMaterialQuantity())));
				mplist.get(end).setMaterialProcessGroupName(
						Integer.toString(seqno));
				result.add(mg);
				seqno++;
			}
			// MaterialPackingServiceProxy.getMaterialPackingService().update(mplist);
			result.addAll(GroupOQAByInner(mplist, ms, first, end, seqno, num));

		} else {
			result.addAll(GroupOQAByInner(mplist, ms, first, end, seqno, num));
		}
		return result;
	}
	public List<InnerRequestDetailInfo> GroupOQAByInner(List<MaterialPacking> mp,
			InnerRequestDetailInfo ms, int first, int end, int seqno, double num) {

		List<InnerRequestDetailInfo> result2 = new ArrayList<InnerRequestDetailInfo>();
		DecimalFormat df=new DecimalFormat("#.##");
		Double sum = (double) 0.0;
		int count = 0;
		while (first <= end) {// 死循环了

			if (sum < num) {
				double nu = num - sum;
				double nu1 = mp.get(end).getMaterialQuantity();
				if (num - sum >= mp.get(end).getMaterialQuantity()) {
					sum = sum + mp.get(end).getMaterialQuantity();
					mp.get(end--).setMaterialProcessGroupName(
							Integer.toString(seqno));

					count++;
				} else if (num - sum >= mp.get(first).getMaterialQuantity()) {
					sum = sum + mp.get(first).getMaterialQuantity();
					mp.get(first++).setMaterialProcessGroupName(
							Integer.toString(seqno));
					count++;
				} else {
					InnerRequestDetailInfo mg = new InnerRequestDetailInfo();// ms;
					//mg.setCustomdate(ms.getCustomdate());
					//mg.setCustomform(ms.getCustomform());
					mg.setReceiveTime(ms.getReceiveTime());
					//mg.setCustomformstate(ms.getCustomformstate());
					mg.setMaterialOqaNum(ms.getMaterialOqaNum());
					//mg.setTaxid(ms.getTaxid());
					//mg.setTransportformno(ms.getTransportformno());
					mg.setErpLocation(ms.getErpLocation());
					mg.setErpFactory(ms.getErpFactory());
					mg.setMaterialSpecName(ms.getMaterialSpecName());
					//mg.setMaterialtype(ms.getMaterialtype());
					mg.setSiteName(ms.getSiteName());
					mg.setSeqNO(Integer.toString(seqno));
					mg.setIqcFlag(ms.getIqcFlag());
					mg.setReceiveActNo(ms.getReceiveActNo());
					mg.setReceiveRequestDetailName(ms
							.getReceiveRequestDetailName());
					mg.setReceiveRequestName(ms.getReceiveRequestName());
					mg.setMakeDate(ms.getMakeDate());
					//mg.setShipRequestDetailType(ms.getShipRequestDetailType());
					mg.setPreGroupName(Integer.toString(seqno));
					mg.setSeqNO(Integer.toString(seqno));
					mg.setReceivedQuantity(df.format(sum));
					result2.add(mg);
					seqno++;
					count = 0;
					sum = (double) 0;
				}
				if (first > end) {// youwenti meiyou =
					InnerRequestDetailInfo mg = new InnerRequestDetailInfo();// ms;
					//mg.setCustomdate(ms.getCustomdate());
					//mg.setCustomform(ms.getCustomform());
					mg.setReceiveTime(ms.getReceiveTime());
					//mg.setCustomformstate(ms.getCustomformstate());
					mg.setMaterialOqaNum(ms.getMaterialOqaNum());
					//mg.setTaxid(ms.getTaxid());
					mg.setSiteName(ms.getSiteName());
					//mg.setTransportformno(ms.getTransportformno());
					mg.setErpLocation(ms.getErpLocation());
					mg.setErpFactory(ms.getErpFactory());
					mg.setMaterialSpecName(ms.getMaterialSpecName());
					//mg.setMaterialtype(ms.getMaterialtype());
					mg.setSeqNO(Integer.toString(seqno));
					mg.setIqcFlag(ms.getIqcFlag());
					mg.setReceiveActNo(ms.getReceiveActNo());
					mg.setReceiveRequestDetailName(ms
							.getReceiveRequestDetailName());
					mg.setReceiveRequestName(ms.getReceiveRequestName());
					mg.setMakeDate(ms.getMakeDate());
					//mg.setShipRequestDetailType(ms.getShipRequestDetailType());
					mg.setPreGroupName(Integer.toString(seqno));
					//mg.setSeqno(seqno);
					mg.setReceivedQuantity(df.format(sum));
					result2.add(mg);
					seqno++;
					count = 0;
					sum = (double) 0;
				}

			} else {
				InnerRequestDetailInfo mg = new InnerRequestDetailInfo();// ms;
				//mg.setCustomdate(ms.getCustomdate());
				//mg.setCustomform(ms.getCustomform());
				mg.setReceiveTime(ms.getReceiveTime());
				//mg.setCustomformstate(ms.getCustomformstate());
				mg.setMaterialOqaNum(ms.getMaterialOqaNum());
				//mg.setTaxid(ms.getTaxid());
				//mg.setTransportformno(ms.getTransportformno());
				mg.setErpLocation(ms.getErpLocation());
				mg.setErpFactory(ms.getErpFactory());
				mg.setMaterialSpecName(ms.getMaterialSpecName());
				//mg.setMaterialtype(ms.getMaterialtype());
				mg.setSiteName(ms.getSiteName());
				mg.setSeqNO(Integer.toString(seqno));
				mg.setIqcFlag(ms.getIqcFlag());
				mg.setReceiveActNo(ms.getReceiveActNo());
				mg.setReceiveRequestDetailName(ms.getReceiveRequestDetailName());
				mg.setReceiveRequestName(ms.getReceiveRequestName());
				mg.setMakeDate(ms.getMakeDate());
				//mg.setShipRequestDetailType(ms.getShipRequestDetailType());
				mg.setPreGroupName(Integer.toString(seqno));
				//mg.setSeqno(seqno);
				mg.setReceivedQuantity(df.format(sum));
				result2.add(mg);
				seqno++;
				count = 0;
				sum = (double) 0;
			}
		}

		MaterialPackingServiceProxy.getMaterialPackingService().update(mp);
		return result2;
	}
	public List<MaterialStockInClass> GroupOQA(List<MaterialPacking> mp,
			MaterialStockInClass ms, int first, int end, int seqno, double num) {

		List<MaterialStockInClass> result2 = new ArrayList<MaterialStockInClass>();
		DecimalFormat df=new DecimalFormat("#.##");
		Double sum = (double) 0.0;
		int count = 0;
		while (first <= end) {// 死循环了

			if (sum < num) {
				double nu = num - sum;
				double nu1 = mp.get(end).getMaterialQuantity();
				if (num - sum >= mp.get(end).getMaterialQuantity()) {
					sum = sum + mp.get(end).getMaterialQuantity();
					mp.get(end--).setMaterialProcessGroupName(
							Integer.toString(seqno));

					count++;
				} else if (num - sum >= mp.get(first).getMaterialQuantity()) {
					sum = sum + mp.get(first).getMaterialQuantity();
					mp.get(first++).setMaterialProcessGroupName(
							Integer.toString(seqno));
					count++;
				} else {
					MaterialStockInClass mg = new MaterialStockInClass();// ms;
					mg.setCustomdate(ms.getCustomdate());
					mg.setCustomform(ms.getCustomform());
					mg.setReceiveTime(ms.getReceiveTime());
					mg.setCustomformstate(ms.getCustomformstate());
					mg.setMaterialOQAnum(ms.getMaterialOQAnum());
					mg.setTaxid(ms.getTaxid());
					mg.setTransportformno(ms.getTransportformno());
					mg.setErplocation(ms.getErplocation());
					mg.setErpfactory(ms.getErpfactory());
					mg.setMaterialSpecName(ms.getMaterialSpecName());
					mg.setMaterialtype(ms.getMaterialtype());
					mg.setSiteName(ms.getSiteName());
					mg.setSeqno(seqno);
					mg.setIcqflag(ms.getIcqflag());
					mg.setReceiveActNo(ms.getReceiveActNo());
					mg.setReceiveRequestDetailName(ms
							.getReceiveRequestDetailName());
					mg.setReceiveRequestName(ms.getReceiveRequestName());
					mg.setMakedate(ms.getMakedate());
					mg.setShipRequestDetailType(ms.getShipRequestDetailType());
					mg.setPreGroupName(Integer.toString(seqno));
					mg.setSeqno(seqno);
					mg.setReceiveQuantity(sum.toString());
					result2.add(mg);
					seqno++;
					count = 0;
					sum = (double) 0;
				}
				if (first > end) {// youwenti meiyou =
					MaterialStockInClass mg = new MaterialStockInClass();// ms;
					mg.setCustomdate(ms.getCustomdate());
					mg.setCustomform(ms.getCustomform());
					mg.setReceiveTime(ms.getReceiveTime());
					mg.setCustomformstate(ms.getCustomformstate());
					mg.setMaterialOQAnum(ms.getMaterialOQAnum());
					mg.setTaxid(ms.getTaxid());
					mg.setSiteName(ms.getSiteName());
					mg.setTransportformno(ms.getTransportformno());
					mg.setErplocation(ms.getErplocation());
					mg.setErpfactory(ms.getErpfactory());
					mg.setMaterialSpecName(ms.getMaterialSpecName());
					mg.setMaterialtype(ms.getMaterialtype());
					mg.setSeqno(seqno);
					mg.setIcqflag(ms.getIcqflag());
					mg.setReceiveActNo(ms.getReceiveActNo());
					mg.setReceiveRequestDetailName(ms
							.getReceiveRequestDetailName());
					mg.setReceiveRequestName(ms.getReceiveRequestName());
					mg.setMakedate(ms.getMakedate());
					mg.setShipRequestDetailType(ms.getShipRequestDetailType());
					mg.setPreGroupName(Integer.toString(seqno));
					mg.setSeqno(seqno);
					mg.setReceiveQuantity(sum.toString());
					result2.add(mg);
					seqno++;
					count = 0;
					sum = (double) 0;
				}

			} else {
				MaterialStockInClass mg = new MaterialStockInClass();// ms;
				mg.setCustomdate(ms.getCustomdate());
				mg.setCustomform(ms.getCustomform());
				mg.setReceiveTime(ms.getReceiveTime());
				mg.setCustomformstate(ms.getCustomformstate());
				mg.setMaterialOQAnum(ms.getMaterialOQAnum());
				mg.setTaxid(ms.getTaxid());
				mg.setTransportformno(ms.getTransportformno());
				mg.setErplocation(ms.getErplocation());
				mg.setErpfactory(ms.getErpfactory());
				mg.setMaterialSpecName(ms.getMaterialSpecName());
				mg.setMaterialtype(ms.getMaterialtype());
				mg.setSiteName(ms.getSiteName());
				mg.setSeqno(seqno);
				mg.setIcqflag(ms.getIcqflag());
				mg.setReceiveActNo(ms.getReceiveActNo());
				mg.setReceiveRequestDetailName(ms.getReceiveRequestDetailName());
				mg.setReceiveRequestName(ms.getReceiveRequestName());
				mg.setMakedate(ms.getMakedate());
				mg.setShipRequestDetailType(ms.getShipRequestDetailType());
				mg.setPreGroupName(Integer.toString(seqno));
				mg.setSeqno(seqno);
				mg.setReceiveQuantity(sum.toString());
				result2.add(mg);
				seqno++;
				count = 0;
				sum = (double) 0;
			}
		}

		MaterialPackingServiceProxy.getMaterialPackingService().update(mp);
		return result2;
	}

	public List<InnerRequestDetailInfo> GetERPListByInner(
			List<InnerRequestDetailInfo> msilist, int num) throws ParseException {
		List<InnerRequestDetailInfo> toerplist = new ArrayList<InnerRequestDetailInfo>();
		int seqno = 1;
		CommonValidation commonVal = new CommonValidation();
		for (InnerRequestDetailInfo ms : msilist) {

			// 查询该物料是否根据ERP批次进行管理
			String ERPChargeFlag = "N";
			ERPChargeFlag = commonVal.getMaterialSpecCharge(ms.getErpFactory(),
					ms.getMaterialSpecName());
			if (ms.getOqaFlag().equals("Y")) {
				List<InnerRequestDetailInfo> oqalist =GetOQAGroupListByInner(ms,
					Double.parseDouble(ms.getMaterialOqaNum()), seqno);
				String makedate = "";
				String charge = "";
				for (InnerRequestDetailInfo oqa : oqalist) {
					//oqa.setCustomdate(ms.getCustomdate());
					//oqa.setCustomform(ms.getCustomform());
					oqa.setReceiveTime(ms.getReceiveTime());
					//oqa.setCustomformstate(ms.getCustomformstate());
					oqa.setMaterialOqaNum(ms.getMaterialOqaNum());
					//oqa.setTaxid(ms.getTaxid());
					//oqa.setTransportformno(ms.getTransportformno());
					oqa.setErpLocation(ms.getErpLocation());
					oqa.setErpFactory(ms.getErpFactory());
					oqa.setMaterialSpecName(ms.getMaterialSpecName());
					//oqa.setMaterialtype(ms.getMaterialtype());
					oqa.setSiteName(ms.getSiteName());
					oqa.setIqcFlag(ms.getIqcFlag());
					oqa.setInnerRequestName(ms.getInnerRequestName());
					oqa.setInnerRequestDetailName(ms.getInnerRequestDetailName());
					oqa.setUnit(ms.getUnit());
					oqa.setReceivedQuantity(ms.getReceivedQuantity());
					/**
					 * 根据ERP分批标准来进行，不再需要根据接收时间创建批次
					 * 用BS_MATERIALSPECCHARGEFLAG表中数据来确定是否需要进行批次管理；如果不需要进行批次管理的，
					 * 那么就不用在入库的时候创建批次 ，不用在退库的时候选择批次；还有一个问题，是PO的行项目中如果有charge的话，
					 * 那么在入库的时候就不用生成批次。
					 */
					if (ERPChargeFlag.equals("Y") && ms.getCharge().equals("")) {
						if (!oqa.getMakeDate().equals(makedate)) {
							List<String> sqldata = new ArrayList<String>();
							sqldata.add(oqa.getErpFactory());
							String spec = oqa.getMaterialSpecName()
									+ "************";
							sqldata.add(spec.substring(0, 10));

							String str = oqa.getMakeDate().substring(0, 4)
									+ oqa.getMakeDate().substring(5, 7)
									+ oqa.getMakeDate().substring(8);
							String time = str + "00";
							sqldata.add(time.substring(2, 8));
							charge = NameServiceProxy.getNameRuleDefService()
									.generateName("ChargeNo", sqldata, 1)
									.get(0);
							oqa.setCharge(charge.substring(14));
							
                            if(ms.getSiteName().equals("B7")){
                        	   oqa.setCharge(charge.substring(14,20));
							}
							makedate = oqa.getMakeDate();
						} else {
							oqa.setCharge(charge.substring(14));
						}
					}
				}
				toerplist.addAll(oqalist);
				seqno = seqno + oqalist.size();
			} else {

				List<InnerRequestDetailInfo> oqalist = new MaterialPackingStockInUtil()
						.GetOQAMakedateGroupListByInner(ms.getReceiveRequestName(),
								ms.getReceiveRequestDetailName(),
								ms.getReceiveActNo(), ms.getSiteName());
				String makedate = "";
				String charge = "";
				for (InnerRequestDetailInfo oqa : oqalist) {
					//oqa.setCustomdate(ms.getCustomdate());
					//oqa.setCustomform(ms.getCustomform());
					oqa.setReceiveTime(ms.getReceiveTime());
					//oqa.setCustomformstate(ms.getCustomformstate());
					oqa.setMaterialOqaNum(ms.getMaterialOqaNum());
					//oqa.setTaxid(ms.getTaxid());
					//oqa.setTransportformno(ms.getTransportformno());
					oqa.setErpLocation(ms.getErpLocation());
					oqa.setErpFactory(ms.getErpFactory());
					oqa.setMaterialSpecName(ms.getMaterialSpecName());
					//oqa.setMaterialtype(ms.getMaterialtype());
					oqa.setSiteName(ms.getSiteName());
					oqa.setSeqNO(Integer.toString(seqno++));
					oqa.setIqcFlag(ms.getIqcFlag());
					oqa.setInnerRequestName(ms.getInnerRequestName());
					oqa.setInnerRequestDetailName(ms.getInnerRequestDetailName());
					oqa.setUnit(ms.getUnit());
					oqa.setReceivedQuantity(ms.getReceivedQuantity());
					if (ERPChargeFlag.equals("Y") && ms.getCharge().equals("")) {
						if (!oqa.getMakeDate().equals(makedate)) {
							List<String> sqldata = new ArrayList<String>();
							sqldata.add(oqa.getErpFactory());
							String spec = oqa.getMaterialSpecName()
									+ "************";
							sqldata.add(spec.substring(0, 10));
							String str = oqa.getMakeDate().substring(0, 4)
									+ oqa.getMakeDate().substring(5, 7)
									+ oqa.getMakeDate().substring(8);
							String time = str + "00";
							sqldata.add(time.substring(2, 8));
							charge = NameServiceProxy.getNameRuleDefService()
									.generateName("ChargeNo", sqldata, 1)
									.get(0);
							oqa.setCharge(charge.substring(14));
							if(ms.getSiteName().equals("B7")){
	                        	   oqa.setCharge(charge.substring(14,20));
								}
							makedate = oqa.getMakeDate();
						} else {
							oqa.setCharge(charge.substring(14));
						}
					}
				}
				toerplist.addAll(oqalist);
			}
		}

		return toerplist;
	}

	
	public List<MaterialStockInClass> GetToERPList(
			List<MaterialStockInClass> msilist, int num) throws ParseException {
		List<MaterialStockInClass> toerplist = new ArrayList<MaterialStockInClass>();
		int seqno = 1;
		CommonValidation commonVal = new CommonValidation();
		String sql2 = "SELECT MAX(UNDODETAILNAME) AS SEQ FROM materialpacking "
				+ "WHERE sitename = :sitename and receiveActNo=:receiveActNo and erpstate='ERPSUCCESS' ";

		Map<String, Object> bindMap3 = new HashMap<String, Object>();
		bindMap3.put("sitename", msilist.get(0).getSiteName());
		bindMap3.put("receiveActNo", msilist.get(0).getReceiveActNo());

		List<Map<String, Object>> queryResult2 = IDMFrameServiceProxy
				.getSqlTemplate()
				.queryForList(sql2, bindMap3);
		if(!(queryResult2.size()<=0||queryResult2.get(0).get("SEQ")==null||queryResult2.get(0).get("SEQ").toString().equals("")))
		{
			seqno=Integer.parseInt(queryResult2.get(0).get("SEQ").toString())+seqno;
		}
		for (MaterialStockInClass ms : msilist) {

			// 查询该物料是否根据ERP批次进行管理
			String ERPChargeFlag = "N";
			ERPChargeFlag = commonVal.getMaterialSpecCharge(ms.getErpfactory(),
					ms.getMaterialSpecName());
			if (ms.getOqaflag().equals("Y")) {
				List<MaterialStockInClass> oqalist = GetOQAGroupList(ms,
						ms.getMaterialOQAnum(), seqno);
				String makedate = "";
				String charge = ms.getCharge();
				if(ms.getErpfactory().equals("2001"))
				{
					charge="E0000001";
				}
				for (MaterialStockInClass oqa : oqalist) {

					oqa.setCustomdate(ms.getCustomdate());
					oqa.setCustomform(ms.getCustomform());
					oqa.setReceiveTime(ms.getReceiveTime());
					oqa.setCustomformstate(ms.getCustomformstate());
					oqa.setMaterialOQAnum(ms.getMaterialOQAnum());
					oqa.setTaxid(ms.getTaxid());
					oqa.setTransportformno(ms.getTransportformno());
					oqa.setErplocation(ms.getErplocation());
					oqa.setErpfactory(ms.getErpfactory());
					oqa.setMaterialSpecName(ms.getMaterialSpecName());
					oqa.setMaterialtype(ms.getMaterialtype());
					oqa.setSiteName(ms.getSiteName());
					oqa.setIcqflag(ms.getIcqflag());
					oqa.setZlshm(ms.getZlshm());
					oqa.setCharge(charge);
					oqa.setReceiveRequestName(ms.getReceiveRequestName());
					oqa.setReceiveRequestDetailName(ms.getReceiveRequestDetailName());
					oqa.setZcino(ms.getZcino());
					if(factory.equals("B2")) oqa.setSuppliername(ms.getSuppliername());//B2新增
					/**
					 * 根据ERP分批标准来进行，不再需要根据接收时间创建批次
					 * 用BS_MATERIALSPECCHARGEFLAG表中数据来确定是否需要进行批次管理；如果不需要进行批次管理的，
					 * 那么就不用在入库的时候创建批次 ，不用在退库的时候选择批次；还有一个问题，是PO的行项目中如果有charge的话，
					 * 那么在入库的时候就不用生成批次。
					 */
					if (ERPChargeFlag.equals("Y") && ms.getCharge().equals("")) {
						if (!oqa.getMakedate().equals(makedate)) {
							List<String> sqldata = new ArrayList<String>();
							sqldata.add(oqa.getErpfactory());
							String spec = oqa.getMaterialSpecName()
									+ "************";
							sqldata.add(spec.substring(0, 10));
							// String materialspecflag = new
							// CommonValidation().getMaterialSpecState(ms.getSiteName(),
							// ms.getMaterialSpecName());
							// if(materialspecflag.equals("Y")){
							// String str = oqa.getMakedate().substring(0,
							// 4)+oqa.getMakedate().substring(5,
							// 7)+oqa.getMakedate().substring(8);
							// String time = str+"00";
							// sqldata.add(time.substring(2, 8));
							// }else{
							// String str = ms.getReceiveTime().substring(0,
							// 4)+ms.getReceiveTime().substring(5,
							// 7)+ms.getReceiveTime().substring(8);
							// String time = str+"00";
							// sqldata.add(time.substring(2, 8));
							// }
							String str = oqa.getMakedate().substring(0, 4)
									+ oqa.getMakedate().substring(5, 7)
									+ oqa.getMakedate().substring(8);
							String time = str + "00";
							sqldata.add(time.substring(2, 8));
							charge = NameServiceProxy.getNameRuleDefService()
									.generateName("ChargeNo", sqldata, 1)
									.get(0);
							
							oqa.setCharge(charge.substring(14));
                           if(ms.getSiteName().equals("B7") || "B12".equals(ms.getSiteName())){
                        	   oqa.setCharge(charge.substring(14,20));
							}
                           if(factory.equals("B2")){
								if(oqa.getSuppliername()!=null)
									oqa.setCharge(oqa.getSuppliername().substring(3,oqa.getSuppliername().length()));//lpf
								else
								{
									if(oqa.getCharge().length()>7)
										oqa.setCharge(oqa.getCharge().substring(3,oqa.getCharge().length()));
								}							
                         }
							makedate = oqa.getMakedate();
						} else {
							oqa.setCharge(charge.substring(14));
						}
					}

				}
				toerplist.addAll(oqalist);
				seqno = seqno + oqalist.size();
			} else {

				List<MaterialStockInClass> oqalist = new MaterialPackingStockInUtil()
						.GetOQAMakedateGroupList(ms.getReceiveRequestName(),
								ms.getReceiveRequestDetailName(),
								ms.getReceiveActNo(), ms.getSiteName());
				String makedate = "";
				String charge = ms.getCharge();
				if(ms.getErpfactory().equals("2001"))
				{
					charge="E0000001";
				}
				for (MaterialStockInClass oqa : oqalist) {
					oqa.setCustomdate(ms.getCustomdate());
					oqa.setCustomform(ms.getCustomform());
					oqa.setReceiveTime(ms.getReceiveTime());
					oqa.setCustomformstate(ms.getCustomformstate());
					oqa.setMaterialOQAnum(ms.getMaterialOQAnum());
					oqa.setTaxid(ms.getTaxid());
					oqa.setTransportformno(ms.getTransportformno());
					oqa.setErplocation(ms.getErplocation());
					oqa.setErpfactory(ms.getErpfactory());
					oqa.setMaterialSpecName(ms.getMaterialSpecName());
					oqa.setMaterialtype(ms.getMaterialtype());
					oqa.setSiteName(ms.getSiteName());
					oqa.setSeqno(seqno++);
					oqa.setIcqflag(ms.getIcqflag());
					oqa.setZlshm(ms.getZlshm());
					oqa.setCharge(charge);
					oqa.setReceiveRequestName(ms.getReceiveRequestName());
					oqa.setReceiveRequestDetailName(ms.getReceiveRequestDetailName());
					oqa.setZcino(ms.getZcino());
					if(factory.equals("B2")) oqa.setSuppliername(ms.getSuppliername());
					if (ERPChargeFlag.equals("Y") && ms.getCharge().equals("")) {
						if (!oqa.getMakedate().equals(makedate)) {
							List<String> sqldata = new ArrayList<String>();
							sqldata.add(oqa.getErpfactory());
							String spec = oqa.getMaterialSpecName()
									+ "************";
							sqldata.add(spec.substring(0, 10));
							String str = oqa.getMakedate().substring(0, 4)
									+ oqa.getMakedate().substring(5, 7)
									+ oqa.getMakedate().substring(8);
							
							String time = str + "00";
							sqldata.add(time.substring(2, 8));
							charge = NameServiceProxy.getNameRuleDefService()
									.generateName("ChargeNo", sqldata, 1)
									.get(0);
							oqa.setCharge(charge.substring(14));
							if(ms.getSiteName().equals("B7") || "B12".equals(ms.getSiteName())){
	                        	   oqa.setCharge(charge.substring(14,20));
								}
							if(factory.equals("B2")){
								if(oqa.getSuppliername()!=null)
									oqa.setCharge(oqa.getSuppliername().substring(3,oqa.getSuppliername().length()));//lpf
								else
								{
									if(oqa.getCharge().length()>7)
										oqa.setCharge(oqa.getCharge().substring(3,oqa.getCharge().length()));
								}							
                         }
							makedate = oqa.getMakedate();
						} else {
							oqa.setCharge(charge.substring(14));
						}
					}

					// if(!oqa.getMakedate().equals(makedate)){
					// List<String> sqldata = new ArrayList<String>();
					// sqldata.add(oqa.getErpfactory());
					// String spec = oqa.getMaterialSpecName()+"************";
					// sqldata.add(spec.substring(0,10));
					// String materialspecflag = new
					// CommonValidation().getMaterialSpecState(ms.getSiteName(),
					// ms.getMaterialSpecName());
					// if(materialspecflag.equals("Y")){
					// String str = oqa.getMakedate().substring(0,
					// 4)+oqa.getMakedate().substring(5,
					// 7)+oqa.getMakedate().substring(8);
					// String time = str+"00";
					// sqldata.add(time.substring(2, 8));
					// }else{
					// String str = ms.getReceiveTime().substring(0,
					// 4)+ms.getReceiveTime().substring(5,
					// 7)+ms.getReceiveTime().substring(8);
					// String time = str+"00";
					// sqldata.add(time.substring(2, 8));
					// }
					//
					// charge =
					// NameServiceProxy.getNameRuleDefService().generateName("ChargeNo",
					// sqldata, 1).get(0);
					// //oqa.setCharge(charge);
					// oqa.setCharge(charge.substring(14));
					// makedate = oqa.getMakedate();
					// }else{
					// oqa.setCharge(charge.substring(14));
					// }

				}
				toerplist.addAll(oqalist);
			}
			// }

		}

		return toerplist;
	}


	public void SaveInnerStockInInfo(List<InnerRequestDetailInfo> toerplist,
			List<MaterialUnDoinfo> undolist, EventInfo eventinfo)
			throws Exception {
		List<MaterialProcessGroupCreateInfo> mpglist = new ArrayList<MaterialProcessGroupCreateInfo>();
		if (undolist.size() == toerplist.size() && toerplist.size() > 0) {// undolist.size()<1
																			// 说明ERP过账失败
			try {
				for (int i = 0; i < toerplist.size(); i++) {
					InnerRequestDetailInfo ms = toerplist.get(i);
					MaterialUnDoinfo undo = undolist.get(i);
					for (int j = 0; j < undolist.size(); j++) {
						if(toerplist.get(i).getSeqNO().equals(undolist.get(j).getSeq().substring(15)))	
						{
							undo = undolist.get(j);
							break;
						}
					}//匹配发送ERP的seq号对应返回的undoinfo by maxinghua
					List<MaterialPacking> mplist = new ArrayList<MaterialPacking>();
					if (ms.getPreGroupName() == null
							|| ms.getPreGroupName().equals("")) {
						mplist = new MaterialPackingStockInUtil()
								.GetOQADetailGroupListByInner1(ms);
					} else {

						mplist = new MaterialPackingStockInUtil()
								.GetOQADetailGroupListByInner2(ms);
					}
					MaterialReceiveRequestDetailKey mrrdk = new MaterialReceiveRequestDetailKey();
					mrrdk.setSiteName(ms.getSiteName());
					mrrdk.setReceiveRequestName(ms.getReceiveRequestName());
					mrrdk.setReceiveRequestDetailName(ms
							.getReceiveRequestDetailName());
					MaterialReceiveRequestDetail mrrd = ReceiveRequestDetailServiceProxy
							.getReceiveRequestDetailService()
							.selectByKey(mrrdk);

					// 存packing
					for (MaterialPacking mp : mplist) {
						
						//erp升级字段Q库存
						String sql = "SELECT POCATEGORY,PS_POSID  FROM MATERIALRECEIVEREQUESTDETAIL " +
		                        " WHERE SITENAME  =:sitename and RECEIVEREQUESTNAME =:receiveRequestName " +
		                        " AND RECEIVEREQUESTDETAILNAME =:receiveRequestDetailName";
						Map<String, Object> bindMap1 = new HashMap<String, Object>();
						bindMap1.put("sitename", ms.getSiteName());
						bindMap1.put("receiveRequestName", ms.getReceiveRequestName());
						bindMap1.put("receiveRequestDetailName", ms.getReceiveRequestDetailName());

		                List<Map<String, Object>> queryResult1 = IDMFrameServiceProxy
		                        .getSqlTemplate()
		                        .queryForList(sql, bindMap1);
		                
		                String pocategory = "";
		                String po_posid = "";
		                
		                if (queryResult1.get(0).get("POCATEGORY") != null) {
		                	pocategory = queryResult1.get(0).get("POCATEGORY").toString();
		                }
		                
		                if (queryResult1.get(0).get("PS_POSID") != null) {
		                	 po_posid = queryResult1.get(0).get("PS_POSID").toString();
		                }
						
						Timestamp time = null;

						try {
							time = Timestamp.valueOf(ms.getReceiveTime()
									+ " 00:00:00");
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

						Date date = new Date();
						SimpleDateFormat df = new SimpleDateFormat(
								"yyyy-MM-dd HH:mm:ss");
						String receivedate = df.format(date);

						MaterialPackingKey mpkey = new MaterialPackingKey();
						mpkey.setSiteName(mp.getKey().getSiteName());
						mpkey.setMaterialPackingName(mp.getKey()
								.getMaterialPackingName());
						SetEventInfo setevent = new SetEventInfo();
						Map<String, Object> bindMap = new HashMap<String, Object>();
						bindMap.put("packingState", "Released");
						bindMap.put("erpLocation", ms.getErpLocation());
						bindMap.put("stockState", "Stocked");
						bindMap.put("sobkz", pocategory);
						bindMap.put("ps_Posid", po_posid);
						bindMap.put("wbs_o", po_posid);
						bindMap.put("wbs_n", po_posid);
						bindMap.put("charge", ms.getCharge());
						bindMap.put("unDoID", undo.getUnDoID());
						bindMap.put("unDoDetailName", undo.getUnDoDetailName());
						bindMap.put("erpEventTime", time);
						bindMap.put("stockInType", "Normal");
						bindMap.put("erpState", "SUCCESS");
						bindMap.put("receiveTime",
								Timestamp.valueOf(receivedate));
						bindMap.put("receiveUser", eventinfo.getEventUser());

						if (ms.getPreGroupName() != null) {
							bindMap.put("materialProcessGroupName",
									undo.getOqaname());
							bindMap.put(
									"oqaResultState",
									GenericServiceProxy.getConstantMap().OQA_State_Pre);
						} else {
							if (mrrd.getIqcFlag() == null
									|| mrrd.getIqcFlag().equals("")) {
								bindMap.put("packingGrade", "OK");
							} else if (mrrd.getIqcFlag().equals("S")) {
								bindMap.put("packingGrade", "NG");
							} else if (mrrd.getIqcFlag().equals("X")) {
								bindMap.put("packingGrade", "");
								bindMap.put("materialProcessGroupName",
										"OICOQA");
								bindMap.put(
										"oqaResultState",
										GenericServiceProxy.getConstantMap().OQA_State_Pre);
							}
						}
						setevent.setUserColumns(bindMap);
						eventinfo.setEventName("NormalStockIn");
						eventinfo.setEventComment("NormalStockIn");
						eventinfo.setReasonCode(mp.getReasonCode());
						eventinfo.setReasonCodeType(mp.getReasonCodeType());
						MaterialPackingServiceProxy.getMaterialPackingService()
								.setEvent(mpkey, eventinfo, setevent);

					}
					// //存储质检批信息
					if (ms.getPreGroupName() != null) {

						MaterialProcessGroupCreateInfo mpg = new MaterialProcessGroupCreateInfo();
						mpg.setSiteName(ms.getSiteName());
						mpg.setMaterialProcessGroupName(undo.getOqaname());
						//mpg.setContentMaterialType(ms.getMaterialtype());
						mpg.setProcessGroupState(GenericServiceProxy
								.getConstantMap().OQA_State_Pre);
						MaterialProcessGroupServiceProxy
								.getMaterialProcessGroupService().create(
										eventinfo, mpg);
					}
					// 存抬头文本信息
					MaterialReceiveActKey mrk = new MaterialReceiveActKey();
					String sql =" SELECT RECEIVEREQUESTNAME FROM MATERIALRECEIVEACT WHERE SITENAME =:SITENAME AND RECEIVEACTNO =:RECEIVEACTNO ";

					Map<String, Object> bindMap1 = new HashMap<String, Object>();
					bindMap1.put("SITENAME", ms.getSiteName());
					bindMap1.put("RECEIVEACTNO", ms.getReceiveActNo());
					List<Map<String, Object>> queryResult = IDMFrameServiceProxy
							.getSqlTemplate()
							.queryForList(sql, bindMap1);
					mrk.setSiteName(ms.getSiteName());
					mrk.setReceiveactNO(ms.getReceiveActNo());
					mrk.setReceiveRequestName(queryResult.get(0).get("RECEIVEREQUESTNAME").toString());
					com.cim.idm.wmspackage.materialreceiverequestact.management.info.SetEventInfo setevent = new com.cim.idm.wmspackage.materialreceiverequestact.management.info.SetEventInfo();
					Map<String, Object> bindMap = new HashMap<String, Object>();
					bindMap.put("receiveActState", "Received");
					setevent.setUserColumns(bindMap);
					MaterialReceiveRequestActServiceProxy
							.getReceiveRequestBatchService().setEvent(mrk,
									eventinfo, setevent);

				}

				// 存物料凭证
				SaveUnDoInfo(toerplist.get(0).getReceiveActNo(), undolist
						.get(0).getUnDoIdDate(), undolist.get(0).getUnDoID());
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				throw e;
			}

		}

	}
	public List<MaterialPacking> SaveNormalStockInInfoForERPAccount(List<MaterialStockInClass> toerplist,
			List<MaterialUnDoinfo> undolist, EventInfo eventinfo,String messageID)
			throws Exception {
		List<MaterialProcessGroupCreateInfo> mpglist = new ArrayList<MaterialProcessGroupCreateInfo>();
		List<MaterialPacking> tqmsList=new ArrayList<MaterialPacking>();
		System.out.println("*******************************#####################");
		System.out.println("*******************************#####################");
		System.out.println("*******************************#####################");
		System.out.println(undolist.size() + "undolist.size()");
		System.out.println(toerplist.size() + "toerplist.size()");
		System.out.println("*******************************#####################");
		System.out.println("*******************************#####################");
		System.out.println("*******************************#####################");
		if (undolist.size() == toerplist.size() && toerplist.size() > 0) {// undolist.size()<1
																			// 说明ERP过账失败
			try {
				
				List<String> boxlist = new ArrayList<String>();  // 质检中的BOX ID，用来发送邮件
				for (int i = 0; i < toerplist.size(); i++) {
					MaterialStockInClass ms = toerplist.get(i);
					MaterialUnDoinfo undo = undolist.get(i);
					for (int j = 0; j < undolist.size(); j++) {
						if(Integer.toString(toerplist.get(i).getSeqno()).equals(undolist.get(j).getSeq().substring(15,undolist.get(j).getSeq().length())))	
						{
							undo = undolist.get(j);
							break;
						}
					}//匹配发送ERP的seq号对应返回的undoinfo by maxinghua
					List<MaterialPacking> mplist = new ArrayList<MaterialPacking>();
					if (ms.getPreGroupName() == null
							|| ms.getPreGroupName().equals("")) {
						mplist = new MaterialPackingStockInUtil()
								.GetOQADetailGroupList1(ms);
					} else {

						mplist = new MaterialPackingStockInUtil()
								.GetOQADetailGroupList2(ms);
					}
					MaterialReceiveRequestDetailKey mrrdk = new MaterialReceiveRequestDetailKey();
					mrrdk.setSiteName(ms.getSiteName());
					mrrdk.setReceiveRequestName(ms.getReceiveRequestName());
					mrrdk.setReceiveRequestDetailName(ms
							.getReceiveRequestDetailName());
					MaterialReceiveRequestDetail mrrd = ReceiveRequestDetailServiceProxy
							.getReceiveRequestDetailService()
							.selectByKey(mrrdk);

					// 存packing
					for (MaterialPacking mp : mplist) {

						Timestamp time = null;

						try {
							time = Timestamp.valueOf(ms.getReceiveTime()
									+ " 00:00:00");
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

						Date date = new Date();
						SimpleDateFormat df = new SimpleDateFormat(
								"yyyy-MM-dd HH:mm:ss");
						String receivedate = df.format(date);

						MaterialPackingKey mpkey = new MaterialPackingKey();
						mpkey.setSiteName(mp.getKey().getSiteName());
						mpkey.setMaterialPackingName(mp.getKey()
								.getMaterialPackingName());
						SetEventInfo setevent = new SetEventInfo();
						Map<String, Object> bindMap = new HashMap<String, Object>();
						bindMap.put("packingState", "Released");
						bindMap.put("erpLocation", ms.getErplocation());
						bindMap.put("stockState", "Stocked");
						bindMap.put("charge", undo.getCharge());
						bindMap.put("unDoID", undo.getUnDoID());
						bindMap.put("unDoDetailName", undo.getUnDoDetailName());
						bindMap.put("erpEventTime", time);
						bindMap.put("stockInType", "Normal");
						bindMap.put("erpState", "SUCCESS");
						bindMap.put("messageId",mp.getErpState().equalsIgnoreCase("ERPSUCCESS")?mp.getMessageId():messageID);
						bindMap.put("receiveTime",
								Timestamp.valueOf(receivedate));
						bindMap.put("receiveUser", eventinfo.getEventUser());
                        bindMap.put("remark", ms.getRemark());
						if (ms.getPreGroupName() != null) {
							bindMap.put("materialProcessGroupName",
									undo.getOqaname());
							bindMap.put(
									"oqaResultState",
									GenericServiceProxy.getConstantMap().OQA_State_Pre);
						} else {
							if (mrrd.getIqcFlag() == null
									|| mrrd.getIqcFlag().equals("")) {
								bindMap.put("packingGrade", "OK");
								bindMap.put(
										"oqaResultState",
										GenericServiceProxy.getConstantMap().OQA_State_End);
								bindMap.put("oqaResult","OK");
							} else if (mrrd.getIqcFlag().equals("S")) {
								bindMap.put("packingGrade", "NG");
								bindMap.put(
										"oqaResultState",
										GenericServiceProxy.getConstantMap().OQA_State_End);
								bindMap.put("oqaResult","NG");
							} else if (mrrd.getIqcFlag().equals("X")) {
								bindMap.put("packingGrade", "");
								bindMap.put("materialProcessGroupName",
										"OICOQA");
								bindMap.put(
										"oqaResultState",
										GenericServiceProxy.getConstantMap().OQA_State_Pre);
							}
						}
						//PO入库统一入库至虚拟库位 DJQ-1-1-1-1
						bindMap.put("locationName", "DJQ-1-1-1-1");
						setevent.setUserColumns(bindMap);
						//eventinfo.setEventName("NormalStockIn");
						//eventinfo.setEventComment("NormalStockIn");
						eventinfo.setEventName(eventinfo.getEventName());
						eventinfo.setEventComment(eventinfo.getEventComment());
//						eventinfo.setReasonCode(mp.getReasonCode());
//						eventinfo.setReasonCodeType(mp.getReasonCodeType());
						
						String sqlSelect = "SELECT nvl(MATERIALQUANTITY, 0) AS MATERIALQUANTITY FROM MATERIALPACKING WHERE MATERIALPACKINGNAME=:MATERIALPACKINGNAME AND SITENAME =:SITENAME";
						Map<String, Object> hashMap = new HashMap<String, Object>();
						hashMap.put("MATERIALPACKINGNAME", mp.getKey().getMaterialPackingName());
						hashMap.put("SITENAME", mp.getKey().getSiteName());
						List<Map<String, Object>> queryResult = IDMFrameServiceProxy
								.getSqlTemplate()
								.queryForList(sqlSelect, hashMap);
						
						MaterialPackingServiceProxy.getMaterialPackingService()
								.setEvent(mpkey, eventinfo, setevent);
						
						String sql = "UPDATE MATERIALPACKING SET MATERIALQUANTITY =:MATERIALQUANTITY,MATERIALCREATEQUANTITY =:MATERIALQUANTITY WHERE MATERIALPACKINGNAME=:MATERIALPACKINGNAME AND SITENAME =:SITENAME";
						Map<String, Object> map = new HashMap<String, Object>();
						map.put("MATERIALQUANTITY", new BigDecimal(queryResult.get(0).get("MATERIALQUANTITY").toString()));
						map.put("MATERIALPACKINGNAME", mp.getKey().getMaterialPackingName());
						map.put("SITENAME", mp.getKey().getSiteName());
						IDMFrameServiceProxy.getSqlTemplate().update(sql, map);
						
						//更新历史表
						String updateHisSql = "UPDATE MATERIALPACKINGHISTORY SET MATERIALQUANTITY =:MATERIALQUANTITY,MATERIALCREATEQUANTITY =:MATERIALQUANTITY WHERE MATERIALPACKINGNAME=:MATERIALPACKINGNAME AND SITENAME =:SITENAME";
						Map<String, Object> mapHis = new HashMap<String, Object>();
						mapHis.put("MATERIALQUANTITY", new BigDecimal(queryResult.get(0).get("MATERIALQUANTITY").toString()));
						mapHis.put("MATERIALPACKINGNAME", mp.getKey().getMaterialPackingName());
						mapHis.put("SITENAME", mp.getKey().getSiteName());
						IDMFrameServiceProxy.getSqlTemplate().update(updateHisSql, mapHis);
						
						if(mrrd.getIqcFlag().equals("X"))
							tqmsList.add(mp);
						
						// 如果是判断为 质检中 的BOX，则主动发送邮件
						if(bindMap.get("oqaResultState").equals(GenericServiceProxy.getConstantMap().OQA_State_Pre)) {
							boxlist.add(mp.getKey().getMaterialPackingName());
						}
					}
					// //存储质检批信息
					if (ms.getPreGroupName() != null) {
						String sql =" SELECT MATERIALPROCESSGROUPNAME FROM MATERIALPROCESSGROUP WHERE SITENAME =:SITENAME AND MATERIALPROCESSGROUPNAME =:MATERIALPROCESSGROUPNAME ";

						Map<String, Object> bindMap1 = new HashMap<String, Object>();
						bindMap1.put("SITENAME", ms.getSiteName());
						bindMap1.put("MATERIALPROCESSGROUPNAME", undo.getOqaname());
						List<Map<String, Object>> queryResult = IDMFrameServiceProxy
								.getSqlTemplate()
								.queryForList(sql, bindMap1);
						if(queryResult==null||queryResult.size()<1){
						MaterialProcessGroupCreateInfo mpg = new MaterialProcessGroupCreateInfo();
						mpg.setSiteName(ms.getSiteName());
						mpg.setMaterialProcessGroupName(undo.getOqaname());
						mpg.setContentMaterialType(ms.getMaterialtype());
						mpg.setProcessGroupState(GenericServiceProxy
								.getConstantMap().OQA_State_Pre);
						MaterialProcessGroupServiceProxy
								.getMaterialProcessGroupService().create(
										eventinfo, mpg);
						}
					}
					// 存抬头文本信息
					MaterialReceiveActKey mrk = new MaterialReceiveActKey();
					String sql =" SELECT RECEIVEREQUESTNAME FROM MATERIALRECEIVEACT WHERE SITENAME =:SITENAME AND RECEIVEACTNO =:RECEIVEACTNO ";

					Map<String, Object> bindMap1 = new HashMap<String, Object>();
					bindMap1.put("SITENAME", ms.getSiteName());
					bindMap1.put("RECEIVEACTNO", ms.getReceiveActNo());
					List<Map<String, Object>> queryResult = IDMFrameServiceProxy
							.getSqlTemplate()
							.queryForList(sql, bindMap1);
					mrk.setSiteName(ms.getSiteName());
					mrk.setReceiveactNO(ms.getReceiveActNo());
					mrk.setReceiveRequestName(queryResult.get(0).get("RECEIVEREQUESTNAME").toString());
					com.cim.idm.wmspackage.materialreceiverequestact.management.info.SetEventInfo setevent = new com.cim.idm.wmspackage.materialreceiverequestact.management.info.SetEventInfo();
					Map<String, Object> bindMap = new HashMap<String, Object>();
					bindMap.put("receiveActState", "Received");
					setevent.setUserColumns(bindMap);
					MaterialReceiveRequestActServiceProxy
							.getReceiveRequestBatchService().setEvent(mrk,
									eventinfo, setevent);

				}
				// 存物料凭证
				SaveUnDoInfo(toerplist.get(0).getReceiveActNo(), undolist
						.get(0).getUnDoIdDate(), undolist.get(0).getUnDoID());
				
				// 发送邮件
				if(boxlist != null && boxlist.size() > 0) {
					try {
						log.info("入库后时时发送质检状态的BOX邮件任务1  ==========> ");
						MailUtil mailUtil = new MailUtil();
						if(StringUtils.isNoneBlank(toerplist.get(0).getRemark()) && toerplist.get(0).getRemark().equals("加急质检")) {
							boxlist.add("加急质检");
						}
						mailUtil.sendPreOQAReportNow(boxlist);
					} catch (IDMFrameDBErrorSignal e) {
//							e.printStackTrace();
						log.info("PO入库为质检状态的材料,发送邮件失败 ==========> ");
					}
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				throw e;
			}

		}
		else{
			throw new CustomException("ERP-0001", "");
		}
		return tqmsList;
	}
	
	// 在用
	public List<MaterialPacking> SaveNormalStockInInfo(List<MaterialStockInClass> toerplist,
			List<MaterialUnDoinfo> undolist, EventInfo eventinfo)
			throws Exception {
		List<MaterialProcessGroupCreateInfo> mpglist = new ArrayList<MaterialProcessGroupCreateInfo>();
		List<MaterialPacking> tqmsList=new ArrayList<MaterialPacking>();
		if (undolist.size() == toerplist.size() && toerplist.size() > 0) {// undolist.size()<1
																			// 说明ERP过账失败
			try {
				for (int i = 0; i < toerplist.size(); i++) {
					MaterialStockInClass ms = toerplist.get(i);
					MaterialUnDoinfo undo = undolist.get(i);
					for (int j = 0; j < undolist.size(); j++) {
						if(Integer.toString(toerplist.get(i).getSeqno()).equals(undolist.get(j).getSeq()))	
						{
							undo = undolist.get(j);
							break;
						}
					}//匹配发送ERP的seq号对应返回的undoinfo by maxinghua
					List<MaterialPacking> mplist = new ArrayList<MaterialPacking>();
					if (ms.getPreGroupName() == null
							|| ms.getPreGroupName().equals("")) {
						mplist = new MaterialPackingStockInUtil()
								.GetOQADetailGroupList1(ms);
					} else {

						mplist = new MaterialPackingStockInUtil()
								.GetOQADetailGroupList2(ms);
					}
					MaterialReceiveRequestDetailKey mrrdk = new MaterialReceiveRequestDetailKey();
					mrrdk.setSiteName(ms.getSiteName());
					mrrdk.setReceiveRequestName(ms.getReceiveRequestName());
					mrrdk.setReceiveRequestDetailName(ms
							.getReceiveRequestDetailName());
					MaterialReceiveRequestDetail mrrd = ReceiveRequestDetailServiceProxy
							.getReceiveRequestDetailService()
							.selectByKey(mrrdk);

					// 存packing
					for (MaterialPacking mp : mplist) {

						Timestamp time = null;

						try {
							time = Timestamp.valueOf(ms.getReceiveTime()
									+ " 00:00:00");
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

						Date date = new Date();
						SimpleDateFormat df = new SimpleDateFormat(
								"yyyy-MM-dd HH:mm:ss");
						String receivedate = df.format(date);

						MaterialPackingKey mpkey = new MaterialPackingKey();
						mpkey.setSiteName(mp.getKey().getSiteName());
						mpkey.setMaterialPackingName(mp.getKey()
								.getMaterialPackingName());
						SetEventInfo setevent = new SetEventInfo();
						Map<String, Object> bindMap = new HashMap<String, Object>();
						bindMap.put("packingState", "Released");
						bindMap.put("erpLocation", ms.getErplocation());
						bindMap.put("stockState", "Stocked");
						bindMap.put("charge", ms.getCharge());
						bindMap.put("unDoID", undo.getUnDoID());
						bindMap.put("unDoDetailName", undo.getUnDoDetailName());
						bindMap.put("erpEventTime", time);
						bindMap.put("stockInType", "Normal");
						bindMap.put("erpState", "SUCCESS");
						bindMap.put("receiveTime",
								Timestamp.valueOf(receivedate));
						bindMap.put("receiveUser", eventinfo.getEventUser());

//						if (ms.getPreGroupName() != null) {
//							bindMap.put("materialProcessGroupName",
//									undo.getOqaname());
//							bindMap.put(
//									"oqaResultState",
//									GenericServiceProxy.getConstantMap().OQA_State_Pre);
//						} else {
							if (mrrd.getIqcFlag() == null
									|| mrrd.getIqcFlag().equals("")) {
								bindMap.put("packingGrade", "OK");
							} else if (mrrd.getIqcFlag().equals("S")) {
								bindMap.put("packingGrade", "NG");
							} else if (mrrd.getIqcFlag().equals("X")) {
								bindMap.put("packingGrade", "");
								bindMap.put("materialProcessGroupName",
										"OICOQA");
								bindMap.put(
										"oqaResultState",
										GenericServiceProxy.getConstantMap().OQA_State_Pre);
								
							}
//						}
						setevent.setUserColumns(bindMap);
						eventinfo.setEventName("NormalStockIn");
						eventinfo.setEventComment("NormalStockIn");
						eventinfo.setReasonCode(mp.getReasonCode());
						eventinfo.setReasonCodeType(mp.getReasonCodeType());
						MaterialPackingServiceProxy.getMaterialPackingService()
								.setEvent(mpkey, eventinfo, setevent);
						if(mrrd.getIqcFlag().equals("X"))
							tqmsList.add(mp);

					}
					
					MaterialReceiveActKey mrk = new MaterialReceiveActKey();
					String sql =" SELECT RECEIVEREQUESTNAME FROM MATERIALRECEIVEACT WHERE SITENAME =:SITENAME AND RECEIVEACTNO =:RECEIVEACTNO ";

					Map<String, Object> bindMap1 = new HashMap<String, Object>();
					bindMap1.put("SITENAME", ms.getSiteName());
					bindMap1.put("RECEIVEACTNO", ms.getReceiveActNo());
					List<Map<String, Object>> queryResult = IDMFrameServiceProxy
							.getSqlTemplate()
							.queryForList(sql, bindMap1);
					mrk.setSiteName(ms.getSiteName());
					mrk.setReceiveactNO(ms.getReceiveActNo());
					mrk.setReceiveRequestName(queryResult.get(0).get("RECEIVEREQUESTNAME").toString());
					com.cim.idm.wmspackage.materialreceiverequestact.management.info.SetEventInfo setevent = new com.cim.idm.wmspackage.materialreceiverequestact.management.info.SetEventInfo();
					Map<String, Object> bindMap = new HashMap<String, Object>();
					bindMap.put("receiveActState", "Received");
					setevent.setUserColumns(bindMap);
					MaterialReceiveRequestActServiceProxy
							.getReceiveRequestBatchService().setEvent(mrk,
									eventinfo, setevent);

				}

				// 存物料凭证
				SaveUnDoInfo(toerplist.get(0).getReceiveActNo(), undolist
						.get(0).getUnDoIdDate(), undolist.get(0).getUnDoID());
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				throw e;
			}

		}
		return tqmsList;
	}
	// 弃用
	public void UnDoStockIn(List<MaterialPacking> undolist,
			EventInfo eventinfo, String newUnDoId, String UnDoID) {

		for (MaterialPacking mp : undolist) {
			mp.setPackingState("Created");
			mp.setStockInType("");
			mp.setReceiveTime(null);
			mp.setOqaResult("");
			mp.setMaterialProcessGroupName("");
			mp.setUnDoID(newUnDoId);
			mp.setOqaResultState("");
			mp.setLastEventComment(eventinfo.getEventComment());
			mp.setLastEventName(eventinfo.getEventName());
			mp.setLastEventTime(eventinfo.getEventTime());
			mp.setLastEventUser(eventinfo.getEventUser());
			mp.setLastEventTimeKey(eventinfo.getLastEventTimekey());

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

	// 在用
	public void makeUnStockIn(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'";

			String sql_selUndoBoxInfo2 = " 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 LASTEVENTNAME<>'MToM' )"
					+ " union "
					+ "SELECT SITENAME,MATERIALPACKINGNAME "
					+ "FROM BS_MATERIALPACKINGUNDOINFO BS "
					+ "WHERE BS.UNDOID=:UNDOID AND "
					+ "BS.SITENAME=:sitename "
					+ "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()));
				// bindMap_UndoBoxInfo.put("REQUESTDETAILNAME",requestDetailName);
				List<Map<String, Object>> queryResult_BoxInfo = IDMFrameServiceProxy
						.getSqlTemplate()
						
						.queryForList(sql_selUndoBoxInfo,
								bindMap_selUndoBoxInfo);
				if (queryResult_BoxInfo.size() > 0) {

					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());
						materialPackingKeyList.add(keyInfo);
					}
					SetEventInfo setEventInfo = new SetEventInfo();
					Map<String, Object> bindMap = new HashMap<String, Object>();
					bindMap.put("packingState", "Created");
					bindMap.put("unDoID", newUnDoList.get(0).getUnDoID());
					bindMap.put("unDoDetailName", newUnDoList.get(0)
							.getUnDoDetailName());
					bindMap.put("stockState", "Created");
					bindMap.put("locationName", "");
					bindMap.put("oqaResult", "");
					bindMap.put("oqaResultState", "");
					setEventInfo.setUserColumns(bindMap);
					MaterialPackingServiceProxy.getMaterialPackingService()
							.setEvent(materialPackingKeyList, eventInfo,
									setEventInfo);
				}

			}

			// Map<String, Object> bindMap_selUndoBoxInfo = new HashMap<String,
			// Object>();
			// bindMap_selUndoBoxInfo.put("UNDOID", UnDoID);
			// bindMap_selUndoBoxInfo.put("sitename", siteNameList.get(0));
			// //bindMap_UndoBoxInfo.put("REQUESTDETAILNAME",requestDetailName);
			// List<Map<String, Object>> queryResult_BoxInfo2 =
			// IDMFrameServiceProxy.getSqlTemplate().queryForList(sql_selUndoBoxInfo2,
			// bindMap_selUndoBoxInfo);
			// if(queryResult_BoxInfo2.size()>0){
			String sql_UndoBoxInfo = " UPDATE BS_MATERIALPACKINGUNDOINFO SET UNDOIDSTATE='N' WHERE MATERIALPACKINGNAME IN (SELECT MATERIALPACKINGNAME"
					+ " FROM BS_MATERIALPACKINGUNDOINFO BS"
					+ " WHERE BS.UNDOID=:UNDOID AND("
					+ " ("
					+ " BS.UNDODETAILNAME=:UNDODETAILNAME"
					+ " AND BS.SITENAME=:SITENAME"
					+ " )"
					+ " OR"
					+ " ( "
					+ " BS.UNDODETAILNAME=:UNDODETAILNAME"
					+ " AND BS.SITENAME=:SITENAME))"
					+ " AND UNDOIDSTATE<>'N'"
					+ " AND LASTEVENTNAME<>'MToM')";
			String sql_insert = new MaterialPackingServiceImpl().insertUnDOMaterialPackingInfo_v2;
			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) {
			throw ex;
		} catch (NotFoundSignal ex) {
			throw ex;
		}
	}

	public String GetActType(String UnDoID, List<String> siteNameList) {

		String Stocktype = "";
		String condition = "select distinct STOCKINTYPE from BS_MATERIALPACKINGUNDOINFO where SITENAME=:SITENAME AND UNDOID =:UNDOID";
		Map<String, Object> bindMap = new HashMap<String, Object>();
		bindMap.put("SITENAME", siteNameList.get(0));
		bindMap.put("UNDOID", UnDoID);
		List<Map<String, Object>> undolist = IDMFrameServiceProxy
				.getSqlTemplate().queryForList(condition, bindMap);
		if (undolist.size() > 0) {
			Stocktype = undolist.get(0).get("STOCKINTYPE") == null ? ""
					: undolist.get(0).get("STOCKINTYPE").toString();
		}
		String acttype = Stocktype.split(":")[0];
		return acttype;
	}

	public String GetReceiveActNo(String acttype, List<String> siteNameList)
			throws Exception {
		String condition = "";

		try {

			condition = new MaterialReceiveRequestServiceImpl()
					.GenerateMaterialReceiveRequestNameUsedInCancel(
							siteNameList.get(0), acttype);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw e;
		}

		return condition;
	}

	public String GetCancelReceiveActNo(String UnDoID, String siteName)
			throws Exception {
		String condition = "";

		try {
			String receiveactno = new MaterialPackingStockInUtil()
					.GetUnDoInfoList(UnDoID);
			if (!receiveactno.equals("")) {
				condition = new MaterialReceiveRequestServiceImpl()
						.GenerateMaterialCancelReceiveRequestNameUsedInCancel(receiveactno
								+ "+");
			} else {
				throw new Exception("There is no ReceiveActNo found in :"
						+ UnDoID);
			}

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

		return condition;
	}
	public void updataPallet(EventInfo eventInfo,String siteName, String receiveActNo)
			throws Exception {
		try {
			String sql_query = " SELECT  DISTINCT SUPERMATERIALPACKINGNAME AS MATERIALPACKINGNAME,PACKINGGRADE,materialProcessGroupName "
					+ " FROM MATERIALPACKING BS"
					+ " WHERE "
					+ " BS.RECEIVEACTNO=:receiveActNo"
					+ " AND BS.SUPERMATERIALPACKINGNAME IS NOT NULL"
					+ " AND BS.SITENAME=:SITENAME";
			
				Map<String, Object> bindMap_insert = new HashMap<String, Object>();
				bindMap_insert.put("SITENAME", siteName);
				bindMap_insert.put("receiveActNo",
						receiveActNo);
				MaterialPackingKey materialPackingKey = new MaterialPackingKey();
				Map<String, Object> bindMap = new HashMap<String, Object>();
				List<Map<String, Object>> PalletList =IDMFrameServiceProxy.getSqlTemplate().queryForList(sql_query, bindMap_insert);
				SetEventInfo setEventInfo = new SetEventInfo();
				for(int i = 0; i < PalletList.size(); i++)
				{
					if(PalletList.get(i).get("MATERIALPACKINGNAME")!=null)
					{
						materialPackingKey.setMaterialPackingName(PalletList.get(i).get("MATERIALPACKINGNAME").toString());
						materialPackingKey.setSiteName(siteName);
						bindMap.put("packingState","Released");
						bindMap.put("stockState","Stocked");
						bindMap.put("materialProcessGroupName",PalletList.get(i).get("MATERIALPROCESSGROUPNAME")==null?"":PalletList.get(i).get("MATERIALPROCESSGROUPNAME").toString());
						bindMap.put("packingGrade",PalletList.get(i).get("PACKINGGRADE")==null?"":PalletList.get(i).get("PACKINGGRADE").toString());
						setEventInfo.setUserColumns(bindMap);
						MaterialPackingServiceProxy.getMaterialPackingService()
						.setEvent(materialPackingKey, eventInfo,
								setEventInfo);
					}
				}
				
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
					throw e;
				}

	}
	public void updataStockOutPallet(EventInfo eventInfo,String siteName, String receiveActNo)
			throws Exception {
		try {
			String sql_query = " SELECT  DISTINCT SUPERMATERIALPACKINGNAME AS MATERIALPACKINGNAME,PACKINGGRADE,materialProcessGroupName "
					+ " FROM MATERIALPACKING BS"
					+ " WHERE "
					+ " BS.RECEIVEACTNO=:receiveActNo"
					+ " AND BS.SUPERMATERIALPACKINGNAME IS NOT NULL"
					+ " AND BS.SITENAME=:SITENAME";
			
				Map<String, Object> bindMap_insert = new HashMap<String, Object>();
				bindMap_insert.put("SITENAME", siteName);
				bindMap_insert.put("receiveActNo",
						receiveActNo);
				MaterialPackingKey materialPackingKey = new MaterialPackingKey();
				Map<String, Object> bindMap = new HashMap<String, Object>();
				List<Map<String, Object>> PalletList =IDMFrameServiceProxy.getSqlTemplate().queryForList(sql_query, bindMap_insert);
				SetEventInfo setEventInfo = new SetEventInfo();
				for(int i = 0; i < PalletList.size(); i++)
				{
					if(PalletList.get(i).get("MATERIALPACKINGNAME")!=null)
					{
						materialPackingKey.setMaterialPackingName(PalletList.get(i).get("MATERIALPACKINGNAME").toString());
						materialPackingKey.setSiteName(siteName);
						bindMap.put("packingState","Completed");
						bindMap.put("stockState","StockOut");
						//bindMap.put("materialProcessGroupName",PalletList.get(i).get("MATERIALPROCESSGROUPNAME")==null?"":PalletList.get(i).get("MATERIALPROCESSGROUPNAME").toString());
						//bindMap.put("packingGrade",PalletList.get(i).get("PACKINGGRADE")==null?"":PalletList.get(i).get("PACKINGGRADE").toString());
						setEventInfo.setUserColumns(bindMap);
						MaterialPackingServiceProxy.getMaterialPackingService()
						.setEvent(materialPackingKey, eventInfo,
								setEventInfo);
					}
				}
				
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
					throw e;
				}

	}
	public void updataPalletStateByPC(EventInfo eventInfo,String siteName, String receiveActNo,String shipRequestName)
			throws Exception {
		try {
			String sql_query = " SELECT  DISTINCT SUPERMATERIALPACKINGNAME AS MATERIALPACKINGNAME,SUM(MATERIALQUANTITY) AS MATERIALQUANTITY "
					+ " FROM MATERIALPACKING BS"
					+ " WHERE "
					+ " BS.RECEIVEACTNO=:receiveActNo"
					+ " AND BS.SUPERMATERIALPACKINGNAME IS NOT NULL"
					+ " AND BS.SITENAME=:SITENAME"
					+ " AND SHIPREQUESTNAME=:SHIPREQUESTNAME "
					+ " GROUP BY SUPERMATERIALPACKINGNAME";
			String sql_insert = " UPDATE MATERIALPACKING SET MATERIALQUANTITY=MATERIALQUANTITY-:quantity  WHERE MATERIALPACKINGNAME=:materialpackingName ";
				Map<String, Object> bindMap_query = new HashMap<String, Object>();
				bindMap_query.put("SITENAME", siteName);
				bindMap_query.put("receiveActNo",
						receiveActNo);
				bindMap_query.put("SHIPREQUESTNAME", shipRequestName);
				List<Map<String, Object>> PalletList =IDMFrameServiceProxy.getSqlTemplate().queryForList(sql_query, bindMap_query);
				for(int i = 0; i < PalletList.size(); i++)
				{
					if(PalletList.get(i).get("MATERIALPACKINGNAME")!=null)
					{
						Map<String, Object> bindMap_insert = new HashMap<String, Object>();
						bindMap_insert.put("materialpackingName",PalletList.get(i).get("MATERIALPACKINGNAME").toString());
						bindMap_insert.put("quantity",PalletList.get(i).get("MATERIALQUANTITY").toString());
							IDMFrameServiceProxy.getSqlTemplate()
									
									.update(sql_insert, bindMap_insert);
					}
				}
				
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
					throw e;
				}

	}
	
	public void updataPalletStateByPC(EventInfo eventInfo,String siteName, String receiveActNo)
			throws Exception {
		try {
			String sql_query = " SELECT  DISTINCT SUPERMATERIALPACKINGNAME AS MATERIALPACKINGNAME,SUM(MATERIALQUANTITY) AS MATERIALQUANTITY "
					+ " FROM MATERIALPACKING BS"
					+ " WHERE "
					+ " BS.RECEIVEACTNO=:receiveActNo"
					+ " AND BS.SUPERMATERIALPACKINGNAME IS NOT NULL"
					+ " AND BS.SITENAME=:SITENAME"			
					+ " GROUP BY SUPERMATERIALPACKINGNAME";
			String sql_insert = " UPDATE MATERIALPACKING SET MATERIALQUANTITY=MATERIALQUANTITY-:quantity  WHERE MATERIALPACKINGNAME=:materialpackingName ";
				Map<String, Object> bindMap_query = new HashMap<String, Object>();
				bindMap_query.put("SITENAME", siteName);
				bindMap_query.put("receiveActNo",
						receiveActNo);
				//bindMap_query.put("SHIPREQUESTNAME", shipRequestName);
				List<Map<String, Object>> PalletList =IDMFrameServiceProxy.getSqlTemplate().queryForList(sql_query, bindMap_query);
				for(int i = 0; i < PalletList.size(); i++)
				{
					if(PalletList.get(i).get("MATERIALPACKINGNAME")!=null)
					{
						Map<String, Object> bindMap_insert = new HashMap<String, Object>();
						bindMap_insert.put("materialpackingName",PalletList.get(i).get("MATERIALPACKINGNAME").toString());
						bindMap_insert.put("quantity",PalletList.get(i).get("MATERIALQUANTITY").toString());
							IDMFrameServiceProxy.getSqlTemplate()
									
									.update(sql_insert, bindMap_insert);
					}
				}
				
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
					throw e;
				}

	}
	public void updataPalletQuantity(EventInfo eventInfo,String siteName, String materialpackingName,String quantity)
			throws Exception {
		try {
			if(!(materialpackingName==null||materialpackingName.equals("")))
			{
			String sql_insert = " UPDATE MATERIALPACKING SET MATERIALQUANTITY=MATERIALQUANTITY-:quantity  WHERE MATERIALPACKINGNAME=:materialpackingName ";
					
				Map<String, Object> bindMap_insert = new HashMap<String, Object>();
				bindMap_insert.put("materialpackingName",materialpackingName);
				bindMap_insert.put("quantity",quantity);
					IDMFrameServiceProxy.getSqlTemplate()
							
							.update(sql_insert, bindMap_insert);
			
		}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			throw e;
		}
	}
	// 在用
	public void makeUnStockInUsedInCancel(EventInfo eventInfo,
			List<MaterialUnDoinfo> newUnDoList, String UnDoID,
			List<String> siteNameList, List<String> unDoDetailNameList,
			String receiveActNo, String acttype) throws Exception {
		if (unDoDetailNameList.size() == 0) {
			throw new CustomException("PK-0001", "", "");
		}

		if (receiveActNo.equals("")) {
			throw new Exception("Failed to generate receiveActNo !");
		}
		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'";

			String sql_selUndoBoxInfo2 = " 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 LASTEVENTNAME<>'MToM' )"
					+ " union "
					+ "SELECT SITENAME,MATERIALPACKINGNAME "
					+ "FROM BS_MATERIALPACKINGUNDOINFO BS "
					+ "WHERE BS.UNDOID=:UNDOID AND "
					+ "BS.SITENAME=:sitename "
					+ "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>();
				List<SetEventInfo> setlist = new ArrayList<SetEventInfo>();
				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);
				if (queryResult_BoxInfo.size() > 0) 
				{
					if (!eventInfo.getReasonCodeType().equals("302")) 
					{
						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());
							materialPackingKeyList.add(keyInfo);
							MaterialPacking mp = MaterialPackingServiceProxy
									.getMaterialPackingService().selectByKey(
											keyInfo);
							String receiverequestname = "";
							String receiverequestdetail = "";
							if (acttype.equals("POOEM")) {
								receiverequestname = mp.getReceiveRequestName();
								receiverequestdetail = mp
										.getReceiveRequestDetailName()
										+ "_"
										+ mp.getMaterialSpecName();
							}
							// else if(acttype.equals("POOEM")){
							// receiverequestname = mp.getReceiveRequestName();
							// receiverequestdetail =
							// mp.getReceiveRequestDetailName()+"_"+mp.getMaterialSpecName();
							// }
							else {
								receiverequestname = mp.getReceiveRequestName();
								receiverequestdetail = mp
										.getReceiveRequestDetailName();
							}
							new MaterialReceiveRequestServiceImpl()
									.CreateMaterialReceiveRequestActUsedInCancel(
											eventInfo, siteNameList.get(i),
											receiverequestname,
											receiverequestdetail,
											mp.getMakeDate(), receiveActNo,
											acttype, mp.getMaterialQuantity());

							SetEventInfo setEventInfo = new SetEventInfo();
							Map<String, Object> bindMap = new HashMap<String, Object>();
							bindMap.put("packingState", "Created");
							bindMap.put("receiveActNo", receiveActNo);
							bindMap.put("unDoID", newUnDoList.get(i)
									.getUnDoID());
							bindMap.put("unDoDetailName", newUnDoList.get(i)
									.getUnDoDetailName());
							bindMap.put("stockState", "Created");
							bindMap.put("erpState","SUCCESS");
							bindMap.put("locationName", "");
							bindMap.put("oqaResult", "");
							bindMap.put("oqaResultState", "");
							setEventInfo.setUserColumns(bindMap);
							setlist.add(setEventInfo);
						}
						// List<MaterialPacking> mplist =
						// MaterialPackingServiceProxy.getMaterialPackingService().

						MaterialPackingServiceProxy.getMaterialPackingService()
								.setEvent(materialPackingKeyList, eventInfo,
										setlist);

					}
					//转储冲销
					else {
						String queryPreUndo = "SELECT SITENAME,ERPLOCATION,ERPFACTORY,STOCKINTYPE,PACKINGSTATE,RECEIVEACTNO FROM BS_MATERIALPACKINGUNDOINFO "
								+ "WHERE MATERIALPACKINGNAME=:MATERIALPACKINGNAME AND  UNDOID IN (SELECT PREUNDOID FROM BS_MATERIALPACKINGUNDOINFO WHERE MATERIALPACKINGNAME=:MATERIALPACKINGNAME AND SITENAME=:SITENAME AND UNDOID=:UNDOID)";
						Map<String, Object> bsMap = new HashMap<String, Object>();
						bsMap.put("MATERIALPACKINGNAME", queryResult_BoxInfo
								.get(0).get("MATERIALPACKINGNAME").toString());
						bsMap.put("SITENAME",
								queryResult_BoxInfo.get(0).get("SITENAME")
										.toString());
						bsMap.put("UNDOID", UnDoID);
						List<Map<String, Object>> preUndo_result = IDMFrameServiceProxy
								.getSqlTemplate().queryForList(queryPreUndo,
										bsMap);
						String oldSiteName = preUndo_result.size() > 0 ? preUndo_result
								.get(0).get("SITENAME").toString()
								: "";
						String updateSite = "UPDATE MATERIALPACKING SET SITENAME=:OLDSITENAME WHERE MATERIALPACKINGNAME=:MATERIALPACKINGNAME AND SITENAME=:SITENAME";
						String queryShip="SELECT RECEIVEREQUESTNAME,RECEIVEREQUESTDETAILNAME FROM BS_MATERIALPACKINGUNDOINFO WHERE MATERIALPACKINGNAME=:MATERIALPACKINGNAME AND SITENAME=:SITENAME AND UNDOID=:UNDOID";
						List<Map<String,Object>> shipResult=IDMFrameServiceProxy.getSqlTemplate().queryForList(queryShip, bsMap);
						if(shipResult.size()>0)
						{
							//将shipreques的状态还原为confirm
							MaterialShipRequestKey keyInfo=new MaterialShipRequestKey(oldSiteName, shipResult.get(0).get("RECEIVEREQUESTNAME").toString());
							MaterialShipRequestSetEventInfo setEventInfo= new MaterialShipRequestSetEventInfo();
							Map<String, Object> bindMap = new HashMap<String, Object>();
							bindMap.put("shipRequestState", "Confirmed");
							setEventInfo.setUserColumns(bindMap);
							MaterialShipRequestServiceProxy.getMaterialShipRequestService().setEvent(keyInfo, eventInfo, setEventInfo);
						}
						for (int j = 0; j < queryResult_BoxInfo.size(); j++) {
							// 先把box的sitename更新到上一状态
							Map<String, Object> updateMap = new HashMap<String, Object>();
							updateMap.put("SITENAME", queryResult_BoxInfo
									.get(j).get("SITENAME").toString());
							updateMap.put(
									"MATERIALPACKINGNAME",
									queryResult_BoxInfo.get(j)
											.get("MATERIALPACKINGNAME")
											.toString());
							updateMap.put("OLDSITENAME", oldSiteName);
							IDMFrameServiceProxy.getSqlTemplate()
									
									.update(updateSite, updateMap);
							MaterialPackingKey mpKey = new MaterialPackingKey();
							mpKey.setSiteName(oldSiteName);
							mpKey.setMaterialPackingName(queryResult_BoxInfo
									.get(j).get("MATERIALPACKINGNAME")
									.toString());
							materialPackingKeyList.add(mpKey);
						}
						SetEventInfo setEventInfo = new SetEventInfo();
						Map<String, Object> newMap = new HashMap<String, Object>();
						newMap.put(
								"erpLocation",
								preUndo_result.size() > 0 ? preUndo_result
										.get(0).get("ERPLOCATION").toString()
										: "");
						newMap.put(
								"erpFactory",
								preUndo_result.size() > 0 ? preUndo_result
										.get(0).get("ERPFACTORY").toString()
										: "");
						newMap.put(
								"stockInType",
								preUndo_result.size() > 0 ? preUndo_result
										.get(0).get("STOCKINTYPE").toString()
										: "");
						//转储将原shiprequestname存入receiverequestname，shiprequestdetailname存入receiverequestdetailname中
						newMap.put("shipRequestName", shipResult.size()>0?shipResult.get(0).get("RECEIVEREQUESTNAME").toString():"");
						newMap.put("shipRequestDetailName", shipResult.size()>0?shipResult.get(0).get("RECEIVEREQUESTDETAILNAME").toString():"");
						newMap.put(
								"receiveActNo",
								preUndo_result.size() > 0 ? preUndo_result
										.get(0).get("RECEIVEACTNO").toString()
										: "");
						newMap.put(
								"packingState",
								preUndo_result.size() > 0 ? preUndo_result
										.get(0).get("PACKINGSTATE").toString()
										: "");
						newMap.put("unDoID", newUnDoList.get(i).getUnDoID());
						newMap.put("unDoDetailName", newUnDoList.get(i)
								.getUnDoDetailName());
						setEventInfo.setUserColumns(newMap);
						setlist.add(setEventInfo);
						MaterialPackingServiceProxy.getMaterialPackingService()
								.setEvent(materialPackingKeyList, eventInfo,
										setlist);
					}
				}
			}
			// Map<String, Object> bindMap_selUndoBoxInfo = new HashMap<String,
			// Object>();
			// bindMap_selUndoBoxInfo.put("UNDOID", UnDoID);
			// bindMap_selUndoBoxInfo.put("sitename", siteNameList.get(0));
			// //bindMap_UndoBoxInfo.put("REQUESTDETAILNAME",requestDetailName);
			// List<Map<String, Object>> queryResult_BoxInfo2 =
			// IDMFrameServiceProxy.getSqlTemplate().queryForList(sql_selUndoBoxInfo2,
			// bindMap_selUndoBoxInfo);
			// if(queryResult_BoxInfo2.size()>0){
			String sql_UndoBoxInfo = " UPDATE BS_MATERIALPACKINGUNDOINFO SET UNDOIDSTATE='N' WHERE MATERIALPACKINGNAME IN (SELECT MATERIALPACKINGNAME"
					+ " FROM BS_MATERIALPACKINGUNDOINFO BS"
					+ " WHERE BS.UNDOID=:UNDOID AND("
					+ " ("
					+ " BS.UNDODETAILNAME=:UNDODETAILNAME"
					+ " AND BS.SITENAME=:SITENAME"
					+ " )"
					+ " OR"
					+ " ( "
					+ " BS.UNDODETAILNAME=:UNDODETAILNAME"
					+ " AND BS.SITENAME=:SITENAME))"
					+ " AND UNDOIDSTATE<>'N'"
					+ " AND LASTEVENTNAME<>'MToM')";
			String sql_insert = new MaterialPackingStockInImpl().insertUnDOMaterialPackingInfo_v2;
			// 将原有UNDOINFO重置状态为N
			for (int i = 0; i < unDoDetailNameList.size(); i++) {
				Map<String, Object> bindMap_UndoBoxInfo = new HashMap<String, Object>();
				bindMap_UndoBoxInfo.put("SITENAME", siteNameList.get(i));
				bindMap_UndoBoxInfo.put("UNDOID", UnDoID);
				bindMap_UndoBoxInfo.put("UNDODETAILNAME",
						unDoDetailNameList.get(i));
				IDMFrameServiceProxy.getSqlTemplate()
						.update(sql_UndoBoxInfo, bindMap_UndoBoxInfo);
			}
			// 存储新的UNDOINFO
			for (int i = 0; i < newUnDoList.size(); i++) {
				Map<String, Object> bindMap_insert = new HashMap<String, Object>();
				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());
				try {
					IDMFrameServiceProxy.getSqlTemplate()
							
							.update(sql_insert, bindMap_insert);
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
					throw e;
				}
			}
			//是否包含内向交货单信息，存在则清空已接收数量
			String queryInner="SELECT DISTINCT INNERREQUESTNAME,INNERREQUESTDETAILNAME FROM MATERIALRECEIVEACTDETAIL WHERE RECEIVEACTNO=:RECEIVEACTNO ";
			Map<String,Object> innerMap=new HashMap<String, Object>();
			String[] a=receiveActNo.split("\\+");
			innerMap.put("RECEIVEACTNO", receiveActNo.split("\\+")[0]);
			List<Map<String,Object>> innerResult=IDMFrameServiceProxy.getSqlTemplate().queryForList(queryInner, innerMap);
			if(innerResult != null && innerResult.get(0).get("INNERREQUESTNAME")!=null)
			{
				for(int i=0;i<innerResult.size();i++)
				{
					//内向交货单已接收数量置为0
					String updateInner="UPDATE INNERREQUESTDETAIL SET RECEIVEDQUANTITY=0 WHERE INNERREQUESTNAME=:INNERREQUESTNAME AND INNERREQUESTDETAILNAME=:INNERREQUESTDETAILNAME ";
					Map<String,Object> updateMap=new HashMap<String, Object>();
					updateMap.put("INNERREQUESTNAME",innerResult.get(i).get("INNERREQUESTNAME"));
					updateMap.put("INNERREQUESTDETAILNAME",innerResult.get(i).get("INNERREQUESTDETAILNAME"));
					IDMFrameServiceProxy.getSqlTemplate().update(updateInner, updateMap);					
				}
				//清空原有抬头中绑定的内向交货单号
				String updateAct="UPDATE MATERIALRECEIVEACT SET INNERREQUESTNAME='' WHERE  RECEIVEACTNO=:RECEIVEACTNO";
				IDMFrameServiceProxy.getSqlTemplate().update(updateAct, innerMap);
			}
						
		} catch (IDMFrameDBErrorSignal ex) {
			throw ex;
		} catch (NotFoundSignal ex) {
			throw ex;
		}
	}

	public String GetMessageID(String sitename){
		String messageid = "";
		
		List<String> args = new ArrayList<String>();
		args.add("MID");
		if(sitename.equals("B10"))
			sitename ="BA";
		else if(sitename.equals("B11"))
			sitename ="BB";
		else if(sitename.equals("BMDT"))
			sitename ="BM";
		else if(sitename.equals("BMOT"))
			sitename ="BO";
		else if(sitename.equals("B17"))
			sitename ="BN";
		else if ("B12".equals(sitename)) {
			sitename ="BC";
		}else if ("B20".equals(sitename)) {
			sitename ="BJ";
		}
		args.add(sitename);
		messageid = NameServiceProxy.getNameRuleDefService()
				.generateName("MessageID", args, 1).get(0);
		
		return messageid;
	}
	
	public void SaveMessageIDToMaterialPackingUsedByUnDO(String unDoID,List<String> unDoDetailNameList,EventInfo eventInfo,String sitename,String messageid)throws Exception{
		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'";
		try {
			String eventComment=eventInfo.getEventComment();
			String eventName =eventInfo.getEventName();
			for (int i = 0; i < unDoDetailNameList.size(); i++) {
				List<MaterialPackingKey> materialPackingKeyList = new ArrayList<MaterialPackingKey>();
				List<SetEventInfo> setlist = new ArrayList<SetEventInfo>();
				Map<String, Object> bindMap_selUndoBoxInfo = new HashMap<String, Object>();
				bindMap_selUndoBoxInfo.put("sitename", sitename);
				bindMap_selUndoBoxInfo.put("UNDOID", unDoID);
				bindMap_selUndoBoxInfo.put("undodetailname",
						unDoDetailNameList.get(i));
				// bindMap_UndoBoxInfo.put("REQUESTDETAILNAME",requestDetailName);
				List<Map<String, Object>> queryResult_BoxInfo = IDMFrameServiceProxy
						.getSqlTemplate()
						
						.queryForList(sql_selUndoBoxInfo,
								bindMap_selUndoBoxInfo);
				if (queryResult_BoxInfo.size() > 0) 
				{
					
						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());
							materialPackingKeyList.add(keyInfo);
							
							//setlist.add(setEventInfo);
						}
						SetEventInfo setEventInfo = new SetEventInfo();
						Map<String, Object> bindMap = new HashMap<String, Object>();
						bindMap.put(MaterialPacking.Field.messageID,messageid);
						bindMap.put("erpState","ERPSUCCESS");
						setEventInfo.setUserColumns(bindMap);
						eventInfo.setEventComment("SaveMessageID");
						eventInfo.setEventName("SaveMessageID");
						// List<MaterialPacking> mplist =
						// MaterialPackingServiceProxy.getMaterialPackingService().

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

					}
				eventInfo.setEventName(eventName);
				eventInfo.setEventComment(eventComment);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw e;
		}
	}
	

	
	public List<MaterialPackingFromTQMS> getInformationList(String information) throws Exception
	{
		List<MaterialPackingFromTQMS> informationList=new ArrayList<MaterialPackingFromTQMS>();
		if(information!="")
		{
			try
			{
				ObjectMapper mapper=new ObjectMapper();
				informationList=mapper.readValue(information, new TypeReference<List<MaterialPackingFromTQMS>>() {});	
			}
			catch(Exception e)
			{
				e.getMessage();
				throw e;
			}
		}
		return informationList;
			
	}
	
	
	public String GetOqaFlag(List<MaterialPackingFromTQMS> informationList) throws Exception
	{				
		
		String oqaFlag="";
		try
		{
			for(MaterialPackingFromTQMS mp : informationList)
			{
				if(mp.getOqaFlag().equals("1"))
				{
					oqaFlag="1";
					break;				
				}
				if(mp.getOqaFlag().equals("2"))
				{
					oqaFlag="2";
					break;				
				}
			}
		}catch (Exception e)
		{
			e.getMessage();
			throw e;
		}
		return oqaFlag;
	}

	public String GetSiteName(List<MaterialPackingFromTQMS> informationList) throws Exception
	{		
		try
		{
			return informationList.get(0).getSiteName().toString();
		}catch(Exception e)
		{
			e.getMessage();
			throw e;
		}
	}
	
public List<MaterialPacking> GetOQAList(List<MaterialPackingFromTQMS> informationList,EventInfo eventInfo,String oqaFlag) throws Exception
	{		
		List<MaterialPacking> resultList=new ArrayList<MaterialPacking>();		
		MaterialPackingServiceImpl serviceImpl=new MaterialPackingServiceImpl();		
		if(informationList.size()>0)
		{						
			for(MaterialPackingFromTQMS mt:informationList)
			{
				if(mt.getProcessState().isEmpty())
				{
					BigDecimal okCou=new BigDecimal(Double.toString(mt.getBoxQunlityAmount()));
					BigDecimal ngCou=new BigDecimal(Double.toString(mt.getBoxUnQunlityAmount()));
					double count=okCou.add(ngCou).doubleValue();
					if(mt.getMaterialQuantity()!=count)
					{															
						throw new CustomException("BOX{0}OK数量加NG数量与当前BOX数量不符！",mt.getMaterialPackingName());								
					}						
					MaterialPacking mp=new MaterialPacking();
					MaterialPackingKey mpk=new MaterialPackingKey();
					//根据主键查询出原BOX信息 
					mpk.setSiteName(mt.getSiteName());
					mpk.setMaterialPackingName(mt.getMaterialPackingName());
					mp.setKey(mpk);						
					MaterialPacking materialPackingData = MaterialPackingServiceProxy
						.getMaterialPackingService()
						.selectByKey(mpk);
					//质检时判断当前BOX是否已存在质检结果
					if(materialPackingData!=null)
					{
						if(!materialPackingData.getOqaResult().isEmpty()&&oqaFlag.equals("1") && materialPackingData.getErpState().equalsIgnoreCase("SUCCESS"))
							throw new CustomException("BOX{0}当前已存在质检结果,请选择改判或其他操作！",mt.getMaterialPackingName());
						
					}else
						throw new CustomException("BOX{0}信息在WMS系统中不存在！",mt.getMaterialPackingName());						
					//存在两种质检状态，需要做拆分处理
					try
					{
						if(mt.getBoxQunlityAmount() !=0&&mt.getBoxUnQunlityAmount()!=0&&mt.getOqaMethod().isEmpty())
						{	
                         if(!materialPackingData.getStockState().equalsIgnoreCase("Stocked")||materialPackingData.getEtcState().equalsIgnoreCase("EtcOut"))
							throw new CustomException("BOX{0}当前为非在库状态！",mt.getMaterialPackingName());
							int index=mt.getMaterialPackingName().indexOf("+");							
								//将当前BOX拆分为两个新的BOX
								for(int i=1;i<3;i++)
								{									
									//生成新的主键
									MaterialPackingKey mpkNew=new MaterialPackingKey();
									mpkNew.setSiteName(mt.getSiteName());		
									//BOX已拆分
									if(index>-1)
									{
										String sql="SELECT MAX(MATERIALPACKINGNAME) AS MATERIALPACKINGNAME FROM MATERIALPACKING WHERE MATERIALPACKINGNAME LIKE :MATERIALPACKINGNAME ";
										Map<String ,Object> map=new HashMap<String, Object>();
										map.put("MATERIALPACKINGNAME",mt.getMaterialPackingName().substring(0, index+1)+"%");
										List<Map<String, Object>> maxBoxID=IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, map);
										int suffix=Integer.parseInt(maxBoxID.get(0).get("MATERIALPACKINGNAME").toString().substring(index+1))+1;
										String suf=String.valueOf(suffix);
										if(suf.length()==1)
											mpkNew.setMaterialPackingName(mt.getMaterialPackingName().substring(0, index+1)+"00"+suf);
										else if(suf.length()==2)
											mpkNew.setMaterialPackingName(mt.getMaterialPackingName().substring(0, index+1)+"0"+suf);
										else if(suf.length()==3)
											mpkNew.setMaterialPackingName(mt.getMaterialPackingName().substring(0, index+1)+suf);
										else 
											throw new CustomException("BOX不可再拆分");
									}else
									{
										mpkNew.setMaterialPackingName(mt.getMaterialPackingName()+"+00"+i);	
									}
									materialPackingData.setKey(mpkNew);	
									//将拆分前的BOX信息赋值到新的BOX
									CreateInfo createInfo = new CreateInfo();
									createInfo.setSiteName(mpkNew.getSiteName());
									createInfo.setMaterialPackingName(mpkNew.getMaterialPackingName());
									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("SubPackingQuantity",
											materialPackingData.getSubPackingQuantity());
									bindMap.put("MaterialCreateQuantity",
											materialPackingData.getMaterialCreateQuantity());
									//第一遍BOX保存OK数量，第二遍保存NG数量																		
									if(i==1)
									{
										bindMap.put("MaterialQuantity", mt.getBoxQunlityAmount());// 数量		
										bindMap.put("PackingGrade", "OK");
										bindMap.put("oqaResult", "OK");																				
									}else
									{
										bindMap.put("MaterialQuantity", mt.getBoxUnQunlityAmount());// 数量
										bindMap.put("PackingGrade", "NG");
										bindMap.put("oqaResult", "NG");
									}
									bindMap.put("oqaResultState","END");
									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",
											mt.getMaterialProcessGroupName());									
									bindMap.put("CreateTime", materialPackingData.getCreateTime());
									bindMap.put("CreateUser", materialPackingData.getCreateUser());
									bindMap.put("ReceiveRequestName",
											materialPackingData.getReceiveRequestName());
									bindMap.put("ReceiveRequestDetailName",
											materialPackingData.getReceiveRequestDetailName());									
									bindMap.put("MakeDate", materialPackingData.getMakeDate());
									bindMap.put("expiringDate", materialPackingData.getExpiringDate());
									bindMap.put("ReceiveActNo", materialPackingData.getReceiveActNo());									
									bindMap.put("ReceiveTime", materialPackingData.getReceiveTime());
									bindMap.put("ReceiveUser", materialPackingData.getReceiveUser());
									bindMap.put("ShipRequestName",
											materialPackingData.getShipRequestName());
									bindMap.put("ShipRequestDetailName",
											materialPackingData.getShipRequestDetailName());
									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("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());
									//TQMS新增字段
									bindMap.put("oqaMethod", mt.getOqaMethod());
									bindMap.put("remark", mt.getRemark());
									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[] { mt.getSiteName(), mt.getMaterialPackingName(),
											mpkNew.getMaterialPackingName(),
											TimeStampUtil.getCurrentEventTimeKey().toString(), "Split",
											materialPackingData.getPackingGrade(),
											TimeStampUtil.getCurrentTimestamp(), "TQMS",
											mt.getMaterialQuantity(),
											i==1?mt.getBoxQunlityAmount():mt.getBoxUnQunlityAmount()};

									IDMFrameServiceProxy.getSqlTemplate().update(strCondition, bind);																																				
									//保存新生成box，后续与ERP过账
									MaterialPacking mk=MaterialPackingServiceProxy.getMaterialPackingService().selectByKey(mpkNew);
									//改判操作时，当前状态未变动的不需要发送给ERP，只需要做拆分操作
									if(oqaFlag.equals("2"))		
									{
										if((i==1&&mt.getOqaResult().equalsIgnoreCase("OK"))||(i==2&&mt.getOqaResult().equalsIgnoreCase("NG")))
											continue;
									}																		
									resultList.add(mk);
									
								}
								//将拆分前BOX置为空
								MaterialPackingServiceImpl impl=new MaterialPackingServiceImpl();
								impl.ModifyMaterialPackingState(eventInfo,mt.getSiteName(),mt.getMaterialPackingName(),"Empty");
						}
						else
						{
							//根据主键选择BOX，保存BOX的质检状态和新增字段值
							mpk.setMaterialPackingName(mt.getMaterialPackingName());
							mpk.setSiteName(mt.getSiteName());							
							mp=MaterialPackingServiceProxy.getMaterialPackingService().selectByKey(mpk);
							//TQMS生成的质检批
							mp.setMaterialProcessGroupName(mt.getMaterialProcessGroupName());												
							//MRB标记视为OK状态
							if(!mt.getOqaMethod().isEmpty())
							{
								mp.setOqaMethod(mt.getOqaMethod());
								mp.setOqaResult("OK");
								mp.setPackingGrade("OK");
							}else
							{
								if(mt.getBoxQunlityAmount()!=0)	
								{
									mp.setOqaResult("OK");
								    mp.setPackingGrade("OK");
								}
									
								else if(mt.getBoxUnQunlityAmount()!=0)
								{
									mp.setOqaResult("NG");
								    mp.setPackingGrade("NG");
								}																	
								else
								{
									mp.setOqaResult("OK");
								    mp.setPackingGrade("OK");
								}
							}
							mp.setRemark(mt.getRemark());					
							MaterialPackingServiceProxy.getMaterialPackingService().update(mp);										
							resultList.add(mp);
						}
					}catch(Exception e)
					{
						//需要在BS_ERRORDEFINITION表中注册错误类型，errorcode自定义，kkk只用于测试
						throw new CustomException("kkk","BOX已拆分或拆分处理异常！");
					}
				}
				//processState不为空，示意为HOLD/RELEASE操作
				else
				{
					try
					{
						EventInfo event = new EventInfo();
						MaterialPackingKey key=new MaterialPackingKey();
						key.setMaterialPackingName(mt.getSiteName());
						key.setSiteName(mt.getSiteName());
						if(mt.getProcessState().equalsIgnoreCase("Holding"))
							eventInfo.setEventName("HoldBox");
						else
							eventInfo.setEventName("ReleaseBox");
						
						serviceImpl.hold(eventInfo, mt.getSiteName(), mt.getMaterialPackingName(), mt.getProcessState().equalsIgnoreCase("Holding")?"Y":"N", mt.getReasonCode(),"tqms");
					}catch(Exception e)
					{
						//需要在BS_ERRORDEFINITION表中注册错误类型，errorcode自定义，jjj只用于测试
						throw new CustomException("jjj","BOX拆分处理异常！");
					}
				}					
			}	
			
		}			
		return resultList;
	}
	public List<Map<String,Object>> getRTStockinList(String siteName,String shipRequestName) throws Exception{
		try
		{
			
			String queryShipDetail="SELECT MD.SHIPREQUESTDETAILNAME,MD.MATERIALSPECNAME,MD.REQUESTQUANTITY,MD.ASSIGNEDQUANTITY,MD.ERPLOCATION,MD.ERPFACTORYNAME,MD.CHARGE,MD.ERPRECEIVELOCATION,MD.WORKORDER,MD.WORKORDERTYPE,MD.RETURNTYPE,MD.LINE,MD.REMARK,MD.REASONCODETYPE,MD.REASONCODE,MD.RETURNTYPEDESC"
				+" FROM MATERIALSHIPREQUESTDETAIL MD"
				+" WHERE SITENAME=:SITENAME AND SHIPREQUESTNAME=:SHIPREQUESTNAME"
				+" ORDER BY SHIPREQUESTNAME";
			if(siteName.equals("B5"))
			{
				 queryShipDetail="SELECT MD.SHIPREQUESTDETAILNAME,MD.MATERIALSPECNAME,MD.REQUESTQUANTITY,MD.ASSIGNEDQUANTITY,MD.ERPLOCATION,MD.ERPFACTORYNAME,A.CHARGE,MD.ERPRECEIVELOCATION,MD.WORKORDER,MD.WORKORDERTYPE,MD.RETURNTYPE,MD.LINE,MD.REMARK,MD.REASONCODETYPE,MD.REASONCODE,MD.RETURNTYPEDESC"
							+" FROM MATERIALSHIPREQUESTDETAIL MD"
							+" LEFT JOIN MATERIALPACKING A ON A.RECEIVEREQUESTNAME=MD.SHIPREQUESTNAME AND A.RECEIVEREQUESTDETAILNAME=MD.SHIPREQUESTDETAILNAME"
							+" WHERE MD.SITENAME=:SITENAME AND MD.SHIPREQUESTNAME=:SHIPREQUESTNAME"
							+" AND A.PACKINGSTATE='Created' "
							+" ORDER BY MD.SHIPREQUESTNAME";
			}
				Map<String,Object> shipMap=new HashMap<String, Object>();
				shipMap.put("SITENAME", siteName);
				shipMap.put("SHIPREQUESTNAME", shipRequestName);
			
				return IDMFrameServiceProxy.getSqlTemplate().queryForList(queryShipDetail, shipMap);
				
					
		}catch(Exception e)
		{
			e.printStackTrace();
			throw e;
		}
	}
	public List<Map<String,Object>> getERPRefundList(String siteName,String shipRequestName) throws Exception{
		try
		{
			String queryShipDetail="SELECT MD.SHIPREQUESTDETAILNAME,MD.MATERIALSPECNAME,MD.REQUESTQUANTITY,MD.ASSIGNEDQUANTITY,MD.ERPLOCATION,MD.ERPFACTORYNAME,MD.CHARGE,MD.ERPRECEIVELOCATION,MD.WORKORDER,MD.WORKORDERTYPE,MD.RETURNTYPE,MD.LINE,MD.REMARK,MD.REASONCODETYPE,MD.REASONCODE,MD.RETURNTYPEDESC"
				+" FROM MATERIALSHIPREQUESTDETAIL MD"
				+" WHERE SITENAME=:SITENAME AND SHIPREQUESTNAME=:SHIPREQUESTNAME"
				+" ORDER BY SHIPREQUESTNAME";
				Map<String,Object> shipMap=new HashMap<String, Object>();
				shipMap.put("SITENAME", siteName);
				shipMap.put("SHIPREQUESTNAME", shipRequestName);
			
				return IDMFrameServiceProxy.getSqlTemplate().queryForList(queryShipDetail, shipMap);
				
					
		}catch(Exception e)
		{
			e.printStackTrace();
			throw e;
		}
	}
	public void checkAssignedQuantity(String siteName,String shipRequestName) throws CustomException
	{
		try
		{
			String sql="SELECT MD.SHIPREQUESTDETAILNAME,MD.MATERIALSPECNAME,MD.REQUESTQUANTITY,MD.ASSIGNEDQUANTITY,MD.ERPLOCATION,MD.ERPFACTORYNAME,MD.CHARGE,MD.ERPRECEIVELOCATION,MD.WORKORDER,MD.WORKORDERTYPE,MD.RETURNTYPE,MD.LINE,MD.REMARK,MD.REASONCODETYPE,MD.REASONCODE,MD.RETURNTYPEDESC"
					+" FROM MATERIALSHIPREQUESTDETAIL MD"
					+" WHERE SITENAME=:SITENAME AND SHIPREQUESTNAME=:SHIPREQUESTNAME"
					+" ORDER BY SHIPREQUESTNAME";
			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("REQUESTQUANTITY")))
					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 saveRTStockinInfo(List<Map<String,Object>> stockinList,List<MaterialUnDoinfo> undoList,String siteName,EventInfo eventInfo,String shipRequestName) throws ParseException
	{		
		List<SetEventInfo> eventlist = new ArrayList<SetEventInfo>();
		String receiveActNO="";
		CommonValidation cv = new CommonValidation();
		for (int i = 0; i < stockinList.size(); i++) 
		{
			List<MaterialPackingKey> mpklist = new ArrayList<MaterialPackingKey>();
			MaterialUnDoinfo undo = null;		
			String condition=" WHERE SITENAME= ? AND RECEIVEREQUESTNAME = ? AND RECEIVEREQUESTDETAILNAME = ?";					
			Object[] bind={siteName , shipRequestName , stockinList.get(i).get("SHIPREQUESTDETAILNAME").toString()};
			List<MaterialPacking> mpList=MaterialPackingServiceProxy.getMaterialPackingService().select(condition, bind);
			String sql_insertUndoInfo =new MaterialPackingServiceImpl().insertUnDOMaterialPackingInfo_v3
					+ "select P.SITENAME,P.MATERIALPACKINGNAME,P.LASTEVENTTIMEKEY FROM MATERIALPACKING P WHERE P.UNDODETAILNAME=:unDoDetailName AND P.UNDOID=:unDoID )";
			for (int j = 0; j < undoList.size(); j++) {
				String a = undoList.get(j).getSeq();
				String b = mpList.get(0).getMessageId()+ Integer.toString(i + 1);
				if (a.equals(b)) {
					undo = undoList.get(j);
					break;
				}
			}
			SetEventInfo setevent = new SetEventInfo();
			Map<String, Object> bindMap = new HashMap<String, Object>();
			bindMap.put("packingState", "Released");
			bindMap.put("stockState", "Stocked");
			bindMap.put("oqaResult", "OK");
			bindMap.put("packingGrade", "OK");
			bindMap.put("materialProcessGroupName", "");
			bindMap.put("oqaResultState",GenericServiceProxy.getConstantMap().OQA_State_End);			
			bindMap.put("charge", stockinList.get(i).get("CHARGE")!=null ? stockinList.get(i).get("CHARGE").toString():"");
			//正品/财损修正库位
			//bindMap.put("erpLocation", stockinList.get(i).get("ERPRECEIVELOCATION")!=null ? stockinList.get(i).get("ERPRECEIVELOCATION").toString():"");
			bindMap.put("unDoID", undo.getUnDoID());
			bindMap.put("unDoDetailName", undo.getUnDoDetailName());			
			bindMap.put("stockInType","Refund");
			Date date = new Date();
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String receivedate = df.format(date);
			bindMap.put("receiveTime",Timestamp.valueOf(receivedate));
			bindMap.put("erpEventTime",Timestamp.valueOf(receivedate));
			bindMap.put("receiveUser", eventInfo.getEventUser());
			bindMap.put("erpState", "SUCCESS");
			setevent.setUserColumns(bindMap);
			eventlist.add(setevent);
			eventInfo.setReasonCode(mpList.get(0).getReasonCode());
			eventInfo.setReasonCodeType(mpList.get(0).getReasonCodeType());
			eventInfo.setEventName("MESStockIn");
			eventInfo.setEventComment("MESStockIn");
			for(MaterialPacking box : mpList)
			{
				mpklist.add(box.getKey());
			}
			MaterialPackingServiceProxy.getMaterialPackingService()
					.setEvent(mpklist, eventInfo, setevent);		
			bindMap.put("UNDOIDDATE", undo.getUnDoIdDate());
			bindMap.put("LASTEVENTNAME", eventInfo.getEventName());
			bindMap.put("LASTEVENTUSER", eventInfo.getEventUser());
			bindMap.put("LASTEVENTCOMMENT", eventInfo.getEventComment());
			setevent.setUserColumns(bindMap);
			int count=IDMFrameServiceProxy.getSqlTemplate()
					.update(sql_insertUndoInfo, bindMap);
			receiveActNO=mpList.get(0).getReceiveActNo();	
		}
		//更新抬头文本状态
		MaterialReceiveActKey mrk = new MaterialReceiveActKey();
		String sql =" SELECT RECEIVEREQUESTNAME FROM MATERIALRECEIVEACT WHERE SITENAME =:SITENAME AND RECEIVEACTNO =:RECEIVEACTNO ";
		Map<String, Object> bindMap1 = new HashMap<String, Object>();
		bindMap1.put("SITENAME", siteName);
		bindMap1.put("RECEIVEACTNO", receiveActNO);
		List<Map<String, Object>> queryResult = IDMFrameServiceProxy
				.getSqlTemplate()
				.queryForList(sql, bindMap1);
		MaterialReceiveActKey actKey=new MaterialReceiveActKey();
		actKey.setSiteName(siteName);
		actKey.setReceiveactNO(receiveActNO);
		actKey.setReceiveRequestName(shipRequestName);
		MaterialReceiveAct act=  MaterialReceiveRequestActServiceProxy.getReceiveRequestBatchService().selectByKey(actKey);
		act.setReceiveActState("Received");
		MaterialReceiveRequestActServiceProxy.getReceiveRequestBatchService().update(act);	
		
	}
	public void updateRTStockinShipInfo(List<Map<String,Object>> stockinList,String siteName,String shipRequestName)
	{
		
		for (int i = 0; i < stockinList.size(); i++) 
		{
			//更新shipdetail单据状态
			MaterialShipRequestDetailKey key=new MaterialShipRequestDetailKey();
			key.setSiteName(siteName);
			key.setShipRequestName(shipRequestName);
			key.setShipRequestDetailName(stockinList.get(i).get("SHIPREQUESTDETAILNAME").toString());
			MakeShipDetailIncreaseAssignedInfo info=new MakeShipDetailIncreaseAssignedInfo();
			info.setAssignedQuantity(Double.parseDouble(stockinList.get(i).get("REQUESTQUANTITY").toString()));
			MaterialShipRequestDetailServiceProxy.getMaterialShipRequestDetailService().increaseAssignedQuantity(key, info);
		
		}
		//更新单据
		MaterialShipRequestKey key = new MaterialShipRequestKey();
		key.setSiteName(siteName);
		key.setShipRequestName(shipRequestName);
		MaterialShipRequest mp = MaterialShipRequestServiceProxy.getMaterialShipRequestService().selectByKey(key);
		mp.setShipRequestState("Completed");
		String eventTime=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
		mp.setLastEventTime(Timestamp.valueOf(eventTime));
		MaterialShipRequestServiceProxy.getMaterialShipRequestService().update(mp);
	}
	//PC端创建box在绑定抬头文本的时候会更新AssignedQuantity，所以过账之后不再需要增加
	public void updateRTStockinShipInfoForPC(String siteName,String shipRequestName)
	{
		
		//更新单据
		MaterialShipRequestKey key = new MaterialShipRequestKey();
		key.setSiteName(siteName);
		key.setShipRequestName(shipRequestName);
		MaterialShipRequest mp = MaterialShipRequestServiceProxy.getMaterialShipRequestService().selectByKey(key);
		mp.setShipRequestState("Completed");
		String eventTime=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
		mp.setLastEventTime(Timestamp.valueOf(eventTime));
		MaterialShipRequestServiceProxy.getMaterialShipRequestService().update(mp);
	}
	
	public List<MaterialStockInClass> GetPCBAStockInList(String receiveActNo,String receiveRequestName,String siteName,String erpFactory,String remark) throws Exception {

		List<MaterialStockInClass> mplist = new ArrayList<MaterialStockInClass>();
		
	
		String sql="select rownum as seq,RECEIVEREQUESTDETAILNAME,materialspecname as MATNR,erplocation as UMLGO,materialquantity as MENGE from  "
				+ "         (select M.MATERIALSPECNAME,M.RECEIVEREQUESTDETAILNAME,M.ERPLOCATION,sum(materialquantity)materialquantity  "
				+ "         from materialpacking m  "
				+ "         where M.RECEIVEREQUESTNAME=:RECEIVEREQUESTNAME  "
				+ "          and M.RECEIVEACTNO=:RECEIVEACTNO  "
				+ "          AND M.RECEIVEREQUESTDETAILNAME IN  "
				+ "           (SELECT RECEIVEREQUESTDETAILNAME FROM MATERIALRECEIVEREQUESTDETAIL  "
				+ "              WHERE requestquantity = RECEIVEDQUANTITY "
				+ "              AND RECEIVEREQUESTNAME=:RECEIVEREQUESTNAME "
				+ "              AND SITENAME=:SITENAME) "
				+ "          group by materialspecname,erplocation,RECEIVEREQUESTDETAILNAME order by materialspecname) ";   //修改SQL，增加行项目号条件，按照整行项目过账
		
		Map<String, Object> bindMap1 = new HashMap<String, Object>();
		bindMap1.put("RECEIVEREQUESTNAME", receiveRequestName);
		bindMap1.put("RECEIVEACTNO", receiveActNo);
		bindMap1.put("SITENAME", siteName);
		List<Map<String, Object>> sqlResult = IDMFrameServiceProxy
				.getSqlTemplate()
				.queryForList(sql, bindMap1);
		
		int seqno = 1;
		try {
			if (sqlResult.size()>0) {
				for (int i=0;i<sqlResult.size();i++) {
					
					String materialSpecName =sqlResult.get(i).get("MATNR").toString();
					String materialquantity =sqlResult.get(i).get("MENGE").toString();
					String erpLocation =sqlResult.get(i).get("UMLGO").toString();
					String receiveRequestDetailName =sqlResult.get(i).get("RECEIVEREQUESTDETAILNAME").toString();//修改原detailname取seq为实际detailname
					String charge="";

					MaterialStockInClass msc = new MaterialStockInClass();
					msc.setCharge(charge);
					msc.setErpfactory(erpFactory);
					msc.setErplocation(erpLocation);
					msc.setMaterialSpecName(materialSpecName);
					msc.setReceiveActNo(receiveActNo);
					msc.setReceiveQuantity(materialquantity);
					msc.setReceiveRequestName(receiveRequestName);
					msc.setSeqno(seqno++);
					msc.setSiteName(siteName);
					msc.setReceiveRequestDetailName(receiveRequestDetailName);
					msc.setRemark(remark);
					
					

					mplist.add(msc);
				}
			}

		} catch (Exception e) {
			e.getMessage();
			throw e;
		}
		return mplist;
	}
	

			
//PCBA 322收货到质检&919收到非限制
public boolean SaveRefundStockInListForPCBAReceive(List<MaterialStockInClass> msilist,List<MaterialUnDoinfo> undolist, EventInfo eventinfo,Document doc)throws Exception {

	
	if (msilist.size() <= 0 || undolist.size() <= 0) {
		throw (new Exception("ERP返回结果为" + undolist.size()));
		}

	try {
		Element bodyElem = doc.getRootElement().getChild("Body");
		String moveType= bodyElem.getChildText("MOVETYPE");
		String erpEventTime=bodyElem.getChildText("RECEIVETIME");
		 List<MaterialPackingKey> mpklist = new ArrayList<MaterialPackingKey>();
		 List<SetEventInfo> eventlist = new ArrayList<SetEventInfo>();
		
		 for (int i = 0; i < msilist.size(); i++) {
				MaterialStockInClass msa = msilist.get(i);
				MaterialUnDoinfo undo = null;
				 List<MaterialPacking> mplist = new MaterialPackingStockInUtil()
					.GetPCBAStockInList(msa);
				for (int j = 0; j < undolist.size(); j++) {
					  String a = undolist.get(j).getSeq();
					 String b = mplist.get(0).getMessageId()+Integer.toString(i + 1);

					if (a.equals(b)) {
						undo = undolist.get(j);
						break;
						}
					}

		// 首先从shiprequest表中查找出ERPlocation和移动类型，根据ERPlocation决定OQAResult和oqaresultstate，用以修改box信息
						
		//List<MaterialPacking> mplist = new MaterialPackingStockInUtil().GetPCBAStockInList(msa);
		CommonValidation cv=new CommonValidation();
		for (MaterialPacking mp : mplist) {
			
				MaterialPackingKey mpkey = new MaterialPackingKey();
				mpkey.setSiteName(mp.getKey().getSiteName());
				mpkey.setMaterialPackingName(mp.getKey().getMaterialPackingName());
				mpklist.add(mpkey);
				SetEventInfo setevent = new SetEventInfo();
				Map<String, Object> bindMap = new HashMap<String, Object>();
				bindMap.put("erpState", "SUCCESS");
				bindMap.put("packingState", "Released");
				bindMap.put("stockState", "Stocked");
				/*bindMap.put("packingGrade", "");*/
				//B3/B4/B5/B9/B10 919移动类型收货SMT退货发来的组件直接收货到OK状态，且不需要质检
				if(moveType.equals("919")&&(factory.equals("B4")||factory.equals("B3")||factory.equals("B10")||factory.equals("B5")||factory.equals("B9")||factory.equals("B17"))){
					bindMap.put("packingGrade", "OK");
					bindMap.put("oqaResultState", GenericServiceProxy.getConstantMap().OQA_State_End);
					bindMap.put("oqaResult",  GenericServiceProxy.getConstantMap().OQA_Result_OK);
				}
				else{
					bindMap.put("packingGrade", "");
					bindMap.put("oqaResultState", GenericServiceProxy.getConstantMap().OQA_State_Pre);
					bindMap.put("oqaResult", "");
				}

				//bindMap.put("erpLocation", "130N");
				bindMap.put("charge", msa.getCharge());
				bindMap.put("unDoID", undo.getUnDoID());
				bindMap.put("unDoDetailName", undo.getUnDoDetailName());
				bindMap.put("remark", msa.getRemark());//PDA端新加
				/*bindMap.put(
								"erpEventTime",
									Timestamp.valueOf(cv.getDate(msa
									.getReceiveTime()) + " 00:00:00"));*/
				//bindMap.put("stockInType","Y29");
				bindMap.put("stockInType","Normal:PCBAStockIn");
				Date date = new Date();
				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				String receivedate = df.format(date);
				String budat=cv.getDate(erpEventTime)+" 00:00:00";
				
				bindMap.put("receiveTime",Timestamp.valueOf(receivedate));
				bindMap.put("receiveUser", eventinfo.getEventUser());
				bindMap.put("erpEventTime", Timestamp.valueOf(budat));//增加ERP过账时间插入，用于过账历史记录查询
				setevent.setUserColumns(bindMap);
				eventlist.add(setevent);
				eventinfo.setReasonCode(mp.getReasonCode());
				eventinfo.setReasonCodeType(mp.getReasonCodeType());
				MaterialPackingServiceProxy.getMaterialPackingService().setEvent(mpkey, eventinfo, setevent);

			}
							// MaterialPackingServiceProxy.getMaterialPackingService().setEvent(mpklist,
							// eventinfo, eventlist);
						

		MaterialReceiveActKey mrk = new MaterialReceiveActKey();
		mrk.setSiteName(msa.getSiteName());
		mrk.setReceiveactNO(msa.getReceiveActNo());
		mrk.setReceiveRequestName(msa.getReceiveRequestName());
		com.cim.idm.wmspackage.materialreceiverequestact.management.info.SetEventInfo setevent1 = new com.cim.idm.wmspackage.materialreceiverequestact.management.info.SetEventInfo();
		Map<String, Object> bindMap1 = new HashMap<String, Object>();
		bindMap1.put("receiveActState", "Received");
		setevent1.setUserColumns(bindMap1);
		MaterialReceiveRequestActServiceProxy.getReceiveRequestBatchService().setEvent(mrk,
										eventinfo, setevent1);

		// 存物料凭证
		// 针对WO中对LCM的领料问题，同一笔过账会出现多个物料凭证号。
		SaveUnDoInfoWO(msilist.get(0).getReceiveActNo(),undo.getUnDoIdDate(), undo.getUnDoID(),
								undo.getUnDoDetailName());

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

				return true;
			}
//获取MES退库单据
public String GetMESStockInInvioce (List<MaterialUnDoinfo> newUnDoList ,List<String> siteNameList){
	
	
	String condition = "select distinct RECEIVEREQUESTNAME from MATERIALPACKING where SITENAME=:SITENAME AND UNDOID =:UNDOID";
	Map<String, Object> bindMap = new HashMap<String, Object>();
	bindMap.put("SITENAME", siteNameList.get(0));
	bindMap.put("UNDOID", newUnDoList.get(0).getUnDoID());
	List<Map<String, Object>> invoicelist = IDMFrameServiceProxy
			.getSqlTemplate().queryForList(condition, bindMap);
	
		String invoice = invoicelist.get(0).get("RECEIVEREQUESTNAME") == null ? ""
				: invoicelist.get(0).get("RECEIVEREQUESTNAME").toString();

	return invoice;
}
public void ChangeMaterialpackingsmtState(List<MaterialStockInClass> mplist,String lastEventName,String receiveRequestName){
	
	for(int i=0;i<mplist.size();i++){
		
		MaterialStockInClass msa = mplist.get(i);
		String materialSpecName=msa.getMaterialSpecName();
		//更新materialpackingsmt表
		String sqlUpdate="UPDATE MATERIALPACKINGSMT  "
				+" SET  LASTEVENTNAME=:LASTEVENTNAME"
				+" ,LASTEVENTTIMEKEY=:LASTEVENTTIMEKEY"
				+" ,LASTEVENTTIME=sysdate"
				+" ,LASTEVENTUSER=:LASTEVENTUSER"
				+" WHERE SHIPREQUESTDETAILNAME=:SHIPREQUESTDETAILNAME "
				+ " AND MATERIALSPECNAME=:MATERIALSPECNAME ";

		Map<String, String> bindMapSmt = new HashMap<String, String>();
		
		bindMapSmt.put("LASTEVENTNAME",lastEventName);
		bindMapSmt.put("LASTEVENTTIMEKEY",TimeStampUtil.getCurrentEventTimeKey());
		bindMapSmt.put("LASTEVENTUSER","BOE");
		bindMapSmt.put("SHIPREQUESTDETAILNAME",receiveRequestName);
		bindMapSmt.put("MATERIALSPECNAME", materialSpecName);

		IDMFrameServiceProxy.getTransactionManager().beginTransaction();
		IDMFrameServiceProxy.getSqlTemplate().update(sqlUpdate, bindMapSmt);
		IDMFrameServiceProxy.getTransactionManager().commitTransaction();
	   
	}
	
}

public List<MaterialStockInClass> GetToERPList_forSMT(
		List<MaterialStockInClass> msilist, int num) throws ParseException {
	List<MaterialStockInClass> toerplist = new ArrayList<MaterialStockInClass>();
	int seqno = 1;
	CommonValidation commonVal = new CommonValidation();
	String sql2 = "SELECT MAX(UNDODETAILNAME) AS SEQ FROM materialpacking "
			+ "WHERE sitename = :sitename and receiveActNo=:receiveActNo and erpstate='ERPSUCCESS' ";

	Map<String, Object> bindMap3 = new HashMap<String, Object>();
	bindMap3.put("sitename", msilist.get(0).getSiteName());
	bindMap3.put("receiveActNo", msilist.get(0).getReceiveActNo());

	List<Map<String, Object>> queryResult2 = IDMFrameServiceProxy
			.getSqlTemplate()
			.queryForList(sql2, bindMap3);
	if(!(queryResult2.size()<=0||queryResult2.get(0).get("SEQ")==null||queryResult2.get(0).get("SEQ").toString().equals("")))
	{
		seqno=Integer.parseInt(queryResult2.get(0).get("SEQ").toString())+seqno;
	}
	for (MaterialStockInClass ms : msilist) {

		// 查询该物料是否根据ERP批次进行管理
		String ERPChargeFlag = "N";
		ERPChargeFlag = commonVal.getMaterialSpecCharge(ms.getErpfactory(),
				ms.getMaterialSpecName());


		List<MaterialStockInClass> oqalist = new MaterialPackingStockInUtil()
				.GetOQAMakedateGroupList(ms.getReceiveRequestName(),
						ms.getReceiveRequestDetailName(),
						ms.getReceiveActNo(), ms.getSiteName());
		String makedate = "";
		String charge = ms.getCharge();
		if(ms.getErpfactory().equals("2001"))
		{
			charge="E0000001";
		}
		for (MaterialStockInClass oqa : oqalist) {
			oqa.setCustomdate(ms.getCustomdate());
			oqa.setCustomform(ms.getCustomform());
			oqa.setReceiveTime(ms.getReceiveTime());
			oqa.setCustomformstate(ms.getCustomformstate());
			oqa.setMaterialOQAnum(ms.getMaterialOQAnum());
			oqa.setTaxid(ms.getTaxid());
			oqa.setTransportformno(ms.getTransportformno());
			oqa.setErplocation(ms.getErplocation());
			oqa.setErpfactory(ms.getErpfactory());
			oqa.setMaterialSpecName(ms.getMaterialSpecName());
			oqa.setMaterialtype(ms.getMaterialtype());
			oqa.setSiteName(ms.getSiteName());
			oqa.setSeqno(seqno++);
			oqa.setIcqflag(ms.getIcqflag());
			oqa.setCharge(charge);
			if (ERPChargeFlag.equals("Y") && ms.getCharge().equals("")) {
				if (!oqa.getMakedate().equals(makedate)) {
					List<String> sqldata = new ArrayList<String>();
					sqldata.add(oqa.getErpfactory());
					String spec = oqa.getMaterialSpecName()
							+ "************";
					sqldata.add(spec.substring(0, 10));
					String str = oqa.getMakedate().substring(0, 4)
							+ oqa.getMakedate().substring(5, 7)
							+ oqa.getMakedate().substring(8);
					
					String time = str + "00";
					sqldata.add(time.substring(2, 8));
					charge = NameServiceProxy.getNameRuleDefService()
							.generateName("ChargeNo", sqldata, 1)
							.get(0);
					oqa.setCharge(charge.substring(14));
					if(ms.getSiteName().equals("B7")){
                 	   oqa.setCharge(charge.substring(14,20));
						}
					makedate = oqa.getMakedate();
				} else {
					oqa.setCharge(charge.substring(14));
				}
			}
		}
		toerplist.addAll(oqalist);
	
	}

	return toerplist;
}


public List<MaterialPacking> PCBAStockInTQMSList(List<MaterialStockInClass> toerplist,
		List<MaterialUnDoinfo> undolist, EventInfo eventinfo,String messageID)
		throws Exception {
	List<MaterialProcessGroupCreateInfo> mpglist = new ArrayList<MaterialProcessGroupCreateInfo>();
	List<MaterialPacking> tqmsList=new ArrayList<MaterialPacking>();
	if (undolist.size() == toerplist.size() && toerplist.size() > 0) {// undolist.size()<1
																		// 说明ERP过账失败
		try {
			for (int i = 0; i < toerplist.size(); i++) {
				MaterialStockInClass ms = toerplist.get(i);
				MaterialUnDoinfo undo = undolist.get(i);
				for (int j = 0; j < undolist.size(); j++) {
					if(Integer.toString(toerplist.get(i).getSeqno()).equals(undolist.get(j).getSeq().substring(15,undolist.get(j).getSeq().length())))	
					{
						undo = undolist.get(j);
						break;
					}
				}//匹配发送ERP的seq号对应返回的undoinfo by maxinghua
				List<MaterialPacking> mplist = new ArrayList<MaterialPacking>();
				if (ms.getPreGroupName() == null
						|| ms.getPreGroupName().equals("")) {
					mplist = new MaterialPackingStockInUtil()
							.GetOQADetailGroupList1(ms);
				} else {

					mplist = new MaterialPackingStockInUtil()
							.GetOQADetailGroupList2(ms);
				}
				MaterialReceiveRequestDetailKey mrrdk = new MaterialReceiveRequestDetailKey();
				mrrdk.setSiteName(ms.getSiteName());
				mrrdk.setReceiveRequestName(ms.getReceiveRequestName());
				mrrdk.setReceiveRequestDetailName(ms
						.getReceiveRequestDetailName());
				MaterialReceiveRequestDetail mrrd = ReceiveRequestDetailServiceProxy
						.getReceiveRequestDetailService()
						.selectByKey(mrrdk);

				// tqmslist
				for (MaterialPacking mp : mplist) {

					if(mrrd.getIqcFlag().equals("X")){
						tqmsList.add(mp);
					}
				}

			}

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

	}
	else{
		throw new CustomException("ERP-0001", "");
	}
	return tqmsList;
}

public List<MaterialPacking> PCBAStockInTQMSListF(List<MaterialStockInClass> toerplist)
		throws Exception {

	     List<MaterialPacking> tqmsList=new ArrayList<MaterialPacking>();
	    
		try {
			for (int i = 0; i < toerplist.size(); i++) {
				 MaterialStockInClass ms = toerplist.get(i);
					List<MaterialPacking> mplist = new ArrayList<MaterialPacking>();
					if (ms.getPreGroupName() == null
							|| ms.getPreGroupName().equals("")) {
						mplist = new MaterialPackingStockInUtil()
								.GetOQADetailGroupList1(ms);
					} else {

						mplist = new MaterialPackingStockInUtil()
								.GetOQADetailGroupList2(ms);
					}
					MaterialReceiveRequestDetailKey mrrdk = new MaterialReceiveRequestDetailKey();
					mrrdk.setSiteName(ms.getSiteName());
					mrrdk.setReceiveRequestName(ms.getReceiveRequestName());
					mrrdk.setReceiveRequestDetailName(ms
							.getReceiveRequestDetailName());
					MaterialReceiveRequestDetail mrrd = ReceiveRequestDetailServiceProxy
							.getReceiveRequestDetailService()
							.selectByKey(mrrdk);

				// tqmslist
				for (MaterialPacking mp : mplist) {

					if(mrrd.getIqcFlag().equals("X")){
						tqmsList.add(mp);
					}
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw e;
		}

	    return tqmsList;
	  }

	public void StockInPCBATrayforB17(List<MaterialStockInClass> toerplist,String siteName)
			throws Exception{
		for (MaterialStockInClass ms : toerplist) {
			String materialSpecName = ms.getMaterialSpecName();
			String sql = "SELECT * FROM DURABLESMT "
					+ " WHERE SITENAME=:SITENAME "
					+ " AND MATERIALSPECNAME = :MATERIALSPECNAME ";
			Map<String, Object> bindMap = new HashMap<String, Object>();
			bindMap.put("MATERIALSPECNAME", materialSpecName);
			bindMap.put("SITENAME", siteName);
			
			List<Map<String, Object>> sqlResult
			= IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, bindMap);
			if(sqlResult.size()>0){
				String Qty = ms.getReceiveQuantity();
				String sqlUpdate = "UPDATE DURABLESMT "
						+ " SET QTY = QTY+TO_NUMBER(:QTY) "
						+ " WHERE SITENAME = :SITENAME "
						+ " AND MATERIALSPECNAME = :MATERIALSPECNAME ";
				Map<String, Object> bindMapUpdate = new HashMap<String, Object>();
				bindMapUpdate.put("MATERIALSPECNAME", materialSpecName);
				bindMapUpdate.put("SITENAME", siteName);
				bindMapUpdate.put("QTY", Qty);
				IDMFrameServiceProxy.getSqlTemplate().update(sqlUpdate, bindMapUpdate);
			}
		}
	}
	
	//FORGERP
	//更新pallet状态
	public void updataPalletStateByPC14980(EventInfo eventInfo,String siteName, String receiveActNo,String shipRequestName)
			throws Exception {
		try {
			String sql_query = " SELECT  DISTINCT SUPERMATERIALPACKINGNAME AS MATERIALPACKINGNAME,SUM(MATERIALQUANTITY) AS MATERIALQUANTITY "
					+ " FROM MATERIALPACKING BS"
					+ " WHERE "
					+ " BS.RECEIVEACTNO=:receiveActNo"
					+ " AND BS.SUPERMATERIALPACKINGNAME IS NOT NULL"
					+ " AND BS.SITENAME=:SITENAME"
					+ " GROUP BY SUPERMATERIALPACKINGNAME";
			String sql_insert = " UPDATE MATERIALPACKING SET MATERIALQUANTITY=MATERIALQUANTITY-:quantity  WHERE MATERIALPACKINGNAME=:materialpackingName ";
				Map<String, Object> bindMap_query = new HashMap<String, Object>();
				bindMap_query.put("SITENAME", siteName);
				bindMap_query.put("receiveActNo",
						receiveActNo);
				//bindMap_query.put("SHIPREQUESTNAME", shipRequestName);
				List<Map<String, Object>> PalletList =IDMFrameServiceProxy.getSqlTemplate().queryForList(sql_query, bindMap_query);
				for(int i = 0; i < PalletList.size(); i++)
				{
					if(PalletList.get(i).get("MATERIALPACKINGNAME")!=null)
					{
						Map<String, Object> bindMap_insert = new HashMap<String, Object>();
						bindMap_insert.put("materialpackingName",PalletList.get(i).get("MATERIALPACKINGNAME").toString());
						bindMap_insert.put("quantity",PalletList.get(i).get("MATERIALQUANTITY").toString());
							IDMFrameServiceProxy.getSqlTemplate()
									
									.update(sql_insert, bindMap_insert);
					}
				}
				
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
					throw e;
				}

	}
	
	// 获取订单数据
	public List<MaterialPacking> GetScrapManualStockOutList(
			org.jdom.Document document) throws Exception {

		List<MaterialPacking> mplist = new ArrayList<MaterialPacking>();
		Element root = document.getDocument().getRootElement();
		Element bodyElement = root.getChild("Body");
		Element requestlist = bodyElement.getChild("DATALIST");//解析数据
		CommonValidation cv = new CommonValidation();
		int seqno = 1;
		try {
			if (requestlist != null) {
				for (Iterator<?> iterator = requestlist.getChildren()
						.iterator(); iterator.hasNext();) {
					Element element = (Element) iterator.next();									
					String sitename = element.getChild("SITENAME").getText();
					String materialSpecName = element.getChild(
							"MATERIALSPECNAME").getText();
					String materialPackingName = element.getChild(
							"MATERIALPACKINGNAME").getText();
					String materialQuantity = element.getChild("MATERIALQUANTITY")
							.getText();																																	
					String erpfactory = element.getChild("ERPFACTORY")
							.getText();
					String erplocation = element.getChild("ERPLOCATION")
							.getText();
					String makedate = element.getChild("MAKEDATE").getText();
					String expiringdate = cv.getDate(element.getChild(
							"EXPIRINGDATE").getText());
					String charge = element.getChild("CHARGE").getText();
					String lasteventcomment = element.getChild("LASTEVENTCOMMENT").getText();
					String kostl = element.getChild("KOSTL").getText();
					String shipRequestName = element.getChild("SHIPREQUESTNAME").getText();
					String shipRequestDetailName = element.getChild("SHIPREQUESTDETAILNAME").getText();
					MaterialPacking msc = new MaterialPacking();
					/**
					 * 暂时用不到操作类型，前端已传使用时可直接取值
					String ACTTYPE = element.getChild("ACTTYPE").getText();
					**/
							msc.getKey().setSiteName(sitename);
							msc.setMaterialSpecName(materialSpecName);
							msc.getKey().setMaterialPackingName(materialPackingName);
							msc.setMaterialQuantity( Double.parseDouble(materialQuantity));														
							msc.setErpFactory(erpfactory);
							msc.setErpLocation(erplocation);					     
							msc.setMakeDate(Timestamp.valueOf(makedate));
							msc.setCharge(charge);	
							msc.setLastEventComment(lasteventcomment);
							msc.setShipRequestName(shipRequestName);
							msc.setShipRequestDetailName(shipRequestDetailName);
							mplist.add(msc);
						}
					}

				} catch (Exception e) {
					e.getMessage();
					throw e;
				}
				return mplist;
			}


	
	public List<MaterialPacking> SaveNormalStockInInfoForERPAccountStockState(List<MaterialStockInClass> toerplist,
			List<MaterialUnDoinfo> undolist, EventInfo eventinfo,String messageID)
			throws Exception {
		List<MaterialProcessGroupCreateInfo> mpglist = new ArrayList<MaterialProcessGroupCreateInfo>();
		List<MaterialPacking> tqmsList=new ArrayList<MaterialPacking>();
		//if (undolist.size() == toerplist.size() && toerplist.size() > 0)// undolist.size()<1 wyz 注释  ERP 不分行项目过账
		if (undolist.size() > 0)
		{
																			// 说明ERP过账失败
			try {
				for (int i = 0; i < toerplist.size(); i++) {  
					//for (int i = 0; i < undolist.size(); i++) {
					MaterialStockInClass ms = toerplist.get(i);
					//MaterialUnDoinfo undo = undolist.get(i);//wyz 注释 ERP 不分行项目过账
					MaterialUnDoinfo undo = undolist.get(i);
					/*
					 * wyz 注释  badt ERP 返回值无SEQ
					 */
//					for (int j = 0; j < undolist.size(); j++) {
//						if(Integer.toString(toerplist.get(i).getSeqno()).equals(undolist.get(j).getSeq().substring(15,undolist.get(j).getSeq().length())))	
//						{
//							undo = undolist.get(j);
//							break;
//						}
//					}//匹配发送ERP的seq号对应返回的undoinfo by maxinghua
					List<MaterialPacking> mplist = new ArrayList<MaterialPacking>();
					if (ms.getPreGroupName() == null
							|| ms.getPreGroupName().equals("")) {
						mplist = new MaterialPackingStockInUtil()
								.GetOQADetailGroupList1(ms);
					} else {

						mplist = new MaterialPackingStockInUtil()
								.GetOQADetailGroupList2(ms);
					}
					MaterialReceiveRequestDetailKey mrrdk = new MaterialReceiveRequestDetailKey();
					mrrdk.setSiteName(ms.getSiteName());
					mrrdk.setReceiveRequestName(ms.getReceiveRequestName());
					mrrdk.setReceiveRequestDetailName(ms
							.getReceiveRequestDetailName());
					MaterialReceiveRequestDetail mrrd = ReceiveRequestDetailServiceProxy
							.getReceiveRequestDetailService()
							.selectByKey(mrrdk);

					// 存packing
					for (MaterialPacking mp : mplist) {

						Timestamp time = null;

						try {
							time = Timestamp.valueOf(ms.getReceiveTime()
									+ " 00:00:00");
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

						Date date = new Date();
						SimpleDateFormat df = new SimpleDateFormat(
								"yyyy-MM-dd HH:mm:ss");
						String receivedate = df.format(date);

						MaterialPackingKey mpkey = new MaterialPackingKey();
						mpkey.setSiteName(mp.getKey().getSiteName());
						mpkey.setMaterialPackingName(mp.getKey()
								.getMaterialPackingName());
						SetEventInfo setevent = new SetEventInfo();
						Map<String, Object> bindMap = new HashMap<String, Object>();
						bindMap.put("packingState", "Released");
						bindMap.put("erpLocation", ms.getErplocation());
						bindMap.put("stockState", GenericServiceProxy.getConstantMap().ProcessGroup_PreStocked);
						bindMap.put("charge", ms.getCharge());
						bindMap.put("unDoID", undo.getUnDoID());
						bindMap.put("unDoDetailName", undo.getUnDoDetailName());
						bindMap.put("erpEventTime", time);
						bindMap.put("stockInType", "Normal");
						bindMap.put("erpState", "SUCCESS");
						bindMap.put("messageId",mp.getErpState().equalsIgnoreCase("ERPSUCCESS")?mp.getMessageId():messageID);
						bindMap.put("receiveTime",
								Timestamp.valueOf(receivedate));
						bindMap.put("receiveUser", eventinfo.getEventUser());
                        bindMap.put("remark", ms.getRemark());
						/*
						 * if (ms.getPreGroupName() != null) { bindMap.put("materialProcessGroupName",
						 * undo.getOqaname()); bindMap.put( "oqaResultState",
						 * GenericServiceProxy.getConstantMap().OQA_State_Pre); } else { if
						 * (mrrd.getIqcFlag() == null || mrrd.getIqcFlag().equals("")) {
						 * bindMap.put("packingGrade", "OK"); bindMap.put( "oqaResultState",
						 * GenericServiceProxy.getConstantMap().OQA_State_End);
						 * bindMap.put("oqaResult","OK"); } else if (mrrd.getIqcFlag().equals("S")) {
						 * bindMap.put("packingGrade", "NG"); bindMap.put( "oqaResultState",
						 * GenericServiceProxy.getConstantMap().OQA_State_End);
						 * bindMap.put("oqaResult","NG"); } else if (mrrd.getIqcFlag().equals("X")) {
						 * bindMap.put("packingGrade", ""); bindMap.put("materialProcessGroupName",
						 * "OICOQA"); bindMap.put( "oqaResultState",
						 * GenericServiceProxy.getConstantMap().OQA_State_Pre); } }
						 */
                        bindMap.put("materialProcessGroupName",
								undo.getOqaname());
						bindMap.put(
								"oqaResultState",
								GenericServiceProxy.getConstantMap().OQA_State_Pre);
						setevent.setUserColumns(bindMap);
						eventinfo.setEventName(eventinfo.getEventName());
						eventinfo.setEventComment(eventinfo.getEventComment());
//						eventinfo.setReasonCode(mp.getReasonCode());
//						eventinfo.setReasonCodeType(mp.getReasonCodeType());
						MaterialPackingServiceProxy.getMaterialPackingService()
								.setEvent(mpkey, eventinfo, setevent);
						if(mrrd.getIqcFlag().equals("X"))
							tqmsList.add(mp);


					}
					// //存储质检批信息
					if (ms.getPreGroupName() != null) {
						String sql =" SELECT MATERIALPROCESSGROUPNAME FROM MATERIALPROCESSGROUP WHERE SITENAME =:SITENAME AND MATERIALPROCESSGROUPNAME =:MATERIALPROCESSGROUPNAME ";

						Map<String, Object> bindMap1 = new HashMap<String, Object>();
						bindMap1.put("SITENAME", ms.getSiteName());
						bindMap1.put("MATERIALPROCESSGROUPNAME", undo.getOqaname());
						List<Map<String, Object>> queryResult = IDMFrameServiceProxy
								.getSqlTemplate()
								.queryForList(sql, bindMap1);
						if(queryResult==null||queryResult.size()<1){
						MaterialProcessGroupCreateInfo mpg = new MaterialProcessGroupCreateInfo();
						mpg.setSiteName(ms.getSiteName());
						mpg.setMaterialProcessGroupName(undo.getOqaname());
						mpg.setContentMaterialType(ms.getMaterialtype());
						mpg.setProcessGroupState(GenericServiceProxy
								.getConstantMap().OQA_State_Pre);
						MaterialProcessGroupServiceProxy
								.getMaterialProcessGroupService().create(
										eventinfo, mpg);
						}
					}
					// 存抬头文本信息
					MaterialReceiveActKey mrk = new MaterialReceiveActKey();
					String sql =" SELECT RECEIVEREQUESTNAME FROM MATERIALRECEIVEACT WHERE SITENAME =:SITENAME AND RECEIVEACTNO =:RECEIVEACTNO ";

					Map<String, Object> bindMap1 = new HashMap<String, Object>();
					bindMap1.put("SITENAME", ms.getSiteName());
					bindMap1.put("RECEIVEACTNO", ms.getReceiveActNo());
					List<Map<String, Object>> queryResult = IDMFrameServiceProxy
							.getSqlTemplate()
							.queryForList(sql, bindMap1);
					mrk.setSiteName(ms.getSiteName());
					mrk.setReceiveactNO(ms.getReceiveActNo());
					mrk.setReceiveRequestName(queryResult.get(0).get("RECEIVEREQUESTNAME").toString());
					com.cim.idm.wmspackage.materialreceiverequestact.management.info.SetEventInfo setevent = new com.cim.idm.wmspackage.materialreceiverequestact.management.info.SetEventInfo();
					Map<String, Object> bindMap = new HashMap<String, Object>();
					bindMap.put("receiveActState", "Received");
					setevent.setUserColumns(bindMap);
					MaterialReceiveRequestActServiceProxy
							.getReceiveRequestBatchService().setEvent(mrk,
									eventinfo, setevent);

				}

				// 存物料凭证
				SaveUnDoInfo(toerplist.get(0).getReceiveActNo(), undolist
						.get(0).getUnDoIdDate(), undolist.get(0).getUnDoID());
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				throw e;
			}

		}
		else{
			throw new CustomException("ERP-0001", "");
		}
		return tqmsList;
	}
	
	public List<MaterialPacking> SaveRefundStockInListForERPAccountStockState(List<MaterialStockInClass> msilist,
			List<MaterialUnDoinfo> undolist, EventInfo eventinfo,String messageID)
			throws Exception {

		if (msilist.size() <= 0 || undolist.size() <= 0) {
			throw (new Exception("ERP返回结果为" + undolist.size()));
		}
		List<MaterialPacking> tqmsList=new ArrayList<MaterialPacking>();
		try {
			
			List<MaterialPackingKey> mpklist = new ArrayList<MaterialPackingKey>();
			List<SetEventInfo> eventlist = new ArrayList<SetEventInfo>();
			CommonValidation cv = new CommonValidation();
			MaterialUnDoinfo undo = undolist.get(0);
			for (int i = 0; i < msilist.size(); i++) {
				MaterialStockInClass msa = msilist.get(i);
				List<MaterialPacking> materialPackingList = new MaterialPackingStockInUtil()
				.GetBackStockInList(msa);
				
				/*
				 * wyz 注释  badt ERP 返回值无SEQ
				 */
//				for (int j = 0; j < undolist.size(); j++) {
//					String a = undolist.get(j).getSeq();
//					String b = materialPackingList.get(0).getMessageId()+ Integer.toString(i + 1);
//
//					if (a.equals(b)) {
//						undo = undolist.get(j);
//						break;
//					}
//				}

				String oqaresult = "";
				// 首先从shiprequest表中查找出ERPlocation和移动类型，根据ERPlocation决定OQAResult和oqaresultstate，用以修改box信息
				//B9增加||msa.getActtype().equals("WO")||msa.getActtype().equals("POOEM")||msa.getActtype().equals("Manual")两个条件
				if (msa.getActtype().equals("Refund")||msa.getActtype().equals("WO")||msa.getActtype().equals("POOEM")||msa.getActtype().equals("Manual")) {
					String grade = new CommonValidation()
							.getGradeByErplocation(msa.getErpfactory(),
									msa.getErplocation());
					if (grade.equals("zp")) {
						oqaresult = "OK";
					} else if (grade == "cs") {
						oqaresult = "OK";
					} else if (grade == "zs") {
						oqaresult = "OK";
					} else {	
						oqaresult = "OK";
					}



					for (MaterialPacking mp : materialPackingList) {
						MaterialPackingKey mpkey = new MaterialPackingKey();
						mpkey.setSiteName(mp.getKey().getSiteName());
						mpkey.setMaterialPackingName(mp.getKey()
								.getMaterialPackingName());
						mpklist.add(mpkey);
						SetEventInfo setevent = new SetEventInfo();
						Map<String, Object> bindMap = new HashMap<String, Object>();
						bindMap.put("packingState", "Released");
						bindMap.put("stockState", GenericServiceProxy.getConstantMap().ProcessGroup_PreStocked);
						bindMap.put("charge", msa.getCharge());
						bindMap.put("kostl", msa.getKostl());
						bindMap.put("unDoID", undo.getUnDoID());
						bindMap.put("unDoDetailName", undo.getUnDoDetailName());
						bindMap.put(
								"erpEventTime",
								Timestamp.valueOf(cv.getDate(msa
										.getReceiveTime()) + " 00:00:00"));
						bindMap.put(
								"stockInType",
								msa.getActtype() + ":"
										+ msa.getShipRequestDetailType());
						//BMDT 311移库不需要质检
			            if(mp.getKey().getSiteName()=="BMDT"){
			            	if(mp.getReasonCodeType().equals("311")||mp.getReasonCodeType().equals("926"))
							{
								
								bindMap.put("packingGrade", "OK");
								bindMap.put("oqaResult", "OK");
								bindMap.put("oqaResultState", "END");
							}
							else
							{
								bindMap.put("oqaResult", "");
								bindMap.put("packingGrade", "");
								bindMap.put(
										"oqaResultState",
										GenericServiceProxy.getConstantMap().OQA_State_Pre);
								bindMap.put("materialProcessGroupName",
											"OICOQA");
							}
			            }
						else
						{
						if(mp.getReasonCodeType().equals("503"))
						{
							if(mp.getKey().getSiteName().equals("TM1"))//tm1 新增 OEM 收货类型503 移动类型 收货到质检新增20191128
							{
								bindMap.put("oqaResult", "");
								bindMap.put("packingGrade", "");
								bindMap.put("materialProcessGroupName",
										"OICOQA");
								bindMap.put(
										"oqaResultState",
										GenericServiceProxy.getConstantMap().OQA_State_Pre);
							}
							else{
							if(cv.getIQCFlagOfMaterialSpec(msa.getMaterialSpecName(), msa.getErpfactory())){
								bindMap.put("oqaResult", "");
								bindMap.put("packingGrade", "");
								bindMap.put("materialProcessGroupName",
										"OICOQA");
								bindMap.put(
										"oqaResultState",
										GenericServiceProxy.getConstantMap().OQA_State_Pre);
								tqmsList.add(mp);
							}//add by mxh  for b10 new need
							else
							{
								bindMap.put("packingGrade", "OK");
								bindMap.put(
										"oqaResultState",
										GenericServiceProxy.getConstantMap().OQA_State_End);
								bindMap.put("oqaResult","OK");
							}
						}
						}
						else if(mp.getReasonCodeType().equals("505"))
						{
							bindMap.put("packingGrade", "NG");
							bindMap.put(
									"oqaResultState",
									GenericServiceProxy.getConstantMap().OQA_State_End);
							bindMap.put("oqaResult","NG");
						}
						else{
							bindMap.put("packingGrade", "OK");
							bindMap.put("oqaResult", oqaresult);
							bindMap.put("oqaResultState", "END");
						}}
			            //tm1 根据shiprequestdetailtype判断是否收货到质检
			            if(mp.getKey().getSiteName().equals("TM1")&&msa.getShipRequestDetailType().equals("503"))
			            {

							bindMap.put("oqaResult", "");
							bindMap.put("packingGrade", "");
							bindMap.put("materialProcessGroupName",
									"OICOQA");
							bindMap.put(
									"oqaResultState",
									GenericServiceProxy.getConstantMap().OQA_State_Pre);						
			            }
			            
						bindMap.put("messageId", mp.getErpState().equalsIgnoreCase("ERPSUCCESS")?mp.getMessageId():messageID);
						Date date = new Date();
						SimpleDateFormat df = new SimpleDateFormat(
								"yyyy-MM-dd HH:mm:ss");
						String receivedate = df.format(date);
						bindMap.put("receiveTime",
								Timestamp.valueOf(receivedate));
						bindMap.put("receiveUser", eventinfo.getEventUser());
						bindMap.put("erpState", "SUCCESS");
						setevent.setUserColumns(bindMap);
						eventlist.add(setevent);
						eventinfo.setReasonCode(mp.getReasonCode());
						eventinfo.setReasonCodeType(mp.getReasonCodeType());
						eventinfo.setEventName("RefundStockIn");
						eventinfo.setEventComment("RefundStockIn");
						MaterialPackingServiceProxy.getMaterialPackingService()
								.setEvent(mpkey, eventinfo, setevent);
					}
					// MaterialPackingServiceProxy.getMaterialPackingService().setEvent(mpklist,
					// eventinfo, eventlist);

				}else if(msa.getActtype().equals("BMDTOEM")||msa.getActtype().equals("ERPReserve")||msa.getActtype().equals("B5OEM")){
					
					
					List<MaterialPacking> mplist = new MaterialPackingStockInUtil()
					.GetBackStockInList(msa);

					for (MaterialPacking mp : mplist) {
						MaterialPackingKey mpkey = new MaterialPackingKey();
						mpkey.setSiteName(mp.getKey().getSiteName());
						mpkey.setMaterialPackingName(mp.getKey()
								.getMaterialPackingName());
						mpklist.add(mpkey);
						SetEventInfo setevent = new SetEventInfo();
						Map<String, Object> bindMap = new HashMap<String, Object>();
						bindMap.put("packingState", "Released");
						bindMap.put("stockState", GenericServiceProxy.getConstantMap().ProcessGroup_PreStocked);
						if(mp.getKey().getSiteName().equals("BMDT")){
							bindMap.put("oqaResult", "");
							bindMap.put("packingGrade", "");
							bindMap.put("oqaResultState",GenericServiceProxy.getConstantMap().OQA_State_Pre);
						}else{
							bindMap.put("oqaResult", "OK");
							bindMap.put("packingGrade", "OK");
							bindMap.put("oqaResultState","END");
						}
				
						bindMap.put("materialProcessGroupName",
									"OICOQA");
				
							tqmsList.add(mp);
						bindMap.put("charge", msa.getCharge());
						bindMap.put("kostl", msa.getKostl());
						bindMap.put("unDoID", undo.getUnDoID());
						bindMap.put("unDoDetailName", undo.getUnDoDetailName());
						bindMap.put(
								"erpEventTime",
								Timestamp.valueOf(cv.getDate(msa
										.getReceiveTime()) + " 00:00:00"));
						bindMap.put(
								"stockInType",
								msa.getActtype() + ":"
										+ msa.getShipRequestDetailType());
						Date date = new Date();
						SimpleDateFormat df = new SimpleDateFormat(
								"yyyy-MM-dd HH:mm:ss");
						String receivedate = df.format(date);
						bindMap.put("receiveTime",
								Timestamp.valueOf(receivedate));
						bindMap.put("receiveUser", eventinfo.getEventUser());
						bindMap.put("erpState", "SUCCESS");
						setevent.setUserColumns(bindMap);
						eventlist.add(setevent);
						eventinfo.setReasonCode(mp.getReasonCode());
						eventinfo.setReasonCodeType(mp.getReasonCodeType());
						if(mp.getKey().getSiteName().equals("BMDT")){
							eventinfo.setEventName("BMDTOEMStockIn");
							eventinfo.setEventComment("BMDTOEMStockIn");
						}else{
							eventinfo.setEventName("B5OEMStockIn");
							eventinfo.setEventComment("B5OEMStockIn");
						}
						
						MaterialPackingServiceProxy.getMaterialPackingService()
								.setEvent(mpkey, eventinfo, setevent);
					}
					
				}else {
				
					List<MaterialPacking> mplist = new MaterialPackingStockInUtil()
							.GetBackStockInList(msa);

					for (MaterialPacking mp : mplist) {
						MaterialPackingKey mpkey = new MaterialPackingKey();
						mpkey.setSiteName(mp.getKey().getSiteName());
						mpkey.setMaterialPackingName(mp.getKey()
								.getMaterialPackingName());
						mpklist.add(mpkey);
						SetEventInfo setevent = new SetEventInfo();
						Map<String, Object> bindMap = new HashMap<String, Object>();
						bindMap.put("packingState", "Released");
						bindMap.put("stockState", GenericServiceProxy.getConstantMap().ProcessGroup_PreStocked);
						if(mp.getReasonCodeType().equals("503")){
							bindMap.put("packingGrade", "");
							bindMap.put("oqaResult", "");
							bindMap.put("oqaResultState", "PREOQA");
							bindMap.put("materialProcessGroupName",
									"OICOQA");
							tqmsList.add(mp);
						}//add by mxh  for b10 new need
						
						else if(mp.getReasonCodeType().equals("505"))
						{
							bindMap.put("packingGrade", "NG");
							bindMap.put("oqaResult", oqaresult);
							bindMap.put("oqaResultState", "END");
						}
						else if(mp.getKey().getSiteName().equals("TM1")&& mp.getReasonCodeType().equals("501"))//tm1 新增501 移动类型 新增20190523
						{
							bindMap.put("packingGrade", "OK");
							bindMap.put("oqaResult", "OK");
							bindMap.put("oqaResultState", "END");
						}
						else if(mp.getKey().getSiteName().equals("TM1")&& mp.getReasonCodeType().equals("503"))//tm1 新增 OEM503 移动类型 收货到质检新增20191128
						{
							bindMap.put("oqaResult", "");
							bindMap.put("packingGrade", "");
							bindMap.put("materialProcessGroupName",
									"OICOQA");
							bindMap.put(
									"oqaResultState",
									GenericServiceProxy.getConstantMap().OQA_State_Pre);
						}
						else if(mp.getKey().getSiteName().equals("B7")&&mp.getReasonCodeType().equals("Z32"))//B7新增20190415
						{
							bindMap.put("packingGrade", "OK");
							bindMap.put("oqaResult", "OK");
							bindMap.put("oqaResultState", "END");
						}else if(mp.getKey().getSiteName().equals("B11")&&mp.getReasonCodeType().equals("501"))//B11新增20190712
						{
							bindMap.put("packingGrade", "OK");
							bindMap.put("materialProcessGroupName","OICOQA");
							bindMap.put("oqaResult","OK");
							bindMap.put("oqaResultState", "END");
						}else if(mp.getKey().getSiteName().equals("BADT")&&mp.getReasonCodeType().equals("ZC5") ||mp.getReasonCodeType().equals("ZC3")) {
							bindMap.put("packingGrade", "OK");
							bindMap.put("oqaResult", "OK");
							bindMap.put("oqaResultState", "END");//ZC3 或者ZC5退库写质检状态
						}
						else{
							bindMap.put("packingGrade", "OK");
							bindMap.put("oqaResult", oqaresult);
							bindMap.put("oqaResultState", "END");
						}
						bindMap.put("messageId", mp.getErpState().equalsIgnoreCase("ERPSUCCESS")?mp.getMessageId():messageID);
						bindMap.put("charge", msa.getCharge());
						bindMap.put("kostl", msa.getKostl());
						bindMap.put("unDoID", undo.getUnDoID());
						bindMap.put("unDoDetailName", undo.getUnDoDetailName());
						bindMap.put(
								"erpEventTime",
								Timestamp.valueOf(cv.getDate(msa
										.getReceiveTime()) + " 00:00:00"));
						bindMap.put(
								"stockInType",
								msa.getActtype() + ":"
										+ msa.getShipRequestDetailType());
						Date date = new Date();
						SimpleDateFormat df = new SimpleDateFormat(
								"yyyy-MM-dd HH:mm:ss");
						String receivedate = df.format(date);
						bindMap.put("receiveTime",
								Timestamp.valueOf(receivedate));
						bindMap.put("receiveUser", eventinfo.getEventUser());
						bindMap.put("erpState", "SUCCESS");
						setevent.setUserColumns(bindMap);
						eventlist.add(setevent);
						eventinfo.setReasonCode(mp.getReasonCode());
						eventinfo.setReasonCodeType(mp.getReasonCodeType());
						eventinfo.setEventName("RefundStockIn");
						eventinfo.setEventComment("RefundStockIn");
						MaterialPackingServiceProxy.getMaterialPackingService()
								.setEvent(mpkey, eventinfo, setevent);

					}
					// MaterialPackingServiceProxy.getMaterialPackingService().setEvent(mpklist,
					// eventinfo, eventlist);
				}

				MaterialReceiveActKey mrk = new MaterialReceiveActKey();
				mrk.setSiteName(msa.getSiteName());
				mrk.setReceiveactNO(msa.getReceiveActNo());
				mrk.setReceiveRequestName(msa.getReceiveRequestName());
				com.cim.idm.wmspackage.materialreceiverequestact.management.info.SetEventInfo setevent1 = new 

com.cim.idm.wmspackage.materialreceiverequestact.management.info.SetEventInfo();
				Map<String, Object> bindMap1 = new HashMap<String, Object>();
				bindMap1.put("receiveActState", "Received");
				setevent1.setUserColumns(bindMap1);
				MaterialReceiveRequestActServiceProxy
						.getReceiveRequestBatchService().setEvent(mrk,
								eventinfo, setevent1);
			}
			// 存物料凭证
			// 针对WO中对LCM的领料问题，同一笔过账会出现多个物料凭证号。
			SaveUnDoInfoWO(msilist.get(0).getReceiveActNo(),
					undo.getUnDoIdDate(), undo.getUnDoID(),
					undo.getUnDoDetailName());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw e;
		}

		return tqmsList;
	}
}
