package com.dev.swms.server.service.interfaceLog.pojo;

import java.io.StringWriter;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import com.dev.swms.server.model.base.Address;
import com.dev.swms.server.model.base.BillType;
import com.dev.swms.server.model.base.Contact;
import com.dev.swms.server.model.base.Item;
import com.dev.swms.server.model.base.Location;
import com.dev.swms.server.model.base.LocationType;
import com.dev.swms.server.model.base.LotInfo;
import com.dev.swms.server.model.base.NewLotInfo;
import com.dev.swms.server.model.base.Store;
import com.dev.swms.server.model.base.Structure;
import com.dev.swms.server.model.base.PackageUnit;
import com.dev.swms.server.model.base.Warehouse;
import com.dev.swms.server.model.interfaceLog.AvaliableOrderResponse;
import com.dev.swms.server.model.interfaceLog.InterfaceLog;
import com.dev.swms.server.model.interfaceLog.InterfaceLogConstant;
import com.dev.swms.server.model.interfaceLog.ResponseCode;
import com.dev.swms.server.model.interfaces.InterfaceWmsAddress;
import com.dev.swms.server.model.interfaces.InterfaceWmsDiary;
import com.dev.swms.server.model.interfaces.InterfaceWmsDownload;
import com.dev.swms.server.model.interfaces.InterfaceWmsItem;
import com.dev.swms.server.model.interfaces.InterfaceWmsOut;
import com.dev.swms.server.model.interfaces.InterfaceWmsOutReturn;
import com.dev.swms.server.model.interfaces.InterfaceWmsProject;
import com.dev.swms.server.model.interfaces.InterfaceWmsPurchase;
import com.dev.swms.server.model.interfaces.InterfaceWmsReturn;
import com.dev.swms.server.model.interfaces.InterfaceWmsUnit;
import com.dev.swms.server.model.interfaces.InterfaceWmsWarehouse;
import com.dev.swms.server.model.inventory.ProductInventory;
import com.dev.swms.server.model.receiving.ASN;
import com.dev.swms.server.model.receiving.ASNDetail;
import com.dev.swms.server.model.receiving.ASNStatus;
import com.dev.swms.server.model.receiving.MoveDoc;
import com.dev.swms.server.model.receiving.MoveDocDetail;
import com.dev.swms.server.model.shipping.BOL;
import com.dev.swms.server.model.shipping.Package;
import com.dev.swms.server.model.shipping.PickTicket;
import com.dev.swms.server.model.shipping.PickTicketDetail;
import com.dev.swms.server.model.shipping.PickTicketStatus;
import com.dev.swms.server.service.base.ItemManager;
import com.dev.swms.server.service.interfaceLog.InterfaceItemManager;
import com.dev.swms.server.service.interfaceLog.InterfaceLogManager;
import com.dev.swms.server.service.inventory.InventoryManager;
import com.dev.swms.server.service.receiving.ASNManager;
import com.dev.swms.server.service.sequence.BussinessCodeManager;
import com.dev.swms.server.service.shipping.PickTicketManager;
import com.dev.swms.server.utils.ConnectionHelper;
import com.dev.swms.server.utils.DateUtil;
import com.dev.swms.server.utils.DoubleUtils;
import com.dev.swms.server.utils.ServerUnreachableException;
import com.dev.swms.server.utils.XMLUtils;
import com.dev.swms.server.web.filter.WarehouseHolder;
import com.dev.energy.server.exception.BusinessException;
import com.dev.energy.server.model.EntityFactory;
import com.dev.energy.server.service.pojo.DefaultBaseManager;
import com.dev.energy.server.web.security.UserHolder;

public class DefaultInterfaceItemManager extends DefaultBaseManager implements
		InterfaceItemManager {
	protected Log log = LogFactory.getLog(DefaultInterfaceLogManager.class);
	public static final int TIMES_PER = 20;
	
	protected InventoryManager inventoryManager;
	protected ConnectionHelper connectionHelper;
	protected ItemManager itemManager;
	protected PickTicketManager pickTicketManager;
	protected  BussinessCodeManager bussinessCodeManager;
	protected ASNManager asnManager;
	
	public DefaultInterfaceItemManager(InventoryManager manager, ConnectionHelper helper,
			ItemManager itemManager,PickTicketManager pickTicketManager,
			BussinessCodeManager bussinessCodeManager,ASNManager asnManager) {
		super();
		this.inventoryManager = manager;
		this.connectionHelper = helper;
		this.itemManager=itemManager;
		this.pickTicketManager=pickTicketManager;
		this.bussinessCodeManager=bussinessCodeManager;
		this.asnManager=asnManager;
	}

	public void storeItem( String xml) {
		Document xmlDoc=null;
		try {
			xmlDoc = DocumentHelper.parseText(xml.trim());
		} catch (DocumentException e) {
			if(logger.isDebugEnabled()) {
				e.printStackTrace();
			} 
		}
		Element root = xmlDoc.getRootElement();
		Element body = root.element("Body"); 
		Element ShowF57WEH13ResponseElement = body.element("ShowF57WEH13ResponseElement"); 
		List<Element> list = ShowF57WEH13ResponseElement.elements() ;
		for (Element show:list){
			if(show.getName().equals("Outs")){
				System.out.println(show.elementTextTrim("Identifier2ndItem"));
				String Identifier2ndItem=show.elementTextTrim("Identifier2ndItem");
				String CostCenter=show.elementTextTrim("CostCenter");
				String SessionID=show.elementTextTrim("SessionID");
				String YesOrNoEntry=show.elementTextTrim("YesOrNoEntry");
				String DateUpdated=show.elementTextTrim("DateUpdated");
				String TimeLastUpdated=show.elementTextTrim("TimeLastUpdated");
				String UserId=show.elementTextTrim("UserId");
				String DescriptionLine1=show.elementTextTrim("DescriptionLine1");
				String UnitOfMeasurePrimary=show.elementTextTrim("UnitOfMeasurePrimary");
				InterfaceWmsItem item=EntityFactory.getEntity(InterfaceWmsItem.class);
				item.setIdentifier2ndItem(Identifier2ndItem);
				item.setCostCenter(CostCenter);
				item.setSessionID(SessionID);
				item.setYesOrNoEntry(YesOrNoEntry);
				item.setDateUpdated(DateUpdated);
				item.setTimeLastUpdated(TimeLastUpdated);
				item.setUserId(UserId);
				item.setDescriptionLine1(DescriptionLine1);
				item.setUnitOfMeasurePrimary(UnitOfMeasurePrimary);
				item.setStatus("READY");
				item.setCreateDate(new Date());
				this.commonDao.store(item);
			}
		}
	}
	
	public void storeAddress( String xml) {
		Document xmlDoc=null;
		try {
			xmlDoc = DocumentHelper.parseText(xml.trim());
		} catch (DocumentException e) {
			if(logger.isDebugEnabled()) {
				e.printStackTrace();
			} 
		}
		Element root = xmlDoc.getRootElement();
		Element body = root.element("Body"); 
		Element ShowF57WEH14ResponseElement = body.element("ShowF57WEH14ResponseElement"); 
		List<Element> list = ShowF57WEH14ResponseElement.elements() ;
		for (Element show:list){
			if(show.getName().equals("Outs")){
				System.out.println(show.elementTextTrim("AddressNumber"));
				String AddressNumber=show.elementTextTrim("AddressNumber");
				String DateUpdated=show.elementTextTrim("DateUpdated");
				String TimeLastUpdated=show.elementTextTrim("TimeLastUpdated");
				String YesOrNoEntry=show.elementTextTrim("YesOrNoEntry");
				String UserId=show.elementTextTrim("UserId");
				String NameAlpha=show.elementTextTrim("NameAlpha");
				String AddressType1=show.elementTextTrim("AddressType1");
				String LineNumberID=show.elementTextTrim("LineNumberID");
				String NameMailing=show.elementTextTrim("NameMailing");
				String PhoneNumber=show.elementTextTrim("PhoneNumber");
				String EmailAddressow=show.elementTextTrim("EmailAddressow");
				String AddressLine1=show.elementTextTrim("AddressLine1");
				String AddressLine2=show.elementTextTrim("AddressLine2");
				String AddressLine3=show.elementTextTrim("AddressLine3");
				String AddressLine4=show.elementTextTrim("AddressLine4");
				String City=show.elementTextTrim("City");
				String CountyAddress=show.elementTextTrim("CountyAddress");
				String State=show.elementTextTrim("State");
				InterfaceWmsAddress address=EntityFactory.getEntity(InterfaceWmsAddress.class);
				address.setAddressNumber(AddressNumber);
				address.setDateUpdated(DateUpdated);
				address.setTimeLastUpdated(TimeLastUpdated);
				address.setYesOrNoEntry(YesOrNoEntry);
				address.setUserId(UserId);
				address.setNameAlpha(NameAlpha);
				address.setAddressType1(AddressType1);
				address.setLineNumberID(LineNumberID);
				address.setNameMailing(NameMailing);
				address.setPhoneNumber(PhoneNumber);
				address.setEmailAddressow(EmailAddressow);
				address.setAddressLine1(AddressLine1);
				address.setAddressLine2(AddressLine2);
				address.setAddressLine3(AddressLine3);
				address.setAddressLine4(AddressLine4);
				address.setCity(City);
				address.setCountyAddress(CountyAddress);
				address.setState(State);
				address.setStatus("READY");
				address.setCreateDate(new Date());
				this.commonDao.store(address);
			}
		}
	}
	
	public void storeUnit( String xml) {
		Document xmlDoc=null;
		try {
			xmlDoc = DocumentHelper.parseText(xml.trim());
		} catch (DocumentException e) {
			if(logger.isDebugEnabled()) {
				e.printStackTrace();
			} 
		}
		Element root = xmlDoc.getRootElement();
		Element body = root.element("Body");                
		Element ShowF57WEH15ResponseElement = body.element("ShowF57WEH15ResponseElement"); 
		List<Element> list = ShowF57WEH15ResponseElement.elements() ;
		for (Element show:list){
			if(show.getName().equals("Outs")){
				System.out.println(show.elementTextTrim("UnitOfMeasure"));
				String UnitOfMeasure=show.elementTextTrim("UnitOfMeasure");
				String RelatedUnitOfMeasure=show.elementTextTrim("RelatedUnitOfMeasure");
				String SessionID=show.elementTextTrim("SessionID");
				String Identifier2ndItem=show.elementTextTrim("Identifier2ndItem");
				String YesOrNoEntry=show.elementTextTrim("YesOrNoEntry");
				String DateUpdated=show.elementTextTrim("DateUpdated");
				String UserId=show.elementTextTrim("UserId");
				String TimeLastUpdated=show.elementTextTrim("TimeLastUpdated");
				String ConversionFactor=show.elementTextTrim("ConversionFactor");
				
				InterfaceWmsUnit unit=EntityFactory.getEntity(InterfaceWmsUnit.class);
				unit.setUnitOfMeasure(UnitOfMeasure);
				unit.setRelatedUnitOfMeasure(RelatedUnitOfMeasure);
				unit.setSessionID(SessionID);
				unit.setIdentifier2ndItem(Identifier2ndItem);
				unit.setYesOrNoEntry(YesOrNoEntry);
				unit.setDateUpdated(DateUpdated);
				unit.setUserId(UserId);
				unit.setTimeLastUpdated(TimeLastUpdated);
				unit.setConversionFactor(ConversionFactor);
				unit.setStatus("READY");
				unit.setCreateDate(new Date());
				this.commonDao.store(unit);
			}
		}
	}
	
	/**接收临时销售单发送数据Out*/
	public void storeOut( String xml) {
		Document xmlDoc=null;
		try {
			xmlDoc = DocumentHelper.parseText(xml.trim());
		} catch (DocumentException e) {
			if(logger.isDebugEnabled()) {
				e.printStackTrace();
			} 
		}
		Element root = xmlDoc.getRootElement();
		Element body = root.element("Body");   
		Element ShowF57WEH01ResponseElement  = body.element("ShowF57WEH01ResponseElement"); 
		List<Element> list = ShowF57WEH01ResponseElement.elements() ;
		System.out.println("outs====="+list.size());
		for (Element show:list){
			if(show.getName().equals("Outs")){
				System.out.println(show.elementTextTrim("UnitOfMeasure"));
				String CompanyKeyOrderNo=show.elementTextTrim("CompanyKeyOrderNo");
				String OrderType=show.elementTextTrim("OrderType");
				String DocumentOrderInvoiceE=show.elementTextTrim("DocumentOrderInvoiceE");
				String LineNumber=show.elementTextTrim("LineNumber");
				String CostCenter=show.elementTextTrim("CostCenter");
				String CostCenterHeader=show.elementTextTrim("CostCenterHeader");
				String DateTransactionJulian=show.elementTextTrim("DateTransactionJulian");
				String DateRequestedJulian=show.elementTextTrim("DateRequestedJulian");
				String AddressNumber=show.elementTextTrim("AddressNumber");
				String AddressNumberShipTo=show.elementTextTrim("AddressNumberShipTo");
				String Identifier2ndItem=show.elementTextTrim("Identifier2ndItem");
				String UnitsTransactionQty=show.elementTextTrim("UnitsTransactionQty");
				String UnitOfMeasurePrimary=show.elementTextTrim("UnitOfMeasurePrimary");
				String SessionID=show.elementTextTrim("SessionID");
				String Description001=show.elementTextTrim("Description001");
				String YesOrNoEntry=show.elementTextTrim("YesOrNoEntry");
				String UserId=show.elementTextTrim("UserId");
				String ProgramId=show.elementTextTrim("ProgramId");
				String WorkStationId=show.elementTextTrim("WorkStationId");
				String DateUpdated=show.elementTextTrim("DateUpdated");
				String TimeLastUpdated=show.elementTextTrim("TimeLastUpdated");
				String IsNegative =show.elementTextTrim("IsNegative");
				InterfaceWmsOut out=EntityFactory.getEntity(InterfaceWmsOut.class);
				out.setCompanyKeyOrderNo(CompanyKeyOrderNo);
				out.setOrderType(OrderType);
				out.setDocumentOrderInvoiceE(DocumentOrderInvoiceE);
				out.setLineNumber(LineNumber);
				out.setCostCenter(CostCenter);
				out.setCostCenterHeader(CostCenterHeader);
				out.setDateTransactionJulian(DateTransactionJulian);
				out.setDateRequestedJulian(DateRequestedJulian);
                out.setAddressNumber(AddressNumber);
                out.setAddressNumberShipTo(AddressNumberShipTo);
                out.setIdentifier2ndItem(Identifier2ndItem);
                out.setUnitsTransactionQty(UnitsTransactionQty);
                out.setUnitOfMeasurePrimary(UnitOfMeasurePrimary);
                out.setSessionID(SessionID);
                out.setDescription001(Description001);
				out.setYesOrNoEntry(YesOrNoEntry);
				out.setUserId(UserId);
				out.setProgramId(ProgramId);
				out.setWorkStationId(WorkStationId);
				out.setDateUpdated(DateUpdated);
				out.setTimeLastUpdated(TimeLastUpdated);
				out.setIsNegative(IsNegative);
				out.setStatus("READY");
				out.setCreateDate(new Date());
				this.commonDao.store(out);
			}
		}
	}
	
	/**接收临时销售单发送数据OutReturn*/
	public void storeOutReturn( String xml) {
		Document xmlDoc=null;
		try {
			xmlDoc = DocumentHelper.parseText(xml.trim());
		} catch (DocumentException e) {
			if(logger.isDebugEnabled()) {
				e.printStackTrace();
			} 
		}
		Element root = xmlDoc.getRootElement();
		Element body = root.element("Body"); 
		Element howF57WEH02ResponseElement = body.element("howF57WEH02ResponseElement"); 
		List<Element> list = howF57WEH02ResponseElement.elements() ;
		for (Element show:list){
			if(show.getName().equals("Outs")){
				System.out.println(show.elementTextTrim("UnitOfMeasure"));
				String CompanyKeyOrderNo=show.elementTextTrim("CompanyKeyOrderNo");
				String OrderType=show.elementTextTrim("OrderType");
				String DocumentOrderInvoiceE=show.elementTextTrim("DocumentOrderInvoiceE");
				String LineNumber=show.elementTextTrim("LineNumber");
				String CostCenter=show.elementTextTrim("CostCenter");
				String CostCenterHeader=show.elementTextTrim("CostCenterHeader");
				String DateTransactionJulian=show.elementTextTrim("DateTransactionJulian");
				String DateRequestedJulian=show.elementTextTrim("DateRequestedJulian");
				String AddressNumber=show.elementTextTrim("AddressNumber");
				String AddressNumberShipTo=show.elementTextTrim("AddressNumberShipTo");
				String Identifier2ndItem=show.elementTextTrim("Identifier2ndItem");
				String UnitsTransactionQty=show.elementTextTrim("UnitsTransactionQty");
				String UnitOfMeasurePrimary=show.elementTextTrim("UnitOfMeasurePrimary");
				String SessionID=show.elementTextTrim("SessionID");
				String Description001=show.elementTextTrim("Description001");
				String YesOrNoEntry=show.elementTextTrim("YesOrNoEntry");
				String UserId=show.elementTextTrim("UserId");
				String ProgramId=show.elementTextTrim("ProgramId");
				String WorkStationId=show.elementTextTrim("WorkStationId");
				String DateUpdated=show.elementTextTrim("DateUpdated");
				String TimeLastUpdated=show.elementTextTrim("TimeLastUpdated");
				String IsNegative =show.elementTextTrim("IsNegative");
				//String Status =show.elementTextTrim("Status");
				//String CreateDate =show.elementTextTrim("CreateDate");
				InterfaceWmsOutReturn outReturn=EntityFactory.getEntity(InterfaceWmsOutReturn.class);
				outReturn.setCompanyKeyOrderNo(CompanyKeyOrderNo);
				outReturn.setOrderType(OrderType);
				outReturn.setDocumentOrderInvoiceE(DocumentOrderInvoiceE);
				outReturn.setLineNumber(LineNumber);
				outReturn.setCostCenter(CostCenter);
				outReturn.setCostCenterHeader(CostCenterHeader);
				outReturn.setDateTransactionJulian(DateTransactionJulian);
				outReturn.setDateRequestedJulian(DateRequestedJulian);
				outReturn.setAddressNumber(AddressNumber);
				outReturn.setAddressNumberShipTo(AddressNumberShipTo);
				outReturn.setIdentifier2ndItem(Identifier2ndItem);
				outReturn.setUnitsTransactionQty(UnitsTransactionQty);
				outReturn.setUnitOfMeasurePrimary(UnitOfMeasurePrimary);
				outReturn.setSessionID(SessionID);
				outReturn.setDescription001(Description001);
				outReturn.setYesOrNoEntry(YesOrNoEntry);
				outReturn.setUserId(UserId);
				outReturn.setProgramId(ProgramId);
				outReturn.setWorkStationId(WorkStationId);
				outReturn.setDateUpdated(DateUpdated);
				outReturn.setTimeLastUpdated(TimeLastUpdated);
				outReturn.setIsNegative(IsNegative);
				outReturn.setStatus("READY");
				outReturn.setCreateDate(new Date());
				this.commonDao.store(outReturn);
			}
		}
	}
	
	/**接收临时采购单发送数据Purchase*/
	public void storePurchase( String xml) {
		Document xmlDoc=null;
		try {
			xmlDoc = DocumentHelper.parseText(xml.trim());
		} catch (DocumentException e) {
			if(logger.isDebugEnabled()) {
				e.printStackTrace();
			} 
		}
		Element root = xmlDoc.getRootElement();
		Element body = root.element("Body"); 
		Element ShowF57WEH07ResponseElement = body.element("ShowF57WEH07ResponseElement"); 
		List<Element> list = ShowF57WEH07ResponseElement.elements() ;
		for (Element show:list){
			if(show.getName().equals("Outs")){
				String companyKeyOrderNo =show.elementTextTrim("companyKeyOrderNo");
				String documentNumber =show.elementTextTrim("documentNumber");
				String orderType =show.elementTextTrim("orderType");
				String orderSuffix =show.elementTextTrim("orderSuffix");
				String lineNumber =show.elementTextTrim("lineNumber");
				String costCenter =show.elementTextTrim("costCenter");
				String company =show.elementTextTrim("company");
				String companyKeyOriginal =show.elementTextTrim("companyKeyOriginal");
				String addressNumber =show.elementTextTrim("addressNumber");
				String addressNumberShipTo =show.elementTextTrim("addressNumberShipTo");
				String dateRequestedJulian =show.elementTextTrim("dateRequestedJulian");
				String dateTransactionJulian =show.elementTextTrim("dateTransactionJulian");
				String scheduledPickDate =show.elementTextTrim("scheduledPickDate");
				String actualShipDate =show.elementTextTrim("actualShipDate");
				String identifier2ndItem =show.elementTextTrim("identifier2ndItem");
				String descriptionLine1 =show.elementTextTrim("descriptionLine1");
				String descriptionLine2 =show.elementTextTrim("descriptionLine2");
				String unitOfMeasureAsInput =show.elementTextTrim("unitOfMeasureAsInput");
				String unitsTransactionQty  =show.elementTextTrim("unitsTransactionQty");
				String everestEventPoint01  =show.elementTextTrim("everestEventPoint01");
				String transactionOriginator  =show.elementTextTrim("transactionOriginator");
				String userId  =show.elementTextTrim("userId");
				String dateUpdated  =show.elementTextTrim("dateUpdated");
				String sessionID  =show.elementTextTrim("sessionID");
				String description001  =show.elementTextTrim("description001");
				String yesOrNoEntry  =show.elementTextTrim("yesOrNoEntry");
				String timeLastUpdated  =show.elementTextTrim("timeLastUpdated");
				InterfaceWmsPurchase purchase=EntityFactory.getEntity(InterfaceWmsPurchase.class);
				purchase.setCompanyKeyOrderNo(companyKeyOrderNo);
				purchase.setDocumentNumber(documentNumber);
				purchase.setOrderType(orderType);
				purchase.setOrderSuffix(orderSuffix); 
				purchase.setLineNumber(lineNumber); 
				purchase.setCostCenter(costCenter);
				purchase.setCompany(company);
				purchase.setCompanyKeyOriginal(companyKeyOriginal);
				purchase.setAddressNumber(addressNumber);
				purchase.setAddressNumberShipTo(addressNumberShipTo);
				purchase.setDateRequestedJulian(dateRequestedJulian);
				purchase.setDateTransactionJulian(dateTransactionJulian);
				purchase.setScheduledPickDate(scheduledPickDate);
				purchase.setActualShipDate(actualShipDate);
				purchase.setIdentifier2ndItem(identifier2ndItem);
				purchase.setDescriptionLine1(descriptionLine1);
				purchase.setDescriptionLine2(descriptionLine2);
				purchase.setUnitOfMeasureAsInput(unitOfMeasureAsInput);
				purchase.setUnitsTransactionQty(unitsTransactionQty);
				purchase.setEverestEventPoint01(everestEventPoint01);
				purchase.setTransactionOriginator(transactionOriginator);;
				purchase.setUserId(userId);
				purchase.setDateUpdated(dateUpdated); 
				purchase.setSessionID(sessionID); 
				purchase.setDescription001(description001); 
				purchase.setYesOrNoEntry(yesOrNoEntry); 
				purchase.setTimeLastUpdated(timeLastUpdated);
				purchase.setStatus("READY");
				purchase.setCreateDate(new Date());
				this.commonDao.store(purchase);
			}
		}
	}
	
	/**接收临时采购退货单发送数据Return*/
	public void storeReturn( String xml) {
		Document xmlDoc=null;
		try {
			xmlDoc = DocumentHelper.parseText(xml.trim());
		} catch (DocumentException e) {
			if(logger.isDebugEnabled()) {
				e.printStackTrace();
			} 
		}
		Element root = xmlDoc.getRootElement();
		Element body = root.element("Body");                
		Element ShowF57WEH08ResponseElement = body.element("ShowF57WEH08ResponseElement"); 
		List<Element> list = ShowF57WEH08ResponseElement.elements() ;
		for (Element show:list){
			if(show.getName().equals("Outs")){
				String companyKeyOrderNo  =show.elementTextTrim("companyKeyOrderNo");
				String documentNumber  =show.elementTextTrim("documentNumber");
				String orderType =show.elementTextTrim("orderType");
				String orderSuffix =show.elementTextTrim("orderSuffix");
				String lineNumber =show.elementTextTrim("lineNumber");
				String costCenter =show.elementTextTrim("costCenter");
				String company =show.elementTextTrim("company");
				String companyKeyOriginal =show.elementTextTrim("companyKeyOriginal");
				String addressNumber =show.elementTextTrim("addressNumber");
				String addressNumberShipTo =show.elementTextTrim("addressNumberShipTo");
				String dateRequestedJulian =show.elementTextTrim("dateRequestedJulian");
				String dateTransactionJulian =show.elementTextTrim("dateTransactionJulian");
				String scheduledPickDate =show.elementTextTrim("scheduledPickDate");
				String actualShipDate =show.elementTextTrim("actualShipDate");
				String identifier2ndItem =show.elementTextTrim("identifier2ndItem");
				String descriptionLine1 =show.elementTextTrim("descriptionLine1");
				String descriptionLine2 =show.elementTextTrim("descriptionLine2");
				String unitOfMeasureAsInput =show.elementTextTrim("unitOfMeasureAsInput");
				String unitsTransactionQty  =show.elementTextTrim("unitsTransactionQty");
				String everestEventPoint01  =show.elementTextTrim("everestEventPoint01");
				String transactionOriginator  =show.elementTextTrim("transactionOriginator");
				String userId  =show.elementTextTrim("userId");
				String dateUpdated  =show.elementTextTrim("dateUpdated");
				String sessionID  =show.elementTextTrim("sessionID");
				String description001  =show.elementTextTrim("description001");
				String yesOrNoEntry  =show.elementTextTrim("yesOrNoEntry");
				String timeLastUpdated  =show.elementTextTrim("timeLastUpdated");
				InterfaceWmsReturn returns=EntityFactory.getEntity(InterfaceWmsReturn.class);
				returns.setCompanyKeyOrderNo(companyKeyOrderNo);
				returns.setDocumentNumber(documentNumber);
				returns.setOrderType(orderType);
				returns.setOrderSuffix(orderSuffix); 
				returns.setLineNumber(lineNumber); 
				returns.setCostCenter(costCenter);
				returns.setCompany(company);
				returns.setCompanyKeyOriginal(companyKeyOriginal);
				returns.setAddressNumber(addressNumber);
				returns.setAddressNumberShipTo(addressNumberShipTo);
				returns.setDateRequestedJulian(dateRequestedJulian);
				returns.setDateTransactionJulian(dateTransactionJulian);
				returns.setScheduledPickDate(scheduledPickDate);
				returns.setActualShipDate(actualShipDate);
				returns.setIdentifier2ndItem(identifier2ndItem);
				returns.setDescriptionLine1(descriptionLine1);
				returns.setDescriptionLine2(descriptionLine2);
				returns.setUnitOfMeasureAsInput(unitOfMeasureAsInput);
				returns.setUnitsTransactionQty(unitsTransactionQty);
				returns.setEverestEventPoint01(everestEventPoint01);
				returns.setTransactionOriginator(transactionOriginator);;
				returns.setUserId(userId);
				returns.setDateUpdated(dateUpdated); 
				returns.setSessionID(sessionID); 
				returns.setDescription001(description001); 
				returns.setYesOrNoEntry(yesOrNoEntry); 
				returns.setTimeLastUpdated(timeLastUpdated);
				returns.setStatus("READY");
				returns.setCreateDate(new Date());
				this.commonDao.store(returns);
			}
		}
	}
	
	/**接收临时项目发送数据Project*/
	public void storeProject( String xml) {
		Document xmlDoc=null;
		try {
			xmlDoc = DocumentHelper.parseText(xml.trim());
		} catch (DocumentException e) {
			if(logger.isDebugEnabled()) {
				e.printStackTrace();
			} 
		}
		Element root = xmlDoc.getRootElement();
		Element body = root.element("Body");                
		Element ShowF57WEH11ResponseElement = body.element("ShowF57WEH11ResponseElement"); 
		List<Element> list = ShowF57WEH11ResponseElement.elements() ;
		for (Element show:list){
			if(show.getName().equals("Outs")){
				String Identifier2ndItem   =show.elementTextTrim("Identifier2ndItem");
				String DescriptionLine1   =show.elementTextTrim("DescriptionLine1");
				String DescriptionLine2  =show.elementTextTrim("DescriptionLine2");
				String UnitOfMeasurePrimary  =show.elementTextTrim("UnitOfMeasurePrimary");
				String SessionID  =show.elementTextTrim("SessionID");
				String YesOrNoEntry  =show.elementTextTrim("YesOrNoEntry");
				String DateUpdated  =show.elementTextTrim("DateUpdated");
				String TimeLastUpdated  =show.elementTextTrim("TimeLastUpdated");
				String UserId  =show.elementTextTrim("UserId");
				
				InterfaceWmsProject project=EntityFactory.getEntity(InterfaceWmsProject.class);
				project.setIdentifier2ndItem(Identifier2ndItem);
				project.setDescriptionLine1(DescriptionLine1);
				project.setDescriptionLine2(DescriptionLine2);
				project.setUnitOfMeasurePrimary(UnitOfMeasurePrimary);
				project.setSessionID(SessionID);
				project.setYesOrNoEntry(YesOrNoEntry);
				project.setDateUpdated(DateUpdated);
				project.setTimeLastUpdated(TimeLastUpdated);
				project.setUserId(UserId);
				project.setStatus("READY");
				project.setCreateDate(new Date());
				this.commonDao.store(project);
			}
		}
	}
	
	/**接收临时项目发送数据Warehouse*/
	public void storeWarehouse( String xml) {
		Document xmlDoc=null;
		try {
			xmlDoc = DocumentHelper.parseText(xml.trim());
		} catch (DocumentException e) {
			if(logger.isDebugEnabled()) {
				e.printStackTrace();
			} 
		}
		Element root = xmlDoc.getRootElement();
		Element body = root.element("Body");                
		Element ShowF57WEH12ResponseElement = body.element("ShowF57WEH12ResponseElement"); 
		List<Element> list = ShowF57WEH12ResponseElement.elements() ;
		for (Element show:list){
			if(show.getName().equals("Outs")){
				String CostCenter    =show.elementTextTrim("Identifier2ndItem");
				String SessionID   =show.elementTextTrim("DescriptionLine1");
				String YesOrNoEntry  =show.elementTextTrim("DescriptionLine2");
				String DateUpdated  =show.elementTextTrim("UnitOfMeasurePrimary");
				String UserId  =show.elementTextTrim("SessionID");
				String TimeLastUpdated  =show.elementTextTrim("YesOrNoEntry");
				String Description001  =show.elementTextTrim("DateUpdated");
				InterfaceWmsWarehouse warehouse=EntityFactory.getEntity(InterfaceWmsWarehouse.class);
				warehouse.setCostCenter(CostCenter);
				warehouse.setSessionID(SessionID);
				warehouse.setYesOrNoEntry(YesOrNoEntry);
				warehouse.setDateUpdated(DateUpdated);
				warehouse.setUserId(UserId);
				warehouse.setTimeLastUpdated(TimeLastUpdated);
				warehouse.setDescription001(Description001);
				warehouse.setStatus("READY");
				warehouse.setCreateDate(new Date());
				this.commonDao.store(warehouse);
			}
		}
	}
	
	
	/**接收临时项目发送数据Download*/
	public void storeDownload( String xml) {
		Document xmlDoc=null;
		try {
			xmlDoc = DocumentHelper.parseText(xml.trim());
		} catch (DocumentException e) {
			if(logger.isDebugEnabled()) {
				e.printStackTrace();
			} 
		}
		Element root = xmlDoc.getRootElement();
		Element body = root.element("Body");                
		Element ShowF57WEHB2ResponseElement = body.element("ShowF57WEHB2ResponseElement"); 
		List<Element> list = ShowF57WEHB2ResponseElement.elements() ;
		System.out.println("down==="+list.size());
		for (Element show:list){
			if(show.getName().equals("Outs")){
				String BarCodeString1    =show.elementTextTrim("BarCodeString1");
				String BarCodeString2   =show.elementTextTrim("BarCodeString2");
				String BarCodeString3  =show.elementTextTrim("BarCodeString3");
				String CostCenter  =show.elementTextTrim("CostCenter");
				String Identifier2ndItem  =show.elementTextTrim("Identifier2ndItem");
				String UnitOfMeasure  =show.elementTextTrim("UnitOfMeasure");
				String QuantityTransaction  =show.elementTextTrim("QuantityTransaction");
				String BarcodeState  =show.elementTextTrim("BarcodeState");
				String DateTransactionJulian  =show.elementTextTrim("DateTransactionJulian");
				String DateRequestedJulian  =show.elementTextTrim("DateRequestedJulian");
				String Description001  =show.elementTextTrim("Description001");
				String Description01002  =show.elementTextTrim("Description01002");
				String Description01003  =show.elementTextTrim("Description01003");
				String Description01004  =show.elementTextTrim("Description01004");
				String Description01005  =show.elementTextTrim("Description01005");
				String Description01006  =show.elementTextTrim("Description01006");
				String Description01007  =show.elementTextTrim("Description01007");
				String Description01008  =show.elementTextTrim("Description01008");
				String Description01009  =show.elementTextTrim("Description01009");
				String NameRemark  =show.elementTextTrim("NameRemark");
				String EverestEventPoint01  =show.elementTextTrim("EverestEventPoint01");
				String EverestEventPoint02  =show.elementTextTrim("EverestEventPoint02");
				String EverestEventPoint03  =show.elementTextTrim("EverestEventPoint03");
				String EverestEventPoint04  =show.elementTextTrim("EverestEventPoint04");
				String EverestEventPoint05  =show.elementTextTrim("EverestEventPoint05");
				String Description11  =show.elementTextTrim("Description11");
				String Description12  =show.elementTextTrim("Description12");
				String Description13  =show.elementTextTrim("Description13");
				String Description14  =show.elementTextTrim("Description14");
				String Description15  =show.elementTextTrim("Description15");
				String ProgramId  =show.elementTextTrim("ProgramId");
				String UserId  =show.elementTextTrim("UserId");
				String WorkStationId  =show.elementTextTrim("WorkStationId");
				String DateUpdated  =show.elementTextTrim("DateUpdated");
				String TimeLastUpdated  =show.elementTextTrim("TimeLastUpdated");
				InterfaceWmsDownload download=EntityFactory.getEntity(InterfaceWmsDownload.class);
				download.setBarCodeString1(BarCodeString1);
				download.setBarCodeString2(BarCodeString2);
				download.setBarCodeString3(BarCodeString3);
				download.setCostCenter(CostCenter);
				download.setIdentifier2ndItem(Identifier2ndItem);
				download.setUnitOfMeasure(UnitOfMeasure);
				download.setQuantityTransaction(QuantityTransaction);
				download.setBarcodeState(BarcodeState);
				download.setDateTransactionJulian(DateTransactionJulian);
				download.setDateRequestedJulian(DateRequestedJulian);
				download.setDescription001(Description001);
				download.setDescription01002(Description01002);
				download.setDescription01003(Description01003);
				download.setDescription01004(Description01004);
				download.setDescription01005(Description01005);
				download.setDescription01006(Description01006);
				download.setDescription01007(Description01007);
				download.setDescription01008(Description01008);
				download.setDescription01009(Description01009);
				download.setNameRemark(NameRemark);
				download.setEverestEventPoint01(EverestEventPoint01);
				download.setEverestEventPoint02(EverestEventPoint02);
				download.setEverestEventPoint03(EverestEventPoint03);
				download.setEverestEventPoint04(EverestEventPoint04);
				download.setEverestEventPoint05(EverestEventPoint05);
				download.setDescription11(Description11);
				download.setDescription12(Description12);
				download.setDescription13(Description13);
				download.setDescription14(Description14);
				download.setDescription15(Description15);
				download.setProgramId(ProgramId);
				download.setUserId(UserId);
				download.setWorkStationId(WorkStationId);
				download.setDateUpdated(DateUpdated);
				download.setTimeLastUpdated(TimeLastUpdated);
				download.setStatus("READY");
				download.setCreateDate(new Date());
				this.commonDao.store(download);
			}
			
		}
	}
	
	
	/**接收临时项目发送数据Warehouse*/
	public void storeDiary( String xml) {
		Document xmlDoc=null;
		try {
			xmlDoc = DocumentHelper.parseText(xml.trim());
		} catch (DocumentException e) {
			if(logger.isDebugEnabled()) {
				e.printStackTrace();
			} 
		}
		Element root = xmlDoc.getRootElement();
		Element body = root.element("Body");                
		Element ProcessF57WEHB3ResponseElement = body.element("ProcessF57WEHB3ResponseElement"); 
		List<Element> list = ProcessF57WEHB3ResponseElement.elements() ;
		for (Element show:list){
			if(show.getName().equals("Outs")){
				String E1MessageList     =show.elementTextTrim("BarCodeString1");
				String ErrorCode    =show.elementTextTrim("BarCodeString2");
				String DataItem   =show.elementTextTrim("BarCodeString3");
				InterfaceWmsDiary diary=EntityFactory.getEntity(InterfaceWmsDiary.class);
				diary.setE1MessageList(E1MessageList);
				diary.setErrorCode(ErrorCode);
				diary.setDataItem(DataItem);
				diary.setStatus("READY");
				diary.setCreateDate(new Date());
				this.commonDao.store(diary);
			}
		}
	}
	
	/**
	 * 调用接口发送数据
	 * @param log
	 * @return
	 */
	public boolean send(InterfaceLog log, String type) {
		boolean successToConnectServer = false;//如果成功连接服务器
		try{
			String response = connectionHelper.sendMessage(buildXML(log, type));
			if(!ResponseCode.SUCCESS.equals(response)) {
				log.setErrorLog(response);
				log.setStatus(InterfaceLogConstant.ERROR);
			} else {
				if (InterfaceLogConstant.REQUEST.equals(type)) {
					log.setStatus(InterfaceLogConstant.SEND);
				} else {
					log.setStatus(InterfaceLogConstant.FINISH);
				}
			}
			successToConnectServer = true;
		} catch (ServerUnreachableException e) {
			log.setResponseContent(e.getMessage());
			log.setStatus(InterfaceLogConstant.ERROR);
		} catch (Exception e) {
			log.setResponseContent(e.getMessage());
			log.setStatus(InterfaceLogConstant.ERROR);
			successToConnectServer = true;
		}
		
		log.setDealTime(new Date());
		commonDao.store(log);
		return successToConnectServer;
	}

	protected String buildXML(InterfaceLog log, String type) {
		DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");		
		String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
		xml += "<XML>"+"\r\n";
		xml += "<MESSAGEHEAD>"+"\r\n";
		xml += "  <FROM>" + (log.getFromSYS() == null ? "" : log.getFromSYS()) + "</FROM>"+"\r\n";
		xml += "  <SENDER>" + (log.getRequest() == null ? "" : log.getRequest()) + "</SENDER>"+"\r\n";
		xml += "  <TO>" + (log.getToSYS() == null ? "" : log.getToSYS()) + "</TO>"+"\r\n";
		xml += "  <RECIEVER>" + (log.getResponse() == null ? "" : log.getResponse()) + "</RECIEVER>"+"\r\n";  
		xml += "  <FILETYPE>XML</FILETYPE> "+"\r\n";
		xml += "  <CONTENTTYPE>" + log.getType() + "</CONTENTTYPE>"+"\r\n";
		xml += "  <FILEFUNCTION>" + log.getFunction() + "</FILEFUNCTION>"+"\r\n";
		xml += "  <SENDTIME>" + DateUtil.formatDateToStr(new Date()) + "</SENDTIME>"+"\r\n";
		xml += "  <ISBASE64>FALSE</ISBASE64>\r\n";
		xml += "  <FILENAME>" + "" + "</FILENAME>\r\n";
		xml += "  <REFERENCE>" + log.getReference() + "</REFERENCE>\r\n";
		xml += "  <LOG_ID>" + log.getLogID() + "</LOG_ID>\r\n";
		xml += "</MESSAGEHEAD>\r\n";
		xml += "<MESSAGEDETAIL> \r\n";
		xml += "<![CDATA[\r\n";	
		if (InterfaceLogConstant.REQUEST.equals(type)) {
			xml += log.getRequestContent();
		} else {
			xml += log.getResponseContent();
		}
		xml += "]]>\r\n";	
		xml += "</MESSAGEDETAIL> \r\n";	
		xml += "</XML>";
		//System.out.println(xml);
		return xml;
	}
	
	public void inventoryResponse(InterfaceLog log) throws Exception {
		List<String> products = new ArrayList<String>();
		
		String str = log.getRequestContent();
		String newStr = XMLUtils.del_r(str);
		Document message = DocumentHelper.parseText(newStr.trim());
		Element root = message.getRootElement();
		
		//获取发送方和接收方代码
		String receiver = log.getResponse();	//仓库代码

		Element xml = root.element("CONTENTLIST");
		Element content = xml.element("CONTENT");
		Element inventories = content.element("INVENTORIES");
		Iterator inventory = inventories.elementIterator("INVENTORY");
		while (inventory.hasNext()) {
			Element node = (Element) inventory.next();
			String lot = node.elementText("LOT"); 					//批次号
			products.add(receiver + "|" + node.elementText("CUSTOMER")
					+ "|" + node.elementText("PRODUCT") 
					+ (StringUtils.isEmpty(lot) ? "" : ("|" + lot)));
		}
		if (products.size() == 0) {
			log.setStatus(InterfaceLogConstant.ERROR);
			log.setErrorLog("no product need to query inventory!");
			commonDao.store(log);
		} else {
			//调用查询接口得到库存情况
			List<ProductInventory> pinvs = inventoryManager.getProductInventories(products, receiver);
			//回调OMS/TMS接口，发送库存查询结果数据
			pushInventoryResponse(log, pinvs);
		}
	}


	private void pushInventoryResponse(InterfaceLog log,
			List<ProductInventory> pinvs) {
		//更新日志状态
		log.setResponseContent(getInventoryResponse(pinvs));
		log.setResponseTime(new Date());
		commonDao.store(log);
		
		//调用方法发送接口数据
		send(log, InterfaceLogConstant.RESPONSE);
	}

	private String getInventoryResponse(List<ProductInventory> pinvs) {
		// 明细内甙xml
		Document _doc = DocumentHelper.createDocument();
		Element _root = _doc.addElement("XML");
		Element contentList = _root.addElement("CONTENTLIST");
		Element content = contentList.addElement("CONTENT");
		Element inventories = content.addElement("INVENTORIES");
		for (ProductInventory pinv : pinvs) {
			// 内甙头
			Element header = inventories.addElement("INVENTORY");
			Element customer = header.addElement("CUSTOMER");
			Element product = header.addElement("PRODUCT");
			Element lot = header.addElement("LOT");
			Element quantity = header.addElement("QUANTITY");
			
			customer.setText(pinv.getCustomer());
			product.setText(pinv.getProduct());			
			lot.setText(pinv.getLot() == null ? "":pinv.getLot());
			quantity.setText(String.valueOf(pinv.getQuantity()));
		}

		return _doc.asXML();
	}

	public void availableOrderResponse(InterfaceLog log) throws Exception {
		String str = log.getRequestContent();
		
		AvaliableOrderResponse aor = null;
		String newStr = XMLUtils.del_r(str);
		Document message = DocumentHelper.parseText(newStr.trim());
		Element xml = message.getRootElement();
		//获取发送方和接收方代码
		Element contentList = xml.element("CONTENTLIST");
		Element contents = contentList.element("CONTENT");
		Iterator orderIterator = contents.elementIterator("ORDER");
		while (orderIterator.hasNext()) {
			Element order = (Element) orderIterator.next();
			Element head = order.element("HEAD");
			Element customerCode = head.element("CUSTOMER_CODE"); 		// 客户代码
			Element code = head.element("CODE"); 						// 订单编号
			Element orderTypeCode = head.element("ORDERTYPE"); 			// 单据类型编码
			Element relateBillCode1 = head.element("RELATEBILL1");		// 销售、采购订单号
			Element fromLocationCode = head.element("FROMLOCATION"); 	// 出发运输地代码
			Element toLocationCode = head.element("TOLOCATION"); 		// 目的运输地代码
			Element shipmentType = head.element("SHIPMENT_TYPE"); 		// 运输类型代码
			Element shipmentMethod = head.element("SHIPMENT_METHOD"); 	// 运输方式代码
			Element planArriveTime = head.element("PLAN_ARRIVE_TIME");	// 要求到货日期
			Element orderDate = head.element("ORDERDATE");				// 订单日期

			Element fromCode = head.element("FROM_CODE"); 				// 发货人代码
			Element fromName = head.element("FROM_NAME"); 				// 发货人名称
			Element fromContact = head.element("FROM_LINKMAN"); 		// 发货联系人
			Element fromPhone = head.element("FROM_PHONE"); 			// 发货人电话
			Element fromFax = head.element("FROM_FAX"); 				// 发货人传真
			Element fromEmail = head.element("FROM_EMAIL"); 			// 发货人邮箱
			Element fromAddress = head.element("FROM_ADDRESS"); 		// 发货人地址
			Element fromPostcode = head.element("FROM_POSTCODE"); 		// 发货人地址
			
			Element toCode = head.element("TO_CODE");					// 收货人代码,收货客户代码
			Element toName = head.element("TO_NAME"); 					// 收货人名称
			Element toContact = head.element("TO_LINKMAN");				// 收货联系人
			Element toPhone = head.element("TO_PHONE"); 				// 收货人电话
			Element toFax = head.element("TO_FAX"); 					// 收货人传真
			Element toEmail = head.element("TO_EMAIL");					// 收货人邮箱
			Element toAddress = head.element("TO_ADDRESS"); 			// 收货人地址
			Element toPostcode = head.element("TO_POSTCODE"); 			// 收货人地址

			Element priority = head.element("PRIORITY");				// 优先级
			Element description = head.element("DESCRIPTION");			// 备注
			
			Element details = order.element("DETAILS");					// 单据明细
			Iterator detail = details.elementIterator("DETAIL");		// 单据明细Iterator

			if (InterfaceLogConstant.AVAILABLE_ORDER_PO.equals(log.getType())) {
				//创建ASN收货单
				ASN asn = new ASN();
				if (!StringUtils.isEmpty(log.getRequest())) {
					asn.setWarehouse((Warehouse) commonDao.findByNamedQueryUniqueResult("getWarehouseByCode", 
							new String[] {"code"}, new Object[] {log.getRequest()}));
				}
				if (!StringUtils.isEmpty(customerCode.getTextTrim())) {
					asn.setCompany((Structure) commonDao.findByNamedQueryUniqueResult("getCompanyByCode", 
							new String[] {"code"}, new Object[] {customerCode.getTextTrim()}));
				}
				if (!StringUtils.isEmpty(orderTypeCode.getTextTrim())) { 
					asn.setBillType((BillType) commonDao.findByNamedQueryUniqueResult("getBillTypeByCompanyAndCode", 
							new String[] {"companyId","code"}, new Object[] {asn.getCompany().getId(), orderTypeCode.getTextTrim()}));
				}
				//asn.setCode(codeManager.generateASNDocCode(new HashMap()));
				asn.setCode(code.getTextTrim());
				asn.setRelatedBill1(code.getTextTrim());			//记录TMS订单号
				asn.setRelatedBill2(relateBillCode1.getTextTrim());	//记录客户订单号
				asn.setRelatedBill3(log.getRequest());				//记录发送平台代码
				if (!StringUtils.isEmpty(planArriveTime.getTextTrim())) {
					asn.setEstimateDate(DateUtil.formatStrToDate(planArriveTime.getTextTrim()));
				}
				asn.setFromName(fromName.getTextTrim());
				asn.setFromAddress(new Address(fromAddress.getTextTrim(), fromPostcode.getTextTrim()));
				asn.setFromContact(new Contact(fromContact.getTextTrim(), 
						fromPhone.getTextTrim(),	fromFax.getTextTrim(), fromEmail.getTextTrim()));
				asn.setOrderDate(new Date());
				asn.setStatus(ASNStatus.ACTIVE);
				asn.setAsnDetails(new HashSet<ASNDetail>());
				addAsnDetails(asn, detail);
				commonDao.store(asn);
				
				aor = new AvaliableOrderResponse(asn.getCompany().getCode(), InterfaceLogConstant.AVAILABLE_ORDER_PO, asn.getRelatedBill1(), asn.getCode(),	new Date());
			} else if (InterfaceLogConstant.AVAILABLE_ORDER_SO.equals(log.getType())) {
				//创建PickTicket发货单
				PickTicket pickTicket = new PickTicket();
				if (!StringUtils.isEmpty(log.getResponse())) {
					pickTicket.setWarehouse((Warehouse) commonDao.findByNamedQueryUniqueResult("getWarehouseByCode", 
							new String[] {"code"}, new Object[] {log.getResponse()}));
				}
				if (!StringUtils.isEmpty(customerCode.getTextTrim())) {
					pickTicket.setCompany((Structure) commonDao.findByNamedQueryUniqueResult("getCompanyByCode", 
							new String[] {"code"}, new Object[] {customerCode.getTextTrim()}));
				}
				if (!StringUtils.isEmpty(orderTypeCode.getTextTrim())) { 
					pickTicket.setBillType((BillType) commonDao.findByNamedQueryUniqueResult("getBillTypeByCompanyAndCode", 
							new String[] {"companyId","code"}, new Object[] {pickTicket.getCompany().getId(), orderTypeCode.getTextTrim()}));
				}
				pickTicket.setCode(code.getTextTrim());
				pickTicket.setRelatedBill1(code.getTextTrim());				//记录TMS订单号
				pickTicket.setRelatedBill2(relateBillCode1.getTextTrim());	//记录客户订单号
				pickTicket.setRelatedBill3(log.getRequest());				//记录发送平台代码
				pickTicket.setRequireArriveDate(DateUtil.formatStrToDate(planArriveTime.getTextTrim()));
				pickTicket.setCustomer((Structure) commonDao.findByNamedQueryUniqueResult("getCustomerByCode", 
						new String[] {"code"}, new Object[] {toCode.getTextTrim()}));
				pickTicket.setShipToName(toName.getTextTrim());
				pickTicket.setShipToAddress(new Address(toAddress.getTextTrim(), toPostcode.getTextTrim()));
				pickTicket.setShipToContact(new Contact(toContact.getTextTrim(), 
						toPhone.getTextTrim(), toFax.getTextTrim(), toEmail.getTextTrim()));
				pickTicket.setOrderDate(new Date());
				pickTicket.setStatus(PickTicketStatus.ACTIVE);
				List<Location> shipLocs = commonDao.findByNamedQuery("getLocationsByType", 
						new String[] {"type", "warehouseId"}, 
						new Object[] {LocationType.SHIP, pickTicket.getWarehouse().getId()});
				if (shipLocs != null && shipLocs.size() > 0) {
					pickTicket.setDock(shipLocs.get(0));
				}
				addPickTicketDetails(pickTicket, detail);
				commonDao.store(pickTicket);
				
				aor = new AvaliableOrderResponse(pickTicket.getCompany().getCode(),	InterfaceLogConstant.AVAILABLE_ORDER_SO, pickTicket.getRelatedBill1(), pickTicket.getCode(), new Date());
			}
			
			//将创建的订单写入集合，回调STMS接口发送订单生效反馈消息
			pushAvaliableOrderResponse(log, aor);
		}
	}
	
	private void addPickTicketDetails(PickTicket pickTicket, Iterator details) {
		int seq = 1000;
		while (details.hasNext()) {
			Element detail = (Element) details.next();
			
			Element lineNo = detail.element("LINE");// 行号（序号）
			Element productCode = detail.element("PRODUCT");// 货物编号
			Element lot = detail.element("LOT");// 货物批次
			Element quantity = detail.element("QUANTITY");// 货物数量
			Element unit = detail.element("UNIT");// 包装单位名称
			
			PickTicketDetail orderDetail = new PickTicketDetail();
			
			Item item = null;
			if (!StringUtils.isEmpty(productCode.getText().trim())) {
				// 货物编号
				String pCode = XMLUtils.trimLeftZero(productCode.getText().trim());
				item = (Item) this.commonDao.findByNamedQueryUniqueResult("getItemByCompanyAndCode",
								new String[] { "code", "companyId" },
								new Object[] { productCode.getText().trim(), pickTicket.getCompany().getId()});
				orderDetail.setItem(item);
				// 包装单位
				if (!StringUtils.isEmpty(unit.getText().trim())) {
					PackageUnit packageUnit = (PackageUnit) this.commonDao.findByNamedQueryUniqueResult("getPackageUnitByItemAndUnit",
							new String[] { "unit", "itemId" },
							new Object[] { unit.getText().trim(), item.getId()});
					orderDetail.setPackageUnit(packageUnit);
				}
				// 货物批次
				//TODO 这里为什么是这样的  创建一个新的NewLotInfo
				NewLotInfo lotInfo = new NewLotInfo();
				if (!StringUtils.isEmpty(lot.getText().trim())) {
					lotInfo.setPropC1(lot.getText().trim());
				}
				lotInfo.setPropN1("0.0");
				lotInfo.setPropN2("0.0");
				lotInfo.setPropN3("0.0");
				orderDetail.setNewLotInfo(lotInfo);
				// 货物数量
				if (!StringUtils.isEmpty(quantity.getText().trim())) {
					orderDetail.addOrderQuantity(Double.parseDouble(quantity.getText().trim()), orderDetail.getPackageUnit());
				}
				pickTicket.addPickTicketDetail(orderDetail);
			} else {
				//直接丢弃数据
				//buf.append("行号为[" + lineNo.getText() + "]的产品代码[" +  
				//		productCode.getText().trim() + "]不存在 \r\n");
			}
		}
	}

	private void addAsnDetails(ASN asn, Iterator details) {
		int seq = 1000;
		while (details.hasNext()) {
			Element detail = (Element) details.next();
			
			Element lineNo = detail.element("LINE");// 行号（序号）
			Element productCode = detail.element("PRODUCT");// 货物编号
			Element lot = detail.element("LOT");// 货物批次
			Element quantity = detail.element("QUANTITY");// 货物数量
			Element unit = detail.element("UNIT");// 包装单位名称
			
			ASNDetail orderDetail = new ASNDetail();
			
			Item item = null;
			if (!StringUtils.isEmpty(productCode.getText().trim())) {
				// 行号（序号）
				if (!StringUtils.isEmpty(lineNo.getText().trim())) {
					orderDetail.setLineNo(Integer.parseInt(lineNo.getText().trim()));
				} else {
					orderDetail.setLineNo(seq++);
				}
				// 货物编号
				String pCode = XMLUtils.trimLeftZero(productCode.getText().trim());
				item = (Item) this.commonDao.findByNamedQueryUniqueResult("getItemByCompanyAndCode",
								new String[] { "code", "companyId" },
								new Object[] { productCode.getText().trim(), asn.getCompany().getId()});
				orderDetail.setItem(item);
				// 包装单位
				if (!StringUtils.isEmpty(unit.getText().trim())) {
					PackageUnit packageUnit = (PackageUnit) this.commonDao.findByNamedQueryUniqueResult("getPackageUnitByItemAndUnit",
							new String[] { "unit", "itemId" },
							new Object[] { unit.getText().trim(), item.getId()});
					orderDetail.setPackageUnit(packageUnit);
				}
				// 货物批次
				LotInfo lotInfo = new LotInfo();
				if (!StringUtils.isEmpty(lot.getText().trim())) {
					lotInfo.setPropC1(lot.getText().trim());
				}
				lotInfo.setPropN1(0);
				lotInfo.setPropN2(0);
				lotInfo.setPropN3(0);
				orderDetail.setLotInfo(lotInfo);
				// 货物数量
				if (!StringUtils.isEmpty(quantity.getText().trim())) {
					orderDetail.addExpectedQuantity(Double.parseDouble(quantity.getText().trim()));
				}
				asn.addASNDetail(orderDetail);
			} else {
				//直接丢弃数据
				//buf.append("行号为[" + lineNo.getText() + "]的产品代码[" +  
				//		productCode.getText().trim() + "]不存在 \r\n");
			}
		}
	}
	
	/**
	 * 发送生效订单反馈接口内容
	 * @param avaliableOrders
	 * @return
	 */
	private void pushAvaliableOrderResponse(InterfaceLog log, AvaliableOrderResponse aor) {
		//更新日志状态
		try {
			log.setResponseContent(formatXml(getAvaliableOrderResponse(aor)));
		} catch (Exception e) {
			e.printStackTrace();
		}
		log.setResponseTime(new Date());

		//调用方法发送接口数据
		boolean isSend = send(log, InterfaceLogConstant.RESPONSE);
		if (!isSend) {
			throw new BusinessException("orders.avaliable.response.error!");
		}
	}

	private Document getAvaliableOrderResponse(AvaliableOrderResponse aor) {
		// 明细内甙xml
		Document _doc = DocumentHelper.createDocument();
		Element _root = _doc.addElement("XML");
		Element contentList = _root.addElement("CONTENTLIST");
		Element content = contentList.addElement("CONTENT");
		// 内甙头
		Element header = content.addElement("ORDER");
		Element customerCode = header.addElement("CUSTOMER_CODE");
		Element omsCode = header.addElement("OMS_CODE");
		Element code = header.addElement("CODE");
		Element receiveTime = header.addElement("RECEIVE_TIME");
		customerCode.setText(aor.getCustomer());
		omsCode.setText(aor.getOmsCode());
		code.setText(aor.getWmsCode());
		receiveTime.setText(DateUtil.formatDateToStr(aor.getReceiveTime()));

		return _doc;
	}
	
	public void asnReceiveResponse(ASN asn) {
		//ASN关闭时生成收货接口文档，写入interfaceLog，并调用http接口往STMS发送单据收货确认消息
		if (StringUtils.isEmpty(asn.getRelatedBill3())) {
			//当WMS单独启动创建的ASN不进行接口处理
			return;
		}
		asn = commonDao.load(ASN.class, asn.getId());
		InterfaceLog log = new InterfaceLog();
		log.setType(InterfaceLogConstant.RECEIVE_REPORT);
		log.setFromSYS(InterfaceLogConstant.WMS);
		log.setRequest(asn.getWarehouse().getCode());
		log.setRequestTime(new Date());
		try {
			log.setRequestContent(formatXml(generateAsnReceiveContent(asn)));
		} catch (Exception e) {
			e.printStackTrace();
		}
		log.setToSYS(InterfaceLogConstant.TMS);
		log.setResponse(asn.getRelatedBill3());
		log.setFunction("");
		log.setStatus(InterfaceLogConstant.READY);
		log.setFileName("");
		log.setReference("");
		commonDao.store(log);
		//发送ASN收货反馈消息
		log.setLogID(log.getId());
	}

	private Document generateAsnReceiveContent(ASN asn) {
		Document _doc = DocumentHelper.createDocument();
		Element _root = _doc.addElement("XML");
		Element contentList = _root.addElement("CONTENTLIST");
		Element content = contentList.addElement("CONTENT");
		Element order = content.addElement("ORDER");
		//内嵌头
		Element head = order.addElement("HEAD");
		Element customerCode = head.addElement("CUSTOMER_CODE");
		Element code = head.addElement("CODE");
		Element omsCode = head.addElement("OMS_CODE");
		Element finishTime = head.addElement("FINISH_TIME");
		finishTime.setText(DateUtil.formatDateToStr(new Date()));
		customerCode.setText(asn.getCompany().getCode());
		code.setText(asn.getCode());
		omsCode.setText(asn.getRelatedBill1());
		//内嵌明细
		Element details = order.addElement("DETAILS");
		for (ASNDetail asnDetail : asn.getAsnDetails()) {
			Element detail = details.addElement("DETAIL");
			Element product = detail.addElement("PRODUCT");
			Element lot = detail.addElement("LOT");
			Element quantity = detail.addElement("QUANTITY");
			Element unit = detail.addElement("UNIT");
			product.setText(asnDetail.getItem().getCode());
			lot.setText(asnDetail.getLotInfo().getPropC1() == null ? "" : asnDetail.getLotInfo().getPropC1());
			unit.setText(asnDetail.getPackageUnit().getUnit());
			//收货包装数量，折算时保留3位有效小数
			quantity.setText(String.valueOf(DoubleUtils.formatByPrecision(
					asnDetail.getReceivedQuantity()/asnDetail.getPackageUnit().getConvertFigure(), 3)));
		}
		
		return _doc;
	}

	public void putawayResponse(MoveDoc moveDoc) {
//		//ASN关闭时生成收货接口文档，写入interfaceLog，并调用http接口往STMS发送单据收货确认消息
//		moveDoc = commonDao.load(MoveDoc.class, moveDoc.getId());
//		if (!MoveDocType.PUTAWAY.equals(moveDoc.getType())) {
//			//排除移位计划
//			return;
//		}
//		//取得上架计划关联的ASN对象
//		ASN asn = (ASN) commonDao.findByQueryUniqueResult("FROM ASN asn WHERE asn.warehouse.id = :warehouseId AND asn.code = :code", 
//				new String[] {"warehouseId", "code"}, 
//				new Object[] {moveDoc.getWarehouse().getId(), moveDoc.getSoi()});
//		if (asn == null || StringUtils.isEmpty(asn.getRelatedBill3())) {
//			//未定义接口信息收货单不做处理
//			return;
//		}
//		InterfaceLog log = new InterfaceLog();
//		log.setType(InterfaceLogConstant.PUTAWAY_REPORT);
//		log.setFromSYS(InterfaceLogConstant.WMS);
//		log.setRequest(asn.getWarehouse().getCode());
//		log.setRequestTime(new Date());
//		try {
//			log.setRequestContent(formatXml(generateputawayContent(asn, moveDoc.getDetails())));
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		log.setToSYS(InterfaceLogConstant.TMS);
//		log.setResponse(asn.getRelatedBill3());
//		log.setFunction("");
//		log.setStatus(InterfaceLogConstant.READY);
//		log.setFileName("");
//		log.setReference("");
//		commonDao.store(log);
//		//发送ASN收货反馈消息
//		log.setLogID(log.getId());
    }

	private Document generateputawayContent(ASN asn, Set<MoveDocDetail> moveDocDetails) {
		Document _doc = DocumentHelper.createDocument();
		Element _root = _doc.addElement("XML");
		Element contentList = _root.addElement("CONTENTLIST");
		Element content = contentList.addElement("CONTENT");
		Element order = content.addElement("ORDER");
		//内嵌头
		Element head = order.addElement("HEAD");
		Element customerCode = head.addElement("CUSTOMER_CODE");
		Element code = head.addElement("CODE");
		Element omsCode = head.addElement("OMS_CODE");
		Element finishTime = head.addElement("FINISH_TIME");
		finishTime.setText(DateUtil.formatDateToStr(new Date()));
		customerCode.setText(asn.getCompany().getCode());
		code.setText(asn.getCode());
		omsCode.setText(asn.getRelatedBill1());
		//内嵌明细
		Element details = order.addElement("DETAILS");
		for (MoveDocDetail moveDocDetail : moveDocDetails) {
			Element detail = details.addElement("DETAIL");
			Element product = detail.addElement("PRODUCT");
			Element lot = detail.addElement("LOT");
			Element quantity = detail.addElement("QUANTITY");
			Element unit = detail.addElement("UNIT");
			product.setText(moveDocDetail.getItemKey().getItem().getCode());
			lot.setText(moveDocDetail.getItemKey().getLotInfo().getPropC1() == null ? "" : moveDocDetail.getItemKey().getLotInfo().getPropC1());
			unit.setText(moveDocDetail.getPackageUnit().getUnit());
			//上架包装数量，折算时保留3位有效小数
			quantity.setText(String.valueOf(DoubleUtils.formatByPrecision(
					moveDocDetail.getMoveQuantity()/moveDocDetail.getPackageUnit().getConvertFigure(), 3)));
		}
		
		return _doc;
	}

	public void pickResponse(PickTicket pickTicket) {
		//ASN关闭时生成收货接口文档，写入interfaceLog，并调用http接口往STMS发送单据收货确认消息
		pickTicket = commonDao.load(PickTicket.class, pickTicket.getId());
		if (StringUtils.isEmpty(pickTicket.getRelatedBill3())) {
			//发货单上未定义接口信息时，不发送接口消息
			return;
		}
		InterfaceLog log = new InterfaceLog();
		log.setType(InterfaceLogConstant.PICKING_REPORT);
		log.setFromSYS(InterfaceLogConstant.WMS);
		log.setRequest(pickTicket.getWarehouse().getCode());
		log.setRequestTime(new Date());
		try {
			log.setRequestContent(formatXml(generatePickContent(pickTicket)));
		} catch (Exception e) {
			e.printStackTrace();
		}
		log.setToSYS(InterfaceLogConstant.TMS);
		log.setResponse(pickTicket.getRelatedBill3());
		log.setFunction("");
		log.setStatus(InterfaceLogConstant.READY);
		log.setFileName("");
		log.setReference("");
		commonDao.store(log);
		//发送ASN收货反馈消息
		log.setLogID(log.getId());
	}

	private Document generatePickContent(PickTicket pickTicket) {
		Document _doc = DocumentHelper.createDocument();
		Element _root = _doc.addElement("XML");
		Element contentList = _root.addElement("CONTENTLIST");
		Element content = contentList.addElement("CONTENT");
		Element order = content.addElement("ORDER");
		//内嵌头
		Element head = order.addElement("HEAD");
		Element customerCode = head.addElement("CUSTOMER_CODE");
		Element code = head.addElement("CODE");
		Element omsCode = head.addElement("OMS_CODE");
		Element finishTime = head.addElement("FINISH_TIME");
		finishTime.setText(DateUtil.formatDateToStr(new Date()));
		customerCode.setText(pickTicket.getCompany().getCode());
		code.setText(pickTicket.getCode());
		omsCode.setText(pickTicket.getRelatedBill1());
		//内嵌明细
		Element details = order.addElement("DETAILS");
		for (PickTicketDetail pickTicketDetail : pickTicket.getPickTicketDetails()) {
			Element detail = details.addElement("DETAIL");
			Element product = detail.addElement("PRODUCT");
			Element lot = detail.addElement("LOT");
			Element quantity = detail.addElement("QUANTITY");
			Element unit = detail.addElement("UNIT");
			product.setText(pickTicketDetail.getItem().getCode());
			lot.setText(pickTicketDetail.getLotInfo().getPropC1() == null ? "" : pickTicketDetail.getLotInfo().getPropC1());
			unit.setText(pickTicketDetail.getPackageUnit().getUnit());
			//拣货包装数量，折算时保留3位有效小数
			quantity.setText(String.valueOf(DoubleUtils.formatByPrecision(
					pickTicketDetail.getPickedQuantity()/pickTicketDetail.getPackageUnit().getConvertFigure(), 3)));
		}
		
		return _doc;
	}

	public void bolShipResponse(BOL bol) {
		//ASN关闭时生成收货接口文档，写入interfaceLog，并调用http接口往STMS发送单据收货确认消息
		bol = commonDao.load(BOL.class, bol.getId());
		PickTicket pickTicket = bol.getPickTicket();
		if (StringUtils.isEmpty(pickTicket.getRelatedBill3())) {
			//发货单上未定义接口信息时，不发送接口消息
			return;
		}
		InterfaceLog log = new InterfaceLog();
		log.setType(InterfaceLogConstant.SHIPPING_REPORT);
		log.setFromSYS(InterfaceLogConstant.WMS);
		log.setRequest(pickTicket.getWarehouse().getCode());
		log.setRequestTime(new Date());
		try {
			log.setRequestContent(formatXml(generateBolShipContent(pickTicket, bol.getPackages())));
		} catch (Exception e) {
			e.printStackTrace();
		}
		log.setToSYS(InterfaceLogConstant.TMS);
		log.setResponse(pickTicket.getRelatedBill3());
		log.setFunction("");
		log.setStatus(InterfaceLogConstant.READY);
		log.setFileName("");
		log.setReference("");
		commonDao.store(log);
		//发送ASN收货反馈消息
		log.setLogID(log.getId());
	}

	private Document generateBolShipContent(PickTicket pickTicket,
			Set<Package> bolDetails) {
		Document _doc = DocumentHelper.createDocument();
		Element _root = _doc.addElement("XML");
		Element contentList = _root.addElement("CONTENTLIST");
		Element content = contentList.addElement("CONTENT");
		Element order = content.addElement("ORDER");
		//内嵌头
		Element head = order.addElement("HEAD");
		Element customerCode = head.addElement("CUSTOMER_CODE");
		Element code = head.addElement("CODE");
		Element omsCode = head.addElement("OMS_CODE");
		Element finishTime = head.addElement("FINISH_TIME");
		finishTime.setText(DateUtil.formatDateToStr(new Date()));
		customerCode.setText(pickTicket.getCompany().getCode());
		code.setText(pickTicket.getCode());
		omsCode.setText(pickTicket.getRelatedBill1());
		//内嵌明细
		Element details = order.addElement("DETAILS");
//		for (BOLDetail bolDetail : bolDetails) {
//			Element detail = details.addElement("DETAIL");
//			Element product = detail.addElement("PRODUCT");
//			Element lot = detail.addElement("LOT");
//			Element quantity = detail.addElement("QUANTITY");
//			Element unit = detail.addElement("UNIT");
//			product.setText(bolDetail.getPickedRecord().getItemKey().getItem().getCode());
//			lot.setText(bolDetail.getPickedRecord().getItemKey().getLotInfo().getPropC1() == null ? "" : bolDetail.getPickedRecord().getItemKey().getLotInfo().getPropC1());
//			unit.setText(bolDetail.getPackageUnit().getUnit());
//			//拣货包装数量，折算时保留3位有效小数
//			quantity.setText(String.valueOf(DoubleUtils.formatByPrecision(
//					bolDetail.getShippedQuantity()/bolDetail.getPackageUnit().getConvertFigure(), 3)));
//		}
		
		return _doc;
	}
	
	private String formatXml(Document doc) throws Exception {
		StringWriter writer = new StringWriter();
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding("UTF-8");
		XMLWriter xmlWriter = new XMLWriter(writer, format);

		xmlWriter.write(doc);

		return writer.toString();
	}
	
	@SuppressWarnings("unchecked")
	public List<InterfaceLog> getLogsByConditions(List<String> types, String status) {
		List<InterfaceLog> logs = commonDao
		.findByQuery(
				"from InterfaceLog log where log.type in (:types) and log.status = :status",
				new String[] { "types", "status"}, 
				new Object[] { types, status });
		
		List<InterfaceLog> todo = new ArrayList<InterfaceLog>();
		int i = 0;
		for (InterfaceLog log : logs) {
			todo.add(log);
			i++;
			if (i <= TIMES_PER) {
				break;
			}
		}
		return todo;
	}
	
	public void getWmsItem() {
		List<InterfaceWmsItem> iwis = commonDao
				.findByQuery(
						"from InterfaceWmsItem i where i.status = 'READY' ");
			for(InterfaceWmsItem i:iwis){
				
				Structure company=null;
				List<Structure> companys = commonDao.findByQuery(
								"from Structure s where  s.interfaceId =:company_id  ",
								new String[] { "company_id"}, 
								new Object[] { i.getCostCenter() });
				if(companys.size()>0){
					company=companys.get(0);
				}
				if(company==null){
					System.out.println("客户不存在！");
				}
				
				List<Item> items = commonDao.findByQuery(
								"from Item i where  i.company.id =:company_id and i.code=:code ",
								new String[] { "company_id", "code"}, 
								new Object[] { company.getId(),i.getIdentifier2ndItem() });
				Item item=EntityFactory.getEntity(Item.class);
				PackageUnit packageUnit=EntityFactory.getEntity(PackageUnit.class);
				if(items.size()>0){
					item=items.get(0);
					packageUnit= item.getMinPackageUnit();
				}
				item.setCompany(company);
				item.setName(i.getDescriptionLine1());
				item.setCode(i.getIdentifier2ndItem());
				item.setUnit(i.getUnitOfMeasurePrimary());
				packageUnit.setUnit(i.getUnitOfMeasurePrimary());
				try {
					itemManager.storeItem( item);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
//			this.commonDao.store(item);
				System.out.println(item.getCode());
			}
	}


   public void  getWmsPickTicket(){
	   SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd");//小写的mm表示的是分钟  
	   List<InterfaceWmsOut> iwo = commonDao.findByQuery("from InterfaceWmsOut i where i.status = 'READY' order by id");
	   for(InterfaceWmsOut i:iwo){
		   Structure company=null;
		   List<Structure> companys = commonDao.findByQuery("from Structure s where  s.interfaceId =:company_id",new String[] { "company_id"}, new Object[] { i.getCostCenter() });
			if(companys.size()>0){
				company=companys.get(0);
				List<BillType> billTypes = commonDao.findByQuery("from BillType b where  b.company.id =:company_id and b.type='SHIP'",new String[] { "company_id"}, new Object[] { company.getId() });
				BillType b=EntityFactory.getEntity(BillType.class);
				if(billTypes.size()>0){
					b=billTypes.get(0);
					PickTicket p=null;
					List<PickTicket> pickTickets = commonDao.findByQuery("from PickTicket p where  p.relatedBill1 =:relatedBill1 and p.company.id =:company",
							new String[] { "relatedBill1","company"}, new Object[] { i.getDocumentOrderInvoiceE(),company.getId() });
					if(pickTickets.size()>0){
						p=pickTickets.get(0);
					}else{
						p=EntityFactory.getEntity(PickTicket.class);
						p.setCompany(company);
						p.setRelatedBill1(i.getDocumentOrderInvoiceE());
						p.setBillType(b);
						p.setRelatedBill3(i.getOrderType());
						List<Location> objs =  commonDao.findByQuery(" from Location o where o.warehouse.id=:id  and o.type ='SHIP'",
									new String[] { "id"},new Object[] {1l});
						if(objs.size()>0){
						   Location l =objs.get(0);
						   p.setDock(l);
						}
						p.setCode(this.bussinessCodeManager.getCodeForYm("CP", 4));
						p.setWarehouse(commonDao.load(Warehouse.class, 1l));
						p.setStatus(PickTicketStatus.OPEN);
						p.setUserName(i.getUserId());
						p.setUpdateTime(new Date());
						try {
							p.setOrderDate(sdf.parse(i.getDateTransactionJulian()));
							p.setReceivedDate(sdf.parse(i.getDateRequestedJulian()));
						} catch (ParseException e) {
							p.setOrderDate(new Date());
						}
						List<Store> stores = commonDao.findByQuery(" from Store s where  s.code=:code ",
								new String[] { "code"}, new Object[] { i.getAddressNumber()});
						if(stores.size()>0){
							Store st=stores.get(0);
							p.setStore(st);
							p.setShipToName(st.getName());
							p.setShipToContact(st.getContact());
							p.setShipToAddress(st.getAddress());
						}
						commonDao.store(p);
					}
					List<Item> items = commonDao.findByQuery("from Item i where  i.company.id =:company_id and i.code=:code ",
							new String[] { "company_id", "code"}, new Object[] { company.getId(),i.getIdentifier2ndItem() });
					if(items.size()>0){
						PickTicketDetail ptd=EntityFactory.getEntity(PickTicketDetail.class);
						Item item=items.get(0);
						PackageUnit packageUnit= item.getMinPackageUnit();
						ptd.setItem(item);
						ptd.setPackageUnit(packageUnit);
						ptd.setLineNumber(i.getLineNumber());
						ptd.setOrderQuantity(Double.parseDouble(i.getUnitsTransactionQty()));
						if(!item.isBeMarkWeight()){
							System.out.println(item.getCode());
							double ca=item.getCAcoefficient()==null?1.0:item.getCAcoefficient();
							ptd.setOrderQuantity(Math.ceil(ptd.getOrderQuantity()/ca));
							ptd.setWeight(Double.parseDouble(i.getUnitsTransactionQty()));
						}
						System.out.println(ptd.getOrderQuantity());
						pickTicketManager.addPlanPickTicketDetail(p.getId(),ptd);
						i.setStatus("FINISH");
						commonDao.store(i);
					}else{
						if(p.getDescription()!=null){
							p.setDescription(p.getDescription()+i.getIdentifier2ndItem()+";");
						}else{
							p.setDescription(i.getIdentifier2ndItem()+";");
						}
						commonDao.store(p);
						i.setException_des("货品不存在");
						i.setStatus("FAIL");
						commonDao.store(i);
					}
				}else{  
					i.setException_des("出库单类型没有，需要维护！");
					i.setStatus("FAIL");
					commonDao.store(i);
				}
			}else{
				i.setException_des("客户不存在！");
				i.setStatus("FAIL");
				commonDao.store(i);
			}
		}
   }
   
   public void getWmsAsn(){
	   SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd");//小写的mm表示的是分钟  
	   List<InterfaceWmsPurchase> iwa = commonDao
				.findByQuery(
						"from InterfaceWmsPurchase i where i.status = 'READY' order by id");
	   for(InterfaceWmsPurchase i:iwa){
		   Structure company=null;
			List<Structure> companys = commonDao.findByQuery(
							"from Structure s where  s.interfaceId =:company_id  ",
							new String[] { "company_id"}, 
							new Object[] { i.getCostCenter() });
			if(companys.size()>0){
				company=companys.get(0);
			}
			if(company==null){
				System.out.println("客户不存在！");
			}
			ASN asn=EntityFactory.getEntity(ASN.class);
			List<ASN> asns = commonDao.findByQuery(
					"from ASN a where  a.relatedBill1 =:relatedBill1 and a.company.id =:company",
					new String[] { "relatedBill1","company"}, 
					new Object[] { i.getDocumentOrderInvoiceE(),company.getId() });
			if(asns.size()>0){
				asn=asns.get(0);
			}
			List<BillType> billTypes = commonDao.findByQuery(
					"from BillType b where  b.company.id =:company_id and b.type='RECEIVE'  ",
					new String[] { "company_id"}, 
					new Object[] { company.getId() });
			BillType b=EntityFactory.getEntity(BillType.class);
			if(billTypes.size()>0){
				b=billTypes.get(0);
			}else{
				System.out.println("出库单类型没有，需要维护！");
			}
			if(asns.size()<=0){
				asn.setCompany(company);
				asn.setRelatedBill1(i.getDocumentOrderInvoiceE());
				asn.setBillType(b);
				asn.setRelatedBill3(i.getOrderType());
				 List<Location> objs =  commonDao.findByQuery(" from Location o where o.warehouse.id=:id  and o.type ='RECEIVE'",
							new String[] { "id"},new Object[] {1183l});
				 if(objs.size()>0){
				 Location l =objs.get(0);
				asn.setDock(l);
				 }
				 asn.setCode(this.bussinessCodeManager.generateDayCode("AFD", 4));
				 asn.setWarehouse(commonDao.load(Warehouse.class, 1l));
				 asn.setStatus(ASNStatus.OPEN);
				 asn.setUserName(i.getUserId());
				 asn.setUpdateTime(new Date());
				try {
					asn.setOrderDate(sdf.parse(i.getDateTransactionJulian()));
					asn.setReceivedDate(sdf.parse(i.getDateRequestedJulian()));
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				company.setWarehouseId(i.getCostCenter());
				commonDao.store(company);
				commonDao.store(asn);
				}
			
			ASNDetail ad=EntityFactory.getEntity(ASNDetail.class);
			List<Item> items = commonDao.findByQuery(
					"from Item i where  i.company.id =:company_id and i.code=:code ",
					new String[] { "company_id", "code"}, 
					new Object[] { company.getId(),i.getIdentifier2ndItem() });
	Item item=EntityFactory.getEntity(Item.class);
	PackageUnit packageUnit=EntityFactory.getEntity(PackageUnit.class);
	if(items.size()>0){
		item=items.get(0);
		packageUnit= item.getMinPackageUnit();
	}else{
		System.out.println("该货品不存在！");
	}
	ad.setItem(item);
	ad.setPackageUnit(packageUnit);
	ad.setExpectedQuantity(Double.parseDouble(i.getUnitsTransactionQty()));
	ad.setLineNo(Integer.parseInt(i.getLineNumber()));
	asnManager.addASNDetail(asn.getId(), ad);
	i.setYesOrNoEntry("Y");
	i.setStatus("FINISH");
	System.out.println("-------------------------------------");
	commonDao.store(i);
			
		   
	   }
	   
   }
}
