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

import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
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.jdom.Document;
import org.jdom.Element;
import org.springframework.dao.DataAccessException;

import com.cim.idm.framework.IDMFrameServiceProxy;
import com.cim.idm.framework.data.EventInfo;
import com.cim.idm.framework.util.time.TimeStampUtil;
import com.cim.idm.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.wmspackage.materialpacking.MaterialPackingServiceProxy;
import com.cim.idm.wmspackage.materialpacking.management.data.MaterialPacking;
import com.cim.idm.wmspackage.materialpacking.management.data.MaterialPackingKey;
import com.cim.idm.wmspackage.materialpacking.management.info.SetEventInfo;
import com.cim.idm.wmspackage.materialprocessgroup.MaterialProcessGroupServiceProxy;
import com.cim.idm.wmspackage.materialprocessgroup.management.data.MaterialProcessGroupKey;
import com.cim.idm.wmspackage.materialprocessgroup.management.info.MaterialProcessGroupCreateInfo;
import com.cim.idm.wmspackage.materialprocessgroup.management.info.MaterialProcessGroupSetEventInfo;
import com.cim.idm.wmspackage.materialreceiverequestact.MaterialReceiveRequestActServiceProxy;
import com.cim.idm.wmspackage.materialundo.info.MaterialUnDoinfo;
import com.cim.idm.wmspackage.name.NameServiceProxy;
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;


public class MaterialPackingNoPOStockInImpl {
	static String factory = System.getProperty("factory");
	public List<MaterialStockInClass> GetNoPOStockInList(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();
						//sqlResult2.get(i).get("RECEIVEREQUESTDETAILNAME")==null?"":sqlResult2.get(i).get("RECEIVEREQUESTDETAILNAME").toString();
						String sitename = element.getChild("SITENAME")==null?"":element.getChild("SITENAME").getText();
						String erpfactory = element.getChild("ERPFACTORYNAME")==null?"":element.getChild("ERPFACTORYNAME").getText();
						String materialSpecName = element.getChild("MATERIALSPECNAME")==null?"":element.getChild("MATERIALSPECNAME").getText();
						String receiveRequestName = element.getChild("RECEIVEREQUESTNAME")==null?"":element.getChild("RECEIVEREQUESTNAME").getText();
						String receiveRequestDetailName = element.getChild("RECEIVEREQUESTDETAILNAME")==null?"":element.getChild("RECEIVEREQUESTDETAILNAME").getText();
						String receiveActNo = element.getChild("RECEIVEACTNO")==null?"":element.getChild("RECEIVEACTNO").getText();
						String erplocation = element.getChild("ERPLOCATION")==null?"":element.getChild("ERPLOCATION").getText();
						double materialOQAnum =element.getChild("MATERIALOQANUM")==null?0:Double.valueOf(element.getChild("MATERIALOQANUM").getText());
						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")==null?"":element.getChild("RECEIVEQUANTITY").getText();
						String acttype = element.getChild("ACTTYPE")==null?"":element.getChild("ACTTYPE").getText();
						String customform = element.getChild("CUSTOMFORM")==null?"":element.getChild("CUSTOMFORM").getText();
						String customstate = element.getChild("CUSTOMSTATE")==null?"":element.getChild("CUSTOMSTATE").getText();
						//String customdate = element.getChild("CUSTOMDATE").getText();
						String transportformno = element.getChild("TRANSPORTFORMNO")==null?"":element.getChild("TRANSPORTFORMNO").getText();
						String taxid = element.getChild("TAXID")==null?"":element.getChild("TAXID").getText();
						String icqflag = element.getChild("IQCFLAG")==null?"":element.getChild("IQCFLAG").getText();
						String oqaflag = element.getChild("OQAFLAG")==null?"":element.getChild("OQAFLAG").getText();
						String charge = element.getChild("CHARGE")==null?"":element.getChild("CHARGE").getText();
						//String inspectp = element.getChild("INSPECTP").getText();
						String suppliername = element.getChild("SUPPLIERNAME")==null?"":element.getChild("SUPPLIERNAME").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.setCustomform(customform);
						msc.setCustomformstate(customstate);
						msc.setTaxid(taxid);
						msc.setOqaflag(oqaflag);
						msc.setIcqflag(icqflag);
						msc.setCharge(charge);
						msc.setTransportformno(transportformno);
						msc.setSuppliername(suppliername);
	
						
						mplist.add(msc);					
					}
				}
				
			}catch(Exception e){
				e.getMessage();
				throw e;
			}
			return mplist;
		}
	
	public List<MaterialStockInClass> GetToERPList(List<MaterialStockInClass> msilist) throws ParseException{
		List<MaterialStockInClass> toerplist = new ArrayList<MaterialStockInClass>();
		int seqno = 1;
		CommonValidation commonVal=new CommonValidation();
		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 = "";
					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.setSuppliername(ms.getSuppliername());
						

						/**
						 * 根据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") || ms.getSiteName().equals("B12")){
		                        	   oqa.setCharge(charge.substring(14,20));
									}
								if(ms.getSiteName().equals("B2")){
									if(oqa.getSuppliername()!=null)
										oqa.setCharge(oqa.getSuppliername().substring(3,oqa.getSuppliername().length()));
									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 = "";
					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++);
						
						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") || ms.getSiteName().equals("B12")){
		                        	   oqa.setCharge(charge.substring(14,20));
									}
								if(ms.getSiteName().equals("B2")){
									if(oqa.getSuppliername()!=null)
										oqa.setCharge(oqa.getSuppliername().substring(3,oqa.getSuppliername().length()));
									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 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<MaterialStockInClass> GroupOQAList2(MaterialStockInClass ms,double num,int seqno){
	
	List<MaterialPacking> mplist = new MaterialPackingStockInUtil().GetOQADetailGroupList(ms);
	List<MaterialStockInClass> result = new ArrayList<MaterialStockInClass>();
	DecimalFormat df=new DecimalFormat("#.##");
	 int first = 0; 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.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.setShipRequestDetailType(ms.getShipRequestDetailType());
			 mg.setReceiveQuantity(Double.toString(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<MaterialStockInClass> GroupOQA(List<MaterialPacking> mp,MaterialStockInClass ms,int first,int end,int seqno,double num){
	
	List<MaterialStockInClass> result2 = new ArrayList<MaterialStockInClass>();
	Double sum=(double) 0.0;
	DecimalFormat df=new DecimalFormat("#.##");
	int count= 0;
	while(first <= end){
	
		if(sum<num){
			//double nu = num-sum;
			//double nu1= mp.get(end).getMaterialQuantity();
			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.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(df.format(sum));
					 result2.add(mg);
					 seqno++;
					 count=0;
					 sum=(double) 0;
			}
			if(first>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.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.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(df.format(sum));
				 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.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(df.format(sum));
				 result2.add(mg);
				 seqno++;
				 count=0;
				 sum=(double) 0;
		}
	}
	
	MaterialPackingServiceProxy.getMaterialPackingService().update(mp);
	return result2;
	}
	
	
	public void SaveNoPOStockInInfo(List<MaterialStockInClass> toerplist,EventInfo eventinfo)throws Exception{
		List<MaterialProcessGroupCreateInfo> mpglist = new ArrayList<MaterialProcessGroupCreateInfo>();
		if(toerplist.size() > 0){//undolist.size()<1 说明ERP过账失败
			try {
				String undoId = new MaterialPackingServiceImpl().generateVirtualUndoName(toerplist.get(0).getSiteName());
			for(int i=0;i<toerplist.size();i++){			
				MaterialStockInClass ms=toerplist.get(i);
				//MaterialUnDoinfo undo = undolist.get(i);
				String oqaGroupname = "";//new MaterialPackingServiceImpl().generateVirtualUndoName(toerplist.get(0).getSiteName());
				List<MaterialPacking> mplist =new ArrayList<MaterialPacking>();
				if(ms.getPreGroupName()==null ||ms.getPreGroupName().equals("")){							
					mplist =new MaterialPackingStockInUtil().GetOQADetailGroupList1(ms);
				}else{
					oqaGroupname = new MaterialPackingServiceImpl().generateVirtualOQAName(ms.getSiteName());
					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()==null?"":ms.getCharge());
						bindMap.put("unDoID", undoId);
						bindMap.put("unDoDetailName", "V-"+Integer.toString(ms.getSeqno()));
						bindMap.put("erpEventTime", time);
						bindMap.put("stockInType","NoPO");
						bindMap.put("receiveTime",Timestamp.valueOf(receivedate));
						bindMap.put("receiveUser", eventinfo.getEventUser());

						if(ms.getPreGroupName()!=null){	
							bindMap.put("materialProcessGroupName",oqaGroupname);
							bindMap.put("packingGrade","OK");
							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("materialProcessGroupName","VirtualOICOQA");
								bindMap.put("oqaResultState",GenericServiceProxy.getConstantMap().OQA_State_Pre);
							}
						}
						setevent.setUserColumns(bindMap);
						MaterialPackingServiceProxy.getMaterialPackingService().setEvent(mpkey, eventinfo, setevent);
						
					}
					////存储质检批信息
					if(ms.getPreGroupName()!=null){
						
						MaterialProcessGroupCreateInfo mpg = new MaterialProcessGroupCreateInfo();
						mpg.setSiteName(ms.getSiteName());
						mpg.setMaterialProcessGroupName(oqaGroupname);						
						mpg.setContentMaterialType(ms.getMaterialtype());
						mpg.setProcessGroupState(GenericServiceProxy.getConstantMap().OQA_State_Pre);
						MaterialProcessGroupServiceProxy.getMaterialProcessGroupService().create(eventinfo, mpg);
					}	
					//存抬头文本信息
					MaterialReceiveActKey mrk = new MaterialReceiveActKey();
					mrk.setSiteName(ms.getSiteName());
					mrk.setReceiveactNO(ms.getReceiveActNo());
					mrk.setReceiveRequestName(ms.getReceiveRequestName());					
					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);

			}
			
			//存物料凭证
			Date date = new Date();
			SimpleDateFormat df = new SimpleDateFormat("yyyy");
			String receiveyear = df.format(date);
				new MaterialPackingStockInImpl().SaveUnDoInfo(toerplist.get(0).getReceiveActNo(),receiveyear,undoId);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				throw e;
			}
			
		}else{
			throw new Exception("There is no box in the receiveactno !");
		}
		
		
	}
	
public void SaveOQAResult(EventInfo eventInfo,String siteName,org.jdom.Document doc)throws Exception{
		
		Element root = doc.getDocument().getRootElement();
		Element bodyElement = root.getChild("Body");
		Element elementList = bodyElement.getChild("MaterialPackingList");
				
		//List<MaterialPacking> mplist = new ArrayList<MaterialPacking>();
		
		try{
			if(elementList != null){
				
				String undoId = new MaterialPackingServiceImpl().generateVirtualUndoName(siteName);
				
				for(Iterator<?> iterator = elementList.getChildren().iterator();iterator.hasNext();){
					Element mpelement = (Element)iterator.next();
					String sitename = mpelement.getChild("SITENAME").getText();
					String materialpacking = mpelement.getChild("MATERIALPACKINGNAME").getText();
					String oqaresult = mpelement.getChild("OQARESULT").getText();
					//String oqaresultstate = mpelement.getChild("OQARESULTSTATE").getText();
					
					MaterialPackingKey mpkey = new MaterialPackingKey();
					mpkey.setSiteName(sitename);
					mpkey.setMaterialPackingName(materialpacking);
					SetEventInfo setevent = new SetEventInfo();
					Map<String, Object> bindMap = new HashMap<String, Object>();
					bindMap.put("oqaResult",oqaresult);
					bindMap.put("packingGrade", oqaresult);
					bindMap.put("oqaResultState",GenericServiceProxy.getConstantMap().OQA_State_End);//以后改成可传参的
					bindMap.put("unDoID", undoId);
					bindMap.put("unDoDetailName", "V-1");
					setevent.setUserColumns(bindMap);
					MaterialPackingServiceProxy.getMaterialPackingService().setEvent(mpkey, eventInfo, setevent);
				}
				
				//MaterialPackingServiceProxy.getMaterialPackingService().update(mplist);
				//存物料凭证
				Date date = new Date();
				SimpleDateFormat df = new SimpleDateFormat("yyyy");
				String receiveyear = df.format(date);
				new MaterialPackingStockInImpl().SaveOQAUnDoInfo(receiveyear,undoId);
			}
			
		}catch(Exception e){
			e.getMessage();
			throw e;
		}
		
		

	}

public void CancleNPOQAResult(EventInfo eventInfo,String siteName,org.jdom.Document doc,String materialProcessGroupName)throws Exception{
	
	Element root = doc.getDocument().getRootElement();
	Element bodyElement = root.getChild("Body");
	Element elementList = bodyElement.getChild("MaterialPackingList");
			
	//List<MaterialPacking> mplist = new ArrayList<MaterialPacking>();
	
	try{
		if(elementList != null){
			
			//String undoId = new MaterialPackingServiceImpl().generateVirtualUndoName(siteName);
			List<MaterialPackingKey> mpkeyList = new ArrayList<MaterialPackingKey>();
			for(Iterator<?> iterator = elementList.getChildren().iterator();iterator.hasNext();){
				Element mpelement = (Element)iterator.next();
				String sitename = mpelement.getChild("SITENAME").getText();
				String materialpacking = mpelement.getChild("MATERIALPACKINGNAME").getText();
				MaterialPackingKey mpkey = new MaterialPackingKey();
				mpkey.setSiteName(sitename);
				mpkey.setMaterialPackingName(materialpacking);
				if(!checkOQA(mpkey)){
					mpkeyList.add(mpkey);
				}
				else{
					throw new CustomException("CancelError","","");
				}
			}
				SetEventInfo setevent = new SetEventInfo();
				Map<String, Object> bindMap = new HashMap<String, Object>();
				bindMap.put("oqaResult","");
				bindMap.put("packingGrade", "");
				bindMap.put("oqaResultState",GenericServiceProxy.getConstantMap().OQA_State_Pre);//以后改成可传参的
				setevent.setUserColumns(bindMap);
				MaterialPackingServiceProxy.getMaterialPackingService().setEvent(mpkeyList, eventInfo, setevent);
			
			
			//MaterialPackingServiceProxy.getMaterialPackingService().update(mplist);
			//修改物料凭证
				String sql="update BS_MATERIALPACKINGUNDOINFO  set undoidstate='N' WHERE MATERIALPROCESSGROUPNAME=:materialprocessgroupname AND SITENAME=:siteName and lasteventname='NPOQA' ";
				Map<String, Object> bindMap1 = new HashMap<String, Object>();
				bindMap1.put("siteName",siteName);
				bindMap1.put("materialprocessgroupname",materialProcessGroupName);
				IDMFrameServiceProxy.getSqlTemplate().update(sql, bindMap1);
		}
		
	}catch(Exception e){
		e.getMessage();
		throw e;
	}
	
	

}


	public void SaveOQAGroupInfo(EventInfo eventInfo,String sitename,String groupname){
		MaterialProcessGroupKey mpgk = new MaterialProcessGroupKey();
		mpgk.setMaterialProcessGroupName(groupname);
		mpgk.setSiteName(sitename);		
		MaterialProcessGroupSetEventInfo setEventInfo = new MaterialProcessGroupSetEventInfo();
		Map<String, Object> bindMap = new HashMap<String, Object>();
		bindMap.put("processGroupState",GenericServiceProxy.getConstantMap().OQA_State_End);//以后改成可传参的
		setEventInfo.setUserColumns(bindMap);
		MaterialProcessGroupServiceProxy.getMaterialProcessGroupService().setEvent(mpgk, eventInfo, setEventInfo);
	}
	public void CancelOQAGroupInfo(EventInfo eventInfo,String sitename,String groupname){
		MaterialProcessGroupKey mpgk = new MaterialProcessGroupKey();
		mpgk.setMaterialProcessGroupName(groupname);
		mpgk.setSiteName(sitename);		
		MaterialProcessGroupSetEventInfo setEventInfo = new MaterialProcessGroupSetEventInfo();
		Map<String, Object> bindMap = new HashMap<String, Object>();
		bindMap.put("processGroupState",GenericServiceProxy.getConstantMap().OQA_State_Pre);//以后改成可传参的
		setEventInfo.setUserColumns(bindMap);
		MaterialProcessGroupServiceProxy.getMaterialProcessGroupService().setEvent(mpgk, eventInfo, setEventInfo);
	}
	public void changeNPFlag(org.jdom.Document doc,EventInfo eventInfo)throws Exception{
		try{
			Element root = doc.getDocument().getRootElement();
			Element bodyElement = root.getChild("Body");
			Element elementList = bodyElement.getChild("MaterialPackingList");		
			if(elementList != null){
				SetEventInfo setevent = new SetEventInfo();
				List<MaterialPackingKey> mpklist = new ArrayList<MaterialPackingKey>();
				for(Iterator<?> iterator = elementList.getChildren().iterator();iterator.hasNext();){
					Element mpelement = (Element)iterator.next();
					String sitename = mpelement.getChild("SITENAME").getText();
					String materialpacking = mpelement.getChild("MATERIALPACKINGNAME").getText();
					MaterialPackingKey mpkey = new MaterialPackingKey();
					mpkey.setSiteName(sitename);				
					mpkey.setMaterialPackingName(materialpacking);
					if(checkBox(mpkey))
					{
						mpklist.add(mpkey);	
					}
					
				}
				Map<String, Object> bindMap = new HashMap<String, Object>();		
				bindMap.put("NPFlag","N");						
				setevent.setUserColumns(bindMap);
				eventInfo.setEventName("changeNPFlag");
				MaterialPackingServiceProxy.getMaterialPackingService().setEvent(mpklist, eventInfo, setevent);
		
			}
			
			
		}catch(Exception e){
			e.getMessage();
			throw e;
		}

	}
	public void GetOQAList(org.jdom.Document doc,String siteName,EventInfo eventInfo)throws Exception{
		try{
			Element root = doc.getDocument().getRootElement();
			Element bodyElement = root.getChild("Body");
			Element elementList = bodyElement.getChild("MaterialPackingList");		
					
			if(elementList != null){
				List<MaterialPackingKey> mpklist = new ArrayList<MaterialPackingKey>();
				List<SetEventInfo> setlist = new ArrayList<SetEventInfo>();
				String undoId = new MaterialPackingServiceImpl().generateVirtualUndoName(siteName);
				Date date = new Date();
				SimpleDateFormat df1 = new SimpleDateFormat("yyyy");
				String systemyear = df1.format(date);
				int i=1;
				//String receiveactNo="";
				for(Iterator<?> iterator = elementList.getChildren().iterator();iterator.hasNext();){
					
					Element mpelement = (Element)iterator.next();
					String sitename = mpelement.getChild("SITENAME").getText();
					String materialpacking = mpelement.getChild("MATERIALPACKINGNAME").getText();
					String oqaresult = mpelement.getChild("OQARESULT").getText();
					
					
					MaterialPackingKey mpkey = new MaterialPackingKey();
					mpkey.setSiteName(sitename);				
					mpkey.setMaterialPackingName(materialpacking);
					mpklist.add(mpkey);	
					
					//MaterialPacking mp = MaterialPackingServiceProxy.getMaterialPackingService().selectByKey(mpkey);
					//receiveactNo =mp.getReceiveActNo();
					SetEventInfo setevent = new SetEventInfo();
					Map<String, Object> bindMap = new HashMap<String, Object>();		
					bindMap.put("oqaResult",oqaresult);
					bindMap.put("oqaResultState",GenericServiceProxy.getConstantMap().OQA_State_End);	
					bindMap.put("packingGrade", oqaresult);						
					bindMap.put("unDoID", undoId);
					bindMap.put("unDoDetailName", "V-"+Integer.toString(i++));
											
					setevent.setUserColumns(bindMap);
					setlist.add(setevent);
				}
				//eventInfo.setEventName("NPManualOQA");
				MaterialPackingServiceProxy.getMaterialPackingService().setEvent(mpklist, eventInfo, setlist);
				
				new MaterialPackingStockInImpl().SaveOQAUnDoInfo(systemyear,undoId);
		
			}
			
			
		}catch(Exception e){
			e.getMessage();
			throw e;
		}

	}

	public void SaveNoValueOQAResult(List<MaterialPacking> mplist,EventInfo eventInfo)
			throws Exception{
		
		try {
			
			if(mplist.size()>0 ){
				
					List<MaterialPackingKey> mpklist = new ArrayList<MaterialPackingKey>();
					List<SetEventInfo> setlist = new ArrayList<SetEventInfo>();
					String undoId = new MaterialPackingServiceImpl().generateVirtualUndoName(mplist.get(0).getKey().getSiteName());
					Date date = new Date();
					SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					SimpleDateFormat df1 = new SimpleDateFormat("yyyy");
					String systemdate = df.format(date);
					String systemyear = df1.format(date);
					for(int i=0;i<mplist.size();i++){
						MaterialPacking mp = mplist.get(i);
						//MaterialUnDoinfo undo = undolist.get(i);
						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>();
	//						if(mp.getMaterialProcessGroupName().equals("OICOQA")){
	//							bindMap.put("oqaResult",result);
	//							bindMap.put("oqaResultState",GenericServiceProxy.getConstantMap().OQA_State_End);	
	//							bindMap.put("packingGrade", result);								
	//						}
	
							bindMap.put("oqaResult",mp.getOqaResult());
							bindMap.put("oqaResultState",GenericServiceProxy.getConstantMap().OQA_State_End);	
							bindMap.put("packingGrade", mp.getOqaResult());						
							bindMap.put("unDoID", undoId);
							bindMap.put("unDoDetailName", Integer.toString(i));
							//bindMap.put(key, undo.getUnDoIdDate());
												
						setevent.setUserColumns(bindMap);
						setlist.add(setevent);
						
					}
					
					MaterialPackingServiceProxy.getMaterialPackingService().setEvent(mpklist, eventInfo, setlist);
				
				new MaterialPackingStockInImpl().SaveUnDoInfo(mplist.get(0).getReceiveActNo(),systemyear,undoId);
			}
					
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw e;
		}
	
	}

	public String checkNPState(org.jdom.Document messagedocument,String oldPOnamelist1,String sitename,EventInfo eventInfo)throws Exception{
		String resultundo = "";
		if( oldPOnamelist1==null||oldPOnamelist1.equals("")){
			throw new Exception("虚拟PO号为空！ ");
		}
		
		String[] oldPOnamelist  = oldPOnamelist1.split(",");
		for(String oldPOname:oldPOnamelist){
			if(oldPOname ==null ||oldPOname.equals("")){
				break;
			}else if(oldPOname.equals("")){
				continue;
			}
			//List<MaterialUnDoinfo> Undolist= new MaterialPackingStockInUtil().GetNoPOUnDoListByPOname(oldPOname, sitename);
			List<MaterialPackingKey> mpklist= new ArrayList<MaterialPackingKey>();
			List<SetEventInfo> setlist= new ArrayList<SetEventInfo>();
			//if(Undolist.size()<=0){
				List<MaterialPacking> mplist = new MaterialPackingStockInUtil().GetNPBoxList(oldPOname, sitename);
				if (mplist.size()>0) {
					for (MaterialPacking mp : mplist) {
						if(checkBox(mp.getKey()))
						{
//							MaterialReceiveRequestDetailKey mrrdk = new MaterialReceiveRequestDetailKey();
//							mrrdk.setSiteName(mp.getKey().getSiteName());
//							mrrdk.setReceiveRequestName(mp.getReceiveRequestName());
//							mrrdk.setReceiveRequestDetailName(mp
//									.getReceiveRequestDetailName());
//							MaterialReceiveRequestDetail mrrd = ReceiveRequestDetailServiceProxy
//									.getReceiveRequestDetailService().selectByKey(
//											mrrdk);
//	
							MaterialPackingKey mpkey = new MaterialPackingKey();
							mpkey.setSiteName(mp.getKey().getSiteName());
							mpkey.setMaterialPackingName(mp.getKey()
									.getMaterialPackingName());
						
							mpklist.add(mpkey);
							
							//setlist.add(setevent);
						}

					}
					SetEventInfo setevent = new SetEventInfo();
					Map<String, Object> bindMap = new HashMap<String, Object>();
//					bindMap.put("receiveRequestName", mrrd.getErpPoName());
//					bindMap.put("receiveRequestDetailName",
//							mrrd.getErpPoDetailName());
					bindMap.put("npFlag", "N");
					eventInfo.setEventName("ChangeNPflag");
					setevent.setUserColumns(bindMap);
					MaterialPackingServiceProxy.getMaterialPackingService()
							.setEvent(mpklist, eventInfo, setevent);
				}
			//}
		}
		
		//Document document =JdomUtils.loadText(pireturn.getResultData());
		 List<String> newUnDoID = JdomUtils.getNodeTextList(messagedocument, "//Message/Body/UndoItemInfo/MATERIALUNDO/UNDOID");
		 
		
		for(int i=0;i<newUnDoID.size();i++){
			String undo = newUnDoID.get(i);
			List<String> newundo= new MaterialPackingStockInUtil().GetNewUndoIDByOldUndoID(sitename,undo);
			if(resultundo.equals("")){
				resultundo = newundo.get(i);
			}else{
				resultundo = resultundo+","+newundo.get(i);
			}
		}
		
		return resultundo;
		
	}
	
	
	public Boolean checkStock(MaterialPackingKey materialPackingKey){
		String sql="SELECT * "+
					" FROM bs_materialpackingundoinfo"+
					" WHERE"+
					" lasteventname = 'NormalStockIn'"+
					" AND MATERIALPACKINGNAME IN (SELECT MATERIALPACKINGNAME FROM BS_MATERIALPACKINGSPLITMERGE CONNECT BY DESTMATERIALPACKINGNAMENAME =PRIOR MATERIALPACKINGNAME"+
					" START WITH SITENAME = :sitename"+
					" AND DESTMATERIALPACKINGNAMENAME =:materialPackingName)"+
					" AND sitename = :sitename"+
					" AND undoidstate = 'Created'"+
					" UNION"+
					" SELECT * "+
					" FROM bs_materialpackingundoinfo"+
					" WHERE"+
					" lasteventname = 'NormalStockIn'"+
					" AND sitename = :sitename"+
					" AND undoidstate = 'Created'"+
					" AND MATERIALPACKINGNAME = :materialPackingName";
		Map<String, Object> bindmpMap = new HashMap<String, Object>();
		bindmpMap.put("materialPackingName",materialPackingKey.getMaterialPackingName());
		bindmpMap.put("sitename",materialPackingKey.getSiteName());
		List<Map<String,Object>> boxlist=IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, bindmpMap);
		if(boxlist.size()>=1)
		return true;
		else 
			return false;
	}
	
	public Boolean checkOQA(MaterialPackingKey materialPackingKey){
		String sql="SELECT * "+
				" FROM bs_materialpackingundoinfo"+
				" WHERE"+
				" lasteventname = 'OQAResult'"+
				" AND MATERIALPACKINGNAME IN (SELECT MATERIALPACKINGNAME FROM BS_MATERIALPACKINGSPLITMERGE CONNECT BY DESTMATERIALPACKINGNAMENAME =PRIOR MATERIALPACKINGNAME"+
				" START WITH SITENAME = :sitename"+
				" AND DESTMATERIALPACKINGNAMENAME =:materialpackingname)"+
				" AND sitename = :sitename"+
				" AND undoidstate = 'Created'"+
				" UNION"+
				" SELECT * "+
				" FROM bs_materialpackingundoinfo"+
				" WHERE"+
				" lasteventname = 'OQAResult'"+
				" AND sitename = :sitename"+
				" AND undoidstate = 'Created'"+
				" AND MATERIALPACKINGNAME = :materialpackingname";
		Map<String, Object> bindmpMap = new HashMap<String, Object>();
		bindmpMap.put("materialpackingname",materialPackingKey.getMaterialPackingName());
		bindmpMap.put("sitename",materialPackingKey.getSiteName());
		List<Map<String,Object>> boxlist=IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, bindmpMap);
		if(boxlist.size()>=1)
		return true;
		else 
			return false;
	}
	
	public Boolean checkBox(MaterialPackingKey materialPackingKey){
		String sql="SELECT * "+
				" FROM bs_materialpackingundoinfo"+
				" WHERE"+
				" MATERIALPACKINGNAME IN (SELECT MATERIALPACKINGNAME FROM BS_MATERIALPACKINGSPLITMERGE CONNECT BY DESTMATERIALPACKINGNAMENAME =PRIOR MATERIALPACKINGNAME"+
				" START WITH SITENAME = :SITENAME"+
				" AND DESTMATERIALPACKINGNAMENAME =:materialpackingname)"+
				" AND sitename = :SITENAME"+
				" AND undoidstate = 'Created'"+
				" AND UNDOID LIKE 'UNDO-%'"+
				" UNION"+
				" SELECT * "+
				" FROM bs_materialpackingundoinfo"+
				" WHERE"+
				" sitename = :SITENAME"+
				" AND undoidstate = 'Created'"+
				" AND UNDOID LIKE 'UNDO-%'"+
				" AND MATERIALPACKINGNAME = :materialpackingname";
		Map<String, Object> bindmpMap = new HashMap<String, Object>();
		bindmpMap.put("materialpackingname",materialPackingKey.getMaterialPackingName());
		bindmpMap.put("SITENAME",materialPackingKey.getSiteName());
		List<Map<String,Object>> boxlist=IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, bindmpMap);
		if(boxlist.size()>=1)
		return false;
		else 
			return true;
	}
public Boolean checkCancelStockIn(MaterialPackingKey materialPackingKey){
		
		if(!checkStock(materialPackingKey)){
		String sql="SELECT * "+
				" FROM bs_materialpackingundoinfo"+
				" WHERE"+
				" lasteventname = 'NPOQA'"+
				" AND MATERIALPACKINGNAME IN (SELECT MATERIALPACKINGNAME FROM BS_MATERIALPACKINGSPLITMERGE CONNECT BY DESTMATERIALPACKINGNAMENAME =PRIOR MATERIALPACKINGNAME"+
				" START WITH SITENAME = :sitename"+
				" AND DESTMATERIALPACKINGNAMENAME =:materialpackingname)"+
				" AND sitename = :sitename"+
				" AND undoidstate = 'Created'"+
				" UNION"+
				" SELECT * "+
				" FROM bs_materialpackingundoinfo"+
				" WHERE"+
				" lasteventname = 'NPOQA'"+
				" AND sitename = :sitename"+
				" AND undoidstate = 'Created'"+
				" AND MATERIALPACKINGNAME = :materialpackingname";
		Map<String, Object> bindmpMap = new HashMap<String, Object>();
		bindmpMap.put("materialpackingname",materialPackingKey.getMaterialPackingName());
		bindmpMap.put("sitename",materialPackingKey.getSiteName());
		List<Map<String,Object>> boxlist=IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, bindmpMap);
		if(boxlist.size()>=1)
		return false;
		else 
			return true;
		}
		else
			return false;
	}
	public void saveNPStockInInfo(List<MaterialUnDoinfo> UnDoList,EventInfo eventInfo,String undoId)throws Exception{
		
		try {
			List<MaterialUnDoinfo> undolist = new MaterialPackingStockInUtil().GetNoPOStockInUnDoInfoList(undoId);
			HashMap<String, String> unDoDetailNameListMap=new HashMap<String, String>();
			HashMap<String, String> oqagroupMap=new HashMap<String, String>();
			for(int i=0;i<UnDoList.size();i++)
			{
				unDoDetailNameListMap.put(undolist.get(i).getUnDoDetailName().substring(2), UnDoList.get(i).getUnDoDetailName());
				oqagroupMap.put(undolist.get(i).getUnDoDetailName().substring(2), UnDoList.get(i).getOqaname());
			}
			
			if(undolist.size()==UnDoList.size()){
				//存储新的物料凭证
				 for(int i=0;i<UnDoList.size();i++){
					List<MaterialPackingKey> materialPackingKeyList = new ArrayList<MaterialPackingKey>();
					List<SetEventInfo> setlist= new ArrayList<SetEventInfo>();
					MaterialUnDoinfo undoselect = undolist.get(i);
					MaterialUnDoinfo undoerp = UnDoList.get(i);
					List<MaterialUnDoinfo> undoselectbyundodetail = new MaterialPackingStockInUtil().GetNoPOUnDoBoxList(undoselect.getUnDoID(), undoselect.getUnDoDetailName());
					for(MaterialUnDoinfo undo :undoselectbyundodetail){
						MaterialPackingKey  keyInfo = new MaterialPackingKey();
						keyInfo.setMaterialPackingName(undo.getMaterialPackingName());
						keyInfo.setSiteName(undo.getSiteName());
						materialPackingKeyList.add(keyInfo);
						SetEventInfo setEventInfo = new SetEventInfo();
						Map<String, Object> bindmpMap = new HashMap<String, Object>();
						bindmpMap.put("unDoID",undoerp.getUnDoID());
						bindmpMap.put("unDoDetailName",unDoDetailNameListMap.get(undolist.get(i).getUnDoDetailName().substring(2)));
						bindmpMap.put("receiveRequestDetailName",undoselect.getReceiveRequestDetailName());
						bindmpMap.put("receiveRequestName", undoselect.getReceiveRequestName());
						bindmpMap.put("erpState","SUCCESS");
						
						if(undoselect.getMaterialProcessGroupName().contains("OQA-")){
							bindmpMap.put("materialProcessGroupName",oqagroupMap.get(undolist.get(i).getUnDoDetailName().substring(2)));//undoerp.getOqaname());
						}
						setEventInfo.setUserColumns(bindmpMap);
						setlist.add(setEventInfo);
					}
					eventInfo.setEventComment("NormalStockIn");
					eventInfo.setEventName("NormalStockIn");
					eventInfo.setReasonCode("0001");
					eventInfo.setReasonCodeType("101");
					MaterialPackingServiceProxy.getMaterialPackingService().setEvent(materialPackingKeyList, eventInfo, setlist);
					
					//存储新的质检批信息  新加：2016-07-29
					 if(undoselect.getMaterialProcessGroupName().contains("OQA-")){
							//bindmpMap.put("materialProcessGroupName",undoerp.getOqaname());
						 MaterialProcessGroupCreateInfo mpg = new MaterialProcessGroupCreateInfo();
							mpg.setSiteName(undoselect.getSiteName());
							mpg.setMaterialProcessGroupName(oqagroupMap.get(undolist.get(i).getUnDoDetailName().substring(2)));
							mpg.setContentMaterialType("NPOQA");
							mpg.setProcessGroupState(GenericServiceProxy
									.getConstantMap().OQA_State_Pre);
							MaterialProcessGroupServiceProxy
									.getMaterialProcessGroupService().create(
											eventInfo, mpg);
						}
				}
				 
				
				//将旧的虚拟物料凭证的状态置为N
				String sql_UndoBoxInfo="UPDATE BS_MATERIALPACKINGUNDOINFO SET UNDOIDSTATE='N' "
						+ "WHERE UNDOID=:UNDOID AND SITENAME=:SITENAME AND UNDOIDSTATE<>'N' AND LASTEVENTNAME<>'MToM'";
								
					Map<String, Object> bindMap_UndoBoxInfo = new HashMap<String, Object>();
					bindMap_UndoBoxInfo.put("SITENAME", undolist.get(0).getSiteName());
					bindMap_UndoBoxInfo.put("UNDOID", undoId);						
					IDMFrameServiceProxy.getSqlTemplate().update(sql_UndoBoxInfo, bindMap_UndoBoxInfo);
					
					//存储新的物料凭证
					new MaterialPackingStockInImpl().SaveOQAUnDoInfo(UnDoList.get(0).getUnDoIdDate(), UnDoList.get(0).getUnDoID());
					
			}
	
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw e;
		}
	//	else{
	//		throw( new Exception("erp回复物料凭证数目与实际不符！"));
	//	}
	}
	
	public void SaveManualOQAInfo(List<MaterialUnDoinfo> UnDoList,EventInfo eventInfo,String undoId)throws Exception{
		
		try {
			List<MaterialUnDoinfo> Undolist= new MaterialPackingStockInUtil().GetNoPOOQABoxList(undoId);
				HashMap<String, String> unDoDetailNameListMap=new HashMap<String, String>();
				for(int i=0;i<UnDoList.size();i++)
				{
					unDoDetailNameListMap.put(UnDoList.get(i).getSeq(), UnDoList.get(i).getUnDoDetailName());
			
				}
				
				List<MaterialPackingKey> materialPackingKeyList = new ArrayList<MaterialPackingKey>();
				List<SetEventInfo> setlist= new ArrayList<SetEventInfo>();
				//存储新的物料凭证
			 for(int i=0;i<Undolist.size();i++){
				
				MaterialPackingKey  keyInfo = new MaterialPackingKey();
				keyInfo.setMaterialPackingName(Undolist.get(i).getMaterialPackingName());
				keyInfo.setSiteName(Undolist.get(i).getSiteName());
				materialPackingKeyList.add(keyInfo);
				SetEventInfo setEventInfo = new SetEventInfo();
				Map<String, Object> bindmpMap = new HashMap<String, Object>();
				bindmpMap.put("unDoID",UnDoList.get(i).getUnDoID());
				bindmpMap.put("erpState","SUCCESS");
				bindmpMap.put("unDoDetailName",unDoDetailNameListMap.get(UnDoList.get(i).getUnDoDetailName()));
				setEventInfo.setUserColumns(bindmpMap);
				setlist.add(setEventInfo);
			}
			 eventInfo.setEventComment("ChangeOQAResult");
			 eventInfo.setEventName("ChangeOQAResult");
			MaterialPackingServiceProxy.getMaterialPackingService().setEvent(materialPackingKeyList, eventInfo, setlist);
			//将旧的虚拟物料凭证的状态置为N
			String sql_UndoBoxInfo="UPDATE BS_MATERIALPACKINGUNDOINFO SET UNDOIDSTATE='N' "
					+ "WHERE UNDOID=:UNDOID AND SITENAME=:SITENAME AND UNDOIDSTATE<>'N' AND LASTEVENTNAME<>'MToM'";
							
				Map<String, Object> bindMap_UndoBoxInfo = new HashMap<String, Object>();
				bindMap_UndoBoxInfo.put("SITENAME", Undolist.get(0).getSiteName());
				bindMap_UndoBoxInfo.put("UNDOID", undoId);						
				IDMFrameServiceProxy.getSqlTemplate().update(sql_UndoBoxInfo, bindMap_UndoBoxInfo);
				
				//存储新的物料凭证
				new MaterialPackingStockInImpl().SaveUnDoInfo(Undolist.get(0).getReceiveActNo(), UnDoList.get(0).getUnDoIdDate(), UnDoList.get(0).getUnDoID());

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw e;
		}
			
	}
	
	public void SaveOQAMessageInfo(EventInfo eventInfo,MaterialUnDoinfo undoinfo,String undoId)throws Exception{
		
		try {
			List<MaterialUnDoinfo> Undolist= new MaterialPackingStockInUtil().GetNoPOOQABoxList(undoId);
			List<MaterialPackingKey> keyList = new ArrayList<MaterialPackingKey>();
			if (Undolist.size()>0) {
				for (MaterialUnDoinfo mp : Undolist) {
					MaterialPackingKey mpk = new MaterialPackingKey();
					mpk.setSiteName(mp.getSiteName());
					mpk.setMaterialPackingName(mp.getMaterialPackingName());
					keyList.add(mpk);
				}
				//存储BOX信息
				SetEventInfo setevent = new SetEventInfo();
				Map<String, Object> bindMap = new HashMap<String, Object>();
				bindMap.put("oqaResultState",
						GenericServiceProxy.getConstantMap().OQA_State_End);//以后改成可传参的
				bindMap.put("unDoID", undoinfo.getUnDoID());
				bindMap.put("unDoDetailName", undoinfo.getUnDoDetailName());
				bindMap.put("erpState","SUCCESS");
				setevent.setUserColumns(bindMap);
				eventInfo.setEventComment("OQAResult");
				eventInfo.setEventName("OQAResult");
				MaterialPackingServiceProxy.getMaterialPackingService()
						.setEvent(keyList, eventInfo, setevent);
				//将旧的虚拟物料凭证的状态置为N
				String sql_UndoBoxInfo = "UPDATE BS_MATERIALPACKINGUNDOINFO SET UNDOIDSTATE='N' "
						+ "WHERE UNDOID=:UNDOID AND SITENAME=:SITENAME AND UNDOIDSTATE<>'N' AND LASTEVENTNAME<>'MToM'";
				Map<String, Object> bindMap_UndoBoxInfo = new HashMap<String, Object>();
				bindMap_UndoBoxInfo.put("SITENAME", keyList.get(0)
						.getSiteName());
				bindMap_UndoBoxInfo.put("UNDOID", undoId);
				IDMFrameServiceProxy.getSqlTemplate()
						.update(sql_UndoBoxInfo, bindMap_UndoBoxInfo);
				//存储undo信息
				new MaterialPackingStockInImpl().SaveOQAUnDoInfo(
						undoinfo.getUnDoDetailName(), undoinfo.getUnDoID());
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw e;
		}
	}
	public void NPCancleStockOut(EventInfo eventInfo, String siteName,
			String shipRequestName,String shipRequestDetailName)
	{
		//yk
		Map<String, Object> bindMap = new HashMap<String, Object>();
		bindMap.put("SHIPREQUESTNAME", shipRequestName);
		bindMap.put("SHIPREQUESTDETAILNAME", shipRequestDetailName);	
		Map<String, Object> npFlag = new HashMap<String, Object>();
		npFlag.put("npFlag", "N");
		Map<String, Object> stockState = new HashMap<String, Object>();
		stockState.put("stockState", "Stocked");
		Map<String, Object> bindingShipRequest = new HashMap<String, Object>();
		bindingShipRequest.put("shipRequestName", "");
		bindingShipRequest.put("shipRequestDetailName", "");
		//检查是否已和ERP过账
		String SQLCheckERPStockOutState ="Select NPFLAG from MATERIALPACKING where shipRequestName =:SHIPREQUESTNAME and shipRequestDetailName =:SHIPREQUESTDETAILNAME and npFlag='N'";
		//查出行项中的Box
		String SQLSelectBox = "Select sitename,materialpackingname from MATERIALPACKING where shipRequestName =:SHIPREQUESTNAME and shipRequestDetailName =:SHIPREQUESTDETAILNAME";
		//修改Undo信息使取消的Box不参与过账
		String SQLUpdateUndoInfo ="update bs_materialpackingundoinfo set undoIdState='N' where materialPackingName =:MATERIALPACKINGNAME and shipRequestName=:SHIPREQUESTNAME and shipRequestDetailName =:SHIPREQUESTDETAILNAME and lastEventName ='CompleteNpShipRequest'";
		//修改行项绑定数量，解绑Box，修改Box的状态
		String SQLCleanShipRequestDetail = "update MATERIALSHIPREQUESTDETAIL set AssignedQuantity=0 where shipRequestName =:SHIPREQUESTNAME and shipRequestDetailName =:SHIPREQUESTDETAILNAME";
		String SQLCleanShipRequest = "update MATERIALSHIPREQUEST set SHIPREQUESTSTATE='Created' where shipRequestName =:SHIPREQUESTNAME ";
		List<Map<String, Object>> name;
		try {
			name = IDMFrameServiceProxy.getSqlTemplate().queryForList(SQLCheckERPStockOutState, bindMap);				
		if (name.size()==0)
		{
			List<Map<String, Object>> keyList = IDMFrameServiceProxy.getSqlTemplate()
			.queryForList(SQLSelectBox, bindMap);
			if(keyList!=null)
			{
				for(Map<String, Object> key:keyList)
				{
					Map<String, Object> boxBindMap = new HashMap<String, Object>();
					boxBindMap.put("MATERIALPACKINGNAME", key.get("MATERIALPACKINGNAME").toString());
					boxBindMap.put("SHIPREQUESTNAME",shipRequestName);
					boxBindMap.put("SHIPREQUESTDETAILNAME",shipRequestDetailName);
					MaterialPackingKey mKey = new MaterialPackingKey();
					mKey.setMaterialPackingName(key.get("MATERIALPACKINGNAME").toString());
					mKey.setSiteName(key.get("SITENAME").toString());
					if(checkOQA(mKey))
					{						
						SetEventInfo setEventInfo = new SetEventInfo();
						setEventInfo.setUserColumns(npFlag);
						setEventInfo.setUserColumns(stockState);
						setEventInfo.setUserColumns(bindingShipRequest);
						MaterialPackingServiceProxy.getMaterialPackingService().setEvent(mKey, eventInfo, setEventInfo);
					}
					else
					{
						SetEventInfo setEventInfo = new SetEventInfo();
						setEventInfo.setUserColumns(stockState);
						setEventInfo.setUserColumns(bindingShipRequest);
						MaterialPackingServiceProxy.getMaterialPackingService().setEvent(mKey, eventInfo, setEventInfo);
					}
					IDMFrameServiceProxy.getSqlTemplate()
					.update(SQLUpdateUndoInfo, boxBindMap);
				}
			}				
		}
		
						
		IDMFrameServiceProxy.getSqlTemplate()
		.update(SQLCleanShipRequestDetail, bindMap);
		IDMFrameServiceProxy.getSqlTemplate()
		.update(SQLCleanShipRequest, bindMap);
		} catch (DataAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void cancelStockIn(EventInfo eventInfo,String siteName,String receiveActNo,String receiveRequest) throws Exception
	{
		try{
			//删除无PO取消入库的Box
			String sqlBox="delete from materialpacking a where a.receiveactno=:receiveActNo and a.sitename=:siteName";
			Map<String, Object> bindMapBox = new HashMap<String, Object>();
			bindMapBox.put("receiveActNo", receiveActNo);
			bindMapBox.put("siteName", siteName);
			IDMFrameServiceProxy.getSqlTemplate()
			.update(sqlBox, bindMapBox);
			
			//删除无PO创建Box时的虚拟po
			String sqlPo="delete from materialreceiverequest a where a.sitename=:siteName and a.receiverequestname=:receiveRequestName";
			String sqlPoDetail="delete from materialreceiverequestdetail a where a.sitename=:siteName and a.receiverequestname=:receiveRequestName";
			Map<String, Object> bindMapPo = new HashMap<String, Object>();
			bindMapPo.put("receiveRequestName", receiveRequest);
			bindMapPo.put("siteName", siteName);
			IDMFrameServiceProxy.getSqlTemplate()
			.update(sqlPo, bindMapPo);
			IDMFrameServiceProxy.getSqlTemplate()
			.update(sqlPoDetail, bindMapPo);
			
			//删除无Po的抬头文本
			String sqlAct="delete from materialreceiveact a where a.sitename=:siteName and a.receiveactno=:receiveActNo and a.receiverequestname=:receiveRequestName";
			String sqlActDetail="delete from materialreceiveactdetail a where a.sitename=:siteName and a.receiveactno=:receiveActNo and a.receiverequestname=:receiveRequestName";
			Map<String, Object> bindMapAct = new HashMap<String, Object>();
			bindMapAct.put("receiveRequestName", receiveRequest);
			bindMapAct.put("siteName", siteName);
			bindMapAct.put("receiveActNo", receiveActNo);
			IDMFrameServiceProxy.getSqlTemplate()
			.update(sqlAct, bindMapAct);
			IDMFrameServiceProxy.getSqlTemplate()
			.update(sqlActDetail, bindMapAct);
			
		}
		catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw e;
		}
	}
	public void getMaterialPackingKey(String siteName,String receiveRequest) throws Exception
	{
		try{
			//根据无PO单据获取所有Box
			 String sql = "select siteName ,materialPackingName from materialPacking where receiveRequestName=:receiveRequestName and "
		    	   		+ " sitename =:sitename";
		    	   
		    	   Map<String, Object> bindMap = new HashMap<String, Object>();
		    	   
		    	   bindMap.put("receiveRequestName", receiveRequest);
		    	   bindMap.put("sitename", siteName);
		    	   
		    	   List<Map<String, Object>> arg =IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, bindMap);
			
		    	   int i=0;
		    	   MaterialPackingNoPOStockInImpl objMaterialPackingNoPOStockInImpl = new MaterialPackingNoPOStockInImpl();
		    	   
		    	   List<MaterialPackingKey> materialPakcingKeyList = new ArrayList<MaterialPackingKey>();
			
		    	   for(;i<arg.size();i++)
		    	   {
		    		   MaterialPackingKey objMaterialPackingKey = new MaterialPackingKey();
		    		   objMaterialPackingKey.setSiteName(siteName);
		    		   objMaterialPackingKey.setMaterialPackingName(arg.get(i).get("MATERIALPACKINGNAME").toString());
		    		   
		    		   //检查是否可以做取消入库
		    		   if(objMaterialPackingNoPOStockInImpl.checkCancelStockIn(objMaterialPackingKey))
		    		   {
		    			   materialPakcingKeyList.add(objMaterialPackingKey);
		    		   }
		    		   else
		    		   {
		    			   throw new CustomException("PK-0001", "", ""); 
		    		   }
		    		   
		    	   }
		}
		catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw e;
		}
	}
}
