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

import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import net.sf.json.JSONObject;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.hibernate.Query;
import org.hibernate.Session;
import org.jaxen.function.SumFunction;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.transaction.annotation.Transactional;

import com.dev.swms.client.ui.constant.CT_PA;
import com.dev.swms.client.ui.javabean.PT_ALLOCATED;
import com.dev.swms.client.ui.javabean.PT_AVAILABLE;
import com.dev.swms.client.ui.javabean.PT_DETAILS;
import com.dev.swms.client.ui.javabean.PT_INFO;
import com.dev.swms.server.interfaces.ItemJobLauncher;
import com.dev.swms.server.model.abstractEntity.AbstractMoveDoc;
import com.dev.swms.server.model.abstractEntity.AbstractMoveDocDetail;
import com.dev.swms.server.model.abstractEntity.AddOutPlanList;
import com.dev.swms.server.model.abstractEntity.AutoProduction;
import com.dev.swms.server.model.abstractEntity.BigItem;
import com.dev.swms.server.model.abstractEntity.BomAccount;
import com.dev.swms.server.model.abstractEntity.BomList;
import com.dev.swms.server.model.abstractEntity.DesignList;
import com.dev.swms.server.model.abstractEntity.HoistingData;
import com.dev.swms.server.model.abstractEntity.ItemList;
import com.dev.swms.server.model.abstractEntity.ModelPlan;
import com.dev.swms.server.model.abstractEntity.OfflineData;
import com.dev.swms.server.model.abstractEntity.Pinfan;
import com.dev.swms.server.model.abstractEntity.PlanAssembly;
import com.dev.swms.server.model.abstractEntity.PlanPickDetail;
import com.dev.swms.server.model.abstractEntity.PlanPickTicket;
import com.dev.swms.server.model.abstractEntity.ProduceMonthPlan;
import com.dev.swms.server.model.abstractEntity.ProductionPlan;
import com.dev.swms.server.model.abstractEntity.SpareParts;
import com.dev.swms.server.model.base.Address;
import com.dev.swms.server.model.base.BillType;
import com.dev.swms.server.model.base.BoxModel;
import com.dev.swms.server.model.base.BoxModelType;
import com.dev.swms.server.model.base.CompanyCode;
import com.dev.swms.server.model.base.Contact;
import com.dev.swms.server.model.base.Item;
import com.dev.swms.server.model.base.ItemKey;
import com.dev.swms.server.model.base.Line;
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.SignFile;
import com.dev.swms.server.model.base.Structure;
import com.dev.swms.server.model.base.SysCode;
import com.dev.swms.server.model.base.PackageUnit;
import com.dev.swms.server.model.base.StorageType;
import com.dev.swms.server.model.base.Store;
import com.dev.swms.server.model.base.TransSite;
import com.dev.swms.server.model.base.TurnOverMode;
import com.dev.swms.server.model.base.Warehouse;
import com.dev.swms.server.model.base.WarehouseArea;
import com.dev.swms.server.model.base.Worker;
import com.dev.swms.server.model.delivery.ExecutePlan;
import com.dev.swms.server.model.delivery.ExecutePlantStatus;
import com.dev.swms.server.model.fee.BillFee;
import com.dev.swms.server.model.fee.Fee;
import com.dev.swms.server.model.interfaceLog.InterfaceLog;
import com.dev.swms.server.model.inventory.Inventory;
import com.dev.swms.server.model.inventory.InventoryLog;
import com.dev.swms.server.model.inventory.InventoryLogType;
import com.dev.swms.server.model.inventory.ItemKeyInventory;
import com.dev.swms.server.model.inventory.Stock;
import com.dev.swms.server.model.inventory.Task;
import com.dev.swms.server.model.inventory.TaskLog;
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.rules.CompanyWorkRule;
import com.dev.swms.server.model.rules.PresentSaleRule;
import com.dev.swms.server.model.rules.WaveRule;
import com.dev.swms.server.model.shipping.BOL;
import com.dev.swms.server.model.shipping.BOLCaseDetail;
import com.dev.swms.server.model.shipping.BOLDetail;
import com.dev.swms.server.model.shipping.BOLStatus;
import com.dev.swms.server.model.shipping.MasterBOL;
import com.dev.swms.server.model.shipping.MasterBOLStatus;
import com.dev.swms.server.model.shipping.Package;
import com.dev.swms.server.model.shipping.PackageDetail;
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.model.shipping.PlanPickTicketDetail;
import com.dev.swms.server.model.shipping.PlanShipDetail;
import com.dev.swms.server.model.shipping.PreAllocate;
import com.dev.swms.server.model.shipping.Prewave;
import com.dev.swms.server.model.shipping.PrintXppRecord;
import com.dev.swms.server.model.shipping.ProductPackageUnit;
import com.dev.swms.server.model.shipping.RkEwmRecord;
import com.dev.swms.server.model.shipping.ShipmentType;
import com.dev.swms.server.model.shipping.WaveDocStatus;
import com.dev.swms.server.service.GlobalParamUtils;
import com.dev.swms.server.service.base.ItemManager;
import com.dev.swms.server.service.fee.FeeManager;
import com.dev.swms.server.service.interfaceLog.InterfaceLogManager;
import com.dev.swms.server.service.inventory.InventoryManager;
import com.dev.swms.server.service.picking.allocate.AutoAllocator;
import com.dev.swms.server.service.sequence.BussinessCodeManager;
import com.dev.swms.server.service.shipping.PickTicketManager;
import com.dev.swms.server.service.task.AllocateManager;
import com.dev.swms.server.utils.DateUtil;
import com.dev.swms.server.utils.DoubleUtils;
import com.dev.swms.server.utils.NewLotInfoParser;
import com.dev.swms.server.web.filter.WarehouseHolder;
import com.dev.energy.client.ui.page.IPage;
import com.dev.energy.server.config.ui.engine.Mapping.Int;
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.util.LocalizedMessage;
import com.dev.energy.server.web.security.UserHolder;

/**
 * @author  dev
 * 
 */
@SuppressWarnings("unchecked")
public class DefaultPickTicketManager extends DefaultBaseManager implements
		PickTicketManager {
	protected final ItemManager itemManager;
	protected final InventoryManager inventoryManager;
	protected final AutoAllocator autoAllocator;
	private final BussinessCodeManager bussinessCodeManager;
	protected final InterfaceLogManager logManager;
	protected final FeeManager feeManager;
	protected final AllocateManager allocateManager;
	protected final String lotparam = "inventory.itemKeyInventory.itemKey.lotInfo.";
	
	public DefaultPickTicketManager(ItemManager manager,
			InventoryManager manager2, AutoAllocator autoAllocator,
			BussinessCodeManager manager3, InterfaceLogManager manager4, FeeManager feeManager,AllocateManager allocateManager) {
		super();
		this.itemManager = manager;
		this.inventoryManager = manager2;
		this.autoAllocator = autoAllocator;
		this.bussinessCodeManager = manager3;
		this.logManager = manager4;
		this.feeManager=feeManager;
		this.allocateManager=allocateManager;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.dev.swms.server.service.shipping.PickTicketManager#storePickTicket(com.dev.swms.server.model.shipping.PickTicket)
	 */
	public void storePickTicket(PickTicket pickTicket) {
		if(pickTicket.getZone()!=null){
			pickTicket.setCompany(pickTicket.getZone().getSupplier());
		}
		if(pickTicket.getCompany()==null) {
			pickTicket.setCompany(commonDao.load(Structure.class, 1002L));
		}
		if (pickTicket.isNew()) {
//			pickTicket.setCode(this.bussinessCodeManager.generateDayCode("AFD", 4));
			pickTicket.setWarehouse(WarehouseHolder.getWarehouse());
			pickTicket.setStatus(PickTicketStatus.OPEN);
			if(pickTicket.getBillType().getCode().equals("QTCK")){
//				pickTicket.setStatus(PickTicketStatus.OPEN);
				pickTicket.setCode(this.bussinessCodeManager.getCodeForYm("QT",3));
			}else{
				pickTicket.setCode(this.bussinessCodeManager.getCodeForYm("BH",3));
//				pickTicket.setPlanStatus(PickTicketStatus.OPEN);
			}
			pickTicket.setUserTracking();
		}else{
//			if(!pickTicket.getStatus().equals(PickTicketStatus.OPEN)){
//				throw new BusinessException("状态不正确，不能保存！");
//			}
//			if(pickTicket.getBillType().getCode().equals("QTCK")){
//				pickTicket.setStatus(PickTicketStatus.OPEN);
//			}
////			if(pickTicket.getZone()!=null){
////				pickTicket.setCompany(pickTicket.getZone().getSupplier());
////			}
			this.commonDao.store(pickTicket);
		}
		
//		//判断客户订单重复
//		if(pickTicket.getRelatedBill1()!=null&&!pickTicket.getRelatedBill1().equals("")){
//		List<PickTicket> pts =  commonDao.findByQuery(" from PickTicket p where p.relatedBill1=:relatedBill1 ",
//				new String[] { "relatedBill1"},new Object[] {pickTicket.getRelatedBill1()});
//			if(pickTicket.isNew()){
//				if(pts.size()>0){
//					throw new BusinessException(pickTicket.getRelatedBill1()+",重复不能保存！");
//				}
//			}else{
//				if(pts.size()>=1){
//					PickTicket p=pts.get(0);
//					if(p.getId().equals(pickTicket.getId())){
//						
//					}else{
//						throw new BusinessException(pickTicket.getRelatedBill1()+",重复不能保存！");
//					}
//				}
//				
//			}
//		
//		}
		if(pickTicket.getDock()==null) {
			 List<Location> objs =  commonDao.findByQuery(" from Location o where o.warehouse.id=:id  and o.type ='SHIP'",
						new String[] { "id"},new Object[] {WarehouseHolder.getWarehouse().getId()});
			 Location l =objs.get(0);
			 pickTicket.setDock(l); 
		}
//		if (pickTicket.getDock() == null || pickTicket.getDock().getId() == 0) {
//			 List<Location> objs =  commonDao.findByQuery(" from Location o where o.warehouse.id=:id  and o.type ='SHIP' and o.disabled=false",
//						new String[] { "id"},new Object[] {WarehouseHolder.getWarehouse().getId()});
//			 Location l =objs.get(0);
//			 pickTicket.setDock(l); 
//
//		} else {
//			pickTicket.setDock(this.load(Location.class, pickTicket.getDock().getId()));
//		}
		this.commonDao.store(pickTicket);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.dev.swms.server.service.shipping.PickTicketManager#deleteAll(java.util.List)
	 */
	public void deleteAll(List<Long> pickTicketIds) {
		System.out.println("VMI deleteAll");
		String errMsg = "";
		for (Long id : pickTicketIds) {
			PickTicket pickTicket = commonDao.load(PickTicket.class, id);
		
			if(pickTicket.getStatus().equals(PickTicketStatus.OPEN)){
				List<PlanPickTicketDetail> pptds = this.commonDao.findByQuery(
						"from PlanPickTicketDetail p where p.pickTicket.id=:p_id ",new String[] { "p_id" },new Object[] { pickTicket.getId() });
				for(PlanPickTicketDetail pptd:pptds){
					PlanShipDetail psd=pptd.getPsd();
					psd.setPtd(null);
					psd.setPptd(null);
					this.commonDao.store(psd);
					unLockVMI(pptd.getZone().getId(),pptd.getLocation().getId(),pptd.getItemKey().getId(),pptd.getAllocatedQuantity(),Boolean.FALSE,null);
					this.commonDao.delete(pptd);
				}
				List<PickTicketDetail> ptds = this.commonDao.findByQuery(
						"from PickTicketDetail p where p.pickTicket.id=:p_id ",new String[] { "p_id" },new Object[] { pickTicket.getId() });
				for(PickTicketDetail ptd:ptds){
					if(pickTicket.getWarehouse().getId().equals(new Long("1"))){
						List<Task> ts=this.commonDao.findByQuery("from Task t where t.pickTicketDetail.id="+ptd.getId());
						if(ts.size()>0){
							throw new BusinessException("出单数量大于0不能删除,先取消分配");
						}
					}
					if(ptd.getItemKey()!=null&&ptd.getAllocatedQuantity()>0){
						Boolean xbc=Boolean.FALSE;
						if(ptd.getZone().getCode().indexOf("-SL")>0) {
							xbc=Boolean.TRUE;
							if(ptd.getZzkw()==null){
								throw new BusinessException(ptd.getItem().getCode()+"制造库位必填");
							}
						}
						unLockVMI(ptd.getZone().getId(),ptd.getLocation().getId(),ptd.getItemKey().getId(),ptd.getAllocatedQuantity(),xbc,ptd.getZzkw());
					}
					if(ptd.getApplyDocDetailId()!=null){
						PlanPickDetail ppd=this.commonDao.get(PlanPickDetail.class, ptd.getApplyDocDetailId());
						if(ppd!=null){
							ppd.setAllocatedQuantity(ppd.getAllocatedQuantity()-ptd.getOrderQuantity());
							ppd.setQty1(0);
							this.commonDao.store(ppd);
						}
					}
					//删除现品票
					List<PrintXppRecord> rs=this.commonDao.findByQuery("from PrintXppRecord r where r.ptd.id="+ptd.getId());
					this.commonDao.deleteAll(rs);
					this.commonDao.delete(ptd);
				}
				if(pickTicket.getSourceId()!=null){
//					PlanPickTicket ppt=this.commonDao.get(PlanPickTicket.class, new Long(pickTicket.getSourceId()));
//					ppt.setStatus("OPEN");
//					this.commonDao.store(ppt);
				}
				this.commonDao.delete(pickTicket);
				//对应手工指示回到对应状态
				
			}else{
				throw new BusinessException("已审核，不能删除");
			}
		}
//			if (PickTicketStatus.OPEN.equals(pickTicket.getStatus())||PickTicketStatus.PRE_OPEN.equals(pickTicket.getStatus())) {
//				List<PickTicketDetail> ptds = this.commonDao.findByQuery(
//								"from PickTicketDetail p where p.pickTicket.id=:p_id ",new String[] { "p_id" },new Object[] { pickTicket.getId() });
//				for(PickTicketDetail ppd:ptds){
//					commonDao.delete(ppd);
//				}
//				commonDao.delete(pickTicket);
//				errMsg+=pickTicket.getCode()+" 发货单删除成功;";
//			}
//			else
//				errMsg+=pickTicket.getCode()+" 发货单删除失败;";
	}
	
	public void deleteShipDetail(List<Long> ids) {
		for (Long id : ids) {
			PlanShipDetail d = commonDao.load(PlanShipDetail.class, id);
			if(d.getPptd()!=null){
				throw new BusinessException("已加入备货计划，不能删除");
			}else{
				this.commonDao.delete(d);
			}
		}
	}
	public void deletePlanPickDetail(List<Long> ids) {
		for (Long id : ids) {
			PlanPickDetail d = commonDao.load(PlanPickDetail.class, id);
//			PlanShipDetail d = commonDao.load(PlanShipDetail.class, id);
//			if(d.getPptd()!=null){
//				throw new BusinessException("已加入备货计划，不能删除");
//			}else{
//				this.commonDao.delete(d);
//			}
			if(d.getPlanPickTicket().getStatus().equals(PickTicketStatus.OPEN)||d.getAllocatedQuantity()<=0){
				PlanPickTicket pt=d.getPlanPickTicket();
				this.commonDao.delete(d);
				List<PlanPickDetail> ds=this.commonDao.findByQuery("from PlanPickDetail d where d.planPickTicket.id="+pt.getId());
				if(ds.size()<=0){
					this.commonDao.delete(pt);
				}
				
			}else{
				throw new BusinessException("已加入备货计划，不能删除");
			}
		}
	}
	
	public void cancelPlanPick(List<Long> ids) {
		List<PlanPickTicket> ppts=new ArrayList<PlanPickTicket>();
		for (Long id : ids) {
			PlanPickDetail d = commonDao.load(PlanPickDetail.class, id);
			ppts.add(d.getPlanPickTicket());
			List<Long> pt_ids=this.commonDao.findByQuery("select id from PickTicket pt where pt.waveCode='"+d.getPlanPickTicket().getCode()+"'");
			this.deleteAll(pt_ids);
			d.setAllocatedQuantity(0);
			this.commonDao.store(d);
		}
		for(PlanPickTicket ppt:ppts){
			if(!ppt.getStatus().equals(PickTicketStatus.OPEN)){
				ppt.setStatus(PickTicketStatus.OPEN);
				this.commonDao.store(ppt);
				List<PlanPickDetail> ds=this.commonDao.findByQuery("from PlanPickDetail d where d.planPickTicket.id="+ppt.getId());
				for(PlanPickDetail d:ds){
					d.setAllocatedQuantity(0);
					this.commonDao.store(d);
				}
			}
		}
			
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.dev.swms.server.service.shipping.PickTicketManager#cancelAll(java.util.List)
	 */
	public void cancelAll(List<Long> pickTicketIds) {
		String errMsg = "";
		for (Long id : pickTicketIds) {
			PickTicket pickTicket = commonDao.load(PickTicket.class, id);
			if (pickTicket.cancel()) {
				errMsg+=pickTicket.getCode()+" 发货单取消成功;";
			}
			else
				errMsg+=pickTicket.getCode()+" 发货单取消失败;";
		}
		LocalizedMessage.addLocalizedMessage(errMsg);
	}
	
	/*
	 * (non-Javadoc)
	 * @see com.dev.swms.server.service.shipping.PickTicketManager#closeAll(java.util.List)
	 */
	public void closeAll(List<Long> pickTicketIds) {
		for (Long id : pickTicketIds) {
			PickTicket pickTicket = commonDao.load(PickTicket.class, id);
			pickTicket.setStatus(PickTicketStatus.CLOSE);
			this.commonDao.store(pickTicket);
		}
//		int i = 0;
//		for (Long id : pickTicketIds) {
//			PickTicket pickTicket = commonDao.load(PickTicket.class, id);
//			if (pickTicket.close()) {
//		        //如果发货单中有已分配未拣货记录，直接释放分配数量
//				autoAllocator.unallocate(pickTicket);
//				
//				//删除预分配表中与该发货单关联的所有预分配记录
//				commonDao.executeByNamed("deletePreAllocateByWarehouseAndCode", 
//						new String[] {"code", "warehouseId"}, new Object[] {pickTicket.getCode(), pickTicket.getWarehouse().getId()});
//
//				i++;
//			}
//		}
//		LocalizedMessage.addMessage("pickTicket.close.success",
//				new String[] { String.valueOf(i) });
	}

	/*
	 * (non-Javadoc)
	 * @see com.dev.swms.server.service.shipping.PickTicketManager#addPickTicketDetail(java.lang.Long,
	 *      com.dev.swms.server.model.shipping.PickTicketDetail)
	 */
	public void addPickTicketDetail(Long pickTicketId, PickTicketDetail pickTicketDetail) {
		PickTicket pickTicket = commonDao.load(PickTicket.class, pickTicketId);
		PackageUnit packageUnit = commonDao.load(PackageUnit.class,pickTicketDetail.getPackageUnit().getId());
	
		pickTicketDetail.setOrderQuantity(DoubleUtils.formatByPrecision(pickTicketDetail.getOrderQuantity(), packageUnit.getPrecision()));
		if (pickTicketDetail.getOrderQuantity() <= 0) {
			throw new BusinessException("docDetail.add.quantityError");
		}

		if (PickTicketStatus.OPEN.equals(pickTicket.getStatus())) {
			if (!packageUnit.getItem().getId().equals(pickTicketDetail.getItem().getId())) {
				throw new BusinessException("docDetail.itemPackageUnit.disMatch");
			}
			// 新增明细
			if (pickTicketDetail.isNew()) {
				pickTicketDetail.setPackageUnit(packageUnit);
				pickTicketDetail.setOldRecord(true);
				pickTicketDetail.setItem(pickTicketDetail.getItem());
				pickTicketDetail.setOrderQtyOfMasterUnit(pickTicketDetail.getOrderQuantity()*packageUnit.getConvertFigure());
				PickTicketDetail existPickTicketDetail = pickTicket.getPickTicketDetail(pickTicketDetail);
				pickTicketDetail.setCaCoefficient(pickTicketDetail.getItem().getCAcoefficient());
				if (existPickTicketDetail == null) {
					pickTicket.addPickTicketDetail(pickTicketDetail);
				} else {
					pickTicket.addOrderQuantity(existPickTicketDetail,	pickTicketDetail.getOrderQuantity(), packageUnit);
					LocalizedMessage.addMessage("receivingDocDetail.add.modify");
				}
			// 修改明细
			} else {
				double newQuantity = pickTicketDetail.getOrderQuantity();
				
				NewLotInfo newLotInfo= pickTicketDetail.getNewLotInfo();
				
				pickTicketDetail = commonDao.load(PickTicketDetail.class, pickTicketDetail.getId());
				double deltaQuantity = newQuantity - pickTicketDetail.getOrderQuantity();
				
				pickTicketDetail.setOrderQuantity(newQuantity);
				pickTicketDetail.setNewLotInfo(newLotInfo);
				pickTicketDetail.setOrderQtyOfMasterUnit(pickTicketDetail.getOrderQuantity()*packageUnit.getConvertFigure());
				pickTicket.setOrderQuantity(pickTicket.getOrderQuantity()+ deltaQuantity*packageUnit.getConvertFigure());
				if (pickTicketDetail.getOrderQuantity() == 0) {
					pickTicket.getPickTicketDetails().remove(pickTicketDetail);
				}
			}
			commonDao.store(pickTicket);
		}
	}
	
	
	public void addPickTicketDetails(Long pickTicketId,List<Long> ids) {
		PickTicket pickTicket = commonDao.load(PickTicket.class, pickTicketId);
		for(Long id:ids){
			PlanShipDetail psd=this.commonDao.get(PlanShipDetail.class, id);
			if(psd.getPptd()!=null){
				continue;
			}
			PlanPickTicketDetail ptd=EntityFactory.getEntity(PlanPickTicketDetail.class);
			ptd.setPsd(psd);
			ptd.setOrderQuantity(psd.getShsl());
			ptd.setPickTicket(pickTicket);
			this.commonDao.store(ptd);
			psd.setPptd(ptd);
			pickTicket.setOrderQuantity(pickTicket.getOrderQuantity()+psd.getShsl());
			this.commonDao.store(pickTicket);
//			List<WarehouseArea> was=this.commonDao.findByQuery("from WarehouseArea w where w.beReject=0 and "
//					+ " w.supplier.id="+pickTicket.getCompany().getId());
//			if(was.size()>0){
//				pickTicket.setZone(was.get(0));
				this.commonDao.store(pickTicket);
				double qty=lockInvPlanDetail(ptd, pickTicket.getZone());
				if(qty<ptd.getOrderQuantity()){
					throw new BusinessException(psd.getItem().getCode()+"库存不足");
				}
//			}
		}
	}
	//锁定库存方法
	public double lockInvPlanDetail(PlanPickTicketDetail d,WarehouseArea zone){
		double qty=d.getOrderQuantity();
		if(qty>0){
			Item it=d.getPsd().getItem();
			String hql="from Inventory inv where inv.itemKey.item.id="+d.getPsd().getItem().getId()
					+" and inv.zone.id="+zone.getId();
			if(it.getLocation()!=null){
				hql+=" and inv.location.id="+it.getLocation().getId();
			}
			List<Inventory> invs=this.commonDao.findByQuery(hql);
			if(invs.size()>0){
				double kjQty=qty;
				double syqty=qty;
				for(Inventory inv:invs){
					if(syqty>0&&inv.getQuantity()>0){
						ItemKey itemKey=inv.getItemKey();
						if(qty<kjQty){
							continue;
						}
						if((inv.getQuantity()-inv.getQueuedQuantity())<syqty){
							kjQty=(inv.getQuantity()-inv.getQueuedQuantity());
						}
						syqty=syqty-kjQty;
						inv.setQueuedQuantity(inv.getQueuedQuantity()+kjQty);
						this.commonDao.store(inv);
						d.setAllocatedQuantity(d.getAllocatedQuantity()+kjQty);
						d.setItemKey(itemKey);
						d.setLocation(inv.getLocation());
						d.setZone(zone);
						d.setAllocateTime(new Date());
						this.commonDao.store(d);
					}else{
						break;
					}
				}
			}
		}
		return d.getAllocatedQuantity();
	}
	
	//锁定库存方法
		public double lockInvDetail(PickTicketDetail d,WarehouseArea zone,Location zzkw,Boolean xbc){
			double qty=d.getOrderQuantity();
			if(qty>0){
				String hql="from Inventory inv where inv.itemKey.item.id="+d.getItem().getId()
						+" and inv.zone.id="+zone.getId()+" and inv.location.type!='SHIP' and inv.SOI is null ";
				if(d.getBonded()!=null&&!d.getBonded().equals("")){
					hql+=" and inv.itemKey.pinfan.bonded='"+d.getBonded()+"'";
				}
				if(d.getItem().getLocation()!=null){
					hql+=" and inv.location.id='"+d.getItem().getLocation().getId()+"'";
				}
				if(xbc){
					hql+=" and inv.zzkw.id="+zzkw.getId();
				}
				List<Inventory> invs=this.commonDao.findByQuery(hql);
				if(invs.size()>0){
					double kjQty=qty;
					double syqty=qty;
					for(Inventory inv:invs){
						if(syqty>0){
							if(inv.getQuantity()>0){
								ItemKey itemKey=inv.getItemKey();
								if(qty<kjQty){
									continue;
								}
								if((inv.getQuantity()-inv.getQueuedQuantity())<syqty){
									kjQty=(inv.getQuantity()-inv.getQueuedQuantity());
								}
								syqty=syqty-kjQty;
								inv.setQueuedQuantity(inv.getQueuedQuantity()+kjQty);
								this.commonDao.store(inv);
								d.setAllocatedQuantity(d.getAllocatedQuantity()+kjQty);
								d.setItemKey(itemKey);
								d.setLocation(inv.getLocation());
								d.setZone(zone);
								d.setAllocateTime(new Date());
								d.setPf(itemKey.getPinfan());
								this.commonDao.store(d);
								Task t=d.getPickTicket().allocate(null,d, inv, kjQty);
							}
						}else{
							break;
						}
					}
				}
			}
			return d.getAllocatedQuantity();
		}
		
		public double lockInvKAMS(PickTicketDetail d,WarehouseArea zone,Location zzkw){
			double qty=d.getOrderQuantity();
			if(qty>0){
//				List<Inventory> invs=this.commonDao.findByQuery("from Inventory inv where inv.itemKey.item.id="+d.getItem().getId()
//						+" and inv.zone.id="+zone.getId()+ " and inv.itemKey.pinfan.specs='"+d.getSpecs()+"'"
//								+ " and inv.itemKey.pinfan.content='"+d.getContent()+"' and inv.itemKey.pinfan.bonded='"+d.getBonded()+"'");
				String hql="from Inventory inv where inv.itemKey.item.id="+d.getItem().getId()
						+" and inv.zone.id="+zone.getId()+ " and inv.itemKey.pinfan.bonded='"+d.getBonded()+"' and inv.location.type!='SHIP'";
				if(zone.getCode().indexOf("-SL")>0){
					if(zzkw!=null){
						hql+=" and inv.zzkw.id="+zzkw.getId();
					}
				}
				List<Inventory> invs=this.commonDao.findByQuery(hql);
				if(invs.size()>0){
					double kjQty=qty;//可拣货数量
					double syqty=qty;//剩余数量
					for(Inventory inv:invs){
						if(syqty>0&&inv.getQuantity()>0){
							ItemKey itemKey=inv.getItemKey();
//							if(qty<kjQty){
//								continue;
//							}
							if((inv.getQuantity()-inv.getQueuedQuantity())<syqty){
								kjQty=(inv.getQuantity()-inv.getQueuedQuantity());
							}else{
								kjQty=syqty;
							}
							syqty=syqty-kjQty;
							inv.setQueuedQuantity(inv.getQueuedQuantity()+kjQty);
							this.commonDao.store(inv);
							d.setAllocatedQuantity(d.getAllocatedQuantity()+kjQty);
							d.setItemKey(itemKey);
							d.setLocation(inv.getLocation());
							d.setZone(zone);
							d.setAllocateTime(new Date());
							d.setPf(itemKey.getPinfan());
							this.commonDao.store(d);
							Task t=d.getPickTicket().allocate(null,d, inv, kjQty);
						}else{
							continue;
						}
					}
				}
			}
			return d.getAllocatedQuantity();
		}
	/*
	 * (non-Javadoc)
	 * 
	 * @see com.dev.swms.server.service.shipping.PickTicketManager#removePickTicketDetail(java.lang.Long,
	 *      java.util.List)
	 */

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.dev.swms.server.service.shipping.PickTicketManager#manualAllocate(java.lang.Long,
	 *      java.util.Map)
	 */
	
//部分分配 zhuhejing	
	@SuppressWarnings("unchecked")
	public Map manual_Allocate(Map clientParams) {
		Long pickTicketDetailId = (Long) clientParams.get("pickTicketDetailId");
		Map inventories = (Map)clientParams.get(IPage.TABLE_INPUT_VALUES);
		Map result = new HashMap();

		result.put("pickTicketDetailId", pickTicketDetailId);
		PickTicketDetail pickTicketDetail = commonDao.load(PickTicketDetail.class, pickTicketDetailId);
//		if(pickTicketDetail.getPickTicket().getStatus().equals("ACTIVE")){
//		if(!preAllocate(pickTicketDetail.getPickTicket().getId()))
//			return null;
//		}
		autoAllocator.manualAllocate(pickTicketDetail, inventories);
		
		return result;
	}

	
	
//整单分配 zhuhejing
	@SuppressWarnings("unchecked")
	public Map auto_Allocate(Map params) {
		Long pickTicketId = (Long) params.get("pickTicketId");
		List<Long> pickTicketDetailIds = (List<Long>) params.get("parentIds");
		
		Map result = new HashMap();
		result.put("pickTicketId", pickTicketId);
		
		PickTicket pickTicket = this.commonDao.load(PickTicket.class, pickTicketId);
		if(pickTicket.getStatus().equals("ACTIVE")){
		if(!preAllocate(pickTicketId))
			 return result;
		}
		if (PickTicketStatus.PREALLOCATE.equals(pickTicket.getStatus()) 
				|| PickTicketStatus.ALLOCATE.equals(pickTicket.getStatus())
				|| PickTicketStatus.SHIP_PART.equals(pickTicket.getStatus())) {
			List<AbstractMoveDocDetail> details = new ArrayList<AbstractMoveDocDetail>();
			if (pickTicketDetailIds == null || pickTicketDetailIds.size() == 0) {
				if (pickTicket.getPickTicketDetails() == null || pickTicket.getPickTicketDetails().size() == 0) {
					throw new BusinessException("pickTicket.details.none");
				}
				details.addAll(pickTicket.getAbstractMoveDocDetails());
			} else {
				List<PickTicketDetail> pickTicketDetails = this.commonDao.loadAll(PickTicketDetail.class, pickTicketDetailIds.toArray(new Long[] {}));
				for(PickTicketDetail detail :pickTicketDetails){
					details.add(detail);
				}
			}
			autoAllocator.allocate(null, null, null, details);
		}
		
		return result;
	}
	
	public void unallocate(List<Long> pickTicketIds) {
		for (Long id : pickTicketIds) {
			PickTicket pickTicket = commonDao.load(PickTicket.class, id);
			autoAllocator.unallocate(pickTicket);
//			//如果该发货单货主作业规则中预约发货=false时，同时还要取消原自动填写的预分配数量
//			if(!pickTicket.getCompany().getCompanyWorkRule().isInvSubscribe()){
//				for(PickTicketDetail detail : pickTicket.getPickTicketDetails()){
//					detail.setPreAllocatedQuantity(0);
//				}
//			}
			pickTicket.setRelatedBill2(null);
		}
	}	
	
	//取消分配 如果取消分配后，对应发货记录的分配数量为0,则记录下来最后一起删除 zhuhejing	
	@SuppressWarnings("unchecked")
	public Map cancell_Allocate(Map clientParams) {
		String barCode=null;
		Long pickTicketId = (Long) clientParams.get("pickTicketId");
		Map tasks = (Map)clientParams.get(IPage.TABLE_INPUT_VALUES);
		Map result = new HashMap();
		result.put("pickTicketId", pickTicketId);
		for (Object obj : tasks.keySet()) {
			Task task = commonDao.load(Task.class, (Long) obj);
			String cValue = String.valueOf(tasks.get(obj));
			double quantity = Double.valueOf(cValue);
			quantity = quantity*task.getPackageUnit().getConvertFigure();
			//if (quantity > (task.getPlanQuantityMU() - task.getMovedQuantityMU())) {
			if (DoubleUtils.compareByPrecision(quantity,(task.getPlanQuantityMU() - task.getMovedQuantityMU()),task.getPackageUnit().getPrecision())>0)
			{
				quantity = task.getPlanQuantityMU() - task.getMovedQuantityMU();
			}

			task.unallocatePick(quantity);

			ItemKeyInventory itemKeyInventory = inventoryManager.getItemKeyInventory(
					task.getSrcLoc().getWarehouse(), task.getItemKey());
			Inventory inventory = itemKeyInventory.getInventoryWithException(task.getSrcLoc(), 
					task.getPackageUnit(), task.getSrcLP(), barCode,task.getInventoryStatus(), 
					task.getStorageDate(), task.getSOI());
			inventory.unallocate(quantity, null, null);
			
			if (task.getPlanQuantityMU() <= 0) {
				commonDao.delete(task);
			}
		}
		
		return result;
	}

	public void createBOL(List<Long> pickTicketIds) {
		for (Long id : pickTicketIds) {
			//一张发货单创建BOL
			PickTicket pt = commonDao.load(PickTicket.class, id);
			boolean shipPart = true;
			if(pt.getCustomer()==null){
				shipPart = true;
			}else{
				shipPart = pt.getCustomer().isShipPart();
			}
			//if ((pt.getPickedQuantity() - pt.getBOLQuantity()) > 0 
			if (DoubleUtils.compareByPrecision(pt.getPickedQuantity() ,pt.getBOLQuantity(),2) > 0 
					&& StringUtils.isEmpty(pt.getWaveCode())
					&& (shipPart || pt.getOrderQuantity() == pt.getPickedQuantity())) {
				createBOL(id);
			}
		}
	}
	
	@SuppressWarnings("unchecked")
	public void createBOL(Long pickTicketId) {
		PickTicket pickTicket = commonDao.load(PickTicket.class, pickTicketId);
		
		BOL bol= EntityFactory.getEntity(BOL.class);
		bol.setCode(bussinessCodeManager.generateBOLCode(new HashMap()));
		bol.setWarehouse(pickTicket.getWarehouse());
		bol.setPickTicket(pickTicket);
		bol.setStatus(BOLStatus.OPEN);
		bol.setUserTracking();
		bol.setPackages(new HashSet<Package>());
		bol.setCustomer(pickTicket.getCustomer());
		bol.setStartPosition(pickTicket.getStartPosition());
		bol.setAimPosition(pickTicket.getAimPosition());
		bol.setShipToName(pickTicket.getShipToName());
		bol.setShipToAddress(pickTicket.getShipToAddress());
		bol.setShipToContact(pickTicket.getShipToContact());
		createPackage(pickTicket, bol);
		bol.setBOLDetails(new HashSet<BOLDetail>());
		
		//发货单创建BOL时（整单或部分创建）自动产生对应的BOLDetail
		List<PackageDetail> packageDetails = new ArrayList();
		for(Package pkg : bol.getPackages()){
			for(PackageDetail packageDetail : pkg.getDetails()){
				PackageDetail pkgDetail = EntityFactory.getEntity(PackageDetail.class);
				pkgDetail.setItemKey(packageDetail.getItemKey());
				pkgDetail.setPackageUnit(packageDetail.getPackageUnit());
				pkgDetail.setQuantity(packageDetail.getQuantity()*pkg.getQuantity());
				pkgDetail.setWeight(packageDetail.getWeight()*pkg.getQuantity());
				pkgDetail.setVolume(packageDetail.getVolume()*pkg.getQuantity());
				boolean flag = true;
				if(packageDetails.size() > 0){
					for(PackageDetail pd : packageDetails){
						if(pd.equals(pkgDetail)){
							pd.setQuantity(pd.getQuantity()+pkgDetail.getQuantity());
							pd.setWeight(pd.getWeight()+pkgDetail.getWeight());
							pd.setVolume(pd.getVolume()+pkgDetail.getVolume());
							flag = false;
							break;
						}
					}
					if(flag){
						packageDetails.add(pkgDetail);
					}
				}else{
					packageDetails.add(pkgDetail);
				}
			}
		}
		for(PackageDetail detail : packageDetails){
			BOLDetail bolDetail = EntityFactory.getEntity(BOLDetail.class);
			bolDetail.setBol(bol);
			bolDetail.setItemKey(detail.getItemKey());
			bolDetail.setPackageUnit(detail.getPackageUnit());
			bolDetail.setBolQuantity(detail.getQuantity());
			bolDetail.setWeight(detail.getWeight());
			bolDetail.setVolume(detail.getVolume());
			
			bol.getBOLDetails().add(bolDetail);
		}
		commonDao.store(bol);
		
		createBOLCaseDetail(pickTicket,bol);//将笼车加入BOL
	}
	/**
	 * 发货单创建bol时，将波次中产生的笼车信息写入波次对应bol中任意一个（注意不能重复写入）；
	 * @param pickTicket
	 * @param bol
	 */
	private void createBOLCaseDetail(PickTicket pickTicket,BOL bol){
		String hql = "select task from Task task inner join task.waveDocDetail waveDocDetail inner join waveDocDetail.pickTicket pickTicket " +
				" where pickTicket.id="+pickTicket.getId();
		List<Task> tasks = this.commonDao.findByQuery(hql);
		Map<BoxModel,List<Task>> map = new HashMap();//按照箱型对Task进行分组
		for(Task task:tasks){
			if(task.getCageInfo()==null)
				continue;
			if(task.getCageInfo().isBeCage() && !task.getCageInfo().isHasBOL()){//只计算是笼车的CageInfo,并且该笼车没有加入BOL
				if(map.get(task.getCageInfo().getBoxModel())==null){
					List<Task> tempTasks = new ArrayList<Task>();
					tempTasks.add(task);
					map.put(task.getCageInfo().getBoxModel(),tempTasks);
				}else{
					map.get(task.getCageInfo().getBoxModel()).add(task);
				}
				task.getCageInfo().setHasBOL(true);
				this.commonDao.store(task.getCageInfo());
			}
		}
		
		for (Object obj : map.keySet()) {
			BOLCaseDetail detail = new BOLCaseDetail();
			detail.setBol(bol);
			detail.setBoxModel((BoxModel)obj);
			detail.setShipQuantity(map.get((BoxModel)obj).size());
			detail.setSignQuantity(0);
			detail.setBackQuantity(0);
			detail.setShipToName(pickTicket.getShipToName());
			this.commonDao.store(detail);
		}
	}
	
	@SuppressWarnings("unchecked")
	public void manualCreateBOL(Map pickedQuantity, Long pickTicketId) {
		//步骤一：根据ID获取发货单，创建新的BOL
		PickTicket pickTicket = commonDao.load(PickTicket.class, pickTicketId);
		
		BOL bol= EntityFactory.getEntity(BOL.class);
		bol.setCode(bussinessCodeManager.generateBOLCode(new HashMap()));
		bol.setWarehouse(pickTicket.getWarehouse());
		bol.setPickTicket(pickTicket);
		bol.setCustomer(pickTicket.getCustomer());
		bol.setStartPosition(pickTicket.getStartPosition());
		bol.setAimPosition(pickTicket.getAimPosition());
		bol.setShipToName(pickTicket.getShipToName());
		bol.setShipToAddress(pickTicket.getShipToAddress());
		bol.setShipToContact(pickTicket.getShipToContact());
		bol.setStatus(BOLStatus.OPEN);
		bol.setUserTracking();
		bol.setPackages(new HashSet<Package>());
		bol.setBOLDetails(new HashSet<BOLDetail>());
		//步骤二：创建包装
		manualCreatePackage(pickTicket, pickedQuantity, bol);
		
		List<PackageDetail> packageDetails = new ArrayList();
		for(Package pkg : bol.getPackages()){
			for(PackageDetail packageDetail : pkg.getDetails()){
				PackageDetail pkgDetail = EntityFactory.getEntity(PackageDetail.class);
				pkgDetail.setItemKey(packageDetail.getItemKey());
				pkgDetail.setPackageUnit(packageDetail.getPackageUnit());
				pkgDetail.setQuantity(packageDetail.getQuantity()*pkg.getQuantity());
				pkgDetail.setWeight(packageDetail.getWeight()*pkg.getQuantity());
				pkgDetail.setVolume(packageDetail.getVolume()*pkg.getQuantity());
				boolean flag = true;
				if(packageDetails.size() > 0){
					for(PackageDetail pd : packageDetails){
						if(pd.equals(pkgDetail)){
							pd.setQuantity(pd.getQuantity()+pkgDetail.getQuantity());
							pd.setWeight(pd.getWeight()+pkgDetail.getWeight());
							pd.setVolume(pd.getVolume()+pkgDetail.getVolume());
							flag = false;
							break;
						}
					}
					if(flag){
						packageDetails.add(pkgDetail);
					}
				}else{
					packageDetails.add(pkgDetail);
				}
			}
		}
		for(PackageDetail detail : packageDetails){
			BOLDetail bolDetail = EntityFactory.getEntity(BOLDetail.class);
			bolDetail.setBol(bol);
			bolDetail.setItemKey(detail.getItemKey());
			bolDetail.setPackageUnit(detail.getPackageUnit());
			bolDetail.setBolQuantity(detail.getQuantity());
			bolDetail.setWeight(detail.getWeight());
			bolDetail.setVolume(detail.getVolume());
			
			bol.getBOLDetails().add(bolDetail);
		}
		commonDao.store(bol);
	}
	
	/**
	 * 创建包箱信息并添加包箱明细(手工输入数量)
	 * @param pickTicket
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public void manualCreatePackage(PickTicket pickTicket, Map pickedQuantity, BOL bol) {
		if (!pickTicket.getCompany().isBePackagedFollowASN()) {
			// 非按单包箱流程
			manualCreatePackageNotFollowASN(pickedQuantity, bol);
		} else {
			// 按单包箱流程
			manualCreatePackageFollowASN(pickTicket,pickedQuantity, bol);
		}
	}
	
	/**
	 * 非按单包箱(手工输入BOL数量): 每条单位明细的物料单独为一个包装, 对应唯一一条包箱明细
	 * @param pickedQuantity
	 * @param bol
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public void manualCreatePackageNotFollowASN(Map pickedQuantity, BOL bol) {
		for (Object obj : pickedQuantity.keySet()) {
			// 根据ID获得分组数据中的一个task_log对象
			TaskLog taskLog = (TaskLog)commonDao.load(TaskLog.class, Long.parseLong(obj.toString()));
			// 取得非按单包箱箱型
			BoxModel boxModel = (BoxModel)commonDao.findByNamedQueryUniqueResult("getBoxModelByWarehouseAndType",
					new String[]{"warehouseId", "type"},
					new Object[]{bol.getWarehouse().getId(), BoxModelType.PKG_ITEM});
			// 获取输入的数量
			double quantity = Double.parseDouble(pickedQuantity.get(obj).toString().substring(
					1, pickedQuantity.get(obj).toString().length() - 1));
			
			//if (quantity > (taskLog.getMovedQuantity() - taskLog.getBolQuantity()) || quantity <= 0) {
			if (DoubleUtils.compareByPrecision(quantity ,(taskLog.getMovedQuantity() - taskLog.getBolQuantity()),taskLog.getPackageUnit().getPrecision())>0 || quantity <= 0) {
				return;
			}
			// 非按单包箱时, 单一货品为一个Package, 对应唯一一个PackageDetail
			for (double loopQuantity = quantity; loopQuantity > 0; loopQuantity --) {
				Package pkg = new Package();
				pkg.setType(ProductPackageUnit.CASE);
				pkg.setBol(bol);
				pkg.setCode(bussinessCodeManager.generatePackage());
				pkg.setBoxModel(boxModel);
				pkg.setDescription(taskLog.getItemKey().getItem().getName());
				pkg.setUnit(taskLog.getPackageUnit().getUnit());
				pkg.setQuantity(1);
				pkg.setDetails(new HashSet<PackageDetail>());
				// 创建包装明细
				PackageDetail pkgDetail = new PackageDetail();
				pkgDetail.setPkg(pkg);
				pkgDetail.setItemKey(taskLog.getItemKey());
				pkgDetail.setPackageUnit(taskLog.getPackageUnit());
				pkgDetail.setQuantity(1);
				pkg.getDetails().add(pkgDetail);
				bol.getPackages().add(pkg);
				
				pkgDetail.refresh();
			}
			// 回写加入BOL数量到对应的taskLog, pickTicketDetail, pickTicket中
			taskLog.setBolQuantity(taskLog.getBolQuantity() + quantity);
			taskLog.getTask().getPickTicketDetail().manualAutoPack(quantity, taskLog.getPackageUnit());
		}
	}
	
	/**
	 * 按单包箱(手工输入BOL数量): 默认选取所有普通箱型中能装下该单据已经录入的所有明细的最小箱型; 如果不存在, 则使用缺省的"极大箱型"
	 * @param pickTicket
	 * @param pickedQuantity
	 * @param bol
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public void manualCreatePackageFollowASN(PickTicket pickTicket, Map pickedQuantity, BOL bol) {
		// 取出所有的普通箱型
		List<BoxModel> boxModels = commonDao.findByNamedQuery("getBoxModelByWarehouseAndType", 
				new String[] {"warehouseId", "type"},
				new Object[] {bol.getWarehouse().getId(), BoxModelType.PKG_NOMARL});
		// 初始化重量, 体积, 箱型
		double weight = 0.0;
		double volume = 0.0;
		BoxModel thisBoxModel = boxModels.get(0);
		// 汇总当前单据重量和体积
		for (Object obj : pickedQuantity.keySet()) {
			TaskLog taskLog = commonDao.load(TaskLog.class, Long.parseLong(obj.toString()));
			// 获取输入的数量
			double quantity = Double.parseDouble(pickedQuantity.get(obj).toString().substring(
					1, pickedQuantity.get(obj).toString().length() - 1));
			
			if (quantity > 0) {
				weight += taskLog.getPackageUnit().getWeight() * quantity;
				volume += taskLog.getPackageUnit().getVolume() * quantity;
			}
		}
		
		// 寻找最小的能装下整单的箱型
		for (BoxModel boxModel : boxModels) {
			if ((boxModel.getWeight() >= weight && boxModel.getVolume() >= volume)
					&& (boxModel.getWeight() < thisBoxModel.getWeight() && boxModel.getVolume() < thisBoxModel.getVolume())) {
				thisBoxModel = boxModel;
			}
		}
		// 如果没有符合条件的箱型, 则使用预先定义好的极大箱型
		if (thisBoxModel == null) {
			thisBoxModel = (BoxModel)commonDao.findByNamedQueryUniqueResult("getBoxModelByWarehouseAndType",
					new String[]{"type"},
					new Object[]{BoxModelType.PKG_BIG});
		}
		
		manualCreatePackageFollowASN(thisBoxModel, pickedQuantity, bol);
	}
	
	/**
	 * 按单包箱, 创建Package及其对应的PackageDetail(手工录入)
	 * @param boxModel
	 * @param taskLogs
	 * @param bol
	 */
	public void manualCreatePackageFollowASN(BoxModel boxModel, Map pickedQuantity, BOL bol) {
		Package newPackage = EntityFactory.getEntity(Package.class);
		
		newPackage.setBol(bol);
		newPackage.setBoxModel(boxModel);
		newPackage.setCode(bussinessCodeManager.generatePackage());
		newPackage.setType(ProductPackageUnit.CASE);
		newPackage.setQuantity(1);
		//newPackage.setDescription(taskLogs.get(0).getTask().getPickTicketDetail().getPickTicket().getCode());
		newPackage.setDetails(new HashSet<PackageDetail>());
		
		List<PackageDetail> alreadyCreatedPackageDetails = new ArrayList<PackageDetail>();
		for (Object obj : pickedQuantity.keySet()) {
			// 获取输入数量
			double quantity = Double.parseDouble(pickedQuantity.get(obj).toString().substring(
					1, pickedQuantity.get(obj).toString().length() - 1));
			// 已经加入全部加入BOL的不做处理
			if (quantity <= 0) {
				continue;
			}
			TaskLog taskLog = commonDao.load(TaskLog.class, Long.parseLong(obj.toString()));
			// flag标记在已经创建好的Package中是否存在和当前明细相同物料, 相同批次, 相同单位的Package; true表示不存在, false表示存在
			boolean flag = true;
			// 比较已经创建的Package中是否存在相同物料, 相同批次, 相同单位, 存在则合并, 否则新建Package
			for (PackageDetail detail : alreadyCreatedPackageDetails) {
				if (detail.getItemKey().equals(taskLog.getItemKey())
						&& detail.getPackageUnit().equals(taskLog.getPackageUnit())) {
					detail.setQuantity(detail.getQuantity() + quantity);
					
					detail.refresh();
					flag = false;
					
					continue;
				}
			}
			if (flag) {
				PackageDetail newDetail = EntityFactory.getEntity(PackageDetail.class);
				newDetail.setItemKey(taskLog.getItemKey());
				newDetail.setPackageUnit(taskLog.getPackageUnit());
				newDetail.setPkg(newPackage);
				newDetail.setQuantity(quantity);
				
				newPackage.getDetails().add(newDetail);
				bol.getPackages().add(newPackage);
				newDetail.refresh();
				// 将已经新建的PackageDetail保存, 便于后来操作比较合并相同物料, 相同批次, 相同单位明细为同一PackageDetail
				alreadyCreatedPackageDetails.add(newDetail);
			}
			taskLog.setBolQuantity(taskLog.getMovedQuantity());
			taskLog.getTask().getPickTicketDetail().manualAutoPack(quantity, taskLog.getPackageUnit());
		}
	}
	
	/**
	 * 为taskLog里的每个明细记录加入BOL数量
	 * @param taskLog
	 * @param tempQu
	 * */
	@SuppressWarnings("unchecked")
	public void addBolQuantity(TaskLog taskLog, double tempQu ){
		//根据taskLog的task_id获取所有分组成员
		List<TaskLog> taskLogs = commonDao.findByNamedQuery("getTaskLogByTask",
				new String[]{"itemKey","packageUnit","pickTicket"}, 
				new Object[]{taskLog.getItemKey(), taskLog.getPackageUnit(), taskLog.getTask().getPickTicketDetail().getPickTicket()});

		//根据输入的数量增加各个明细的加入BOL数量,
		//每个明细增加的BOL数量不能超过拣货数量
		 
		for(Object o:taskLogs){
			TaskLog taskLog1 = (TaskLog)o;
			
			//更新包箱数量和体积
			taskLog1.getTask().getPickTicketDetail().manualAutoPack(tempQu,taskLog1.getPackageUnit());
			
			/*当前tasklog对象的拣货数量>=输入数量时,直接设置BOL数量=当前BOL数量+输入数量*/
			//if(taskLog1.getMovedQuantity()>=tempQu){
			if(DoubleUtils.compareByPrecision(taskLog1.getMovedQuantity(),tempQu,taskLog1.getPackageUnit().getPrecision())>=0){
				//如果当前BOL数量+输入数量>拣货数量，则设置BOL数量为当前拣货数量
				taskLog1.setBolQuantity((taskLog1.getBolQuantity()+tempQu)>taskLog1.getMovedQuantity()?taskLog1.getMovedQuantity():(taskLog1.getBolQuantity()+tempQu));
				break;
			}
			//当前tasklog对象的拣货数量<输入数量时，设置BOL数量=拣货数量，
			//输入数量减去拣货数量后，进行下一个对象的判断
			 
			//else if(taskLog1.getMovedQuantity()<tempQu){
			else if(DoubleUtils.compareByPrecision(taskLog1.getMovedQuantity(),tempQu,taskLog1.getPackageUnit().getPrecision())<0){
				taskLog1.setBolQuantity(taskLog1.getMovedQuantity());
				tempQu-=taskLog1.getMovedQuantity();
			}
				
		}
		
		taskLog = null;
	}
	
	/**
	 * 创建包箱信息并添加包箱明细
	 * @param pickTicket
	 * @return
	 */
	public void createPackage(PickTicket pickTicket, BOL bol) {
		if (pickTicket.getCompany().isBePackagedFollowASN()) {
			// 按单包箱流程
			if(pickTicket.getBoxModel()!=null){//如果订单指定箱型，则不用在找合适的箱型进行BOL
				List<TaskLog> taskLogs = commonDao.findByNamedQuery("getTaskLogByPickTicket",
						new String[]{"pickTicket"}, 
						new Object[]{pickTicket});
				createPackageFollowASN(pickTicket.getBoxModel(),taskLogs,bol);
			}else{
				createPackageFollowASN(pickTicket, bol);
			}
		} else {
			// 非按单包箱流程
			createPackageNotFollowASN(pickTicket, bol);
		}
	}
	
	/**
	 * 非按单包箱流程, 每条单位明细的物料单独为一个包装, 对应唯一一条包箱明细
	 * @param pickTicket
	 * @param bol
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public void createPackageNotFollowASN(PickTicket pickTicket, BOL bol) {
		List<TaskLog> taskLogs = commonDao.findByNamedQuery("getTaskLogByPickTicket",
				new String[]{"pickTicket"}, 
				new Object[]{pickTicket});
		// 取得非按单包箱箱型
		BoxModel boxModel = (BoxModel)commonDao.findByNamedQueryUniqueResult("getBoxModelByWarehouseAndType",
				new String[]{"warehouseId", "type"},
				new Object[]{bol.getWarehouse().getId(), BoxModelType.PKG_ITEM});
		// 自动包箱
		for (TaskLog taskLog : taskLogs) {
			double quantity = taskLog.getMovedQuantity() - taskLog.getBolQuantity();
			// 已经加入全部加入BOL的不做处理
			if (quantity <= 0) {
				continue;
			}
			for (int i = 0; i < quantity; i ++) {
				Package newPackage = EntityFactory.getEntity(Package.class);
				newPackage.setBol(bol);
				newPackage.setBoxModel(boxModel);
				newPackage.setCode(bussinessCodeManager.generatePackage());
				newPackage.setType(ProductPackageUnit.CASE);
				newPackage.setQuantity(1);
				newPackage.setUnit(taskLog.getPackageUnit().getUnit());
				newPackage.setDetails(new HashSet<PackageDetail>());
				newPackage.setDescription(taskLog.getItemKey().getItem().getName());
				
				PackageDetail packageDetail = EntityFactory.getEntity(PackageDetail.class);
				packageDetail.setItemKey(taskLog.getItemKey());
				packageDetail.setPackageUnit(taskLog.getPackageUnit());
				packageDetail.setPkg(newPackage);
				packageDetail.setQuantity(1);
				
				newPackage.getDetails().add(packageDetail);
				bol.getPackages().add(newPackage);
				
				packageDetail.refresh();
			}
			taskLog.setBolQuantity(taskLog.getMovedQuantity());
			taskLog.getTask().getPickTicketDetail().manualAutoPack(quantity, taskLog.getPackageUnit());
		}
	}
	
	/**
	 * 按单包箱流程, 选择所有箱型中能装下该订单全部物料的最小箱型, 如果没有, 则取最大箱型
	 * @param pickTicket
	 * @param bol
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public void createPackageFollowASN(PickTicket pickTicket, BOL bol) {
		List<TaskLog> taskLogs = commonDao.findByNamedQuery("getTaskLogByPickTicket",
				new String[]{"pickTicket"}, 
				new Object[]{pickTicket});
		// 取出所有的普通箱型
		List<BoxModel> boxModels = commonDao.findByQuery("FROM BoxModel cm " + 
				" WHERE cm.warehouse.id = " + bol.getWarehouse().getId() + 
				" AND cm.type = '" + BoxModelType.PKG_NOMARL + "'" + 
				" AND cm.disabled = false ORDER BY cm.volume,cm.weight asc");
		if (boxModels == null || boxModels.size() == 0) {
			throw new BusinessException("bol.boxModel.none");
		}
		// 初始化重量, 体积, 箱型
		double weight = 0.0;
		double volume = 0.0;
		BoxModel thisBoxModel = new BoxModel();
		// 汇总当前单据重量和体积
		for (TaskLog taskLog : taskLogs) {
			double quantity = taskLog.getMovedQuantity() - taskLog.getBolQuantity();
			if (quantity > 0) {
				weight += taskLog.getPackageUnit().getWeight() * quantity;
				volume += taskLog.getPackageUnit().getVolume() * quantity;
			}
		}
		// 寻找最小的能装下整单的箱型
		for (BoxModel boxModel : boxModels) {
			if ((boxModel.getWeight() >= weight && boxModel.getVolume() >= volume)) {
				thisBoxModel = boxModel;
			}
		}
		// 如果没有符合条件的箱型, 则使用预先定义好的极大箱型
		if (thisBoxModel==null || thisBoxModel.getId() == null) {
			thisBoxModel = (BoxModel)commonDao.findByNamedQueryUniqueResult("getBoxModelByWarehouseAndType",
					new String[]{"warehouseId", "type"},
					new Object[]{bol.getWarehouse().getId(), BoxModelType.PKG_BIG});
		}
		
		createPackageFollowASN(thisBoxModel, taskLogs, bol);
	}
	
	/**
	 * 按单包箱, 创建Package及其对应的PackageDetail
	 * @param boxModel
	 * @param taskLogs
	 * @param bol
	 */
	public void createPackageFollowASN(BoxModel boxModel, List<TaskLog> taskLogs, BOL bol) {
		Package newPackage = EntityFactory.getEntity(Package.class);
		
		newPackage.setBol(bol);
		newPackage.setBoxModel(boxModel);
		newPackage.setCode(bussinessCodeManager.generatePackage());
		newPackage.setType(ProductPackageUnit.CASE);
		newPackage.setQuantity(1);
		newPackage.setDescription(taskLogs.get(0).getTask().getPickTicketDetail().getPickTicket().getCode());
		newPackage.setDetails(new HashSet<PackageDetail>());
		
		List<PackageDetail> alreadyCreatedPackageDetails = new ArrayList<PackageDetail>();
		for (TaskLog taskLog : taskLogs) {
			double quantity = taskLog.getMovedQuantity() - taskLog.getBolQuantity();
			// 已经加入全部加入BOL的不做处理
			if (quantity <= 0) {
				continue;
			}
			// flag标记在已经创建好的Package中是否存在和当前明细相同物料, 相同批次, 相同单位的Package; true表示不存在, false表示存在
			boolean flag = true;
			// 比较已经创建的Package中是否存在相同物料, 相同批次, 相同单位, 存在则合并, 否则新建Package
			for (PackageDetail detail : alreadyCreatedPackageDetails) {
				if (detail.getItemKey().equals(taskLog.getItemKey())
						&& detail.getPackageUnit().equals(taskLog.getPackageUnit())) {
					detail.setQuantity(detail.getQuantity() + quantity);
					
					detail.refresh();
					flag = false;
					
					continue;
				}
			}
			if (flag) {
				PackageDetail newDetail = EntityFactory.getEntity(PackageDetail.class);
				newDetail.setItemKey(taskLog.getItemKey());
				newDetail.setPackageUnit(taskLog.getPackageUnit());
				newDetail.setPkg(newPackage);
				newDetail.setQuantity(quantity);
				
				newPackage.getDetails().add(newDetail);
				bol.getPackages().add(newPackage);
				newDetail.refresh();
				// 将已经新建的PackageDetail保存, 便于后来操作比较合并相同物料, 相同批次, 相同单位明细为同一PackageDetail
				alreadyCreatedPackageDetails.add(newDetail);
			}
			taskLog.setBolQuantity(taskLog.getMovedQuantity());
			taskLog.getTask().getPickTicketDetail().manualAutoPack(quantity, taskLog.getPackageUnit());
		}
	}
	
	public void storeBOL(BOL bol){
		BOL dbBOL = commonDao.load(BOL.class, bol.getId());
		if (bol.getCarrier() == null || bol.getCarrier().getId() == 0) {
			dbBOL.setCarrier(null);
		} else {
			dbBOL.setCarrier(commonDao.load(Structure.class, bol.getCarrier().getId()));
		}
		if (bol.getStartPosition() == null || bol.getStartPosition().getId() == 0) {
			dbBOL.setStartPosition(null);
		} else {
			dbBOL.setStartPosition(commonDao.load(TransSite.class, bol.getStartPosition().getId()));
		}
		if (bol.getAimPosition() == null || bol.getAimPosition().getId() == 0) {
			dbBOL.setAimPosition(null);
		} else {
			dbBOL.setAimPosition(commonDao.load(TransSite.class, bol.getAimPosition().getId()));
		}
		dbBOL.setSealNumber(bol.getSealNumber());
		dbBOL.setTrailer(bol.getTrailer());
		dbBOL.setAllShippedWeight(bol.getAllShippedWeight());
		dbBOL.setAllShippedVolume(bol.getAllShippedVolume());
		dbBOL.setPackageNum(bol.getPackageNum());
		dbBOL.setBulkCargoNum(bol.getBulkCargoNum());
		if (bol.getCustomer() == null || bol.getCustomer().getId() == 0) {
			dbBOL.setCustomer(null);
		} else {
			dbBOL.setCustomer(commonDao.load(Structure.class, bol.getCustomer().getId()));
		}
		dbBOL.setShipToName(bol.getShipToName());
		dbBOL.setShipToAddress(bol.getShipToAddress());
		dbBOL.setShipToContact(bol.getShipToContact());
		dbBOL.setOrders(bol.getOrders());
		dbBOL.setDescription(bol.getDescription());
		commonDao.store(dbBOL);
	}
	public void activeAll(Long pickTicketId) {
		PickTicket pickTicket = commonDao.load(PickTicket.class, pickTicketId);
		double lockQty=0;
		if(pickTicket.getBillType().getName().equals("其他出库单")){
			List<PickTicketDetail> ptds=this.commonDao.findByQuery("from PickTicketDetail d where d.pickTicket.id="+pickTicketId);
			for(PickTicketDetail d:ptds){
				lockQty+=d.getAllocatedQuantity();
			}
		}else{
			List<Object[]> objs=this.commonDao.findByQuery("select max(p.id),p.psd.item.id,p.psd.ddbh,sum(p.psd.shsl),sum(p.psd.shsl.xs),sum(p.allocatedQuantity) "
					+ " from PlanPickTicketDetail p where p.pickTicket.id="+pickTicketId
					+" group by p.psd.item.id,p.psd.ddbh");
			for(Object[] obj:objs){
				Long pdId=obj[0]==null?null:Long.parseLong(obj[0].toString());
				PlanPickTicketDetail ppd=this.commonDao.get(PlanPickTicketDetail.class, pdId);
				if(ppd!=null){
					String ddbh=obj[2]==null?null:obj[2].toString();
					double shsl=obj[3]==null?0:Double.parseDouble(obj[3].toString());
					double xs=obj[4]==null?0:Double.parseDouble(obj[4].toString());
					double fp=obj[4]==null?0:Double.parseDouble(obj[5].toString());
					PickTicketDetail ptd=EntityFactory.getEntity(PickTicketDetail.class);
					ptd.setItem(ppd.getPsd().getItem());
					ptd.setPsd(ppd.getPsd());
					ptd.setPreAllocatedQuantity(xs);
					ptd.setOrderQtyOfMasterUnit(shsl);
					ptd.setOrderQuantity(shsl);
					ptd.setLineNumber(ppd.getPsd().getXh()+"");
					ptd.setPickTicket(pickTicket);
					ptd.setAllocatedQuantity(fp);
					ptd.setSOI(ddbh);
					ptd.setItemKey(ppd.getItemKey());
					ptd.setLocation(ppd.getLocation());
					ptd.setZone(ppd.getZone());
					this.commonDao.store(ptd);
					lockQty+=fp;
				}
			}
		}
		pickTicket.setShipDateStart(new Date());
		if(pickTicket.getRelatedBill2()==null){
			pickTicket.setRelatedBill2(this.bussinessCodeManager.getCodeForYm("BH",3));
		}
		pickTicket.setAllocatedQuantity(lockQty);
		pickTicket.setStatus(PickTicketStatus.ALLOCATE);
		this.commonDao.store(pickTicket);
		if(pickTicket.getBillType().getName().equals("其他出库单")&&pickTicket.getWarehouse().getId().equals(new Long("1"))){
			LockInv(pickTicketId);
			
		}
		if(pickTicket.getBillType().getName().equals("其他出库单")&&pickTicket.getWarehouse().getId().equals(new Long("1020"))){
			List<PickTicketDetail> ds=this.commonDao.findByQuery("from PickTicketDetail d where d.pickTicket.id="+pickTicketId+" "
					+ "and d.allocatedQuantity<d.orderQtyOfMasterUnit");
			for(PickTicketDetail ptd:ds){
				lockInvDetail(ptd, pickTicket.getZone(),ptd.getZzkw(),Boolean.FALSE);
				ptd.setAllocatedQuantity(ptd.getOrderQuantity());
				this.commonDao.store(ptd);
				//查找对应品番，把数据写入进去
				commonDao.store(pickTicket);
				Refresh(pickTicket.getId());//刷新毛重体
			}
		}
	
	}
	
	public void activeAll2(Long pickTicketId) {
		PickTicket pickTicket = commonDao.load(PickTicket.class, pickTicketId);
		List<Object[]> objs=this.commonDao.findByQuery("select max(p.psd.id),p.psd.item.id,p.psd.ddbh,sum(p.psd.shsl),sum(p.psd.shsl.xs) "
				+ " from PlanPickTicketDetail p where p.pickTicket.id="+pickTicketId
				+" group by p.psd.item.id,p.psd.ddbh");
		for(Object[] obj:objs){
			Long pdsId=obj[0]==null?null:Long.parseLong(obj[0].toString());
			PlanShipDetail psd=this.commonDao.get(PlanShipDetail.class, pdsId);
			if(psd!=null){
				Long itemId=obj[1]==null?null:Long.parseLong(obj[1].toString());
				String ddbh=obj[2]==null?null:obj[2].toString();
				double shsl=obj[3]==null?0:Double.parseDouble(obj[3].toString());
				double xs=obj[4]==null?0:Double.parseDouble(obj[4].toString());
				PickTicketDetail ptd=EntityFactory.getEntity(PickTicketDetail.class);
				ptd.setItem(psd.getItem());
				ptd.setPsd(psd);
				ptd.setPreAllocatedQuantity(xs);
				ptd.setOrderQtyOfMasterUnit(shsl);
				ptd.setOrderQuantity(shsl);
				ptd.setLineNumber(psd.getXh()+"");
				ptd.setPickTicket(pickTicket);
//				ptd.setPickedQuantity(shsl);
				ptd.setSOI(ddbh);
				this.commonDao.store(ptd);
				psd.setPtd(ptd);
				this.commonDao.store(psd);
//				pickTicket.addPickTicketDetail(ptd);
				List<PlanPickTicketDetail> pptds=this.commonDao.findByQuery("from PlanPickTicketDetail d where d.pickTicket.id="+pickTicketId+" and d.psd.item.id="+itemId+" and d.psd.ddbh='"+ddbh+"'");
				for(PlanPickTicketDetail pptd:pptds){
					pptd.setAllocateTime(new Date());
					pptd.setAllocatedQuantity(pptd.getOrderQuantity());
					pptd.setPtd(ptd);
					PlanShipDetail psd2=pptd.getPsd();
					psd2.setPtd(ptd);
					this.commonDao.store(psd2);
				}
			}
		}
		pickTicket.setShipDateStart(new Date());
		pickTicket.setRelatedBill2(this.bussinessCodeManager.getCodeForYm("BH",3));
//		pickTicket.setPickedQuantity(pickTicket.getOrderQuantity());
		pickTicket.setStatus(PickTicketStatus.ALLOCATE);
		this.commonDao.store(pickTicket);
		LockInv(pickTicketId);
	}
	//锁定库存
	public void LockInv(Long pickTicketId) {
		PickTicket pickTicket = commonDao.load(PickTicket.class, pickTicketId);
		double sdQty=0;
		List<PickTicketDetail> ptds=this.commonDao.findByQuery("from PickTicketDetail d where d.pickTicket.id="+pickTicketId);
		for(PickTicketDetail d:ptds){
			double qty=d.getOrderQuantity();
//			List<WarehouseArea> was=this.commonDao.findByQuery("from WarehouseArea w where w.beReject=0 and  w.supplier.id="+d.getPickTicket().getCompany().getId());
//			if(was.size()>0&&qty>0){
			if(qty>0){
				WarehouseArea zone=pickTicket.getZone();//was.get(0);
				String hql="from Inventory inv where inv.itemKey.item.id="+d.getItem().getId()+" and inv.zone.id="+zone.getId();
				if(d.getBonded()!=null&&!d.getBonded().equals("")&&pickTicket.getWarehouse().getId().equals(new Long("1"))){
					//
					hql+=" and inv.itemKey.pinfan.bonded='"+d.getBonded()+"'";
				}
				List<Inventory> invs=this.commonDao.findByQuery(hql);
				if(invs.size()>0){//
					double kjQty=qty;
					double syqty=qty;
					for(Inventory inv:invs){
						if(syqty>0){
							ItemKey itemkey=inv.getItemKey();
							if(inv.getAvaliableQuantity()>=kjQty){
								kjQty=kjQty;
							}else{
								kjQty=inv.getAvaliableQuantity();
							}
							syqty=syqty-kjQty;
//							String billCode=d.getPickTicket().getRelatedBill2()==null?d.getPickTicket().getCode():d.getPickTicket().getRelatedBill2();
//							InventoryLog log = new InventoryLog(InventoryLogType.PICK_DOWN, -1, billCode, null, inv.getLocation(), null, itemkey, 
//									new Date(), null, kjQty, null, null, d.getId(), null);
//							commonDao.store(log);
							inv.setQueuedQuantity(inv.getQueuedQuantity()+kjQty);
							this.commonDao.store(inv);
							d.setAllocatedQuantity(d.getAllocatedQuantity()+kjQty);
							d.setLocType(itemkey.getId()+"");
							this.commonDao.store(d);
							sdQty+=kjQty;
//							if (inv.getQtyOfMasterPack() == 0 && inv.getQueuedQuantity() == 0) {
//								itemkey.getInventories().remove(inv);
//							}
						}else{
							break;
						}
					}
//					if(syqty>0){
//						throw new BusinessException(d.getItem().getCode()+"库存数量不足");
//					}
				}
			}
		}
		
		pickTicket.setAllocatedQuantity(sdQty);
		this.commonDao.store(pickTicket);
	}
	
	//锁定库存
		public void unLockInv(PickTicketDetail d) {
			double qty=d.getOrderQuantity();
//			List<WarehouseArea> was=this.commonDao.findByQuery("from WarehouseArea w where w.beReject=0 and  w.supplier.id="+d.getPickTicket().getCompany().getId());
//			if(was.size()>0&&qty>0){
			if(qty>0){
				WarehouseArea zone=d.getPickTicket().getZone();
				List<Inventory> invs=this.commonDao.findByQuery("from Inventory inv where inv.itemKey.item.id="+d.getItem().getId()+" and inv.zone.id="+zone.getId());
				if(invs.size()>0){
					Inventory inv=invs.get(0);
					inv.setQueuedQuantity(inv.getQueuedQuantity()-d.getAllocatedQuantity());
					this.commonDao.store(inv);
				}
			}
		}
	public void activeAll(List<Long> pickTicketIds) {
		for (Long id : pickTicketIds) {
			activeAll(id);
		}
	}
	
	
	public void activeAllOld(List<Long> pickTicketIds) {
		String errMsg = "";
		for (Long id : pickTicketIds) {
			PickTicket pickTicket = commonDao.load(PickTicket.class, id);
//			//客户冻结后出库单不能生效审核
//			if(pickTicket.getCompany().isBeFrozen()==true){
//				throw new BusinessException(pickTicket.getCompany().getName()+"客户已冻结，请解冻！");
//			}
			if (pickTicket.active()) {
//				if(pickTicket.getCompany().isBeExamine()){
//					for(PickTicketDetail d:pickTicket.getPickTicketDetails()){
//						List<Inventory> Inventorys =  commonDao.findByQuery("FROM Inventory i WHERE i.location.type not in('SHIP','RECEIVE') and i.itemKeyInventory.itemKey.item.code=:code",
//								new String[] { "code"},new Object[] {d.getItem().getCode()});
//						double sumQuantity=0;
//						for(Inventory i:Inventorys){
//							sumQuantity+=i.getQuantity();
//						}		
//						//出库审核校验，出库数量>库存数量，则订单不能生效。
//						if(d.getOrderQuantity()>sumQuantity){
//							throw new BusinessException(d.getItem().getName()+"库存不足");
//						}
//					}
//				}
//				//生效时预分配，如果预分配失败则不进行拣货分配
//				if (pickTicket.getPickTicketDetails() != null || pickTicket.getPickTicketDetails().size() > 0) {
//					autoAllocator.prePlanAllocate(pickTicket.getPickTicketDetails());
//				}
//				if(pickTicket.getCompany().isBeExamine()){
//					if(pickTicket.getPreAllocatedQuantity()<pickTicket.getOrderQuantity()){
//						pickTicket.setStatus(PickTicketStatus.OPEN);
//						errMsg+=pickTicket.getCode()+"库存不足";
//						continue;
//					}
//				}else{
//					pickTicket.setStatus(PickTicketStatus.ACTIVE);
//				}
				for(PickTicketDetail d:pickTicket.getPickTicketDetails()){
					d.setPreAllocatedQuantity(d.getOrderQuantity());
					d.setPickedQuantity(d.getOrderQuantity());
					this.commonDao.store(d);
				}
				pickTicket.setStatus(PickTicketStatus.ACTIVE);
				errMsg+=pickTicket.getCode()+" 发货单激活成功;";
				LocalizedMessage.addLocalizedMessage(errMsg);
			}
		}
	}
	/**
	 * 取得体积重量与pickTicket待拣货重量体积最接近的箱型
	 * @param pickTicket
	 * @return
	 */
	private BoxModel getBoxModelForPickTicket(PickTicket pickTicket){
		String hql = "FROM BoxModel boxModel WHERE boxModel.warehouse.id = " + pickTicket.getWarehouse().getId() + 
					" AND boxModel.type='" + BoxModelType.PKG_NOMARL + "' AND boxModel.disabled = false " + 
					" ORDER BY boxModel.volume,boxModel.weight ASC";
		List<BoxModel> boxModels = this.commonDao.findByQuery(hql);
		for(BoxModel cm : boxModels){
			if(cm.getVolume()>=pickTicket.getTotalVolumn() && cm.getWeight()>=pickTicket.getTotalWeight())
				return cm;
		}
		return null;
	}
	
	public void inactiveAll(List<Long> pickTicketIds) {
		System.out.println("VMI inactiveAll");
		String errMsg = "";
		this.unPreAllocate(pickTicketIds);
		for (Long id : pickTicketIds) {
			PickTicket pickTicket = commonDao.load(PickTicket.class, id);
			pickTicket.setStatus(PickTicketStatus.OPEN);
			pickTicket.setRelatedBill2(null);
			pickTicket.setAllocatedQuantity(0);
			pickTicket.setShipDateStart(null);
			List<PickTicketDetail> ds=this.commonDao.findByQuery("from PickTicketDetail d where d.pickTicket.id="+id);
			for(PickTicketDetail d:ds){
				if(d.getOldRecord()){
					throw new BusinessException(pickTicket.getRelatedBill2()+"该单据部分发运，不能撤回");
				}
				//其他发货单退回明细不能删除
				if(!pickTicket.getBillType().getName().equals("其他出库单")&&pickTicket.getWarehouse().getId().equals(new Long("1020"))){
					commonDao.delete(d);
				}else{
					if(d.getPickedQuantity()>0){
						throw new BusinessException(pickTicket.getRelatedBill2()+"该单据部分备货，不能撤回");
					}
//					WarehouseArea z=d.getZone();
//					if(pickTicket.getWarehouse().equals(new Long("1"))){
//						z=d.getZone2();
//					}
//					if(d.getItemKey()!=null&&d.getAllocatedQuantity()>0){
//						unLock(z.getId(),d.getItemKey().getId(),d.getAllocatedQuantity());
//					}
//					d.setAllocatedQuantity(0);
//					List<Task> ts=this.commonDao.findByQuery("from Task t where t.pickTicketDetail.id="+d.getId());
//					if(ts.size()>0){
//						this.commonDao.deleteAll(ts);
//					}
//					this.commonDao.store(d);
				}
			}
			Refresh(id);
		}
		LocalizedMessage.addLocalizedMessage(errMsg);
	}
	
	public void inactiveAllTask(List<Long> pickTicketIds) {
		String errMsg = "";
		for (Long id : pickTicketIds) {
			PickTicket pickTicket = commonDao.load(PickTicket.class, id);
			List<PickTicketDetail> ds=this.commonDao.findByQuery("from PickTicketDetail d where d.pickTicket.id="+id);
			for(PickTicketDetail d:ds){
				if(d.getPickedQuantity()>0){
					throw new BusinessException(pickTicket.getRelatedBill2()+"该单据部分备货，不能撤回");
				}
				List<Task> ts=this.commonDao.findByQuery("from Task t where t.pickTicketDetail.id="+d.getId());
				for(Task t:ts){
					Inventory inv=findInventory(t.getItemKey(), t.getZone(), t.getSrcLoc(), pickTicket.getCode(), SysCode.CK_FP2);
					inv.setQueuedQuantity(inv.getQueuedQuantity()-t.getPlanQuantityMU());
					if(inv.getQueuedQuantity()<0){
						inv.setQueuedQuantity(0);
					}
					this.commonDao.store(inv);
//					unLock(d.getZone2().getId(),t.getItemKey().getId(),t.getPlanQuantityMU());
					this.commonDao.delete(t);
				}
				//删除现品票
				List<PrintXppRecord> rs=this.commonDao.findByQuery("from PrintXppRecord r where r.ptd.id="+d.getId());
				this.commonDao.deleteAll(rs);
				d.setAllocatedQuantity(0);
				this.commonDao.store(d);
			}
			pickTicket.setStatus(PickTicketStatus.OPEN);
			pickTicket.setRelatedBill2(null);
			pickTicket.setAllocatedQuantity(0);
			pickTicket.setShipDateStart(null);
			Refresh(id);
		}
		LocalizedMessage.addLocalizedMessage(errMsg);
	}
	/*
	 * (non-Javadoc)
	 * @see com.dev.swms.server.service.shipping.PickTicketManager#inactiveAll(java.util.List)
	 */
	public void inactiveAllOld(List<Long> pickTicketIds) {
		String errMsg = "";
		this.unPreAllocate(pickTicketIds);
		for (Long id : pickTicketIds) {
			PickTicket pickTicket = commonDao.load(PickTicket.class, id);
			if (pickTicket.inactive()) {
				List<PickTicketDetail> temp = new ArrayList<PickTicketDetail>();
				//删除赠品
				for(PickTicketDetail ptd:pickTicket.getPickTicketDetails()){
					if(!ptd.isOldRecord()){
						temp.add(ptd);
					}
				}
				pickTicket.getPickTicketDetails().removeAll(temp);
				//errMsg+=pickTicket.getCode()+" 发货单反激活成功;";
			}
			else
				errMsg+=pickTicket.getCode()+" 发货单反激活失败;";
		}
		LocalizedMessage.addLocalizedMessage(errMsg);
	}
	public void inactivePlanAll(List<Long> pickTicketIds) {
		String errMsg = "";
		for (Long id : pickTicketIds) {
			PickTicket pickTicket = commonDao.load(PickTicket.class, id);
			if(pickTicket.getStatus().equals(PickTicketStatus.OPEN)||pickTicket.getStatus().equals(PickTicketStatus.ACTIVE)||pickTicket.getStatus().equals(PickTicketStatus.PREALLOCATE)){
				for(PickTicketDetail ptd:pickTicket.getPickTicketDetails()){
					ptd.setPreAllocatedQuantity(0);
					this.commonDao.store(ptd);
				}
				pickTicket.setPreAllocatedQuantity(0);
				pickTicket.setStatus(PickTicketStatus.OPEN);
				this.commonDao.store(pickTicket);
			}
		}
		LocalizedMessage.addLocalizedMessage(errMsg);
	}

	@SuppressWarnings("unchecked")
	public MasterBOL getMasterBOLbyCode(String code) {
		List result = commonDao.findByNamedQuery("getMasterBOLbyCode",
				new String[] { "code" }, new String[] { code });
		if (result.size() >= 1) {
			return (MasterBOL) result.get(0);
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	public PickTicket getPickTicketByCode(String code) {
		List result = commonDao.findByNamedQuery("getPickTicketByCode",
				new String[] {"warehouseId", "code"}, new Object[] {WarehouseHolder.getWarehouse().getId(), code});
		if (result.size() >= 1) {
			return (PickTicket) result.get(0);
		}
		return null;
	}
	public void pickKamsForSys(Long taskId, double pickedQuantity,String bhr,Long workerId) {
		pickConfirmKams(taskId, pickedQuantity,bhr, workerId);
		Task task = commonDao.load(Task.class,taskId);
		PickTicketDetail ptd=task.getPickTicketDetail();
		refPlanPick(ptd.getPickTicket().getId(),ptd.getItem().getId());
	}

	
	public void pickConfirmKams(Long taskId, double pickedQuantity,String bhr, Long workerId) {
		Task task = commonDao.load(Task.class,taskId);
		if(task.getBeBh()){
			throw new BusinessException("已备货");
		}
		String operator=UserHolder.getUser().getName();
		if(DoubleUtils.compareByPrecision(task.getPlanQuantityMU()-task.getMovedQuantityMU(),pickedQuantity,1) <0){
			throw new BusinessException("pick.quantity.error");
		}
		//task.pickConfirm(task.getPackageUnit(), pickedQuantity, w);
		//库存移位处理
		ItemKey itemKey=task.getItemKey();
		Inventory inv1=findInventory(task.getItemKey(), task.getZone(), task.getSrcLoc(), task.getBillCode(), SysCode.CK_BH1);
		if(inv1==null){
			throw new BusinessException("move.inventory.none");
		}
		double srcQty1=inv1.getQtyOfMasterPack();
		//对源库存取消分配
		inv1.setQueuedQuantity(inv1.getQueuedQuantity()-task.getPlanQuantity());
		if(inv1.getQueuedQuantity()<0){
			inv1.setQueuedQuantity(0);
		}
		double qty_s=task.getPlanQuantity()-pickedQuantity;//部分出库
		task.setPlanQuantity(pickedQuantity);
		task.setPlanQuantityMU(pickedQuantity);
		task.setBeBh(Boolean.TRUE);
		this.commonDao.store(task);
		PickTicketDetail ptd=task.getPickTicketDetail();
//		ptd.setAllocatedQuantity(ptd.getAllocatedQuantity()+task.getPlanQuantity());
		this.commonDao.store(ptd);
		PickTicket pt=ptd.getPickTicket();
		if(pt.getRelatedBill2()==null||pt.getRelatedBill2().equals("")){
			pt.setShipDateEnd(new Date());
			pt.setRelatedBill2(this.bussinessCodeManager.getCodeForYm("CK",3));
		}
		pt.setAllocatedQuantity(pt.getAllocatedQuantity()-qty_s);
		this.commonDao.store(pt);
//		inv1.remove(pickedQuantity, 0, 0);
		inv1.setQtyOfMasterPack(inv1.getQtyOfMasterPack()-pickedQuantity);
		if(inv1.getQtyOfMasterPack()<0){
			inv1.setQtyOfMasterPack(0);
		}
		inv1.setQuantity(inv1.getQtyOfMasterPack());
		this.commonDao.store(inv1);
		//减少
		InventoryLog log1=addInventoryLog(InventoryLogType.PICK_DOWN, -1,  task.getZone(), task.getSrcLoc(), task.getBillCode(), task.getItemKey(), pickedQuantity, null, operator, inv1.getId(), (int)srcQty1+"变为"+(int)inv1.getQtyOfMasterPack(),bhr,null);
		task.pickConfirm(itemKey, task.getSrcLoc(), 
				inv1.getLP(), task.getDstLoc(), task.getDstLP(), inv1.getStatus(),
				inv1.getStorageDate(), inv1.getSOI(), 
				null, pickedQuantity, null);
		Inventory inv2 =findInventory(task.getItemKey(), task.getZone(), task.getDstLoc(), task.getBillCode(), SysCode.CK_BH2);
		if(inv2==null){
			inv2=EntityFactory.getEntity(Inventory.class);
			inv2.setLocation(task.getDstLoc());
			inv2.setItemKey(task.getItemKey());
			inv2.setZone(task.getZone());
			task.getItemKey().getInventories().add(inv2);
			this.commonDao.store(inv2);
		}
		double srcQty2=inv2.getQtyOfMasterPack();
		inv2.add(pickedQuantity,0,0);
		this.commonDao.store(inv2);
		//增加
		InventoryLog log2=addInventoryLog(InventoryLogType.PICK_DOWN, 1,  task.getZone(), task.getDstLoc(), task.getBillCode(), task.getItemKey(), pickedQuantity, null, operator, inv2.getId(), (int)srcQty2+"变为"+(int)inv2.getQtyOfMasterPack(),bhr,null);
	}
	public void pickConfirm(Long taskId, double pickedQuantity, Long workerId) {
		Task task = commonDao.load(Task.class,taskId);
		//if((task.getPlanQuantityMU()-task.getMovedQuantityMU()) < pickedQuantity){
		if(DoubleUtils.compareByPrecision(task.getPlanQuantityMU()-task.getMovedQuantityMU(),pickedQuantity,1) <0){
			throw new BusinessException("pick.quantity.error");
		}
		String barCode=null;
		//task.pickConfirm(task.getPackageUnit(), pickedQuantity, w);
		//库存移位处理
//		ItemKeyInventory itemKeyInventory = inventoryManager.getItemKeyInventory(task.getSrcLoc().getWarehouse(), task.getItemKey());
		ItemKey itemKey=task.getItemKey();
//		Inventory srcInv = itemKey.getInventory(task.getSrcLoc(), task.getInventoryStatus());
		List<Inventory> invs=this.commonDao.findByQuery("from Inventory inv where inv.quantity>0 and inv.queuedQuantity>0 and inv.SOI is null and inv.itemKey.id="+itemKey.getId()
		+" and inv.zone.id="+task.getZone().getId());
		
		if (invs.size()>0) {
			Inventory srcInv=invs.get(0);
			//对源库存取消分配
	        srcInv.unallocate(pickedQuantity, null, null);
			//移位确认(捡货确认是将货物捡到月台上面,没有托盘)
			inventoryManager.moveInventory(srcInv.getId(), task.getDstLoc().getId(), null, 
					pickedQuantity, null, task.getId(), workerId);
		} else {
			throw new BusinessException("move.inventory.none");
		}
		
		//如果拣货全部完成而且没有加入波次或者波次已经关闭，自动创建BOL
		/*if(task.getPickTicketDetail().getPickTicket().getStatus().equals(PickTicketStatus.PICK_ALL) 
				&& StringUtils.isEmpty(task.getPickTicketDetail().getPickTicket().getWaveCode())){
			//自动创建BOL
			//createBOL(task.getPickTicketDetail().getPickTicket().getId());
			
			//TODO:调用接口发送拣货确认消息
			//logManager.pickResponse(task.getPickTicketDetail().getPickTicket());
		}*/
	}

	public void pickConfirm(Long taskId, Long srcLocId, String lp, String lot, Long packageUnitId,
			double pickedQuantity,double weight, Long workerId ) {
		String barCode=null;
		Task task = commonDao.load(Task.class,taskId);
		double a=task.getPlanQuantityMU();
		double d=task.getPlanQuantityMU()-pickedQuantity;
		Long p_id=null;
		
         if(d>0) {
        	 PickTicketDetail pick =  commonDao.load(PickTicketDetail.class,task.getPickTicketDetail().getId());
        	 PickTicket p =  commonDao.load(PickTicket.class,pick.getPickTicket().getId());
        	 pick.setAllocatedQuantity(pick.getAllocatedQuantity()-d);
        	 p.setAllocatedQuantity(p.getAllocatedQuantity()-d);
        	 commonDao.store(pick);
        	 commonDao.store(p);
        	 p_id=p.getId();
		 }
		Location srcLocation = commonDao.load(Location.class, srcLocId);
		if(srcLocation.getCountLock()!=null&&!srcLocation.getCountLock().equals("")){
			throw new BusinessException("该库位正在盘点，不能拣货");
		}
//		pickedQuantity = pickedQuantity * packageUnit.getConvertFigure();
		task.setWeight(weight);
		task.setPlanQuantityMU(pickedQuantity);
		task.setPlanQuantity(pickedQuantity);
		commonDao.store(task);
		Stock srcLp = task.getSrcLP();	//源托盘
		//Stock dstLp = task.getDstLP();	//目标托盘号
		Stock dstLp = (Stock) commonDao.findByQueryUniqueResult("FROM Stock stock WHERE stock.warehouse.id = :warehouseId AND stock.LP = :LP", 
				new String[] {"warehouseId", "LP"},
				new Object[] {srcLocation.getWarehouse().getId(), lp});
		ItemKey itemKey = task.getItemKey();
		//是否修改了秕次
		if(StringUtils.isNotEmpty(lot) && !lot.equals(task.getItemKey().getLot())){
			itemKey = (ItemKey) commonDao.findByNamedQueryUniqueResult("getItemKeyByLot", 
					new String[] {"lot"}, new Object[] {lot});
			if(itemKey==null){
				throw new BusinessException("input.lot.error");
			}
		}
		if((task.getPlanQuantityMU()-task.getMovedQuantityMU()) < pickedQuantity){
//		if(DoubleUtils.compareByPrecision(task.getPlanQuantityMU()-task.getMovedQuantityMU(),pickedQuantity,task.getPackageUnit().getPrecision()) < 0){
			throw new BusinessException("pick.quantity.error");
		}

		//对源库存取消分配
//		ItemKeyInventory srcItemKeyInventory = inventoryManager.getItemKeyInventory(
//				task.getSrcLoc().getWarehouse(), task.getItemKey());	
//		ItemKey itemKey=task.getItemKey();
//		Inventory srcInv = srcItemKeyInventory.getInventory(task.getSrcLoc(), task.getPackageUnit(), 
//				task.getSrcLP(), barCode,task.getInventoryStatus(), task.getStorageDate(), task.getSOI());
		List<Inventory> list1=commonDao.findByQuery(" from Inventory inv where inv.itemKey.id="+itemKey.getId()+" and inv.zone.id="+task.getZone().getId());
		Inventory srcInv = null;
		if(list1.size()>0) {
			srcInv=list1.get(0);
		}
		if (srcInv == null) {
			throw new BusinessException("move.inventory.none");
		}
        srcInv.unallocate(a, null, null);
        
        if (srcLocation.equals(task.getSrcLoc())
				&& ((dstLp == null && task.getSrcLP()==null) || dstLp.equals(task.getSrcLP()))
				&& itemKey.equals(task.getItemKey())
				) {
        			inventoryManager.moveInventory(srcInv.getId(), task.getDstLoc().getId(), 
        			dstLp == null ? null : dstLp.getId(), pickedQuantity, 0L, task.getId(), workerId);
        } else {
            //扣减实际拣货库位库存
            ItemKeyInventory actItemKeyInventory = inventoryManager.getItemKeyInventory(srcLocation.getWarehouse(), itemKey);
            List<Inventory> invs = new ArrayList<Inventory>();
            if (dstLp != null) {
            	invs.addAll(actItemKeyInventory.getInventories(dstLp.getLocation(), dstLp, task.getInventoryStatus()));
            } else {
            	actItemKeyInventory.getInventories(srcLocation, null, task.getInventoryStatus());
            }
            double moveQty = 0;
            for (Inventory inv : invs) {
            	//if (pickedQuantity > inv.getAvaliableQuantity()) {
            	if (DoubleUtils.compareByPrecision(pickedQuantity,inv.getAvaliableQuantity(),inv.getPackageUnit().getPrecision()) > 0) {
                	moveQty = inv.getAvaliableQuantity();
            	} else {
            		moveQty = pickedQuantity;
            	}
            	inventoryManager.moveInventory(inv.getId(), task.getDstLoc().getId(), 
            			dstLp == null ? null : dstLp.getId(), moveQty, 0L, task.getId(), workerId);
            	pickedQuantity -= moveQty;
            	if (pickedQuantity <= 0) {
            		break;
            	}
            }
            
    		if (pickedQuantity > 0) {
    			throw new BusinessException("move.inventory.none");
    		}
        }
    	if(p_id!=null) {
    		refPlanPick(p_id,itemKey.getItem().getId());
    	}
        //TODO:手工拣货确认时，应根据选择的库存状态进行处理，而不是原来task中记录的库存状态
		//task.pickConfirm(itemKey, srcLocation, srcLp, task.getDstLoc(), dstLp, task.getInventoryStatus(),
		//		task.getStorageDate(), task.getSOI(), task.getPackageUnit(), pickedQuantity, w);
		
		//如果拣货全部完成，自动创建BOL
		//if(task.getPickTicketDetail().getPickTicket().getStatus().equals(PickTicketStatus.PICK_ALL)){
			//自动创建BOL
			//createBOL(task.getPickTicketDetail().getPickTicket().getId());
			
			//TODO:调用接口发送拣货确认消息
			//logManager.pickResponse(task.getPickTicketDetail().getPickTicket());
		//}
	}

	public void preAllocate(List<Long> pickTicketIds) {
		String errMsg = "";
		for (Long id : pickTicketIds) {
			PickTicket pickTicket = this.commonDao.load(PickTicket.class, id);	
			if (preAllocate(id)) 
				errMsg+=pickTicket.getCode()+" 发货单预分配成功;";
			else
				errMsg+=pickTicket.getCode()+" 发货单预分配失败;";
		}
		LocalizedMessage.addLocalizedMessage(errMsg);
	}
	
	

	public void unPreAllocate(List<Long> pickTicketIds) {
		String errMsg = "";
		for (Long id : pickTicketIds) {
			PickTicket pickTicket = this.commonDao.load(PickTicket.class, id);	
			if (unPreAllocate(id)) 
				errMsg+=pickTicket.getCode()+" 取消预分配成功;";
			else
				errMsg+=pickTicket.getCode()+" 取消预分配失败;";
		}
			//LocalizedMessage.addLocalizedMessage(errMsg);
	}

	public boolean preAllocate(Long pickTicketId) {
		PickTicket pickTicket = commonDao.load(PickTicket.class, pickTicketId);
		if (PickTicketStatus.ACTIVE.equals(pickTicket.getStatus()) 
				|| PickTicketStatus.PREALLOCATE.equals(pickTicket.getStatus())
				|| PickTicketStatus.SHIP_PART.equals(pickTicket.getStatus())) {
			if (pickTicket.getPickTicketDetails() != null || pickTicket.getPickTicketDetails().size() > 0) {
				autoAllocator.preAllocate(pickTicket.getPickTicketDetails());
			}
		}
		if (pickTicket.getPreAllocatedQuantity() - pickTicket.getAllocatedQuantity() >= 0) {
			return true;
		}
		return false;
	}

	@SuppressWarnings("unchecked")
	public void preAllocate(Long pickTicketId, Map pickTicketDetails) {
		PickTicket pickTicket = this.commonDao.load(PickTicket.class, pickTicketId);
		String errMsg = "";
		if (PickTicketStatus.ACTIVE.equals(pickTicket.getStatus()) 
				|| PickTicketStatus.PREALLOCATE.equals(pickTicket.getStatus())
				|| PickTicketStatus.SHIP_PART.equals(pickTicket.getStatus())) {
			for(Iterator it = pickTicketDetails.entrySet().iterator(); it.hasNext();){
				Map.Entry entry = (Entry) it.next();
				Long detailId = (Long) entry.getKey();
				List value = (List) entry.getValue();
				Double preAllocateQty = Double.valueOf(String.valueOf(value.get(0)));
				
				List<PickTicketDetail> details = new ArrayList<PickTicketDetail>();
				details.addAll(pickTicket.getPickTicketDetails());
				PickTicketDetail detail = pickTicket.getPickTicketDetail(detailId);
				Double beforeQty = detail.getUnPreAllocateQuantity();
				//if (detail.getUnPreAllocateQuantity() < preAllocateQty) {
				if (DoubleUtils.compareByPrecision(detail.getUnPreAllocateQuantity(),preAllocateQty,detail.getPackageUnit().getPrecision() )<0 ) {
					throw new BusinessException("preAlloate.quantity.error");
				}
				if (preAllocateQty > 0) {
					autoAllocator.preAllocate(detail, preAllocateQty,"2");
				}
				if (beforeQty != detail.getUnPreAllocateQuantity()) 
					errMsg+=detail.getCode()+" 预分配成功;";
				else
					errMsg+=detail.getCode()+" 预分配失败;";
			}
		}
		LocalizedMessage.addLocalizedMessage(errMsg);
	}

	public boolean unPreAllocate(Long pickTicketId) {
		PickTicket pickTicket = commonDao.load(PickTicket.class, pickTicketId);
		if (PickTicketStatus.PREALLOCATE.equals(pickTicket.getStatus())) {
			if (pickTicket.getPickTicketDetails() != null || pickTicket.getPickTicketDetails().size() > 0) {
				autoAllocator.unPreAllocate(pickTicket.getPickTicketDetails());
			}
		}
		if (pickTicket.getAllocatedQuantity() - pickTicket.getPreAllocatedQuantity() == 0) {
			return true;
		}
		return false;
	}

	@SuppressWarnings("unchecked")
	public void unPreAllocate(Long pickTicketId, Map pickTicketDetails) {
		PickTicket pickTicket = this.commonDao.load(PickTicket.class, pickTicketId);
		String errMsg = "";
		if (PickTicketStatus.PREALLOCATE.equals(pickTicket.getStatus())) {
			for(Iterator it = pickTicketDetails.entrySet().iterator(); it.hasNext();){
				Map.Entry entry = (Entry) it.next();
				Long detailId = (Long) entry.getKey();
				List value = (List) entry.getValue();
				Double unPreAllocateQty = Double.valueOf(String.valueOf(value.get(0)));
				
				List<PickTicketDetail> details = new ArrayList<PickTicketDetail>();
				details.addAll(pickTicket.getPickTicketDetails());
				PickTicketDetail detail = pickTicket.getPickTicketDetail(detailId);
				Double beforeQty = detail.getUnPreAllocateQuantity();
				//if (detail.getUnallocateQuantity() < unPreAllocateQty) {
				if (DoubleUtils.compareByPrecision(detail.getUnallocateQuantity(),unPreAllocateQty,detail.getPackageUnit().getPrecision()) < 0) {
					throw new BusinessException("unPreAlloate.quantity.error");
				}
				autoAllocator.unPreAllocate(detail, unPreAllocateQty);
				
				if (beforeQty != detail.getUnPreAllocateQuantity()) 
					errMsg+=detail.getCode()+" 取消预分配成功;";
				else
					errMsg+=detail.getCode()+" 取消预分配失败;";
			}
		}
		LocalizedMessage.addLocalizedMessage(errMsg);
	}

	public void willShip(List<Long> ids, Long dockId,Date shipDateStart, Date shipDateEnd) {
		for(Long pickTicketId : ids){
			PickTicket pickTicket = this.load(PickTicket.class,pickTicketId);
			if(!pickTicket.getStatus().equals(PickTicketStatus.OPEN)){
				throw new BusinessException("pickTicket.willship.error");
			}
			if(shipDateStart.after(shipDateEnd)) {
				throw new BusinessException("pickTicket.willship.date.error");
			}
			pickTicket.setDock(this.load(Location.class,dockId));
			pickTicket.setShipDateStart(shipDateStart);
			pickTicket.setShipDateEnd(shipDateEnd);
		}
	}

	@SuppressWarnings("unchecked")
	public void pickConfirm(Long pickTicketId, String bhr,Long workerId) {
		Worker w = this.commonDao.load(Worker.class, workerId);
		String hql = "select task from Task task where task.pickTicketDetail.pickTicket.id ="+pickTicketId +
				"and (task.planQuantityMU -task.movedQuantityMU)>0 ";
		List<Task> tasks = commonDao.findByQuery(hql);
		PickTicket pt =commonDao.load(PickTicket.class, pickTicketId);
		for(Task task:tasks){
			if(task.getBeBh()){
				//释放剩余库存
				Inventory inv1=findInventory(task.getItemKey(), task.getZone(), task.getSrcLoc(), task.getBillCode(), SysCode.CK_BH1);
				if(inv1==null){
					throw new BusinessException("move.inventory.none");
				}
				PickTicketDetail ptd=task.getPickTicketDetail();
				double qty_s=task.getPlanQuantityMU()-task.getMovedQuantityMU();//部分出库
				if(qty_s>0){
					inv1.setQueuedQuantity(inv1.getQueuedQuantity()-qty_s);
					if(inv1.getQueuedQuantity()<0){
						inv1.setQueuedQuantity(0);
					}
					task.setPlanQuantity(task.getMovedQuantityMU());
					task.setPlanQuantityMU(task.getMovedQuantityMU());
					this.commonDao.store(task);
					ptd.setAllocatedQuantity(task.getMovedQuantityMU());
					this.commonDao.store(ptd);
					pt.setAllocatedQuantity(pt.getAllocatedQuantity()-qty_s);
				}
			}else{
				double qty = task.getPlanQuantityMU() - task.getMovedQuantityMU();
				if (qty > 0) {
					pickConfirmKams(task.getId(), qty,bhr, workerId);
					//pickConfirm(task.getId(), qty, (w == null ? 0L : w.getId()));
				}
			}
		}
		pt.setShipDateEnd(new Date());
		if(pt.getRelatedBill2()==null||pt.getRelatedBill2().equals("")){
			pt.setRelatedBill2(this.bussinessCodeManager.getCodeForYm("CK",3));
		}
		commonDao.store(pt);
		refPlanPick(pickTicketId,null);
	}
	
	@SuppressWarnings("unchecked")
	public void createBOLByASN(ASN asn) {
		BOL bol = EntityFactory.getEntity(BOL.class);		
		bol.setStatus(BOLStatus.SHIP_ALL);
		bol.setCode(bussinessCodeManager.generateBOLCode(new HashMap()));
		bol.setWarehouse(asn.getWarehouse());
		bol.setUserTracking();
		bol.setPackages(new HashSet<Package>());		
		createPackageByASN(asn, bol);	
		commonDao.store(bol);
	}
	
	@SuppressWarnings("unchecked")
	public void createPackageByASN(ASN asn, BOL bol){		
		for (ASNDetail detail : asn.getAsnDetails()) {
			Package pkg = new Package();
			pkg.setBol(bol);
			pkg.setCode(bussinessCodeManager.generatePackage());
			pkg.setDescription(detail.getItem().getName());
			pkg.setUnit(detail.getPackageUnit().getUnit());
			pkg.setQuantity(detail.getExpectedQuantity());
			pkg.setType(ProductPackageUnit.CASE);
			pkg.setDetails(new HashSet<PackageDetail>());
			ItemKey itemKey = itemManager.getItemKey(new ItemKey(
					"", detail.getItem(), detail.getLotInfo(), asn.getUpdateTime(), asn.getCode(),null), Boolean.FALSE,null);
			PackageDetail pkgDetail = new PackageDetail();
			pkgDetail.setPkg(pkg);
			pkgDetail.setItemKey(itemKey);
			pkgDetail.setPackageUnit(detail.getPackageUnit());
			pkgDetail.setQuantity(1);
			pkg.getDetails().add(pkgDetail);
			bol.getPackages().add(pkg);
			
			pkgDetail.refresh();
			commonDao.store(bol);
		}
	}
	
	//根据参数创建好包箱
	@SuppressWarnings("unchecked")
	public void createNewPackage(Long BOLid, Long boxModelId, Integer packageNum,
			Map packageQtyMap, String packageNo, String description) {
		BOL bol = (BOL)commonDao.load(BOL.class,BOLid);
		Map<Package,Integer> packageObject = new HashMap<Package,Integer>();
		BoxModel boxModel = this.commonDao.load(BoxModel.class, boxModelId);
		for (Object obj : packageQtyMap.keySet()) {
			//根据ID获得一个包装类型为pcs的包装对象--为pcs的对象就是一种货物数量信息
			Package pkg = (Package)commonDao.load(Package.class,Long.parseLong(obj.toString()));
			//获取输入的数量
			String temp    = packageQtyMap.get(obj).toString();
			int tempQu = Integer.parseInt(temp.substring(1,temp.length()-1));
			packageObject.put(pkg, Integer.valueOf(tempQu));
			//获取可包箱的最大包箱数  
			int packAbleQty = Double.valueOf(Math.floor(pkg.getQuantity() / tempQu)).intValue();
			if (packageNum > packAbleQty) {
				packageNum = packAbleQty;
			}
		}
		for(int i=0;i<packageNum;i++){
			Package newPackage = new Package();
			newPackage.setDescription(description);
			newPackage.setDetails(new HashSet<PackageDetail>());
			newPackage.setBoxModel(boxModel);
			if (!StringUtils.isEmpty(packageNo)) {
				if(i==0 && packageNum==1)
					newPackage.setCode(packageNo);
				else
					newPackage.setCode(packageNo+"_"+i);
			} else {
				newPackage.setCode(bussinessCodeManager.generatePackage());
			}
			newPackage.setType(ProductPackageUnit.CASE);
			newPackage.setQuantity(1);
			newPackage.setBol(bol);
			bol.getPackages().add(newPackage);
			//修改原包箱的信息
			for (Package pkg : packageObject.keySet()) {
				int split = packageObject.get(pkg).intValue();
				//新建包箱时，源包箱只有一条包箱明细
				for (PackageDetail packageDetail : pkg.getDetails()) {
					//检查待新增的包箱明细与新建包箱中已有的包箱明细是否相同
					boolean sameCargo = false;
					Set<PackageDetail> details = newPackage.getDetails();
					for (PackageDetail obj : details) {
						if(obj.getItemKey().equals(packageDetail.getItemKey()) 
								&& obj.getPackageUnit().equals(packageDetail.getPackageUnit())){
							obj.setQuantity(obj.getQuantity()+ split);
							
							obj.refresh();
							
							sameCargo = true;
							break;
						}
					}
					
					if(!sameCargo){
						PackageDetail newDetail = new PackageDetail();
						try {
							BeanUtils.copyProperties(newDetail, packageDetail);
						} catch (IllegalAccessException e) {
							e.printStackTrace();
						} catch (InvocationTargetException e) {
							e.printStackTrace();
						}
						newDetail.setId(null);
						newDetail.setQuantity(split);
						newDetail.setPkg(newPackage);
						newPackage.getDetails().add(newDetail);
						
						newDetail.refresh();
					}
				}
				pkg.split(split);
			}
		}
	}

	public void splitPackage(Long  packageId, Integer splitQuantity) {
		Package pkg = (Package)commonDao.load(Package.class, packageId);
		if(pkg.getQuantity() < splitQuantity){
			throw new BusinessException("package.split.quantity.error") ;
		}
		
		Set<PackageDetail> details = pkg.getDetails();
		for(PackageDetail packageDetail : details){
			double qty = packageDetail.getQuantity()*splitQuantity;
			boolean isExist = false;
			
			Package newPackage = new Package();
			newPackage.setCode("");
			newPackage.setType(ProductPackageUnit.PCS);
			newPackage.setBol(pkg.getBol());
			newPackage.setQuantity(qty);
			newPackage.setUnit(packageDetail.getPackageUnit().getUnit());
			newPackage.setDescription(packageDetail.getItemKey().getItem().getName());
			newPackage.setDetails(new HashSet<PackageDetail>());
			if (pkg.getBol().getPackages().contains(newPackage)) {
				for (Package p : pkg.getBol().getPackages()) {
					if (p.equals(newPackage)) {
						newPackage = p;
						isExist = true;
						break;
					}
				}
			} else {
				pkg.getBol().getPackages().add(newPackage);
			}
			
			if (isExist) {
				newPackage.setQuantity(newPackage.getQuantity() + qty);
				newPackage.refresh();
			} else {
				PackageDetail newDetail = new PackageDetail();
				try {
					BeanUtils.copyProperties(newDetail, packageDetail);
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					e.printStackTrace();
				}
				newDetail.setId(null);
				newDetail.setQuantity(1);
				newDetail.setPkg(newPackage);
				newPackage.getDetails().add(newDetail);
				
				newDetail.refresh();
			}
		}
		pkg.split(splitQuantity);
	}
	
	/**
	 * 拆包装
	 */
	public void splitPackageUnit(Long  packageDetail, Integer splitNumber, Long packageUnitId) {
		PackageDetail oldDetail = this.load(PackageDetail.class, packageDetail);
		Package oldPackage = oldDetail.getPkg();
		if (oldPackage.getQuantity() < splitNumber) {
			throw new BusinessException("package.splitUnit.quantity.error") ;
		}
		PackageUnit newPackageUnit = this.commonDao.load(PackageUnit.class,packageUnitId);
		Package newPackag = (Package)this.commonDao.findByNamedQueryUniqueResult("getPackageByUniKey",
				new String[]{"bolId","code","type","unit","description","boxModelId"},
				new Object[]{oldPackage.getBol().getId(),oldPackage.getCode(),oldPackage.getType(),
				newPackageUnit.getUnit(),oldDetail.getItemKey().getItem().getName(),null});
		
		if(newPackag==null){
			newPackag = new Package();
			newPackag.setDescription(oldDetail.getItemKey().getItem().getName());
			newPackag.setDetails(new HashSet<PackageDetail>());
			newPackag.setCode("");
			newPackag.setType(ProductPackageUnit.PCS);
			newPackag.setUnit(newPackageUnit.getUnit());
			newPackag.setQuantity((splitNumber*oldDetail.getPackageUnit().getConvertFigure())/newPackageUnit.getConvertFigure());
			newPackag.setVolume(splitNumber*oldDetail.getPackageUnit().getVolume());
			newPackag.setWeight(splitNumber*oldDetail.getPackageUnit().getWeight());
			newPackag.setBol(oldPackage.getBol());
			newPackag.getBol().refreshPackageQty();
			
			PackageDetail newDetail = new PackageDetail();
			newDetail.setItemKey(oldDetail.getItemKey());
			newDetail.setQuantity(1);
			newDetail.setPackageUnit(newPackageUnit);
			newDetail.setWeight(newPackageUnit.getWeight());
			newDetail.setVolume(newPackageUnit.getVolume());
			newPackag.getDetails().add(newDetail);
			newDetail.setPkg(newPackag);
			this.commonDao.store(newPackag);
			
		}else{
			newPackag.setQuantity(newPackag.getQuantity()+(splitNumber*oldDetail.getPackageUnit().getConvertFigure())/newPackageUnit.getConvertFigure());
			newPackag.setVolume(newPackag.getVolume()+splitNumber*oldDetail.getPackageUnit().getVolume());
			newPackag.setWeight(newPackag.getVolume()+splitNumber*oldDetail.getPackageUnit().getWeight());
			this.commonDao.store(newPackag);
		}
		oldPackage.setQuantity(oldPackage.getQuantity()-splitNumber);
		oldPackage.setVolume(oldPackage.getVolume()-splitNumber*oldDetail.getPackageUnit().getVolume());
		oldPackage.setWeight(oldPackage.getWeight()-splitNumber*oldDetail.getPackageUnit().getWeight());
		this.commonDao.store(oldPackage);
	}

	@SuppressWarnings("unchecked")
	public void pickedBack(Long pickTicketId) {
		PickTicket pickTicket = this.commonDao.load(PickTicket.class, pickTicketId);
		Set<TaskLog> logs = new HashSet<TaskLog>();
		logs.addAll(commonDao.findByNamedQuery("getTaskLogByPickTicket", new String[] {"pickTicket"}, new Object[] {pickTicket}));
		pickedBack(pickTicket, logs);
	}
	
	public void pickedBack(Long pickTicketId, List<Long> taskLogIds) {
		PickTicket pickTicket = this.commonDao.load(PickTicket.class, pickTicketId);
		Set<TaskLog> logs = new HashSet<TaskLog>();
		logs.addAll(this.commonDao.loadAll(TaskLog.class, taskLogIds.toArray(new Long[]{})));
		pickedBack(pickTicket, logs);
	}
	
	public void pickedBackKams(Long pickTicketId, Long taskLogId,Double movedQuantity){
    	TaskLog log = this.commonDao.load(TaskLog.class, taskLogId);
    	Task t=log.getTask();
    	Double movedQuantityOri = log.getMovedQuantity();
    	Double resultQuantity = movedQuantityOri-log.getBolQuantity()-movedQuantity;
    	String operator=UserHolder.getUser().getName();
    	if(resultQuantity < 0){
    		throw new BusinessException("moveDoc.pickedBackQuanti.overFlow");
    	}else{
    		//对选中的拣货记录退拣处理
    		Location pickBackLoc=log.getSrcLoc();//log.getDstLoc().getPickBackLoc() 
    		if (pickBackLoc != null) {
				// 库存移位处理
    			ItemKey ik=log.getItemKey();
    			Inventory inv1 =findInventory(ik, t.getZone(), t.getDstLoc(), t.getBillCode(), SysCode.CK_TH1);
    			double srcQty1=inv1.getQtyOfMasterPack();
    			inv1.remove(movedQuantityOri,0,0);
    			this.commonDao.store(inv1);
    			//减少
    			addInventoryLog(InventoryLogType.PICK_CANCEL, -1,  t.getZone(), t.getDstLoc(), t.getBillCode(), ik, movedQuantityOri, t.getSrcLPCode(), operator, inv1.getId(), (int)srcQty1+"变为"+(int)inv1.getQtyOfMasterPack(),null,null);
    			Inventory inv2 =findInventory(ik, t.getZone(), t.getSrcLoc(), t.getBillCode(), SysCode.CK_TH2);
    			double srcQty2=inv2.getQtyOfMasterPack();
    			inv2.add(movedQuantityOri,0,0);
    			this.commonDao.store(inv2);
    			//增加
    			addInventoryLog(InventoryLogType.PICK_CANCEL, 1,  t.getZone(), t.getSrcLoc(), t.getBillCode(), ik, movedQuantityOri, null, operator, inv2.getId(), (int)srcQty2+"变为"+(int)inv2.getQtyOfMasterPack(),null,null);
    			t.setBeBh(Boolean.FALSE);
    			this.commonDao.store(t);
    		}else {
				throw new BusinessException("moveDoc.pickBackLoc.none");
			}
    		log.pickBack(movedQuantity);
    	}
    	this.commonDao.delete(log);
    	if(t.getPlanQuantityMU()==0){
    		this.commonDao.delete(t);
    	}
    	
    }
    public void pickedBack(Long pickTicketId, Long taskLogId,Double movedQuantity){
    	String barCode=null;
    	TaskLog log = this.commonDao.load(TaskLog.class, taskLogId);
    	Double movedQuantityOri = log.getMovedQuantity();
    	Double resultQuantity = movedQuantityOri-log.getBolQuantity()-movedQuantity;
    	if(resultQuantity < 0){
    		throw new BusinessException("moveDoc.pickedBackQuanti.overFlow");
    	}else{
    		//对选中的拣货记录退拣处理
    		Location pickBackLoc=log.getSrcLoc();//log.getDstLoc().getPickBackLoc() 
    		if (pickBackLoc != null) {
				// 库存移位处理
    			ItemKey ik=log.getItemKey();
//    			List<Inv>
    			Task t=log.getTask();
    			Inventory srcInv =findInventory(ik, t.getZone(), t.getDstLoc(), t.getBillCode(), SysCode.CK_TH1);
//				ItemKeyInventory itemKeyInventory = inventoryManager.getItemKeyInventory(log.getDstLoc().getWarehouse(), log.getItemKey());
//				Inventory srcInv = itemKeyInventory.getInventory(log.getDstLoc(), log.getPackageUnit(), log.getDstLP(), barCode,log.getInventoryStatus(), log.getStorageDate(), log.getSOI());
				if (srcInv != null) {
					// 移位确认
					inventoryManager.moveInventory(srcInv.getId(), 
//							log.getDstLoc().getPickBackLoc().getId(),
							pickBackLoc.getId(),
							log.getDstLP() == null ? null : log.getDstLP().getId(), 
							movedQuantity, null, null, null);

				} else {
					throw new BusinessException("move.inventory.none");
				}
			}else {
					throw new BusinessException("moveDoc.pickBackLoc.none");
			}
    		log.pickBack(movedQuantity);
    	}
    	
    }
    
    private void pickedBack(PickTicket pickTicket, Set<TaskLog> taskLogs) {
		for(TaskLog log : taskLogs){
			double qty = log.getMovedQuantity()-log.getBolQuantity();
			pickedBackKams(pickTicket.getId(),log.getId(),qty);
		}
	}
//查询发货单信息    
    @SuppressWarnings("unchecked")
	public Map init_PA_INFO(Map params){
		Long pickTicketId = (Long)params.get("pickTicketId");
		
		final String hql = "SELECT new com.dev.swms.client.ui.javabean.PT_INFO(pickTicket.id,pickTicket.code,pickTicket.orderQuantity,pickTicket.preAllocatedQuantity,pickTicket.allocatedQuantity,pickTicket.pickedQuantity) "+
		"From PickTicket pickTicket " +
		"WHERE pickTicket.id =:pickTicketId";
		PT_INFO pt_info = (PT_INFO) commonDao.findByQueryUniqueResult(hql,new String[]{"pickTicketId" } , new Object[]{pickTicketId});

		
		Map<String ,PT_INFO> result = new HashMap<String,PT_INFO>();
		result.put(CT_PA.PT_RESULT, pt_info);
		return result;

	}
//查询发货单明细信息 	
	@SuppressWarnings("unchecked")
	public Map init_PD_INFO(Map params){
		Long pickTicketId = (Long)params.get("pickTicketId");
		
		final String hql = "SELECT new com.dev.swms.client.ui.javabean.PT_DETAILS(p.id,"+
	  	" p.item.id,"+
	  	" p.packageUnit.id,"+
	  	" p.packageUnit.convertFigure,"+
	  	" p.item.code,"+
	  	" p.item.name,"+
	  	" p.packageUnit.unit," +
	    " p.orderQuantity,"+ 
	    " p.orderQtyOfMasterUnit,"+
	    " p.preAllocatedQuantity,"+
	    " p.allocatedQuantity,"+
	    " p.pickedQuantity,"+
	    " p.shippedQuantity," +
	    " p.newLotInfo, "+
	    " p.newLotInfo.propC1,"+
	    " p.newLotInfo.propC2," +
	    " p.newLotInfo.propC3," +
	    " p.newLotInfo.propC4," +
	    " p.newLotInfo.propC5,"+
	    " p.newLotInfo.propC6," +
	    " p.newLotInfo.propC7," +
	    " p.newLotInfo.propC8," +
	    " p.newLotInfo.propC9,"+
	    
	    " p.newLotInfo.propN1, " +
	    " p.newLotInfo.propN2, " +
	    " p.newLotInfo.propN3, " +
	    
	    " p.newLotInfo.propD1," +
	    " p.newLotInfo.propD2," +
	    " p.newLotInfo.propD3," +
	    
	    " p.newLotInfo.propL1," +
	    " p.newLotInfo.propL2," +
	    " p.newLotInfo.propL3)" +
	    
	    " From PickTicketDetail p "+
	    " where p.pickTicket.id = :pickTicketId and p.orderQuantity>p.pickedQuantity" +
	    " and p.pickTicket.warehouse.id = :warehouseId";
		List<PT_DETAILS> pt_details = commonDao.findByQuery(hql,new String[]{"pickTicketId","warehouseId" },new Object[]{pickTicketId, WarehouseHolder.getWarehouse().getId()});

		
		Map<String ,List> result = new HashMap<String,List>();
		result.put(CT_PA.PD_RESULT, pt_details);
		return result;

	}
//查询发货单明细对应的库存信息	
	@SuppressWarnings("unchecked")
	public Map init_AL_INFO(Map params){
		Long itemId = (Long)params.get("itemId");
		Integer convertFigure = (Integer)params.get("convertFigure");
		StringBuffer hqlb = new StringBuffer();
		final Map propMap = new HashMap();
		String propC1 = (String)params.get("propC1");
		String propC2 = (String)params.get("propC2");
		String propC3 = (String)params.get("propC3");
		String propC4 = (String)params.get("propC4");
		String propC5 = (String)params.get("propC5");
		String propC6 = (String)params.get("propC6");
		String propC7 = (String)params.get("propC7");
		String propC8 = (String)params.get("propC8");
		String propC9 = (String)params.get("propC9");
		String propN1 = (String)params.get("propN1");
		String propN2 = (String)params.get("propN2");
		String propN3 = (String)params.get("propN3");
		String propD1 = (String)params.get("propD1");
		String propD2 = (String)params.get("propD2");
		String propD3 = (String)params.get("propD3");
		String propL1 = (String)params.get("propL1");
		String propL2 = (String)params.get("propL2");
		String propL3 = (String)params.get("propL3");

		hqlb.append(" select new com.dev.swms.client.ui.javabean.PT_AVAILABLE(inventory.id,inventory.location.code,inventory.itemKeyInventory.itemKey.item.code, ")
			.append("inventory.itemKeyInventory.itemKey.item.name,inventory.packageUnit.unit,")
			.append("inventory.packageUnit.convertFigure,")
			.append("inventory.quantity,")
			.append("inventory.qtyOfMasterPack-inventory.queuedQuantity,0,")
			.append("(inventory.status),inventory.itemKeyInventory.itemKey.lotInfo,")
			.append("inventory.storageDate,inventory.SOI)")
			.append(" from Inventory inventory,Item item")
			.append(" where inventory.itemKeyInventory.itemKey.item = item")
			.append(" and item.id = :itemId")
			.append(" and inventory.packageUnit.convertFigure >= :convertFigure")
			.append(" and (inventory.qtyOfMasterPack - inventory.queuedQuantity)>0")
			.append(" and inventory.location.warehouse.id = :warehouseId")
			.append(" and inventory.location.type in ('STORAGE','TRANSIT')")
			.append(" and (inventory.location.countLock = '' or inventory.location.countLock is null) ")
			.append(" and (inventory.location.inLock = '' or inventory.location.inLock is null) ")
			.append(" and (inventory.location.outLock = '' or inventory.location.outLock is null) ");
		if(params.size()>2){
			hqlb.append(" AND ( 1 = 1 ")
			.append(" AND ").append(NewLotInfoParser.decryptStringOfLot("propC1",propC1))
			.append(" AND ").append(NewLotInfoParser.decryptStringOfLot("propC2",propC2))
			.append(" AND ").append(NewLotInfoParser.decryptStringOfLot("propC3",propC3))
			.append(" AND ").append(NewLotInfoParser.decryptStringOfLot("propC4",propC4))
			.append(" AND ").append(NewLotInfoParser.decryptStringOfLot("propC5",propC5))
			.append(" AND ").append(NewLotInfoParser.decryptStringOfLot("propC6",propC6))
			.append(" AND ").append(NewLotInfoParser.decryptStringOfLot("propC7",propC7))
			.append(" AND ").append(NewLotInfoParser.decryptStringOfLot("propC8",propC8))
			.append(" AND ").append(NewLotInfoParser.decryptStringOfLot("propC9",propC9))
			
			.append(" AND ").append(NewLotInfoParser.decryptDoubleOfLot("propN1",propN1))
			.append(" AND ").append(NewLotInfoParser.decryptDoubleOfLot("propN2",propN2))
			.append(" AND ").append(NewLotInfoParser.decryptDoubleOfLot("propN3",propN3))
//			.append(" AND ").append(NewLotInfoParser.decryptDateOfLot("propD1",propD1))
//			.append(" AND ").append(NewLotInfoParser.decryptDateOfLot("propD2",propD2))
			.append(" AND ").append(NewLotInfoParser.decryptDateOfLot("propD3",propD3))
			.append(" AND ").append(NewLotInfoParser.decryptLongStringOfLot("propLC1",propL1)) 
			.append(" AND ").append(NewLotInfoParser.decryptLongStringOfLot("propLC2",propL2))
			.append(" AND ").append(NewLotInfoParser.decryptLongStringOfLot("propLC3",propL3))		
			.append(" )"); 
		}
		
		String hql  = hqlb.toString();
	 	if(propD1!=null){
	 		hql+=" and to_char(inventory.itemKeyInventory.itemKey.lotInfo.propD1,'yyyy-mm-dd')>='"+propD1+"'";
	 	}
	    	if(propD2!=null){
	    		hql+=" and to_char(inventory.itemKeyInventory.itemKey.lotInfo.propD2,'yyyy-mm-dd')>='"+propD2+"'";
	    	}

		List<PT_AVAILABLE> pt_available = commonDao.findByQuery(hql,new String[]{"itemId","convertFigure","warehouseId"},new Object[]{itemId,convertFigure, WarehouseHolder.getWarehouse().getId()});		
		Map<String ,List> result = new HashMap<String,List>();
		result.put(CT_PA.PTA_RESULT, pt_available);
		return result;
	}
	
//查询发货单已分配信息    
    @SuppressWarnings("unchecked")
	public Map init_ALD_INFO(Map params){
		Long pickTicketId = (Long)params.get("pickTicketId");
		
		final String hql = "SELECT new com.dev.swms.client.ui.javabean.PT_ALLOCATED(task.id," +
								   "task.srcLoc.code," +
								   "task.itemKey.item.code," +
								   "task.itemKey.item.name, " +
								   "task.packageUnit.unit," +
								   "task.planQuantity," +
								   "task.planQuantityMU-task.movedQuantityMU," +
								   "0, " +
								   "task.itemKey.lotInfo," +
								   "task.storageDate,task.SOI) "+
								   "from Task task where task.pickTicketDetail.pickTicket.id = :pickTicketId and task.movedQuantityMU = 0 "+
								   "and task.pickTicketDetail.pickTicket.warehouse.id = :warehouseId";
		List<PT_ALLOCATED> ptad_info = commonDao.findByQuery(hql,new String[]{"pickTicketId","warehouseId" },new Object[]{pickTicketId, WarehouseHolder.getWarehouse().getId()});

		
		Map<String ,List> result = new HashMap<String,List>();
		result.put(CT_PA.PTAD_RESULT , ptad_info);
		return result;

	}

	public String getBePackagedFollowASN(Map map) {
		Long pickTicketId = new Long(map.get("pickTicket.id").toString());
		PickTicket pickTicket = this.commonDao.load(PickTicket.class,pickTicketId);
		if(pickTicket.getCompany().isBePackagedFollowASN())
			return "true";
		else{
			return "false";
		}
	}
	
	//创建预波次
	@Override
	public void createPrewave(List<Long> ids) {
		
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
		//波次规则
		List<WaveRule> waveRules = this.commonDao.findByNamedQuery(
				"getWaveRulesByWarehouse", new String[] { "warehouseId"},
				new Object[] { WarehouseHolder.getWarehouse().getId()});
		WaveRule wr=waveRules.get(0);
		String one="";
		String code = wr.getWaveCode() +"_" + df.format(new Date());
		String hql = "select count(*) from Prewave prewave where prewave.code like '"
				+ code + "%'";
		Long nums = (Long) this.commonDao.findByQueryUniqueResult(hql,
				new String[] {}, new Object[] {});
		if (nums != 0) {
			code = code + "_" + nums;
		}

		Prewave  prewave = new Prewave();
		for(Long id : ids) {
			PickTicket pickTicket =this.load(PickTicket.class, id);//发货单
			if(one.equals("")) {
			one=pickTicket.getCompany().getName();//货主名称
			}else {
				if(pickTicket.getCompany().getName()!=one) {
					throw new BusinessException("只能选中相同货主的生成预波次");
				}
			}
			if(pickTicket.getPrewave()!=null) {
			throw new BusinessException("该单据已创建预波次");
			}
			
			//货主规则
			List<CompanyWorkRule> objs =  commonDao.findByQuery(" from CompanyWorkRule o where o.company.id=:id ",
					new String[] { "id"},new Object[] {pickTicket.getCompany().getId()});
			
			 if(objs.size()>0) { //有对象取周转方式
				 CompanyWorkRule cwr= objs.get(0);
				 prewave.setTurnOverMode(cwr.getCompanyTurnOverMode());
			 }else {
				 prewave.setTurnOverMode(TurnOverMode.FIFO_VALIDDATE);//默认
			 }
			prewave.setCompany(pickTicket.getCompany());//货主
			prewave.setStartDate(new Date());//开始时间
			prewave.setEndDate(new Date());//结束时间
			prewave.setCode(code); //预波次号
			prewave.setWorkModel(wr.getWorkModel());//工作模式
			prewave.setStatus(WaveDocStatus.OPEN);//打开
			Warehouse warehouse =this.load(Warehouse.class, WarehouseHolder.getWarehouse().getId());
			prewave.setWarehouse(warehouse);//仓库
			pickTicket.setPrewave(prewave);//写入发货单
		}
		commonDao.store(prewave);
		
		
		
	}
	
    //添加发货单到预波次列表
	@Override
	public void addpickticket(Long pid, List<Long> ids) {
		Prewave prewave=this.load(Prewave.class, pid);
				String one="";
		for(Long id : ids) {
			
			PickTicket pickTicket =this.load(PickTicket.class, id);
			
			if(one.equals("")) {
				one=pickTicket.getCompany().getName();//货主名称
			}else {
				if(pickTicket.getCompany().getName()!=one) {
					throw new BusinessException("只能选中相同货主添加");
				}else if(pickTicket.getPrewave()!=null) {
					throw new BusinessException("该单据已添加");
				}
			}
			pickTicket.setPrewave(prewave);
			commonDao.store(pickTicket); 
		}
		
	}

	@Override
	public void removepickticket(Long pid, List<Long> ids) {
		Prewave prewave=this.load(Prewave.class, pid);
		for(Long id:ids){
			PickTicketDetail pickTicketDetail =this.load(PickTicketDetail.class, id);
			pickTicketDetail.getPickTicket().setPrewave(null);		
			commonDao.store(pickTicketDetail);
			
		}
		
	}

	@Override
	public void addPlanPickTicketDetail(Long pickTicketId, PickTicketDetail ptd) {
		PickTicket pickTicket = commonDao.load(PickTicket.class, pickTicketId);
		Boolean xbc=Boolean.FALSE;
		if(pickTicket.getZone().getCode().indexOf("-SL")>0) {
			xbc=Boolean.TRUE;
			if(ptd.getZzkw()==null){
				throw new BusinessException(ptd.getItem().getCode()+"制造库位必填");
			}
		}
		if( ptd.getItemKey()!=null){
			unLockVMI(pickTicket.getZone().getId(),ptd.getLocation().getId(), ptd.getItemKey().getId(), ptd.getOrderQtyOfMasterUnit(),xbc,ptd.getZzkw());
		}
		ptd.setOrderQtyOfMasterUnit(ptd.getOrderQuantity());
		if(ptd.isNew()){
			pickTicket.addPickTicketDetail(ptd);
			ptd.setZone(pickTicket.getZone());
			ptd.setZone1(pickTicket.getZone1());
			ptd.setZone2(pickTicket.getZone2());
			ptd.setSingle("1");
		}
		if(ptd.getBonded()==null){
			ptd.setBonded(pickTicket.getApplyDoc());
		}
		if(ptd.getLineNumber()==null || ptd.getLineNumber().length()<=0){
			Long count= (Long) commonDao.findByQuery("select count(ptd.id) from PickTicketDetail ptd where ptd.pickTicket.id=:id  ",
			new String[] { "id"},new Object[] {pickTicketId }).get(0);
			if(count==0){
				ptd.setLineNumber("1");
			}else{
				ptd.setLineNumber(String.valueOf((count.intValue()+1)));
			}
		}
	
		
		double qty=0;
		if(pickTicket.getWarehouse().getId().equals(new Long("1"))){
			qty=lockInvKAMS(ptd,  pickTicket.getZone(), ptd.getZzkw());
		}else{
			qty=lockInvDetail(ptd, pickTicket.getZone(),ptd.getZzkw(),xbc);
			if(pickTicket.getAllocatedQuantity()>0){
				if(pickTicket.getRelatedBill2()==null){
					pickTicket.setRelatedBill2(this.bussinessCodeManager.getCodeForYm("BH",3));
				}
			}
		}
		if(qty<ptd.getOrderQuantity()){
			throw new BusinessException(ptd.getItem().getCode()+"库存不足"+qty);
		}else{
			ptd.setAllocatedQuantity(ptd.getOrderQuantity());
			this.commonDao.store(ptd);
			//查找对应品番，把数据写入进去
			commonDao.store(pickTicket);
			Refresh(pickTicket.getId());//刷新毛重体
		}
		
		if(pickTicket.getWarehouse().getId().equals(new Long("1"))){
			pickTicket.setStatus(PickTicketStatus.OPEN);
			this.commonDao.store(pickTicket);
		}
		
	}
	
	
	@Override
	public void modifyPlanPickTicketDetail(Long detailId, double qty) {
		PickTicketDetail d=this.commonDao.get(PickTicketDetail.class, detailId);
		List<PickTicketDetail> ptds=this.commonDao.findByQuery("from PickTicketDetail d where d.id="+d.getId());
		double movedQuantity=d.getOrderQtyOfMasterUnit()-qty;
		d.setOrderQuantity(qty);
		d.setOrderQtyOfMasterUnit(qty);
		d.setWeight(qty*d.getItem().getWeight());
		d.setRealWeight(qty*d.getItem().getRoughWeight());
		d.setVolume(qty*d.getItem().getLength()*d.getItem().getWidth()*d.getItem().getLength());
		d.setPreAllocatedQuantity(qty);
		this.commonDao.store(d);
		if(ptds.size()>0){
			PickTicketDetail ptd=ptds.get(0);
			if(ptd.getOrderQuantity()<ptd.getPickedQuantity()){
				throw new BusinessException("拣货数量不能大于订单数量");
			}
			if(ptd.getOrderQuantity()<ptd.getAllocatedQuantity()){
				throw new BusinessException("分配数量不能大于订单数量");
			}
			ptd.setOrderQtyOfMasterUnit(qty);
			ptd.setOrderQuantity(qty);
			ptd.setWeight(qty*d.getItem().getWeight());
			ptd.setRealWeight(qty*d.getItem().getRoughWeight());
			ptd.setVolume(qty*d.getItem().getLength()*d.getItem().getWidth()*d.getItem().getLength());
			ptd.setPreAllocatedQuantity(qty);
			this.commonDao.store(d);
		}
		Refresh(d.getPickTicket().getId());//刷新毛重体
	}
	
	public void Refresh(Long pid){
		PickTicket p =this.load(PickTicket.class, pid);
		List<PickTicketDetail> pickTicketDetails =  commonDao.findByQuery(" from PickTicketDetail p where p.pickTicket.id=:id ",
				new String[] { "id"},new Object[] {p.getId()});
		double weight=0;
		double realWeight=0;
		double volume=0;
		double qty=0;
		double preQty=0;
		double a=0;
		for(PickTicketDetail ppd :pickTicketDetails){
			weight+=ppd.getWeight();
			realWeight+=ppd.getRealWeight();
			volume+=ppd.getVolume();
			qty+=ppd.getOrderQtyOfMasterUnit();
			preQty+=ppd.getPreAllocatedQuantity();
			a+=ppd.getAllocatedQuantity();
		}
		p.setWeight(weight);
		if(!p.getWarehouse().getId().equals(1020l)||p.getBillType().getName().equals("其他出库单")){
			p.setOrderQuantity(qty);
		}
		p.setAllocatedQuantity(a);
		p.setRealWeight(realWeight);
		p.setVolume(volume);
		p.setPreAllocatedQuantity(preQty);
		commonDao.store(p);
	}

	@Override
	public void removePlanPickTicketDetail(Long pickTicketId, List<Long> planPickTicketDetailIds) {
		PickTicket pickTicket = commonDao.load(PickTicket.class, pickTicketId);
		double qty=0;
		for(Long id:planPickTicketDetailIds){
			PlanPickTicketDetail d=this.commonDao.get(PlanPickTicketDetail.class, id);
			PlanShipDetail psd=d.getPsd();
			psd.setPptd(null);
			this.commonDao.store(psd);
			pickTicket.setOrderQuantity(pickTicket.getOrderQuantity()-d.getOrderQuantity());
			pickTicket.setAllocatedQuantity(pickTicket.getOrderQuantity());
			this.commonDao.store(pickTicket);
			unLockVMI(d.getZone().getId(),d.getLocation().getId(),d.getItemKey().getId(),d.getAllocatedQuantity(),Boolean.FALSE,null);
			this.commonDao.delete(d);
			//pickTicket.getPickTicketDetails().remove(d);
		}
//		pickTicket.removeDetail(planPickTicketDetailIds);
//		Refresh(pickTicket.getId());
	}
	
	@Override
	public void removePickTicketDetail(Long pickTicketId, List<Long> pickTicketDetailIds) {
		PickTicket pickTicket = commonDao.load(PickTicket.class, pickTicketId);
		for(Long id:pickTicketDetailIds){
			PickTicketDetail d=this.commonDao.get(PickTicketDetail.class, id);
			pickTicket.setOrderQuantity(pickTicket.getOrderQuantity()-d.getOrderQuantity());
			pickTicket.setAllocatedQuantity(pickTicket.getOrderQuantity());
			this.commonDao.store(pickTicket);
			if(!pickTicket.getWarehouse().getId().equals(new Long("1"))&&d.getLocation()!=null){
				Boolean xbc=Boolean.FALSE;
				if(pickTicket.getZone().getCode().indexOf("-SL")>0) {
					xbc=Boolean.TRUE;
					if(d.getZzkw()==null){
						throw new BusinessException(d.getItem().getCode()+"制造库位必填");
					}
				}
				unLockVMI(d.getZone().getId(),d.getLocation().getId(),d.getItemKey().getId(),d.getAllocatedQuantity(),xbc,d.getZzkw());
			}else{
				if(pickTicket.getWarehouse().getId().equals(new Long("1"))){
					List<Task> ts=this.commonDao.findByQuery("from Task t where t.pickTicketDetail.id="+d.getId());
					if(ts.size()>0){
						throw new BusinessException("出单数量大于0不能删除,先取消分配");
					}else{
						pickTicket.setOrderQuantity(pickTicket.getOrderQuantity()-d.getOrderQtyOfMasterUnit());
						this.commonDao.store(pickTicket);
						this.commonDao.delete(d);
					}
//					for(Task t:ts){
//						Inventory inv=findInventory(t.getItemKey(), t.getZone(), t.getSrcLoc(), pickTicket.getCode(), SysCode.CK_FP2);
//						double unQty=t.getPlanQuantityMU();
//						inv.setQueuedQuantity(inv.getQueuedQuantity()-unQty);
//						if(inv.getQueuedQuantity()<0){
//							inv.setQueuedQuantity(0);
//						}
//						this.commonDao.store(inv);
//						this.commonDao.delete(t);
//					}
//					pickTicket.setAllocatedQuantity(pickTicket.getAllocatedQuantity()-d.getAllocatedQuantity());
//					this.commonDao.store(pickTicket);
//					d.setAllocatedQuantity(0);
//					this.commonDao.delete(d);
				}
			}
			this.commonDao.delete(d);
		}
//		Refresh(pickTicket.getId());
	}
	
	
	public void unLock(Long zoneId,Long itemKeyId,double lockQty){
		List<Inventory> invs=this.commonDao.findByQuery("from Inventory i where i.zone.id="+zoneId+" and i.itemKey.id="+itemKeyId
				+" and i.location.type!='SHIP' and i.SOI is null ");
		if(invs.size()>0){
			Inventory inv=invs.get(0);
			inv.setQueuedQuantity(inv.getQueuedQuantity()-lockQty);
			this.commonDao.store(inv);
		}
	}
	
	public void unLockVMI(Long zoneId,Long locationId,Long itemKeyId,double lockQty,Boolean xbc,Location zzkw){
		String hql="from Inventory i where i.zone.id="+zoneId+" and i.itemKey.id="+itemKeyId
				+" and i.location.type!='SHIP' and i.SOI is null and i.location.id="+locationId;
		if(xbc){
			hql+=" and i.zzkw.id="+zzkw.getId();
		}
		List<Inventory> invs=this.commonDao.findByQuery(hql);
		if(invs.size()>0){
			Inventory inv=invs.get(0);
			inv.setQueuedQuantity(inv.getQueuedQuantity()-lockQty);
			this.commonDao.store(inv);
		}
	}

	@Override
	public void Wholepicking(Long masterBOLId, Long workerId,List<Long> pickTicketId) {
		Worker w = this.load(Worker.class, workerId);
		MasterBOL masterBOL=this.load(MasterBOL.class, masterBOLId);
		/*String hql = "select pickTicket from PickTicket pickTicket where pickTicket.masterBOL.id = "+masterBOL.getId()+"";
		List<PickTicket> PickTickets = commonDao.findByQuery(hql);*/
		for(Long id:pickTicketId){
			PickTicket pickTicket =this.load(PickTicket.class, id);
			pickConfirm(pickTicket.getId(),null,workerId);
			if(masterBOL!=null){
				refreshMasterBOL(masterBOLId);
			}
		}
		
	}
	public void multiPickConfirm(List<Long> ids){
		for(Long id:ids){
			PickTicket pickTicket =this.load(PickTicket.class, id);
			pickConfirm(pickTicket.getId(),null,null);
			if(pickTicket.getMasterBOL()!=null){
				refreshMasterBOL(pickTicket.getMasterBOL().getId());
			}
		}
	}
	
	public void multiPickConfirmForBOL(List<Long> ids){
		for(Long id:ids){
			MasterBOL masterBOL = commonDao.load(MasterBOL.class,id);
			
				List<PickTicket> pts=this.commonDao.findByQuery("from PickTicket p where p.masterBOL.id=:masterBOLId",
						new String[]{"masterBOLId"},new Object[]{id});
//				for (PickTicket pt : pts) {
//					if(pt.getPickedQuantity()<pt.getOrderQuantity()){
//						throw new BusinessException("还有未拣货完成的订单，不能发运");
//					}
//				}
				for (PickTicket pt : pts) {
					pickConfirm(pt.getId(),null,null);
				}
				masterBOL.setLeaveTime(new Date());
				masterBOL.setStatus(MasterBOLStatus.SHIP_ALL);
				commonDao.store(masterBOL);
				refreshMasterBOL(masterBOL.getId());
			
		}
	}
	
	
	public void refreshMasterBOL(Long id) {
		MasterBOL masterBOL=this.load(MasterBOL.class, id);
		 List<Object[]> objs =  commonDao.findByQuery("select COALESCE(sum(pickTicket.orderQuantity),0),COALESCE(sum(pickTicket.pickedQuantity),0),COALESCE(sum(pickTicket.shippedQuantity),0)  from PickTicket pickTicket where pickTicket.masterBOL.id=:id ",
					new String[] { "id"},new Object[] {id});
			if(objs.size()>0){
				Object[] obj=objs.get(0);
				masterBOL.setOrderQuantity((Double)obj[0]);
				masterBOL.setPickQuantity((Double)obj[1]);
				masterBOL.setShipQuantity((Double)obj[2]);
			}
		if(masterBOL.getPickQuantity()==masterBOL.getOrderQuantity()) {
			masterBOL.setStatus(MasterBOLStatus.PICK_ALL);
		}else if(masterBOL.getPickQuantity()>masterBOL.getOrderQuantity()){
			masterBOL.setStatus(MasterBOLStatus.PICKUP);
		}else if(masterBOL.getShipQuantity()==masterBOL.getOrderQuantity()){
				masterBOL.setStatus(MasterBOLStatus.SHIP_ALL);
		}else {
			masterBOL.setStatus(MasterBOLStatus.OPEN);
		}
			
			
		commonDao.store(masterBOL);
	}
	

	@Override
	public void mwzh(List<Long> ids, Date date,int qty, String driver, String cph, String remark) {
		for(Long id:ids){
			PickTicket pt =this.commonDao.load(PickTicket.class,id);
			if(pt.getStatus().equals(PickTicketStatus.PRE_OPEN)){
				pt.setStatus(PickTicketStatus.OPEN);
			}
			pt.setDescription(remark);
			pt.setLictrailer(cph);
			pt.setLineName(driver);
			pt.setDriverName(driver);
			pt.setBOLQuantity(qty);
			pt.setShipDate(date);
			this.commonDao.store(pt);
		}
	}
	
	public NewLotInfo convertLot (String cusCode,NewLotInfo lotInfo){
		if(!cusCode.equals(CompanyCode.HLX)){
			return lotInfo;
		}
		if(lotInfo!=null&&lotInfo.getPropC1()!=null&&!lotInfo.getPropC1().equals("")){
			String lot=lotInfo.getPropC1();
			if(lot.length()<6){
				throw new BusinessException(lot+"批次不完整");
			}
			int year=0;
			int week=0;
			int day=0;
			try {
				year=Integer.parseInt("20"+lot.substring(0, 2));
				week=Integer.parseInt(lot.substring(2, 4));
				day=(Integer.parseInt(lot.substring(4, 5))+1);
				if(day==8){
					day=1;
					week=week+1;
				}
				Calendar calendar = Calendar.getInstance();
				calendar.set( Calendar.YEAR, year);
				calendar.set( Calendar.WEEK_OF_YEAR, week);
				calendar.set( Calendar.DAY_OF_WEEK, day );
				lotInfo.setPropD1(DateUtil.formatDateYMDToStr(calendar.getTime()));
				return lotInfo;
			} catch (Exception e) {
				throw new BusinessException(lot+"年周天格式有误，应为数字");
			}
		}else{
			return lotInfo;
		}
		
		
	}
	
	
	public void shipConfirm(Long taskLogId,double shipQuantity) {
		TaskLog log = commonDao.load(TaskLog.class, taskLogId);
		PickTicketDetail detail = log.getTask().getPickTicketDetail();
		PickTicket p = detail.getPickTicket();
		log.setShipQuantity(log.getShipQuantity() + shipQuantity);
//		log.setOperateTime(new Date());
		
		/**扣减库存,添加库存日志*/
		inventoryManager.ship(p.getDock().getId(),
			log.getItemKey(),
			shipQuantity,
			null,//log.getPackageUnit().getId(),
			log.getTask().getSrcLP()==null?null:log.getTask().getSrcLP().getId(),
			log.getInventoryStatus(),
			log.getStorageDate(),
			log.getSOI(),
			p.getCode(),
			p.getBillType());
			int figure=1;//log.getPackageUnit().getConvertFigure()
			detail.setShippedQuantity(detail.getShippedQuantity()+shipQuantity*figure);
			detail.setStorageDate(log.getStorageDate());
			updatePreAllocate(p.getId());
			updatePickTicketQuantity(p.getId());
//		p.setWaveCode(null);
	}
	
	/**更新PickTicket发运数量和预分配数量*/
	public void updatePickTicketQuantity(Long pickTicketId){
		PickTicket p = commonDao.load(PickTicket.class, pickTicketId);
		double q=0;
		List<PickTicketDetail> ptds=this.commonDao.findByQuery(" from PickTicketDetail pd where pd.pickTicket.id ="+pickTicketId);
		for(PickTicketDetail d:ptds){
			q+=d.getShippedQuantity();
		}
		p.setShippedQuantity(q);
		if(p.shippedAllDetails()){
			p.setStatus(PickTicketStatus.CLOSE);
		}else{
			p.setStatus(PickTicketStatus.SHIP_PART);
		}
//		p.setShipDate(new Date());
		p.setUserTracking();
		this.commonDao.store(p);
	}
	
	@SuppressWarnings("unchecked")
	public void updatePreAllocate(Long pickTicketId) {
		//扣减预分配表流程调整
		//1、根据PickTicketDetail中preAllocatedLot依次扣减PreAllocate
		//2、如果PreAllocate中记录的数量被扣减完毕，则直接删除PreAllocate记录
		//3、根据PickTicketDetail中item依次扣减PreAllocate
		//4、如果PreAllocate中记录的数量被扣减完毕，则直接删除PreAllocate记录
		PickTicket p = commonDao.load(PickTicket.class, pickTicketId);
		List<PreAllocate> preAllocates = commonDao.findByNamedQuery("getPreAllocateByCondition", 
				new String[]{"code", "warehouseId"}, 
				new Object[]{p.getCode(), WarehouseHolder.getWarehouse().getId()});
		Map<PickTicketDetail, Double> details = new HashMap<PickTicketDetail, Double>();
		for (PickTicketDetail detail : p.getPickTicketDetails()) {
			if (details == null || !details.containsKey(detail)) {
				details.put(detail, detail.getPickedQuantity());
			} else {
				double qty = details.get(detail);
				qty += detail.getPickedQuantity();
				details.put(detail, qty);
			}
		}
		List<PreAllocate> toBeRemoved = new ArrayList<PreAllocate>();
		
		//第一次循环
		for (PickTicketDetail dtl : details.keySet()) {
			for (PreAllocate preAllocate : preAllocates) {
				if (preAllocate.getItem().equals(dtl.getItem())
						&& ((preAllocate.getLot()==null && dtl.getPreAllocatedLot()==null) 
						|| (preAllocate.getLot().equals(dtl.getPreAllocatedLot())))) {
					if (details.get(dtl) > preAllocate.getPreAllocatedQuantity()) {
						details.put(dtl, details.get(dtl) - preAllocate.getPreAllocatedQuantity());
						toBeRemoved.add(preAllocate);
					} else {
						preAllocate.setPreAllocatedQuantity(preAllocate.getPreAllocatedQuantity() - details.get(dtl));
						if (preAllocate.getPreAllocatedQuantity() == 0) {
							toBeRemoved.add(preAllocate);
						}
						details.put(dtl, 0.0);
					}
				}
			}
		}
		commonDao.deleteAll(toBeRemoved);
		toBeRemoved.clear();
		
		
		//第二次循环
		for (PickTicketDetail dtl : details.keySet()) {
			if (details.get(dtl) <= 0) {
				continue;
			}
			for (PreAllocate preAllocate : preAllocates) {
				if (preAllocate.getItem().equals(dtl.getItem())) {
					if (details.get(dtl) > preAllocate.getPreAllocatedQuantity()) {
						details.put(dtl, details.get(dtl) - preAllocate.getPreAllocatedQuantity());
						toBeRemoved.add(preAllocate);
					} else {
						preAllocate.setPreAllocatedQuantity(preAllocate.getPreAllocatedQuantity() - details.get(dtl));
						if (preAllocate.getPreAllocatedQuantity() == 0) {
							toBeRemoved.add(preAllocate);
						}
						details.put(dtl, 0.0);
					}
				}
			}
		}
		commonDao.deleteAll(toBeRemoved);
	}

	@Override
	public void shipconfirm(List<Long> ids, double fytps, String shipmentType,
			String cphorkddh, Date shipDate) {
		for(Long pickTicketId:ids){
			PickTicket p = commonDao.load(PickTicket.class, pickTicketId);
			p.setShipDate(shipDate);
			p.setShipmentTrayNO(fytps);//发运托盘数
			p.setRequireArriveDate(new Date());
			if (p.getStatus().equals(PickTicketStatus.PICK_ALL)
					|| p.getStatus().equals(PickTicketStatus.PICKUP)||p.getStatus().equals(PickTicketStatus.SHIP_PART)) {
				List<PickTicketDetail> ptds = commonDao.findByQuery("from PickTicketDetail p where p.pickTicket.id=:id", 
						new String[]{"id"}, new Object[]{pickTicketId});
				//物流
				p.setExpressNO(cphorkddh);//快递单号
				
				for (PickTicketDetail detail : ptds) {
					List<TaskLog> taskLogs = commonDao
							.findByQuery("FROM TaskLog log WHERE log.shipQuantity<log.movedQuantity and log.task.pickTicketDetail.id = "
									+ detail.getId());
					for (TaskLog log : taskLogs) {
						double quantity =log.getMovedQuantity() - log.getShipQuantity();
						shipConfirm(log.getId(),quantity);
						
						
					}
					
			}
			}
			feeManager.autoPickFee(pickTicketId);
		}
	}

	// 删除回单影像
	@Override
	public void deleteSignFile(List<Long> ids) {
		for (Long id : ids) {
			SignFile signFile = this.get(SignFile.class, id);
			PickTicket pickTicket = signFile.getPickTicket();
			if (signFile != null) {
				commonDao.delete(signFile);
			} else {
				throw new BusinessException("待删除文件不存在！");
			}
			pickTicket.removeFiles(signFile);// 移除关联
			// 删除对应的图片资料
			String fileUrl = GlobalParamUtils
					.getGloableStringValue("imageTarget")
					+ signFile.getFileName();
			File file = new File(fileUrl);
			file.delete();
			commonDao.store(pickTicket);
		}
	}
	
	@SuppressWarnings("unchecked")
	public void manualAllocate(Map params,List<Long> id) {
		PickTicketDetail pickTicketDetail = commonDao.load(PickTicketDetail.class, id.get(0));
		manualAllocate(pickTicketDetail, params);
	}
	
	
	@SuppressWarnings("unchecked")
	public void manualAllocate(AbstractMoveDocDetail moveDocDetail, Map params) {
		AbstractMoveDoc pickTicket = moveDocDetail.getAbstractMoveDoc();
		Double unallocateQty = moveDocDetail.getUnallocateQuantity();
//		if (unallocateQty <= 0) {
//			return;
//		}
		Set<Map.Entry<Long, List>> itor = params.entrySet();
		for (Map.Entry<Long, List> me : itor) {
			Inventory inventory = commonDao.load(Inventory.class, me.getKey());
			Double quantity = Double.parseDouble(me.getValue().get(0).toString());
			if(quantity <= 0){
				continue;
			}
//			if(!inventory.getStatus().equals("")&&inventory.getStatus()!=null){
//				throw new BusinessException("该库存为不可用库存！");
//			}
			if(inventory.isBeLock()){
				throw new BusinessException("该库存为不可用库存！");
			}
			//待分配数量(转换为基本单位数量)
			quantity = quantity;//*inventory.getPackageUnit().getConvertFigure();
			if (quantity > inventory.getAvaliableQuantity()) {
				quantity = inventory.getAvaliableQuantity();
			}
			if (quantity > unallocateQty) {
				quantity = unallocateQty;
			}
			unallocateQty -= quantity;
			pickTicket.allocate(null,moveDocDetail, inventory, quantity);
			inventory.allocate(quantity, null, null);
			refreshPickWeightInfo(pickTicket.getId());
//			if (unallocateQty <= 0) {
//				return;
//			}
		}
//		wmsOperationHisManager.storeOperationHis(pickTicket.getId(),pickTicket.getCode(), null, null, "发货管理-发货单管理", "手工分配-分配",null,
//				"",0, 0,0, 0, null, "WMS");
	}
	public void manualAllocate(List<Long> pickIds) {
		for(Long id:pickIds) {
			 PickTicket pt=	commonDao.load( PickTicket.class, id);
		List<PickTicketDetail> list1=commonDao.findByQuery(" from  PickTicketDetail p where p.pickTicket.id=");
		 for(PickTicketDetail ptd:list1) {
			 List<Inventory> list2=commonDao.findByQuery("from Inventory i where i.itemKey.item.id="+ptd.getItem().getId());
			
//			 pt.allocate(null,ptd, inventory, quantity);
//				inventory.allocate(quantity, null, null);
//				refreshPickWeightInfo(pt.getId());
			 
		 }
		}
	}
	
	
	//刷新出库单的重量体积
		private void refreshPickWeightInfo(Long id){
			PickTicket pt = commonDao.load(PickTicket.class, id);
			List<PickTicketDetail> ptds = commonDao.findByQuery("from PickTicketDetail p where p.pickTicket.id=:id and p.allocatedQuantity>0 ", 
					new String[]{"id"}, new Object[]{id});
			double totalWeight=0;
			double totalVolume=0;
			for(PickTicketDetail ptd : ptds){
				if(ptd.getAllocatedQuantity()>0){
					Object[] objs = (Object[])commonDao.findByQuery("select sum(COALESCE(t.weight,0)*t.planQuantity),sum(COALESCE(t.volume,0)*t.planQuantity) from Task t where t.pickTicketDetail.id=:id", 
							new String[]{"id"}, new Object[]{ptd.getId()}).get(0);
					double weight=(Double)(objs[0]==null?0D:objs[0]);
					double volume=(Double)(objs[1]==null?0D:objs[1]);
					ptd.setWeight(weight);
					ptd.setVolume(volume);
					totalWeight+=weight;
					totalVolume+=volume;
					this.commonDao.store(ptd);
				}
			}
			pt.setWeight(totalWeight);
			pt.setVolume(totalVolume);
			this.commonDao.store(pt);
		}
	
		//取消分配 如果取消分配后，对应发货记录的分配数量为0,则记录下来最后一起删除	
		@SuppressWarnings("unchecked")
		public void cancellAllocate(List<Long> ids) {
			List<PickTicketDetail> pds=new ArrayList<PickTicketDetail>();
			PickTicket pickTicket = null;
			for(Long pdId:ids){
				PickTicketDetail pd=this.commonDao.get(PickTicketDetail.class, pdId);
				pickTicket=pd.getPickTicket();
				pds.add(pd);
//				wmsOperationHisManager.storeOperationHis(pickTicket.getId(),pickTicket.getCode(), pd.getId(), pd.getCode(), "发货管理-发货单管理", "手工分配-取消分配",pickTicket.getStatus(),
//						"",0, 0,0, 0, pickTicket.getDescription(), "WMS");
			}
			autoAllocator.unallocate(pickTicket,pds);
			
		}

		@Override
		public void returnGoods(Long pickTicketId, Map map) {
			PickTicket pt =this.load(PickTicket.class,pickTicketId);
			Set<Map.Entry<Long, List>> itor = map.entrySet();
			for (Map.Entry<Long, List> me : itor) {
				PickTicketDetail ptd =this.load(PickTicketDetail.class, me.getKey());
				Double rejectQuantity = Double.parseDouble(me.getValue().get(0).toString());
				Double rejectZTQuantity = Double.parseDouble(me.getValue().get(1).toString());
				Double norejectQuantity = Double.parseDouble(me.getValue().get(2).toString());
				Double norejectZTQuantity = Double.parseDouble(me.getValue().get(3).toString());
				double sum=ptd.getRejectQuantity()+rejectQuantity+ptd.getRejectZTQuantity()+rejectZTQuantity+ptd.getNorejectQuantity()+norejectQuantity+ptd.getNorejectZTQuantity()+norejectZTQuantity;
				if(sum<=ptd.getOrderQuantity()&&sum>0){
					String billtype="";
					if(rejectQuantity>0 || rejectZTQuantity>0){
						billtype="良品退货收货单";
						sorteASN(me.getKey(),ptd.getItem().getId(),billtype,rejectQuantity+rejectZTQuantity);
					}else if(norejectQuantity>0 || norejectZTQuantity>0){
						billtype="不良品退货收货单";
						sorteASN(me.getKey(),ptd.getItem().getId(),billtype,norejectQuantity+norejectZTQuantity);
					}
					ptd.setRejectQuantity(ptd.getRejectQuantity()+rejectQuantity);
					ptd.setRejectZTQuantity(ptd.getRejectZTQuantity()+rejectZTQuantity);
					ptd.setNorejectQuantity(ptd.getNorejectQuantity()+norejectQuantity);
					ptd.setNorejectZTQuantity(ptd.getNorejectZTQuantity()+norejectZTQuantity);
					commonDao.store(ptd);
				}else{
					throw new BusinessException("输入的数量不能大于订单数量!");
				}
			}
		}
		
		public void sorteASN(Long ptdId,Long itemId,String billtype,double quanity){
			PickTicketDetail ptd=this.load(PickTicketDetail.class,ptdId);
			PickTicket pt =this.load(PickTicket.class,ptd.getPickTicket().getId());
			Item item=this.load(Item.class,itemId);
			ASN asn=null;
			List<ASN> ASNS =  commonDao.findByQuery(" from ASN a where a.relatedBill3=:relatedBill3",
					new String[] { "relatedBill3"},new Object[] {pt.getCode()});
			if(ASNS.size()>0){
				asn=ASNS.get(0);
			}else{
				asn=EntityFactory.getEntity(ASN.class);
				asn.setCode(this.bussinessCodeManager.getCodeForYm("RP",3));
				asn.setRelatedBill3(pt.getCode());
				asn.setWarehouse(WarehouseHolder.getWarehouse());
				asn.setOrderDate(new Date());
				asn.setStatus(ASNStatus.OPEN);
				asn.setCompany(pt.getCompany());
				BillType billType=null;
				List<BillType> BillTypes =  commonDao.findByQuery(" from BillType b where  b.name=:billtype and b.type ='RECEIVE' and b.disabled=false",
							new String[] {"billtype"},new Object[] {billtype});
				if(BillTypes.size()>0){
					billType=BillTypes.get(0);
				}
				asn.setBillType(billType);
				if (asn.getDock() == null || asn.getDock().getId() == 0) {
					 List<Location> objs =  commonDao.findByQuery(" from Location o where o.warehouse.id=:id  and o.type ='RECEIVE' and o.disabled=false",
								new String[] { "id"},new Object[] {WarehouseHolder.getWarehouse().getId()});
					 Location l =objs.get(0);
					 asn.setDock(l); 

				} else {
					asn.setDock(this.load(Location.class, asn.getDock().getId()));
				}
				asn.setUserTracking();
				commonDao.store(asn);
			}
			ASNDetail asnDetail=null;
			List<ASNDetail> ASNDetails =  commonDao.findByQuery(" from ASNDetail ad where ad.asn.id=:asnId and ad.item.id=:itemId",
					new String[] { "asnId","itemId"},new Object[] {asn.getId(),item.getId()});
			if(ASNDetails.size()>0){
				asnDetail=ASNDetails.get(0);
				asnDetail.setExpectedQuantity(asnDetail.getExpectedQuantity()+quanity);
				commonDao.store(asnDetail);
			}else{
				asnDetail = EntityFactory.getEntity(ASNDetail.class);
				PackageUnit unit = commonDao.load(PackageUnit.class, ptd.getPackageUnit().getId());
				if (asnDetail.getDock() == null || asnDetail.getDock().getId() == 0) {
					asnDetail.setDock(null);
				} else {
					asnDetail.setDock(this.load(Location.class, asnDetail.getDock().getId()));
				}
				asnDetail.setItem(ptd.getItem());
				asnDetail.setPackageUnit(unit);
				asnDetail.setExpectedQuantity(quanity);
				asn.addASNDetail(asnDetail);
			}
				refreshweightandvolume(asn.getId());
		}
		
		public void refreshweightandvolume(Long id) {
			ASN a = commonDao.load(ASN.class, id);

			List<Object[]> objs = commonDao.findByQuery(
					"select COALESCE(sum(o.weight),0),COALESCE(sum(o.receivedWeight),0),COALESCE(sum(o.volume),0),COALESCE(sum(o.expectedQuantity),0)  from ASNDetail o where o.asn.id=:id ",
					new String[] { "id" }, new Object[] { id });
			if (objs.size() > 0) {
				Object[] obj = objs.get(0);
				a.setWeight((Double) obj[0]);
				a.setReceivedWeight((Double) obj[1]);
				a.setVolume((Double) obj[2]);
				a.setExpectedQuantity((Double) obj[3]);
			}
			commonDao.store(a);

		}
		
		public void importPickTicket(File file) {
			String filename = file.getName();	
			try {
				filename = URLDecoder.decode(filename, "GBK");
				importPick(file);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		
		public void importPick(File file){
			Workbook workbook;
			try {
				workbook = Workbook.getWorkbook(file);
				Sheet sheet = workbook.getSheet(0);//得到excel第一页的内容
				if(sheet.getColumns()<3){
					throw new BusinessException("该模版列数不正确，不能小于3");
				}
				 HashMap<String,String> map=new HashMap<String, String>();
				 List<Location> ls =  commonDao.findByQuery(" from Location o where o.warehouse.id=:id  and o.type ='SHIP' and o.disabled=false",
							new String[] { "id"},new Object[] {WarehouseHolder.getWarehouse().getId()});
				 List<BillType> bts =  commonDao.findByQuery(" from BillType o where o.code='QTCK'  and o.type ='SHIP'");
				 Location l =ls.get(0);
				 BillType bt=bts.get(0);
				 Long time=(new Date()).getTime();
				 for (int i = 1; i <sheet.getRows(); i++) {
					 System.out.println("======"+i);
					 //订单号（ASN）货品自编码 数量
				 	String relatedBill1=sheet.getCell(0,i).getContents().trim()+time;
				 	if(relatedBill1==null||relatedBill1.equals("")){
				 		return;
				 	}
					String item_code=sheet.getCell(1,i).getContents().trim();
					String quantity=sheet.getCell(2,i).getContents().trim();
					String zone_code=sheet.getCell(0,i).getContents().trim();
					List<Item> items=this.commonDao.findByQuery("from Item i where i.code='"+item_code+"' and i.warehouse.id="+WarehouseHolder.getWarehouse().getId());
					if(items.size()>0){
						List<PickTicket> pts=this.commonDao.findByQuery("from PickTicket a where a.relatedBill1=:relatedBill1 ",
								new String[]{"relatedBill1"},new Object[]{relatedBill1});
						PickTicket pt=null;
						Item item=items.get(0);
						if(pts.size()>0){
							pt=pts.get(0);
							if(!map.containsKey(relatedBill1)){
								throw new BusinessException("第"+(i+1)+"行订单号已导入");
							}
						}else{
							map.put(relatedBill1, relatedBill1);
							List<WarehouseArea> zones =  commonDao.findByQuery(" from WarehouseArea o where o.warehouse.id=:id  "
									+ "and o.supplier.code ='"+zone_code+"' and o.disabled=false and o.beReject=0",
									new String[] { "id"},new Object[] {WarehouseHolder.getWarehouse().getId()});
							if(zones.size()<=0){
							    throw new BusinessException("第"+(i+1)+"行"+zone_code);
							}
							pt=EntityFactory.getEntity(PickTicket.class);
							pt.setZone(zones.get(0));
							pt.setOrderDate(new Date());
							pt.setCompany(item.getCompany());
							pt.setCode(this.bussinessCodeManager.getCodeForYm("QT",3));
							pt.setWarehouse(WarehouseHolder.getWarehouse());
							pt.setStatus(ASNStatus.OPEN);
							pt.setRelatedBill1(relatedBill1);
							pt.setBillType(bt);
							pt.setDock(l); 
							pt.setUserTracking();
							commonDao.store(pt);
						}
						PickTicketDetail d=EntityFactory.getEntity(PickTicketDetail.class);
						d.setItem(item);
						d.setOrderQtyOfMasterUnit(Double.parseDouble(quantity));
						d.setOrderQuantity(Double.parseDouble(quantity));
						d.setPickTicket(pt);
						d.setZone(pt.getZone());
						Boolean xbc=Boolean.FALSE;
						if((pt.getZone()!=null)){
							if((pt.getZone().getCode().indexOf("-SL")>0)) {
								if(d.getZzkw()==null){
									throw new BusinessException(d.getItem().getCode()+"制造库位不能为空");
								}
							}
							
						}
						this.commonDao.store(d);
						double qty=lockInvDetail(d, pt.getZone(),d.getZzkw(),xbc);
						if(qty<d.getOrderQuantity()){
							throw new BusinessException(d.getItem().getCode()+"库存不足"+qty);
						}else{
							d.setAllocatedQuantity(d.getOrderQuantity());
							this.commonDao.store(d);
						}
						pt.setOrderQuantity(pt.getOrderQuantity()+Double.parseDouble(quantity));
						if(pt.getAllocatedQuantity()>0){
							if(pt.getRelatedBill2()==null){
								pt.setRelatedBill2(this.bussinessCodeManager.getCodeForYm("BH",3));
							}
						}
						this.commonDao.store(pt);
//						asnManager.addASNDetail(asn.getId(),ad);
					}else{
						throw new BusinessException("第"+(i+1)+"行货品代码不存在");
					}
				 }
			} catch (BiffException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
		public void importPickTicketKAMS(Long pickId,File file){
			Workbook workbook;
			try {
				workbook = Workbook.getWorkbook(file);
				Sheet sheet = workbook.getSheet(0);//得到excel第一页的内容
				if(sheet.getColumns()<3){
					throw new BusinessException("该模版列数不正确，不能小于3");
				}
				PickTicket pt=commonDao.load(PickTicket.class, pickId);
				if(pt==null){
						throw new BusinessException("先新建订单号");
				}
				 HashMap<String,String> map=new HashMap<String, String>();
				 List<Location> ls =  commonDao.findByQuery(" from Location o where o.warehouse.id=:id  and o.type ='SHIP' and o.disabled=false",
							new String[] { "id"},new Object[] {WarehouseHolder.getWarehouse().getId()});
				 List<BillType> bts =  commonDao.findByQuery(" from BillType o where o.code='QTCK'  and o.type ='SHIP'");
				 Location l =ls.get(0);
				 BillType bt=bts.get(0);
				 Long time=(new Date()).getTime();
				 for (int i = 1; i <sheet.getRows(); i++) {
					 System.out.println("======"+i);
					 //品番	品名	AC	加工内容	税别	数量	备注
				 	
					String item_code=sheet.getCell(0,i).getContents().trim();
//					String AC=sheet.getCell(2,i).getContents().trim();
//					String jg=sheet.getCell(3,i).getContents().trim();
					String sb=sheet.getCell(4,i).getContents().trim();
					String zzkw=sheet.getCell(5,i).getContents().trim();
					String quantity=sheet.getCell(6,i).getContents().trim();
					String des=sheet.getCell(7,i).getContents().trim();
					Location zz_loc=null;
					if(pt.getZone().getCode().indexOf("-SL")>0){
						List<Location> los=this.commonDao.findByQuery("from Location l where l.code='"+zzkw+"'");
						if(los.size()<=0||zzkw==null||zzkw.equals("")){
							throw new BusinessException("第"+(i+1)+"制造库位不存在");
						}
						zz_loc=los.get(0);
					}
					List<Item> items=this.commonDao.findByQuery("from Item i where i.code='"+item_code+"' and i.warehouse.id="+WarehouseHolder.getWarehouse().getId());
					if(items.size()>0){
						Item item=items.get(0);
						PickTicketDetail d=EntityFactory.getEntity(PickTicketDetail.class);
						d.setItem(item);
						d.setOrderQtyOfMasterUnit(Double.parseDouble(quantity));
						d.setOrderQuantity(Double.parseDouble(quantity));
						d.setPickTicket(pt);
						d.setZzkw(zz_loc);
//						d.setSpecs(AC);
//						d.setContent(jg);
						d.setBonded(sb);
						d.setInvStatus(des);
						this.commonDao.store(d);
						double qty=lockInvKAMS(d, pt.getZone(),zz_loc);
						if(qty<d.getOrderQuantity()){
							throw new BusinessException(d.getItem().getCode()+"库存不足"+qty);
						}else{
							d.setAllocatedQuantity(d.getOrderQuantity());
							this.commonDao.store(d);
						}
						pt.setOrderQuantity(pt.getOrderQuantity()+Double.parseDouble(quantity));
//						pt.setAllocatedQuantity(pt.getAllocatedQuantity()+d.getAllocatedQuantity());
						pt.setStatus(PickTicketStatus.OPEN);
						this.commonDao.store(pt);
//						asnManager.addASNDetail(asn.getId(),ad);
					}else{
						throw new BusinessException("第"+(i+1)+"行货品代码"+item_code+"不存在");
					}
				 }
			} catch (BiffException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
		public void importPickTicketKAMSCancle(Long pickId,File file){
			Workbook workbook;
			try {
				workbook = Workbook.getWorkbook(file);
				Sheet sheet = workbook.getSheet(0);//得到excel第一页的内容
				if(sheet.getColumns()<3){
					throw new BusinessException("该模版列数不正确，不能小于3");
				}
				PickTicket pt=commonDao.load(PickTicket.class, pickId);
				if(pt==null){
						throw new BusinessException("先新建订单号");
				}
				 HashMap<String,String> map=new HashMap<String, String>();
				 List<Location> ls =  commonDao.findByQuery(" from Location o where o.warehouse.id=:id  and o.type ='SHIP' and o.disabled=false",
							new String[] { "id"},new Object[] {WarehouseHolder.getWarehouse().getId()});
				 List<BillType> bts =  commonDao.findByQuery(" from BillType o where o.code='QTCK'  and o.type ='SHIP'");
				 Location l =ls.get(0);
				 BillType bt=bts.get(0);
				 Long time=(new Date()).getTime();
				 for (int i = 1; i <sheet.getRows(); i++) {
					 System.out.println("======"+i);
					 //品番	品名	AC	加工内容	税别	数量	备注
				 	
					String item_code=sheet.getCell(0,i).getContents().trim();
//					String AC=sheet.getCell(2,i).getContents().trim();
//					String jg=sheet.getCell(3,i).getContents().trim();
					String sb=sheet.getCell(4,i).getContents().trim();
					String zzkw=sheet.getCell(5,i).getContents().trim();
					String quantity=sheet.getCell(6,i).getContents().trim();
					String des=sheet.getCell(7,i).getContents().trim();
					Location zz_loc=null;
					if(pt.getZone().getCode().indexOf("-SL")>0){
						List<Location> los=this.commonDao.findByQuery("from Location l where l.code='"+zzkw+"'");
						if(los.size()<=0||zzkw==null||zzkw.equals("")){
							throw new BusinessException("第"+(i+1)+"制造库位不存在");
						}
						zz_loc=los.get(0);
					}
					List<Item> items=this.commonDao.findByQuery("from Item i where i.code='"+item_code+"' and i.warehouse.id="+WarehouseHolder.getWarehouse().getId());
					if(items.size()>0){
						Item item=items.get(0);
						String hql="from Inventory inv where inv.itemKey.item.id="+item.getId()
								+" and inv.zone.id="+ pt.getZone().getId()+ " and inv.itemKey.pinfan.bonded='"+sb+"' and inv.location.type!='SHIP' and inv.queuedQuantity>0";
						if(pt.getZone().getCode().indexOf("-SL")>0){
							if(zzkw!=null){
								hql+=" and inv.zzkw.id="+zz_loc.getId();
							}
						}
						List<Inventory> invs=this.commonDao.findByQuery(hql);
						if(invs.size()>0){
							Inventory inv=invs.get(0);
							if(inv.getQueuedQuantity()>=Double.parseDouble(quantity)){
								inv.setQueuedQuantity(inv.getQueuedQuantity()-Double.parseDouble(quantity));
								this.commonDao.store(inv);
							}else{
								System.out.println((i+1)+"===="+item_code+"占用库存不足");
							}
						}else{
							System.out.println((i+1)+"===="+item_code+"无占用库存");
						}
						
					}else{
						throw new BusinessException("第"+(i+1)+"行货品代码"+item_code+"不存在");
					}
				 }
			} catch (BiffException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		@Override
		public void appAllocate(List<Long> pickTicketIds) {
			allocateManager.pickAllocate(pickTicketIds);
		}
		
		@Override
		public void confirmShip(Long pickId, Map qtys) {
			Iterator it = qtys.entrySet().iterator();
			PickTicket pt=this.commonDao.load(PickTicket.class, pickId);
			if(pt.getStatus().equals(PickTicketStatus.SHIP_ALL)){
				throw new BusinessException(pt.getRelatedBill2()+"已出货");
			}
			//不同仓库扣减库存 VMI仓库放到外协待发货区，KAMS放到待发货区
			Location loc=this.commonDao.get(Location.class, 525l);
//			if(pt.getWarehouse().getCode().indexOf("VMI")>=0){
//				loc=this.commonDao.get(Location.class, 525l);
//			}else{
//				List<Location> locs=this.commonDao.findByQuery("from Location l where l.name='待发货区'");
//				if(locs.size()>1){
//					loc=locs.get(0);
//				}
//				loc=this.commonDao.get(Location.class, 525l);
//			}
			while (it.hasNext()) {
				Map.Entry entry = (Map.Entry) it.next();
				Long dId = (Long) entry.getKey();
				PickTicketDetail d = this.commonDao.get(PickTicketDetail.class, dId);
				List value = (List) entry.getValue();
				String qtystr = String.valueOf(value.get(0));
				if (qtystr != null ) {
					int qty=0;
					try {
						 qty=Integer.parseInt(qtystr);
					} catch (BusinessException e) {
						throw new BusinessException(d.getItem().getCode()+"备货数量格式错误");
					}
					 if(qty>d.getOrderQuantity()||qty<0){
						 throw new BusinessException(d.getItem().getCode()+"备货数量不能负数或大于计划数");
					 }
					 if(d.getOldRecord()){
						 continue;
//						 throw new BusinessException(d.getItem().getCode()+"已出库");
					 }
//					 List<WarehouseArea> was=this.commonDao.findByQuery("from WarehouseArea w where w.beReject=0 and  w.supplier.id="+d.getPickTicket().getCompany().getId());
					 if(qty==0){//数量为0的计算
						List<PlanPickTicketDetail> pptds=this.commonDao.findByQuery("from PlanPickTicketDetail d where d.psd.item.id="+d.getItem().getId()
								+" and d.psd.ddbh='"+d.getSOI()+"'");
						double shipQty=qty;
						List<Inventory> invs=this.commonDao.findByQuery("from Inventory inv where inv.itemKey.id="+d.getItemKey().getId()+" and inv.zone.id="+d.getZone().getId()
								+" and inv.location.id="+d.getLocation().getId() + " and (inv.status is null or inv.status='')");
						if(invs.size()>0){
							Inventory inv=invs.get(0);
							inv.setQueuedQuantity(inv.getQueuedQuantity()-d.getAllocatedQuantity());
//							inv.remove(0,0,0);
							this.commonDao.store(inv);
						}
						for(PlanPickTicketDetail pptd:pptds){
							if(qty>=pptd.getAllocatedQuantity()){
								pptd.setPickedQuantity(pptd.getAllocatedQuantity());
								pptd.setShipTime(new Date());
								pptd.setBePick(Boolean.TRUE);
								this.commonDao.store(pptd);
							}
						}
						d.setPickedQuantity(qty);
						d.setShipTime(new Date());
						d.setOldRecord(Boolean.TRUE);
						this.commonDao.store(d);
						if(pt.getRelatedBill3()==null){
							pt.setRelatedBill3(this.bussinessCodeManager.getCodeForYm("CK",3));
							pt.setShipDateEnd(new Date());
							this.commonDao.store(pt);
						}
						continue;
					 }
//					if(was.size()>0&&qty>0){
					 if(qty>0){
						List<Inventory> invs=this.commonDao.findByQuery("from Inventory inv where inv.itemKey.id="+d.getItemKey().getId()+" and inv.zone.id="+d.getZone().getId()
								+" and inv.location.id="+d.getLocation().getId() + " and (inv.status is null or inv.status='')");
						if(invs.size()>0){
							double kjQty=qty;
							double syqty=qty;
							for(Inventory inv:invs){
								if(syqty>0){
									ItemKey itemkey=inv.getItemKey();
									if(inv.getQueuedQuantity()>=kjQty){
										kjQty=kjQty;
									}else{
										kjQty=inv.getQueuedQuantity();
									}
									syqty=syqty-kjQty;
									String billCode=d.getPickTicket().getRelatedBill2()==null?d.getPickTicket().getCode():d.getPickTicket().getRelatedBill2();
									InventoryLog log = new InventoryLog(InventoryLogType.PICK_DOWN, -1, billCode, null, inv.getLocation(), null, itemkey, 
											new Date(), pt.getCode(), kjQty, null, null, d.getId(), null,inv.getZone());
									commonDao.store(log);
									inv.setQueuedQuantity(inv.getQueuedQuantity()-d.getAllocatedQuantity());
									inv.remove(kjQty,0,0);
									this.commonDao.store(inv);
									//增加库存
									Inventory inventoryNew =null;
									List<Inventory> news=this.commonDao.findByQuery("from Inventory inv where inv.itemKey.id="+itemkey.getId()+" "
											+ " and inv.location.id="+loc.getId());//+" and inv.SOI='"+billCode+"' ");
									if(news.size()>0){
										inventoryNew=news.get(0);
									}else{
										inventoryNew=EntityFactory.getEntity(Inventory.class);
										inventoryNew.setLocation(loc);
										inventoryNew.setItemKey(itemkey);
										inventoryNew.setStatus(inv.getStatus());
//										inventoryNew.setZone(loc.getZone());
//										inventoryNew.setZone(pt.getZone());
										inventoryNew.setZone(d.getZone());
//										inventoryNew.setSOI(billCode);
										itemkey.getInventories().add(inventoryNew);
										this.commonDao.store(inventoryNew);
									}
									inventoryNew.add(kjQty,0,0);
									this.commonDao.store(inventoryNew);
									InventoryLog log2 = new InventoryLog(InventoryLogType.PICK_IN, 1, billCode, null, loc, null, itemkey, 
									new Date(), pt.getCode(), kjQty, null, null, d.getId(), null,inventoryNew.getZone());
									commonDao.store(log2);
								}else{
									break;
								}
							}
							if(syqty>0){
								throw new BusinessException(d.getItem().getCode()+"库存数量不足");
							}
							d.setPickedQuantity(qty);
							d.setShippedQuantity(qty);
							d.setShipTime(new Date());
							d.setOldRecord(Boolean.TRUE);
							this.commonDao.store(d);
							List<PlanPickTicketDetail> pptds=this.commonDao.findByQuery("from PlanPickTicketDetail d where d.psd.item.id="+d.getItem().getId()+" "
									+ " and d.psd.ddbh='"+d.getSOI()+"' and d.pickTicket.id="+pt.getId() 
									+ " order by d.allocatedQuantity asc");
							double shipQty=qty;
							for(PlanPickTicketDetail pptd:pptds){
								if(pptd.getAllocatedQuantity()==0||shipQty==0){
									pptd.setBePick(Boolean.TRUE);
									pptd.setShipTime(new Date());
								}else if(shipQty>=pptd.getAllocatedQuantity()){
									pptd.setShipTime(new Date());
									pptd.setBePick(Boolean.TRUE);
									pptd.setPickedQuantity(pptd.getOrderQuantity());
									this.commonDao.store(pptd);
									shipQty=shipQty-pptd.getOrderQuantity();
								}else{
									throw new BusinessException(d.getItem().getCode()+"登记数量不满足现品票");
								}
								this.commonDao.store(pptd);
							}
							if(pt.getRelatedBill3()==null){
								pt.setRelatedBill3(this.bussinessCodeManager.getCodeForYm("CK",3));
								pt.setShipDateEnd(new Date());
							}
							pt.setPickedQuantity(pt.getPickedQuantity()+qty);
							this.commonDao.store(pt);
						}else{
							throw new BusinessException(d.getItem().getCode()+"库存数量0");
						}
					}else{
						throw new BusinessException(d.getItem().getCode()+"库存数量0");
					}
				} 
			}
			List<PickTicketDetail> ptds=this.commonDao.findByQuery("from PickTicketDetail d where d.pickTicket.id="+pickId);
			Boolean isShip=Boolean.TRUE;
			double pickQty=0;
			for(PickTicketDetail ptd:ptds){
				if(!ptd.isOldRecord()){
					isShip=Boolean.FALSE;
				}
				pickQty+=ptd.getPickedQuantity();
			}
			if(isShip){
				pt.setPickedQuantity(pickQty);
				pt.setStatus(PickTicketStatus.PICK_ALL);
				pt.setShipDateEnd(new Date());
			}
			this.commonDao.store(pt);
		}
		
		@Override
		public void confirmKAMSShip(Long pickId, Map qtys) {
			Iterator it = qtys.entrySet().iterator();
			PickTicket pt=this.commonDao.load(PickTicket.class, pickId);
			if(pt.getStatus().equals(PickTicketStatus.SHIP_ALL)){
				throw new BusinessException(pt.getRelatedBill2()+"已出货");
			}
			//不同仓库扣减库存 VMI仓库放到外协待发货区，KAMS放到待发货区
			Location loc=null;
			if(pt.getWarehouse().getCode().indexOf("VMI")>=0){
				loc=this.commonDao.get(Location.class, 525l);
			}else{
				List<Location> locs=this.commonDao.findByQuery("from Location l where l.name='待发货区'");
				if(locs.size()>1){
					loc=locs.get(0);
				}
				loc=this.commonDao.get(Location.class, 525l);
			}
			while (it.hasNext()) {
				Map.Entry entry = (Map.Entry) it.next();
				Long dId = (Long) entry.getKey();
				PickTicketDetail d = this.commonDao.get(PickTicketDetail.class, dId);
				List value = (List) entry.getValue();
				String qtystr = String.valueOf(value.get(0));
				if (qtystr != null ) {
					int qty=0;
					try {
						 qty=Integer.parseInt(qtystr);
					} catch (BusinessException e) {
						throw new BusinessException(d.getItem().getCode()+"备货数量格式错误");
					}
					 if(qty>d.getOrderQuantity()||qty<0){
						 throw new BusinessException(d.getItem().getCode()+"备货数量不能负数或大于计划数");
					 }
					 if(d.getOldRecord()){
						 continue;
//						 throw new BusinessException(d.getItem().getCode()+"已出库");
					 }
//					 List<WarehouseArea> was=this.commonDao.findByQuery("from WarehouseArea w where w.beReject=0 and  w.supplier.id="+d.getPickTicket().getCompany().getId());
					 if(qty==0){//数量为0的计算
						List<PlanPickTicketDetail> pptds=this.commonDao.findByQuery("from PlanPickTicketDetail d where d.psd.item.id="+d.getItem().getId()
								+" and d.psd.ddbh='"+d.getSOI()+"'");
						double shipQty=qty;
						List<Inventory> invs=this.commonDao.findByQuery("from Inventory inv where inv.itemKey.id="+d.getItemKey().getId()+" and inv.zone.id="+pt.getZone2().getId()
								+" and (inv.status is null or inv.status='')");
						if(invs.size()>0){
							Inventory inv=invs.get(0);
							inv.setQueuedQuantity(inv.getQueuedQuantity()-d.getAllocatedQuantity());
//							inv.remove(0,0,0);
							this.commonDao.store(inv);
						}
						for(PlanPickTicketDetail pptd:pptds){
							if(qty>=pptd.getAllocatedQuantity()){
								pptd.setPickedQuantity(pptd.getAllocatedQuantity());
								pptd.setShipTime(new Date());
								pptd.setBePick(Boolean.TRUE);
								this.commonDao.store(pptd);
							}
						}
						d.setPickedQuantity(qty);
						d.setShipTime(new Date());
						d.setOldRecord(Boolean.TRUE);
						this.commonDao.store(d);
						if(pt.getRelatedBill3()==null){
							pt.setRelatedBill3(this.bussinessCodeManager.getCodeForYm("CK",3));
							pt.setShipDateEnd(new Date());
							this.commonDao.store(pt);
						}
						continue;
					 }
					if(qty>0){
						List<Inventory> invs=this.commonDao.findByQuery("from Inventory inv where inv.itemKey.id="+d.getItemKey().getId()+" and inv.zone.id="+d.getZone().getId()
								 + " and (inv.status is null or inv.status='' and inv.SOI is null ) and inv.quantity>0");
						if(invs.size()>0){
							double kjQty=qty;
							double syqty=qty;
							for(Inventory inv:invs){
								if(syqty>0){
									ItemKey itemkey=inv.getItemKey();
									if(inv.getQueuedQuantity()>=kjQty){
										kjQty=kjQty;
									}else{
										kjQty=inv.getQueuedQuantity();
									}
									syqty=syqty-kjQty;
									String billCode=d.getPickTicket().getRelatedBill2()==null?d.getPickTicket().getCode():d.getPickTicket().getRelatedBill2();
									InventoryLog log = new InventoryLog(InventoryLogType.PICK_DOWN, -1, billCode, null, inv.getLocation(), null, itemkey, 
											new Date(), pt.getCode(), kjQty, null, null, d.getId(), null,inv.getZone());
									commonDao.store(log);
									inv.setQueuedQuantity(inv.getQueuedQuantity()-d.getAllocatedQuantity());
									inv.remove(kjQty,0,0);
									this.commonDao.store(inv);
									//增加库存
									Inventory inventoryNew =null;
									List<Inventory> news=this.commonDao.findByQuery("from Inventory inv where inv.itemKey.id="+itemkey.getId()+" and inv.quantity>0"
											+ " and inv.location.id="+loc.getId());//+" and inv.SOI='"+billCode+"'");
									if(news.size()>0){
										inventoryNew=news.get(0);
									}else{
										inventoryNew=EntityFactory.getEntity(Inventory.class);
										inventoryNew.setLocation(loc);
										inventoryNew.setItemKey(itemkey);
										inventoryNew.setStatus(inv.getStatus());
//										inventoryNew.setZone(loc.getZone());
										inventoryNew.setZone(pt.getZone());
										inventoryNew.setSOI("DFH");
										itemkey.getInventories().add(inventoryNew);
										this.commonDao.store(inventoryNew);
									}
									inventoryNew.add(kjQty,0,0);
									this.commonDao.store(inventoryNew);
									InventoryLog log2 = new InventoryLog(InventoryLogType.PICK_IN, 1, billCode, null, loc, null, itemkey, 
									new Date(), pt.getCode(), kjQty, null, null, d.getId(), null,inventoryNew.getZone());
									commonDao.store(log2);
								}else{
									break;
								}
							}
							if(syqty>0){
								throw new BusinessException(d.getItem().getCode()+"库存数量不足");
							}
							d.setPickedQuantity(qty);
							d.setShippedQuantity(qty);
							d.setShipTime(new Date());
							d.setOldRecord(Boolean.TRUE);
							this.commonDao.store(d);
							List<PlanPickTicketDetail> pptds=this.commonDao.findByQuery("from PlanPickTicketDetail d where d.psd.item.id="+d.getItem().getId()+" "
									+ " and d.psd.ddbh='"+d.getSOI()+"' and d.pickTicket.id="+pt.getId() 
									+ " order by d.allocatedQuantity asc");
							double shipQty=qty;
							for(PlanPickTicketDetail pptd:pptds){
								if(pptd.getAllocatedQuantity()==0||shipQty==0){
									pptd.setBePick(Boolean.TRUE);
									pptd.setShipTime(new Date());
								}else if(shipQty>=pptd.getAllocatedQuantity()){
									pptd.setShipTime(new Date());
									pptd.setBePick(Boolean.TRUE);
									pptd.setPickedQuantity(pptd.getOrderQuantity());
									this.commonDao.store(pptd);
									shipQty=shipQty-pptd.getOrderQuantity();
								}else{
									throw new BusinessException(d.getItem().getCode()+"登记数量不满足现品票");
								}
								this.commonDao.store(pptd);
							}
							if(pt.getRelatedBill3()==null){
								pt.setRelatedBill3(this.bussinessCodeManager.getCodeForYm("CK",3));
								pt.setShipDateEnd(new Date());
							}
							pt.setPickedQuantity(pt.getPickedQuantity()+qty);
							this.commonDao.store(pt);
						}else{
							throw new BusinessException(d.getItem().getCode()+"库存数量0");
						}
					}else{
						throw new BusinessException(d.getItem().getCode()+"库存数量0");
					}
				} 
			}
			List<PickTicketDetail> ptds=this.commonDao.findByQuery("from PickTicketDetail d where d.pickTicket.id="+pickId);
			Boolean isShip=Boolean.TRUE;
			double pickQty=0;
			double cds=0;
			for(PickTicketDetail ptd:ptds){
				if(!ptd.isOldRecord()){
					isShip=Boolean.FALSE;
				}
				pickQty+=ptd.getPickedQuantity();
			}
			if(isShip){
				pt.setPickedQuantity(pickQty);
				pt.setStatus(PickTicketStatus.PICK_ALL);
				pt.setShipDateEnd(new Date());
			}
			this.commonDao.store(pt);
		}
		
		@Override
		public void confirmPickKAMS(Long pickId, Map qtys) {
			Iterator it = qtys.entrySet().iterator();
			PickTicket pt=this.commonDao.load(PickTicket.class, pickId);
			if(pt.getStatus().equals(PickTicketStatus.SHIP_ALL)){
				throw new BusinessException(pt.getRelatedBill2()+"已出货");
			}
			//不同仓库扣减库存 VMI仓库放到外协待发货区，KAMS放到待发货区
			Location loc=null;
			List<Location> locs=this.commonDao.findByQuery("from Location l where l.name='待发货暂存区'");
			if(locs.size()>1){
				loc=locs.get(0);
			}else{
				loc=pt.getDock();
			}
			while (it.hasNext()) {
				Map.Entry entry = (Map.Entry) it.next();
				Long tId = (Long) entry.getKey();
				Task t = this.commonDao.get(Task.class, tId);
				ItemKey ik=t.getItemKey();
				Item item=ik.getItem();
				PickTicketDetail ptd=t.getPickTicketDetail();
				List value = (List) entry.getValue();
				String qtystr = String.valueOf(value.get(0));
				if (qtystr != null ) {
					int qty=0;
					try {
						 qty=Integer.parseInt(qtystr);
					} catch (BusinessException e) {
						throw new BusinessException(item.getCode()+"备货数量格式错误");
					}
					 if(qty>ptd.getOrderQuantity()||qty<0){
						 throw new BusinessException(item.getCode()+"备货数量不能负数或大于计划数");
					 }
					 if(t.getBeBh()){
						 continue;
					 }
					 List<Inventory> invs=this.commonDao.findByQuery("from Inventory inv where inv.itemKey.id="+ik.getId()+" and inv.zone.id="+ptd.getZone2().getId()
								+" and (inv.status is null or inv.status='')");
					 t.setBhQuantityMU(qty);
					 t.setBeBh(Boolean.TRUE);
					 this.commonDao.store(t);
					 if(pt.getRelatedBill3()==null){
						pt.setRelatedBill3(this.bussinessCodeManager.getCodeForYm("CK",3));
						pt.setShipDateEnd(new Date());
						this.commonDao.store(pt);
					}
					 if(qty==0){//数量为0的计算
						double shipQty=qty;
						if(invs.size()>0){
							Inventory inv=invs.get(0);
							inv.setQueuedQuantity(inv.getQueuedQuantity()-t.getPlanQuantityMU());
//							inv.remove(0,0,0);
							this.commonDao.store(inv);
						}
						ptd.setShipTime(new Date());
						ptd.setAllocatedQuantity(ptd.getAllocatedQuantity()-t.getPlanQuantity());
						this.commonDao.store(ptd);
						t.setPlanQuantity(0);
						t.setPlanQuantityMU(0);
						this.commonDao.store(t);
						continue;
					 } else if(qty>0){
						if(invs.size()>0){
							double kjQty=qty;
							double syqty=qty;
							for(Inventory inv:invs){
								if(syqty>0){
									if(inv.getQueuedQuantity()>=kjQty){
										kjQty=kjQty;
									}else{
										kjQty=inv.getQueuedQuantity();
									}
									syqty=syqty-kjQty;
									String billCode=pt.getCode();
									Location loc1=ik.getPinfan().getLocation();
									Location loc2=pt.getDock();
									InventoryLog log = new InventoryLog(InventoryLogType.PICK_DOWN, -1, billCode, null, loc1, null, ik, 
											new Date(), pt.getCode(), kjQty, null, null, ptd.getId(), null,inv.getZone());
									commonDao.store(log);
									inv.setQueuedQuantity(inv.getQueuedQuantity()-kjQty);
									inv.remove(kjQty,0,0);
									this.commonDao.store(inv);
									//增加库存
									Inventory inventoryNew =null;
									List<Inventory> news=this.commonDao.findByQuery("from Inventory inv where inv.itemKey.id="+ik.getId()+" "
											+ " and inv.location.id="+loc2.getId());//+" and inv.SOI='"+billCode+"'");
									if(news.size()>0){
										inventoryNew=news.get(0);
									}else{
										inventoryNew=EntityFactory.getEntity(Inventory.class);
										inventoryNew.setLocation(loc);
										inventoryNew.setItemKey(ik);
										inventoryNew.setStatus(inv.getStatus());
//										inventoryNew.setZone(loc.getZone());
										inventoryNew.setZone(pt.getZone2());
										inventoryNew.setSOI("DFH");
										ik.getInventories().add(inventoryNew);
										this.commonDao.store(inventoryNew);
									}
									inventoryNew.add(kjQty,0,0);
									this.commonDao.store(inventoryNew);
									InventoryLog log2 = new InventoryLog(InventoryLogType.PICK_IN, 1, billCode, null, loc2, null, ik, 
									new Date(), pt.getCode(), kjQty, null, null, ptd.getId(), null,inventoryNew.getZone());
									commonDao.store(log2);
								}else{
									break;
								}
							}
							if(syqty>0){
								throw new BusinessException(item.getCode()+"库存数量不足");
							}
							ptd.setPickedQuantity(ptd.getPickedQuantity()+qty);
							this.commonDao.store(ptd);
						}else{
							throw new BusinessException(item.getCode()+"库存数量0");
						}
					}else{
						throw new BusinessException(item.getCode()+"库存数量0");
					}
				} 
			}
			List<Task> ts=this.commonDao.findByQuery("from Task t where t.pickTicketDetail.pickTicket.id="+pickId);
			Boolean isShip=Boolean.TRUE;
			double pickQty=0;
			for(Task task:ts){
				if(!task.getBeBh()){
					isShip=Boolean.FALSE;
				}
				pickQty+=task.getBhQuantityMU();
			}
			if(isShip){
				pt.setPickedQuantity(pickQty);
				pt.setStatus(PickTicketStatus.PICK_ALL);
				pt.setShipDateEnd(new Date());
			}
			this.commonDao.store(pt);
		}
		
		
		
		@Override
		public void confirmShip(Long pickId) {
			System.out.println("VMI....");
			PickTicket pt=this.commonDao.get(PickTicket.class, pickId);
			//不同仓库扣减库存 VMI仓库放到外协待发货区，KAMS放到待发货区
			Location loc=null;
			if(pt.getWarehouse().getCode().indexOf("VMI")>=0){
				loc=this.commonDao.get(Location.class, 525l);
			}else{
				List<Location> locs=this.commonDao.findByQuery("from Location l where l.name='待发货区'");
				if(locs.size()>1){
					loc=locs.get(0);
				}
				loc=this.commonDao.get(Location.class, 525l);
			}
			if(pt.getStatus().equals(PickTicketStatus.PICK_ALL)){
				pt.setShipDate(new Date());
				pt.setStatus(PickTicketStatus.SHIP_ALL);
				pt.setShippedQuantity(pt.getPickedQuantity());
				this.commonDao.store(pt);
				//扣库存
				String billCode=pt.getRelatedBill2()==null?pt.getCode():pt.getRelatedBill2();
				List<Inventory> news=this.commonDao.findByQuery("from Inventory inv where  inv.location.id="+loc.getId());
//						" and inv.SOI='"+billCode+ "'");
				for(Inventory inv:news){
					InventoryLog log2 = new InventoryLog(InventoryLogType.SHIPPING, -1, billCode, null, loc, null, inv.getItemKey(), 
							new Date(), pt.getCode(), inv.getQuantity(), null, null, inv.getId(), null,inv.getZone());
					commonDao.store(log2);
					this.commonDao.delete(inv);
				}
			}
			List<PickTicketDetail> pds=this.commonDao.findByQuery("from PickTicketDetail d where d.pickTicket.id="+pt.getId());
			for(PickTicketDetail pd:pds){
				pd.setShippedQuantity(pd.getPickedQuantity());
				this.commonDao.store(pd);
			}
			List<PlanPickTicketDetail> ppds=this.commonDao.findByQuery("from PlanPickTicketDetail d where d.pickTicket.id="+pt.getId());
			for(PlanPickTicketDetail d:ppds){
				PlanShipDetail psd=d.getPsd();
				if(d.getPickedQuantity()==0&&pt.getPickedQuantity()<pt.getOrderQuantity()){
					psd.setPptd(null);
					psd.setPtd(null);
					this.commonDao.store(psd);
				}
				d.setShippedQuantity(d.getPickedQuantity());
				d.setBeShip(Boolean.TRUE);
				this.commonDao.store(d);
			}
		}
		
		@Override
		public void confirmKAMSShip(Long pickId) {
			PickTicket pt=this.commonDao.get(PickTicket.class, pickId);
			Location loc=this.commonDao.get(Location.class, 525l);
			if(pt.getStatus().equals(PickTicketStatus.PICK_ALL)){
				pt.setShipDate(new Date());
				pt.setStatus(PickTicketStatus.SHIP_ALL);
				pt.setShippedQuantity(pt.getPickedQuantity());
				this.commonDao.store(pt);
				
			}
			List<PickTicketDetail> pds=this.commonDao.findByQuery("from PickTicketDetail d where d.pickTicket.id="+pt.getId());
			for(PickTicketDetail pd:pds){
				pd.setShippedQuantity(pd.getPickedQuantity());
				this.commonDao.store(pd);
				//扣库存
				String billCode=pt.getRelatedBill2()==null?pt.getCode():pt.getRelatedBill2();
				List<Inventory> news=this.commonDao.findByQuery("from Inventory inv where  inv.itemKey.id="+pd.getItemKey().getId()+" and inv.location.id="+loc.getId());
//						" and inv.SOI='"+billCode+ " and inv.status is null");
				for(Inventory inv:news){
					InventoryLog log2 = new InventoryLog(InventoryLogType.SHIPPING, -1, billCode, null, loc, null, inv.getItemKey(), 
							new Date(), pt.getCode(), inv.getQuantity(), null, null, inv.getId(), null,inv.getZone());
					commonDao.store(log2);
					this.commonDao.delete(inv);
				}
			}
			List<PlanPickTicketDetail> ppds=this.commonDao.findByQuery("from PlanPickTicketDetail d where d.pickTicket.id="+pt.getId());
			for(PlanPickTicketDetail d:ppds){
				PlanShipDetail psd=d.getPsd();
				if(d.getPickedQuantity()==0&&pt.getPickedQuantity()<pt.getOrderQuantity()){
					psd.setPptd(null);
					psd.setPtd(null);
					this.commonDao.store(psd);
				}
				d.setShippedQuantity(d.getPickedQuantity());
				d.setBeShip(Boolean.TRUE);
				this.commonDao.store(d);
			}
		}

		@Override
		public void confirmKAMSShipQT(Long pickId) {
			PickTicket pt=this.commonDao.get(PickTicket.class, pickId);
			if(pt.getStatus().equals(PickTicketStatus.PICK_ALL)){
				pt.setShipDate(new Date());
				pt.setStatus(PickTicketStatus.SHIP_ALL);
				pt.setShippedQuantity(pt.getPickedQuantity());
				this.commonDao.store(pt);
			}
			List<PickTicketDetail> pds=this.commonDao.findByQuery("from PickTicketDetail d where d.pickTicket.id="+pt.getId());
			for(PickTicketDetail pd:pds){
				if(pd.getPickedQuantity()==0) {
				//扣库存
				List<Inventory> news=this.commonDao.findByQuery("from Inventory inv where  inv.itemKey.id="+pd.getItemKey().getId()+
						" and inv.zone.id="+pd.getZone().getId()+ "");
				if(news.size()>0) {
				for(Inventory inv:news){
						inv.setQueuedQuantity(inv.getQueuedQuantity()-pd.getAllocatedQuantity());
						inv.setQtyOfMasterPack(inv.getQtyOfMasterPack()-pd.getAllocatedQuantity());
						inv.setQuantity(inv.getQtyOfMasterPack());
					InventoryLog log2 = new InventoryLog(InventoryLogType.SHIPPING_ADJUST, -1, pt.getCode(), null, inv.getLocation(), null, inv.getItemKey(), 
							new Date(), pt.getCode(), pd.getAllocatedQuantity(), null, null, inv.getId(), pd.getInvStatus(),inv.getZone());
					commonDao.store(log2);
					
					this.commonDao.store(inv);
				}
				}else {
					continue;
				}
				pd.setAllocatedQuantity(pd.getOrderQuantity());
				pd.setPickedQuantity(pd.getAllocatedQuantity());
				pd.setShippedQuantity(pd.getPickedQuantity());
//				pt.setAllocatedQuantity(pt.getAllocatedQuantity()+pd.getOrderQuantity());
				pt.setPickedQuantity(pt.getPickedQuantity()+pd.getAllocatedQuantity());
				pt.setShippedQuantity(pt.getShippedQuantity()+pd.getPickedQuantity());
				pd.setAllocateTime(new Date());
				pd.setShipTime(new Date());
				this.commonDao.store(pd);
				pt.setShipDate(new Date());
				pt.setStatus(PickTicketStatus.SHIP_ALL);
				commonDao.store(pt);
				}
			}
		}
		
	@Override
	public void cancelPick(Long pickId) {
		PickTicket pt=this.commonDao.get(PickTicket.class, pickId);
//		if(pt.getStatus().equals(PickTicketStatus.PICK_ALL)){
//			pt.setShipDateEnd(null);
//			pt.setStatus(PickTicketStatus.ALLOCATE);
//			pt.setPickedQuantity(0);
//		}
		List<PickTicketDetail> pds=this.commonDao.findByQuery("from PickTicketDetail d where d.pickTicket.id="+pt.getId());
		if(!pt.getWarehouse().getId().equals(new Long("1"))){
			for(PickTicketDetail pd:pds){
				if(pd.getPickedQuantity()>0){
					//库存退回
//					String hql="from Inventory inv where inv.itemKey.id="+pd.getItemKey().getId() + " and (inv.status is null or inv.status='')";
//						hql+=" and inv.SOI='"+pt.getRelatedBill2()+"'";
					String hql="from Inventory inv where inv.itemKey.id="+pd.getItemKey().getId() + " and inv.zone.id="+pt.getZone().getId();
					hql+=" and inv.location.id=525";
//					hql+=" and inv.SOI='"+pt.getRelatedBill2()+"'";
					List<Inventory> invs=this.commonDao.findByQuery(hql);
					for(Inventory inv:invs){
						//增加库存
						Inventory inventoryNew =null;
						Location loc=pd.getLocation();
						List<Inventory> news=this.commonDao.findByQuery("from Inventory inv where inv.itemKey.id="+inv.getItemKey().getId()+" "
								+ " and inv.location.id="+pd.getLocation().getId()+" and inv.zone.id="+pd.getZone().getId() );
//								+ "  and (inv.status is null or inv.status='')");
						if(news.size()>0){
							inventoryNew=news.get(0);
						}else{
							inventoryNew=EntityFactory.getEntity(Inventory.class);
							inventoryNew.setLocation(loc);
							inventoryNew.setItemKey(pd.getItemKey());
							inventoryNew.setStatus(inv.getStatus());
							inventoryNew.setZone(pd.getZone());
							inventoryNew.setSOI(null);
							pd.getItemKey().getInventories().add(inventoryNew);
							this.commonDao.store(inventoryNew);
						}
						inventoryNew.add(pd.getPickedQuantity(),0,0);
						inventoryNew.setQueuedQuantity(inventoryNew.getQueuedQuantity()+pd.getPickedQuantity());
						this.commonDao.store(inventoryNew);
						InventoryLog log2 = new InventoryLog(InventoryLogType.PICK_UP, 1, inv.getSOI(), null, loc, null, pd.getItemKey(), 
						new Date(), pt.getCode(), inv.getQuantity(), null, null, inv.getId(), null,inventoryNew.getZone());
						commonDao.store(log2);
						//减少库存
						InventoryLog log = new InventoryLog(InventoryLogType.PICK_CANCEL, -1, inv.getSOI(), null, inv.getLocation(), null, pd.getItemKey(), 
								new Date(), pt.getCode(), inv.getQuantity(), null, null, inv.getId(), null,inv.getZone());
						commonDao.store(log);
						inv.setQuantity(inv.getQuantity()-pd.getPickedQuantity());
						inv.setQtyOfMasterPack(inv.getQuantity());
//						inv.remove(inv.getQuantity(),0,0);
						this.commonDao.store(inv);
					}
					pd.setAllocatedQuantity(pd.getPickedQuantity());
					pd.setPickedQuantity(0);
					pd.setOldRecord(Boolean.FALSE);
					this.commonDao.store(pd);
				}
			}
			pt.setShipDateEnd(null);
			pt.setStatus(PickTicketStatus.ALLOCATE);
			pt.setPickedQuantity(0);
		}else{
			for(PickTicketDetail pd:pds){
				List<Task> ts=this.commonDao.findByQuery("from Task t where t.pickTicketDetail.id="+pd.getId());
				for(Task t:ts){
					double qty=t.getBhQuantityMU();
					if(qty>0){
						String hql="from Inventory inv where inv.itemKey.id="+pd.getItemKey().getId() ;
						hql+="and inv.SOI='"+pt.getCode()+"' and inv.zone.id="+pt.getZone2().getId()+" and inv.location.id="+t.getDstLoc().getId();
						List<Inventory> invs=this.commonDao.findByQuery(hql);
						if(invs.size()<=0){
							throw new BusinessException(pd.getItem().getCode()+"找不到对应库存");
						}
						for(Inventory inv:invs){
							//增加库存
							Inventory inventoryNew =null;
							Location loc=t.getSrcLoc();
							List<Inventory> news=this.commonDao.findByQuery("from Inventory inv where inv.itemKey.id="+inv.getItemKey().getId()+" "
//									+ " and inv.location.id="+t.getSrcLoc().getId()
									+ "  and (inv.status is null or inv.status='')"
									+" and inv.zone.id="+pd.getZone2().getId() 
									+ " and inv.SOI is null"
									);
							if(news.size()>0){
								inventoryNew=news.get(0);
							}else{
								inventoryNew=EntityFactory.getEntity(Inventory.class);
								inventoryNew.setLocation(loc);
								inventoryNew.setItemKey(pd.getItemKey());
								inventoryNew.setStatus(inv.getStatus());
								inventoryNew.setZone(pd.getZone());
								inventoryNew.setSOI(null);
								pd.getItemKey().getInventories().add(inventoryNew);
								this.commonDao.store(inventoryNew);
							}
							inventoryNew.add(qty,0,0);
							inventoryNew.setQueuedQuantity(inventoryNew.getQueuedQuantity()+qty);
							this.commonDao.store(inventoryNew);
							InventoryLog log2 = new InventoryLog(InventoryLogType.PICK_UP, 1, inv.getSOI(), null, loc, null, pd.getItemKey(), 
							new Date(), pt.getCode(), inv.getQuantity(), null, null, inv.getId(), null,inventoryNew.getZone());
							commonDao.store(log2);
							//减少库存
							InventoryLog log = new InventoryLog(InventoryLogType.PICK_CANCEL, -1, inv.getSOI(), null, t.getDstLoc(), null, pd.getItemKey(), 
									new Date(), pt.getCode(), inv.getQuantity(), null, null, inv.getId(), null,inv.getZone());
							commonDao.store(log);
							inv.setQuantity(inv.getQuantity()-qty);
							inv.setQtyOfMasterPack(inv.getQuantity());
	//						inv.remove(inv.getQuantity(),0,0);
							this.commonDao.store(inv);
						}
					}
//					t.setMovedQuantityMU(0);
//					this.commonDao.store(t);
//					List<TaskLog> logs =this.commonDao.findByQuery("from TaskLog l where l.task.id="+t.getId());
//					this.commonDao.deleteAll(logs);
//					pd.setPickedQuantity(pd.getPickedQuantity()-qty);
//					pd.setOldRecord(Boolean.FALSE);
//					this.commonDao.store(pd);
				}
			}
		}
		List<PlanPickTicketDetail> ppds=this.commonDao.findByQuery("from PlanPickTicketDetail d where d.pickTicket.id="+pt.getId());
		for(PlanPickTicketDetail d:ppds){
			PlanShipDetail psd=d.getPsd();
			d.setAllocatedQuantity(d.getPickedQuantity());
			d.setPickedQuantity(0);
			d.setBePick(Boolean.FALSE);
			this.commonDao.store(d);
		}
		
	}
	@Override
	public void cancelShip(Long pickId) {
		PickTicket pt=this.commonDao.get(PickTicket.class, pickId);
		if(!pt.getWarehouse().getId().equals(new Long("1"))){
			cancelShipVMI(pickId);
		}else{
			cancelShipKams(pickId);
		}
	}
	
	public void cancelShipKams(Long pickId) {
		System.out.println("KAMS....");
		PickTicket pt=this.commonDao.get(PickTicket.class, pickId);
		String operator=UserHolder.getUser().getName();
		if(pt.getStatus().equals(PickTicketStatus.SHIP_ALL)){
			pt.setShipDateEnd(null);
			pt.setShipDate(null);
			pt.setStatus(PickTicketStatus.OPEN);
			pt.setAllocatedQuantity(0);
			pt.setPickedQuantity(0);
			pt.setRelatedBill2(null);
			pt.setShippedQuantity(0);
		}
		List<PickTicketDetail> pds=this.commonDao.findByQuery("from PickTicketDetail d where d.pickTicket.id="+pt.getId());
		for(PickTicketDetail pd:pds){
			List<Task> ts=this.commonDao.findByQuery("from Task t where t.pickTicketDetail.id="+pd.getId());
			for(Task t:ts){
				List<TaskLog> logs=this.commonDao.findByQuery("from TaskLog t where t.task.id="+t.getId());
				for(TaskLog l:logs){
					List<PrintXppRecord> rs=this.commonDao.findByQuery("from PrintXppRecord r where r.taskLog.id="+l.getId());
					for(PrintXppRecord r:rs){
						r.setTaskLog(null);
						r.setBhBy(null);
						r.setBhDate(null);
						r.setFhBy(null);
						r.setFhDate(null);
						this.commonDao.store(r);
					}
					List<RkEwmRecord> rrs=this.commonDao.findByQuery("from RkEwmRecord r where r.taskLog.id="+l.getId());
					for(RkEwmRecord r:rrs){
						r.setTaskLog(null);
						r.setBhBy(null);
						r.setBhDate(null);
						r.setFhBy(null);
						r.setFhDate(null);
						this.commonDao.store(r);
					}
					this.commonDao.delete(l);
				}
				//增加库存
				Inventory inv =findInventory(t.getItemKey(), t.getZone(), t.getSrcLoc(), t.getBillCode(), SysCode.CK_FY2);
				if(inv==null){
					inv=EntityFactory.getEntity(Inventory.class);
					inv.setLocation(t.getSrcLoc());
					inv.setItemKey(t.getItemKey());
					inv.setZone(pd.getZone2());
					pd.getItemKey().getInventories().add(inv);
					this.commonDao.store(inv);
				}
				double qty=inv.getQtyOfMasterPack();
				inv.add(t.getMovedQuantityMU(),0,0);
				this.commonDao.store(inv);
				InventoryLog log2 =inventoryManager.addInventoryLog(InventoryLogType.SHIP_CANCEL, 1, inv.getZone(), inv.getLocation(), pt.getCode(),
						inv.getItemKey(), t.getPlanQuantity(), null, UserHolder.getUser().getName(), 
						 inv.getId(), (int)qty+"变为"+(int)inv.getQtyOfMasterPack(), pt.getDescription(), null, null, pd.getZzkw());
				if(pt.getBillType().getName().equals("其他出库单")){
					inv.setQueuedQuantity(inv.getQueuedQuantity()+t.getPlanQuantity());
					this.commonDao.store(inv);
					t.setMovedQuantityMU(0);
					this.commonDao.store(t);
				}else{
					pd.setAllocatedQuantity(0);
					this.commonDao.delete(t);
				}
			}
			pd.setPickedQuantity(0);
			pd.setShippedQuantity(0);
			pd.setOldRecord(Boolean.FALSE);
			this.commonDao.store(pd);
		}
		Refresh(pt.getId());
	}
	
	public void cancelShipVMI(Long pickId) {
		System.out.println("VMI....");
		PickTicket pt=this.commonDao.get(PickTicket.class, pickId);
		String soi=pt.getRelatedBill2();
		if(pt.getStatus().equals(PickTicketStatus.SHIP_ALL)){
			pt.setShipDateEnd(null);
			pt.setShipDate(null);
			pt.setStatus(PickTicketStatus.OPEN);
			pt.setPickedQuantity(0);
			pt.setRelatedBill2(null);
			pt.setShippedQuantity(0);
		}
		List<PickTicketDetail> pds=this.commonDao.findByQuery("from PickTicketDetail d where d.pickTicket.id="+pt.getId());
		for(PickTicketDetail pd:pds){
			if(pd.getPickedQuantity()>0){
					//增加库存
					Inventory inventoryNew =null;
					Location loc=pd.getLocation();
					List<Inventory> news=this.commonDao.findByQuery("from Inventory inv where inv.itemKey.id="+pd.getItemKey().getId()+" "
							+" and inv.zone.id="+pd.getZone().getId());
					if(news.size()>0){
						inventoryNew=news.get(0);
					}else{
						inventoryNew=EntityFactory.getEntity(Inventory.class);
						inventoryNew.setLocation(pd.getItem().getLocation());
						inventoryNew.setItemKey(pd.getItemKey());
						inventoryNew.setZone(pd.getZone());
						inventoryNew.setSOI(null);
						pd.getItemKey().getInventories().add(inventoryNew);
						this.commonDao.store(inventoryNew);
					}
					inventoryNew.add(pd.getPickedQuantity(),0,0);
					inventoryNew.setQueuedQuantity(inventoryNew.getQueuedQuantity()+pd.getShippedQuantity());
					this.commonDao.store(inventoryNew);
					InventoryLog log2 = new InventoryLog(InventoryLogType.SHIP_CANCEL, 1, soi, null, loc, null, pd.getItemKey(), 
					new Date(), pt.getCode(), pd.getShippedQuantity(), null, null, pd.getId(), null,inventoryNew.getZone());
					commonDao.store(log2);
			}
//			pd.setAllocatedQuantity(0);
			pd.setPickedQuantity(0);
			pd.setShippedQuantity(0);
			pd.setOldRecord(Boolean.FALSE);
			this.commonDao.store(pd);
		}
		List<PlanPickTicketDetail> ppds=this.commonDao.findByQuery("from PlanPickTicketDetail d where d.pickTicket.id="+pt.getId());
		for(PlanPickTicketDetail d:ppds){
			PlanShipDetail psd=d.getPsd();
			d.setAllocatedQuantity(d.getPickedQuantity());
			d.setPickedQuantity(0);
			d.setShippedQuantity(0);
			d.setBePick(Boolean.FALSE);
			d.setBeShip(Boolean.FALSE);
			this.commonDao.store(d);
		}
		if(ppds.size()>0){
			for(PickTicketDetail pd:pds){
				this.commonDao.delete(pd);
			}
		}
		Refresh(pt.getId());
		
		
	}
	public void appPlanPickTicket(List<Long> pickTicketIds) {
		for(Long id :pickTicketIds) {
			PlanAssembly p=commonDao.load(PlanAssembly.class, id);
			String jz_hql="select p.procedure from ProduceMonthPlan p where p.planAssembly.id="+id+
					" group by p.procedure ";
			List<String> jzs=commonDao.findByQuery(jz_hql);
			for(String jz:jzs){
				String hql="select p.bigItem.id,p.outType,sum(p.monthQuantity) from ProduceMonthPlan p where p.planAssembly.id="+id+" and p.procedure='"+jz+"'"
						+" group by p.bigItem.id,p.outType ";
				List<Object[]> list=commonDao.findByQuery(hql);
				PlanPickTicket pt =EntityFactory.getEntity(PlanPickTicket.class);
				pt.setWarehouse(WarehouseHolder.getWarehouse());
				pt.setStatus(PickTicketStatus.OPEN);
				pt.setOrderDate(new Date());
				pt.setWarehouse(WarehouseHolder.getWarehouse());
				pt.setStatus(PickTicketStatus.OPEN);
				pt.setCode(this.bussinessCodeManager.getCodeForYm("ZS",3));
				pt.setCompany(commonDao.load(Structure.class, 1002L));
				pt.setPackType1(p.getId()+"");
				List<BillType> list2=commonDao.findByQuery(" from BillType b where b.code='CKD单点' ");
				BillType billType=null;
				if(list2.size()>0) {
					billType=list2.get(0);
					pt.setBillType(billType);
				}else {
					pt.setBillType(commonDao.load(BillType.class, 6L));
				}
				pt.setRelatedBill1("月出库单");
				pt.setZone(commonDao.load(WarehouseArea.class, 37L));
				pt.setRelatedBill3(jz);
				commonDao.store(pt);
				for(Object[] obj:list){
					Long bigId=Long.parseLong(obj[0].toString());
					String outType=obj[1].toString();
					double qty=(Double) obj[2];
					BigItem bi=commonDao.get(BigItem.class, bigId);
					PlanPickDetail ptd =EntityFactory.getEntity(PlanPickDetail.class);
					ptd.setProcedure(bi.getModelType());
					ptd.setBigItem(bi);
					ptd.setPlanPickTicket(pt);
					ptd.setInvStatus(outType);
					ptd.setCode(bi.getCode());
					ptd.setName(bi.getName());
					ptd.setModelName(bi.getName());
					ptd.setCountry(bi.getStr1());
					ptd.setDescription("月度计划"+p.getMonthDate());
					ptd.setOrderQuantity(qty);
					this.commonDao.store(ptd);
					pt.setOrderQuantity(pt.getOrderQuantity()+ptd.getOrderQuantity());
					this.commonDao.store(pt);
				}
			}
			p.setStrExtend2("已生成");
			p.setCreateDate(new Date());
//			p.setPlanNo(pt.getCode());
			this.commonDao.store(p);
		}
	}
	
	public double appQty(ProduceMonthPlan pm) {
		double qty=0;
		if(pm.getQuantity1()>0) {
			qty+=pm.getQuantity1();
		}
		if(pm.getQuantity2()>0) {
			qty+=pm.getQuantity1();
		}
		if(pm.getQuantity3()>0) {
			qty+=pm.getQuantity1();
		}
		if(pm.getQuantity4()>0) {
			qty+=pm.getQuantity1();
		}
		if(pm.getQuantity5()>0) {
			qty+=pm.getQuantity1();
		}
		if(pm.getQuantity6()>0) {
			qty+=pm.getQuantity1();
		}
		if(pm.getQuantity7()>0) {
			qty+=pm.getQuantity1();
		}
		if(pm.getQuantity8()>0) {
			qty+=pm.getQuantity1();
		}
		if(pm.getQuantity9()>0) {
			qty+=pm.getQuantity1();
		}
		if(pm.getQuantity10()>0) {
			qty+=pm.getQuantity1();
		}
		if(pm.getQuantity11()>0) {
			qty+=pm.getQuantity1();
		}
		if(pm.getQuantity12()>0) {
			qty+=pm.getQuantity1();
		}
		if(pm.getQuantity13()>0) {
			qty+=pm.getQuantity1();
		}
		if(pm.getQuantity14()>0) {
			qty+=pm.getQuantity1();
		}
		if(pm.getQuantity15()>0) {
			qty+=pm.getQuantity1();
		}
		if(pm.getQuantity16()>0) {
			qty+=pm.getQuantity1();
		}
		if(pm.getQuantity17()>0) {
			qty+=pm.getQuantity1();
		}
		if(pm.getQuantity18()>0) {
			qty+=pm.getQuantity1();
		}
		if(pm.getQuantity19()>0) {
			qty+=pm.getQuantity1();
		}
		if(pm.getQuantity20()>0) {
			qty+=pm.getQuantity1();
		}
		if(pm.getQuantity21()>0) {
			qty+=pm.getQuantity1();
		}
		if(pm.getQuantity22()>0) {
			qty+=pm.getQuantity1();
		}
		if(pm.getQuantity23()>0) {
			qty+=pm.getQuantity1();
		}
		if(pm.getQuantity24()>0) {
			qty+=pm.getQuantity1();
		}
		if(pm.getQuantity25()>0) {
			qty+=pm.getQuantity1();
		}
		if(pm.getQuantity26()>0) {
			qty+=pm.getQuantity1();
		}
		if(pm.getQuantity27()>0) {
			qty+=pm.getQuantity1();
		}
		if(pm.getQuantity28()>0) {
			qty+=pm.getQuantity1();
		}
		if(pm.getQuantity29()>0) {
			qty+=pm.getQuantity1();
		}
		if(pm.getQuantity30()>0) {
			qty+=pm.getQuantity1();
		}
		if(pm.getQuantity31()>0) {
			qty+=pm.getQuantity1();
		}
		return qty;
	}
	
	public void storePlanPickTicket(PlanPickTicket pickTicket) {
		if (pickTicket.isNew()) {
			pickTicket.setWarehouse(WarehouseHolder.getWarehouse());
			pickTicket.setStatus(PickTicketStatus.OPEN);
			pickTicket.setCode(this.bussinessCodeManager.getCodeForYm("SC",3));
			if(pickTicket.getZone()!=null){
			pickTicket.setCompany(pickTicket.getZone().getSupplier());
			}
		}
			
			commonDao.store(pickTicket);
		
	}
	public void addPlanPick(Map params,List<Long>  id) {
		Set<Map.Entry<Long, List>> itor = params.entrySet();
		for (Map.Entry<Long, List> me : itor) {
			double unallocateQty=0;
			PlanPickDetail ppd = commonDao.load(PlanPickDetail.class, me.getKey());
			PlanPickTicket pa=commonDao.load(PlanPickTicket.class, ppd.getPlanPickTicket().getId());
			Double quantity = Double.parseDouble(me.getValue().get(0).toString());
			if(quantity <= 0){
				continue;
			}

			if(ppd.getAllocatedQuantity()>=ppd.getOrderQuantity()){
				throw new BusinessException("该计划已经出库完成！");
			}else {
				unallocateQty=ppd.getOrderQuantity()-ppd.getAllocatedQuantity();
			}
			
			
			if (quantity > unallocateQty) {
				quantity = unallocateQty;
			}
			unallocateQty -= quantity;
//			ppd.setAllocatedQuantity(ppd.getAllocatedQuantity()+quantity);
//			pa.setAllocatedQuantity(pa.getAllocatedQuantity()+quantity);
//			commonDao.store(pa);
//			commonDao.store(ppd);
			addPlanPick(quantity,ppd,pa,"课税");
			addPlanPick(quantity,ppd,pa,"保税");
			
		}
	}
	
	private void addPlanPick(Double quantity,PlanPickDetail ppd,PlanPickTicket pa,String bonded) {
		List<BomAccount> list1=commonDao.findByQuery(" from BomAccount b where b.bigItem.id="+ppd.getBigItem().getId()+" and b.bonded='"+bonded+"'");
		if(list1.size()>0) {
			PickTicket pt=EntityFactory.getEntity(PickTicket.class);
				pt.setWarehouse(WarehouseHolder.getWarehouse());
				pt.setStatus(PickTicketStatus.OPEN);
				pt.setPackType1(ppd.getBigItem().getModelType());
				pt.setCode(this.bussinessCodeManager.getCodeForYm("YBH",3));
				List<Location> locs=commonDao.findByQuery(" from Location b where b.type='SHIP' and b.warehouse.id="+WarehouseHolder.getWarehouse().getId());
				if(locs.size()>0) {
					pt.setDock(locs.get(0));
				}
					if(pt.getZone()!=null){
						pt.setCompany(pt.getZone().getSupplier());
					}
					if(pt.getCompany()==null) {
						pt.setCompany(commonDao.load(Structure.class, 1002L));
					}
					List<BillType> list2=commonDao.findByQuery(" from BillType b where b.code='预备货' ");
					BillType billType=null;
					if(list2.size()>0) {
						billType=list2.get(0);
						pt.setBillType(billType);
					}else {
						pt.setBillType(commonDao.load(BillType.class, 7L));
					}
					pt.setUserTracking();
					pt.setRelatedBill1(pa.getRelatedBill2());
					pt.setSequenceNo(pa.getId());
					commonDao.store(pt);
			for(BomAccount b:list1) {
				List<PickTicketDetail> list3=new ArrayList<PickTicketDetail>();
				PickTicketDetail ptd=null;
				if(!pt.isNew()) {
					list3=commonDao.findByQuery(" from PickTicketDetail p where p.item.id="+b.getItem().getId()+" and p.pickTicket.id="+pt.getId());
				}
				if(list3.size()>0) {
					ptd=list3.get(0);
					
				}else {
					ptd=EntityFactory.getEntity(PickTicketDetail.class);
				}
				ptd.setOrderQuantity(ptd.getOrderQuantity()+quantity*Integer.parseInt(b.getSingle()));
				ptd.setOrderQtyOfMasterUnit(ptd.getOrderQtyOfMasterUnit()+quantity*Integer.parseInt(b.getSingle()));
				pt.setOrderDate(new Date());
				pt.setOrderQuantity(pt.getOrderQuantity()+quantity*Integer.parseInt(b.getSingle()));
				pt.setCompany(b.getItem().getCompany());	
				ptd.setPickTicket(pt);
				ptd.setItem(b.getItem());
				ptd.setZone1(ppd.getZone1());
				ptd.setZone2(ppd.getZone2());
				ptd.setSingle(b.getSingle());
				commonDao.store(pt);
				commonDao.store(ptd);
			}
		}
	}
	
	
	
	
	
	public void addpick(Map params,List<Long>  id) {
		Set<Map.Entry<Long, List>> itor = params.entrySet();
		for (Map.Entry<Long, List> me : itor) {
			double unallocateQty=0;
			PlanPickDetail ppd = commonDao.load(PlanPickDetail.class, me.getKey());
			PlanPickTicket pa=commonDao.load(PlanPickTicket.class, ppd.getPlanPickTicket().getId());
			Double quantity = Double.parseDouble(me.getValue().get(0).toString());
			if(quantity <= 0){
				continue;
			}

			if(ppd.getAllocatedQuantity()>=ppd.getOrderQuantity()){
				throw new BusinessException("该计划已经出库完成！");
			}else {
				unallocateQty=ppd.getOrderQuantity()-ppd.getAllocatedQuantity();
			}
			
			
			if (quantity > unallocateQty) {
				quantity = unallocateQty;
			}
			unallocateQty -= quantity;
			ppd.setAllocatedQuantity(ppd.getAllocatedQuantity()+quantity);
			pa.setAllocatedQuantity(pa.getAllocatedQuantity()+quantity);
			commonDao.store(pa);
			commonDao.store(ppd);
			addpick(quantity,ppd,pa,"课税");
			addpick(quantity,ppd,pa,"保税");
			
		}
	}
	
	private void addpick(Double quantity,PlanPickDetail ppd,PlanPickTicket pa,String bonded) {
		List<BomAccount> list1=commonDao.findByQuery(" from BomAccount b where b.bigItem.id="+ppd.getBigItem().getId()+" and b.bonded='"+bonded+"'");
		if(list1.size()>0) {
			PickTicket pt=EntityFactory.getEntity(PickTicket.class);
				pt.setWarehouse(WarehouseHolder.getWarehouse());
				pt.setStatus(PickTicketStatus.OPEN);
				pt.setPackType1(ppd.getBigItem().getModelType());
				pt.setCode(this.bussinessCodeManager.getCodeForYm("BH",3));
				List<Location> locs=commonDao.findByQuery(" from Location b where b.type='SHIP' and b.warehouse.id="+WarehouseHolder.getWarehouse().getId());
				if(locs.size()>0) {
					pt.setDock(locs.get(0));
				}
					if(pt.getZone()!=null){
						pt.setCompany(pt.getZone().getSupplier());
					}
					if(pt.getCompany()==null) {
						pt.setCompany(commonDao.load(Structure.class, 1002L));
					}
					List<BillType> list2=commonDao.findByQuery(" from BillType b where b.code='CKD成套' ");
					BillType billType=null;
					if(list2.size()>0) {
						billType=list2.get(0);
						pt.setBillType(billType);
					}else {
						pt.setBillType(commonDao.load(BillType.class, 7L));
					}
					pt.setUserTracking();
					pt.setRelatedBill1(pa.getRelatedBill2());
					pt.setSequenceNo(pa.getId());
					commonDao.store(pt);
			for(BomAccount b:list1) {
				List<PickTicketDetail> list3=new ArrayList<PickTicketDetail>();
				PickTicketDetail ptd=null;
				if(!pt.isNew()) {
					list3=commonDao.findByQuery(" from PickTicketDetail p where p.item.id="+b.getItem().getId()+" and p.pickTicket.id="+pt.getId());
				}
				if(list3.size()>0) {
					ptd=list3.get(0);
					
				}else {
					ptd=EntityFactory.getEntity(PickTicketDetail.class);
				}
				ptd.setOrderQuantity(ptd.getOrderQuantity()+quantity*Integer.parseInt(b.getSingle()));
				ptd.setOrderQtyOfMasterUnit(ptd.getOrderQtyOfMasterUnit()+quantity*Integer.parseInt(b.getSingle()));
				pt.setOrderDate(new Date());
				pt.setOrderQuantity(pt.getOrderQuantity()+quantity*Integer.parseInt(b.getSingle()));
				pt.setCompany(b.getItem().getCompany());	
				ptd.setPickTicket(pt);
				ptd.setItem(b.getItem());
				ptd.setZone1(ppd.getZone1());
				ptd.setZone2(ppd.getZone2());
				ptd.setSingle(b.getSingle());
				commonDao.store(pt);
				commonDao.store(ptd);
			}
		}
	}
	PickTicket createPickTicket(String sb,PlanPickTicket ppt,String strExtend3){
		PickTicket pt=EntityFactory.getEntity(PickTicket.class);
		pt.setWarehouse(WarehouseHolder.getWarehouse());
		pt.setStatus(PickTicketStatus.OPEN);
		pt.setCode(this.bussinessCodeManager.getCodeForYm("BH",3));
		pt.setWaveCode(ppt.getCode());
		List<Location> locs=commonDao.findByQuery(" from Location b where b.type='SHIP' and b.warehouse.id="+WarehouseHolder.getWarehouse().getId());
		if(locs.size()>0) {
			pt.setDock(locs.get(0));
		}
		pt.setCompany(commonDao.load(Structure.class, 1002L));
		List<BillType> list2=commonDao.findByQuery(" from BillType b where b.code='CKD单点' ");
		BillType billType=null;
		if(list2.size()>0) {
			billType=list2.get(0);
			pt.setBillType(billType);
		}else {
			pt.setBillType(commonDao.load(BillType.class, 6L));
		}
		pt.setUserTracking();
		pt.setRelatedBill1("日出库单");
		pt.setRelatedBill2(null);
		pt.setRelatedBill3(ppt.getRelatedBill3());
		pt.setApplyDoc(sb);
		pt.setOrderDate(new Date());
		pt.setZone(commonDao.load(WarehouseArea.class, 37L));
		pt.setExecutePlanNo(strExtend3);//部品种类
		this.commonDao.store(pt);
		return pt;
	}
	public void appPlanAssembly(List<Long> pickTicketIds,int fs1,int fs2,int fs3) {
		String meg="";
		String ptdIds=StringUtils.strip(pickTicketIds.toString(),"[]");
		List<Long> ptIds=commonDao.findByQuery("select distinct(p.planPickTicket.id) from PlanPickDetail p where p.id in ("+ptdIds+")");
		if(ptIds.size()>1){
			throw new BusinessException("只能选择一张计划出库"); 
		}else{
			PlanPickTicket ppt=this.commonDao.get(PlanPickTicket.class, ptIds.get(0));
			List<PlanPickDetail> pds=commonDao.findByQuery(" from PlanPickDetail p where p.planPickTicket.id="+ppt.getId()+" and p.orderQuantity>0");
			Boolean cw=Boolean.FALSE;
			for(PlanPickDetail pd:pds){
				String hql1=" from BomAccount b where b.bigItem.id="+pd.getBigItem().getId() +" and b.bonded='课税' and b.outType='CKD单点' and b.strExtend1='"+ppt.getRelatedBill3()+"'";
				List<BomAccount> list1=commonDao.findByQuery(hql1);
				String hql2=" from BomAccount b where b.bigItem.id="+pd.getBigItem().getId() +" and b.bonded='保税' and b.outType='CKD单点' and b.strExtend1='"+ppt.getRelatedBill3()+"'";
				List<BomAccount> list2=commonDao.findByQuery(hql2);
				if(list1.size()<=0&&list2.size()<=0){
					addlog(ppt.getCode(), "无BOM工位清单", pd.getBigItem(), ppt.getRelatedBill3());
					cw=Boolean.TRUE;
				}
				pd.setAllocatedQuantity(pd.getOrderQuantity());
				this.commonDao.store(pd);
			}
			if(cw){
				LocalizedMessage.addLocalizedMessage("无BOM工位清单");
				return;
			}
			List<Object[]> objs=commonDao.findByQuery(" select b.bonded,b.strExtend3 from BomAccount b "
			+ " where 1=1"
			+ " and b.strExtend1='"+ppt.getRelatedBill3()+"' "
			+ " and b.outType='CKD单点' "
			+ " and b.bigItem.id in (select d.bigItem.id from PlanPickDetail d where d.planPickTicket.id="+ppt.getId()+" )"
			+ " group by b.bonded,b.strExtend3 ");
			for(Object[] obj:objs){
				String bonded=obj[0].toString();
				String bpzl=obj[1].toString();
				PickTicket pt=createPickTicket(bonded, ppt,bpzl);
				System.out.println(pt.getId());
				appPlanAssembly2(pt,ppt,bonded,ppt.getRelatedBill3(),bpzl);
//				for(PlanPickDetail pd:pds){
//					pd.setAllocatedQuantity(pd.getOrderQuantity());
//					appPlanAssembly(pt,pd,ppt,bonded,meg,pd.getOrderQuantity(),bpzl);
//				}
				//刷新出库单的在途库存、纯需求数量
//				shuapick(pt.getId());
				//分成N份生成出库单
				if(bpzl.equals("小")){
					for(int i=1;i<fs1;i++){
						createNewPlanPick(pt, i, fs1);
						pt.setPrintCount(fs1);
						this.commonDao.store(pt);
					}
				}else if(bpzl.equals("中")){
					for(int i=1;i<fs2;i++){
						createNewPlanPick(pt, i, fs2);
						pt.setPrintCount(fs2);
						this.commonDao.store(pt);
					}
				}else if(bpzl.equals("大")){
					for(int i=1;i<fs3;i++){
						createNewPlanPick(pt, i, fs3);
						pt.setPrintCount(fs3);
						this.commonDao.store(pt);
					}
				}
				
			}
			ppt.setAllocatedQuantity(ppt.getOrderQuantity());
			ppt.setStatus("ALLOCATE");
			commonDao.store(ppt);
			
		}
	}
	public PickTicket createNewPlanPick(PickTicket pt,int i,int fs) {
		double new_qty=0;
		double old_qty=0;
		int row=0;
		PickTicket new_pt=EntityFactory.getEntity(PickTicket.class);
		new_pt.setWarehouse(pt.getWarehouse());
		new_pt.setStatus(PickTicketStatus.OPEN);
		new_pt.setCode(pt.getCode()+"-"+i);
		new_pt.setWaveCode(pt.getWaveCode());
		new_pt.setDock(pt.getDock());
		new_pt.setCompany(pt.getCompany());
		new_pt.setBillType(pt.getBillType());
		new_pt.setUserTracking();
		new_pt.setRelatedBill1(pt.getRelatedBill1());
		new_pt.setRelatedBill2(pt.getRelatedBill2());
		new_pt.setRelatedBill3(pt.getRelatedBill3());
		new_pt.setZone(pt.getZone());
		new_pt.setOrderDate(new Date());
		new_pt.setOrderQuantity(pt.getOrderQuantity());
		new_pt.setZone1(pt.getZone1());
		new_pt.setZone2(pt.getZone2());
		new_pt.setQuantity1(pt.getQuantity1());
		new_pt.setQuantity2(pt.getQuantity2());
		new_pt.setQuantity3(pt.getQuantity3());
		new_pt.setQuantity4(pt.getQuantity4());
		new_pt.setExecutePlanNo(pt.getExecutePlanNo());
		new_pt.setApplyDoc(pt.getApplyDoc());
		this.commonDao.store(new_pt);
		List<PickTicketDetail> ptds=this.commonDao.findByQuery("from PickTicketDetail p where p.pickTicket.id="+pt.getId());
		for(PickTicketDetail ptd_o:ptds){
			PickTicketDetail ptd=null;
			double qty=ptd_o.getQuantity4();
			double srs=ptd_o.getQuantity();
			if(ptd_o.getOrderQuantity()>srs&&srs>0){
				ptd=EntityFactory.getEntity(PickTicketDetail.class);
				row++;
				ptd.setLineNumber(ptd_o.getLineNumber());
				ptd.setXqQty(ptd_o.getXqQty());//需要数量
			
				ptd.setQuantity4(ptd_o.getQuantity4());
				ptd.setQuantity5(ptd_o.getQuantity5());
				ptd.setXs(ptd_o.getXs());
				int fs_srs=(int) (qty/srs)/fs;//每份多少收容数
				if(fs_srs==0){
					fs_srs=1;//当每次不足一个收容数时，按照一个收容计算
				}
				ptd.setOrderQuantity(fs_srs*srs);
				ptd.setRejectQuantity(ptd.getOrderQuantity());
				ptd_o.setOrderQuantity(ptd_o.getOrderQuantity()-ptd.getOrderQuantity());
				ptd_o.setOrderQtyOfMasterUnit(ptd_o.getOrderQuantity());
				ptd_o.setRejectQuantity(ptd_o.getRejectQuantity()-ptd.getOrderQuantity());
				this.commonDao.store(ptd_o);
			}else{
//				ptd.setOrderQuantity(0);
				continue;
				//直接覆盖
			}
			new_qty+=ptd.getOrderQuantity();
			ptd.setOrderQtyOfMasterUnit(ptd.getOrderQuantity());
			ptd.setZzkw(ptd_o.getZzkw());
			ptd.setPf(ptd_o.getPf());
			ptd.setZone(ptd_o.getZone());
			ptd.setZone1(ptd_o.getZone1());
			ptd.setZone2(ptd_o.getZone2());
			ptd.setPickTicket(new_pt);
			ptd.setItem(ptd_o.getItem());
			ptd.setSOI(ptd_o.getSOI());
			ptd.setSpecs(ptd_o.getSpecs());
			ptd.setSingle(ptd_o.getSingle());
			ptd.setBonded(ptd_o.getBonded());
			ptd.setContent(ptd_o.getContent());
			ptd.setHezi(ptd_o.getHezi());
			ptd.setQuantity(ptd_o.getQuantity());//收容数
			this.commonDao.store(ptd);
			new_pt.addPickTicketDetail(ptd);
		}
		new_pt.setOrderQuantity(new_qty);
		new_pt.setBOLQuantity(new_qty);
		this.commonDao.store(new_pt);
		pt.setOrderQuantity(pt.getOrderQuantity()-new_qty);
		pt.setBOLQuantity(pt.getBOLQuantity()-new_qty);
		this.commonDao.store(pt);
		if(row==0){
			this.commonDao.delete(new_pt);
			return null;
		}else{
			return new_pt;
		}
	}
	public void copyPlanPick(PickTicket old_pt1,PickTicket old_pt2,int fs) {
		String meg="";
		if(old_pt1!=null){
			int count=1;
			for(int i=1;i<fs;i++){
				createNewPlanPick(old_pt1, count++, fs);
			}
		}
		if(old_pt2!=null){
			int count=1;
			for(int i=1;i<fs;i++){
				createNewPlanPick(old_pt2, count++,fs);
			}
		}
	}
	public void appPlanAssembly(PickTicket pt,PlanPickDetail ppd,PlanPickTicket pa,String bonded,String meg,double quantity,String strExtend3) {
		String hql=" from BomAccount b where b.bigItem.id="+ppd.getBigItem().getId()+
				" and  b.outType='CKD单点' and b.strExtend1='"+pa.getRelatedBill3()+"' and b.bonded='"+bonded+"' and b.strExtend3='"+strExtend3+"'";
		List<BomAccount> list1=commonDao.findByQuery(hql);
		System.out.println(hql);
		if(list1.size()>0) {
			if(list1.size()==1) {
			commonDao.store(pt);
			pa.setRelatedBill2(pt.getCode());
	        commonDao.store(pa);
			}
			for(BomAccount b:list1) {
				List<PickTicketDetail> list3=new ArrayList<PickTicketDetail>();
				PickTicketDetail ptd=null;
				if(!pt.isNew()) {
					list3=commonDao.findByQuery(" from PickTicketDetail p where p.item.id="+b.getItem().getId()+" and p.pickTicket.id="+pt.getId());
				}
				if(list3.size()>0) {
					ptd=list3.get(0);
					System.out.println("重复SKU");
				}else {
					ptd=EntityFactory.getEntity(PickTicketDetail.class);
					List<PickTicketDetail> list4=commonDao.findByQuery(" from PickTicketDetail p where  p.pickTicket.id="+pt.getId());
					int hh=1;
					if(list4.size()>0) {
						hh=list4.size()+1;
					}
					ptd.setLineNumber(hh+"");
				}				
				double qty=Integer.parseInt(b.getSingle())*quantity;//需求数量
				System.out.println("单用"+b.getSingle()+"--需求数量"+qty);
				//需求数量
				ptd.setXqQty(ptd.getXqQty()+qty);//需要数量
//				//纯需要数量
//				ptd.setRejectQuantity(ptd.getRejectQuantity()+qty);
//				//备货数量
//				ptd.setOrderQuantity(ptd.getOrderQuantity()+qty);
//				ptd.setOrderQtyOfMasterUnit(ptd.getOrderQuantity());
				ptd.setZone1(b.getZone());
				ptd.setZone2(b.getZone1());
				System.out.println("需求"+ptd.getXqQty()+"--备货需求"+ptd.getOrderQuantity());
				pt.setOrderDate(new Date());
				pt.setQuantity2(pt.getQuantity2()+qty);
				pt.setOrderQuantity(pt.getOrderQuantity()+qty);
				pt.setBOLQuantity(pt.getBOLQuantity()+qty);
				if(pt.getCompany()==null) {
					pt.setCompany(b.getItem().getCompany());
			    }
				pt.setZone1(b.getZone());
				pt.setZone2(b.getZone1());
				ptd.setPickTicket(pt);
				ptd.setItem(b.getItem());
				ptd.setSOI(b.getProphase());
				ptd.setSpecs(b.getSpecs());
				ptd.setSingle(b.getSingle());
				ptd.setBonded(b.getBonded());
				ptd.setContent(b.getContent());
				ptd.setZone(pt.getZone2());
				String hql2=" from  Pinfan p where p.item.id="+b.getItem().getId();
				if(b.getBonded()!=null&&!b.getBonded().equals("")) {
					hql2=hql2+" and p.bonded='"+b.getBonded()+"'";
				}else {
					hql2=hql2+" and p.bonded is null";
				}
				List<Pinfan> fan1=commonDao.findByQuery(hql2);
				if(fan1.size()>0) {
					Pinfan f=fan1.get(0);
					ptd.setHezi(f.getHezi());
					ptd.setQuantity(f.getQuantity());//收容数
					ptd.setPf(f);
				}	
				//查询在途数量
//				List<Double> li4=commonDao.findByQuery(" select COALESCE(sum(p.shippedQuantity),0) from  PickTicketDetail p where p.pickTicket.relatedBill3='"+pt.getRelatedBill3()+"' "+
//						"and p.itemKey.item.id="+b.getItem().getId()+" and p.bonded='"+b.getBonded()+"'"+" and p.specs='"+b.getSpecs()+"'"
//						+" and p.content='"+b.getContent()+"'" );
//				if(li4.size()>0) {
//					ptd.setNorejectZTQuantity(li4.get(0));
//					double tc=ptd.getRejectQuantity()-ptd.getNorejectZTQuantity();
//					if(tc<=0) {
//						ptd.setRejectQuantity(0);
//						}else {
//							ptd.setRejectQuantity(tc);
//						}
//				}
				
				commonDao.store(pt);
				commonDao.store(ptd);
			}
			
		}else {
			meg=meg+"无成品BOM清单!";
		}
	}
	
	public void appPlanAssembly2(PickTicket pt,PlanPickTicket ppt,String bonded,String gw,String bpzl) {
		String hql="select max(b.id), sum(b.single*pptd.orderQuantity)  "
				+ " from BomAccount b,PlanPickDetail pptd "
				+ " where pptd.planPickTicket.id="+ppt.getId()+" and b.bigItem.id=pptd.bigItem.id and b.outType='CKD单点' "
				+ " and b.strExtend1='"+gw+"' and b.bonded='"+bonded+"' and b.strExtend3='"+bpzl+"'"
				+ " group by b.zzkw.id, b.item.id";
		List<Object[]> list1=commonDao.findByQuery(hql);
		System.out.println(hql);
		if(list1.size()>0) {
			ppt.setRelatedBill2(pt.getCode());
	        commonDao.store(ppt);
			int hh=1;
			for(Object[] obj:list1) {
				Long bId=(Long) obj[0];
				double orderQuantity=(Double) obj[1];
				BomAccount ba=this.commonDao.get(BomAccount.class, bId);
				PickTicketDetail ptd=EntityFactory.getEntity(PickTicketDetail.class);
				ptd.setLineNumber((hh++)+"");
				ptd.setXqQty(orderQuantity);//需要数量
//				//纯需要数量
//				ptd.setRejectQuantity(ptd.getRejectQuantity()+qty);
//				//备货数量
//				ptd.setOrderQuantity(ptd.getOrderQuantity()+qty);
//				ptd.setOrderQtyOfMasterUnit(ptd.getOrderQuantity());
				ptd.setZone1(ba.getZone());//收
				ptd.setZone2(ba.getZone1());//出
				ptd.setPickTicket(pt);
				ptd.setItem(ba.getItem());
				ptd.setSOI(ba.getProphase());
				ptd.setSpecs(ba.getSpecs());
				ptd.setSingle(ba.getSingle());
				ptd.setBonded(ba.getBonded());
				ptd.setContent(ba.getContent());
				ptd.setZone(ptd.getZone2());
				ptd.setZzkw(ba.getZzkw());
				String hql2=" from  Pinfan p where p.item.id="+ba.getItem().getId()+" and p.zone.id="+ptd.getZone().getId();
				if(ba.getBonded()!=null&&!ba.getBonded().equals("")) {
					hql2=hql2+" and p.bonded='"+ba.getBonded()+"'";
				}else {
					hql2=hql2+" and p.bonded is null";
				}
				List<Pinfan> fan1=commonDao.findByQuery(hql2);
				if(fan1.size()>0) {
					Pinfan f=fan1.get(0);
					ptd.setHezi(f.getHezi());
					if(f.getQuantity()==0){
						throw new BusinessException(ptd.getItem().getCode()+"收容数不能为0");
					}
					ptd.setQuantity(f.getQuantity());//收容数
					ptd.setPf(f);
				}else{
					throw new BusinessException(ptd.getItem().getCode()+"无品番关联");
				}
			
				String query_inv=" select COALESCE(sum(p.qtyOfMasterPack),0) from  Inventory p "
						+ " where p.barCode='XB' and p.zone.id="+ptd.getZone1().getId()
						+" and p.itemKey.pinfan.id="+ptd.getPf().getId()
						+" and (p.zzkw.id is null or p.location.id="+ba.getZzkw().getId()+" or p.zzkw.id="+ba.getZzkw().getId()+")";
				List<Double> li3=commonDao.findByQuery(query_inv);
				if(li3.size()>0) {
					ptd.setInvQty(li3.get(0));//线边数量
					double cxq=ptd.getXqQty()-ptd.getInvQty();
					if(cxq<0) {
						ptd.setRejectQuantity(0);//需求数-线边数=0，需求数为1个收容数
					}else if(cxq<0){
						ptd.setRejectQuantity(ptd.getQuantity());
					}else {
						ptd.setRejectQuantity(cxq);
					}
				}
				double d=1;
				if(ptd.getQuantity()>0) {//收容数大于0
					d=Math.ceil(ptd.getRejectQuantity()/ptd.getQuantity());//几份收容数
					ptd.setOrderQuantity(ptd.getQuantity()*d);//备货数量
				}else {
					ptd.setOrderQuantity(ptd.getRejectQuantity());//备货数量
				}
				ptd.setXs(d);
				ptd.setOrderQtyOfMasterUnit(ptd.getOrderQuantity());
				ptd.setQuantity4(ptd.getOrderQuantity());//原备货数量
				ptd.setQuantity5(ptd.getRejectQuantity());
				commonDao.store(ptd);
				
				pt.setQuantity3(pt.getQuantity3()+ptd.getXqQty());//需求数量
				pt.setOrderQuantity(pt.getOrderQuantity()+ptd.getOrderQuantity());//备货数量
				pt.setQuantity4(pt.getOrderQuantity());//原备货数量
				pt.setBOLQuantity(pt.getBOLQuantity()+ptd.getRejectQuantity());//纯需求数量
				pt.setOrderDate(new Date());
				pt.setQuantity2(pt.getQuantity2()+orderQuantity);
				if(pt.getCompany()==null) {
					pt.setCompany(ba.getItem().getCompany());
			    }
				pt.setZone1(ba.getZone());
				pt.setZone2(ba.getZone1());
				commonDao.store(pt);
				commonDao.store(ptd);
			}
			
		}
	}
	
	public void shuapick(Long id) {
		// xqQty 需求数，rejectQuantity 纯需求，rejectQuantity-allocatedQuantity纯需求不足，orderQuantity备货需求，orderQuantity-allocatedQuantity未出单数，
		//allocatedQuantity出单数,pickedQuantity备货数，shippedQuantity在途数，invQty库存数
		PickTicket pt=commonDao.load(PickTicket.class, id);
		pt.setQuantity3(0);//需求数量
		pt.setOrderQuantity(0);//备货数量
		pt.setBOLQuantity(0);//纯需求数量
		List<PickTicketDetail> list4=commonDao.findByQuery(" from PickTicketDetail p where  p.pickTicket.id="+pt.getId());
		for(PickTicketDetail pd:list4) {
			//查询线边数量
			String hql=" select COALESCE(sum(p.qtyOfMasterPack),0) from  Inventory p where p.barCode='XB' and p.zone.id="+pt.getZone1().getId()+
					" and p.itemKey.item.id="+pd.getItem().getId()+" and p.itemKey.pinfan.bonded='"+pd.getBonded()+"'";
			hql+=" and p.itemKey.pinfan.specs='"+pd.getSpecs()+"'";
			List<Double> li3=commonDao.findByQuery(hql);
			if(li3.size()>0) {
				pd.setInvQty(li3.get(0));
				double tc=pd.getXqQty()-pd.getInvQty();
				if(tc<=0) {
					pd.setRejectQuantity(0);
				}else {
					pd.setRejectQuantity(tc);
				}
			}
			double d=1;
			if(pd.getQuantity()>0) {//收容数大于0
				d=Math.ceil(pd.getRejectQuantity()/pd.getQuantity());//几份收容数
				pd.setOrderQuantity(pd.getQuantity()*d);//备货数量
			}else {
				pd.setOrderQuantity(pd.getRejectQuantity());//备货数量
			}
				pd.setOrderQtyOfMasterUnit(pd.getOrderQuantity());
				pd.setQuantity4(pd.getOrderQuantity());//原备货数量
				pt.setQuantity3(pt.getQuantity3()+pd.getXqQty());//需求数量
				pt.setOrderQuantity(pt.getOrderQuantity()+pd.getOrderQuantity());//备货数量
				pt.setQuantity4(pt.getOrderQuantity());//原备货数量
				pt.setBOLQuantity(pt.getBOLQuantity()+pd.getRejectQuantity());//纯需求数量
				commonDao.store(pd);
			
		}
		commonDao.store(pt);
	}
	
	public void addlog (String code,String meg,BigItem bi,String gw) {
	 	InterfaceLog log=new InterfaceLog();
    	log.setDealTime(new Date());
    	log.setFileName(code);
    	log.setFileType("生成备货操作");
    	log.setType("生成备货操作");
    	log.setToSYS(UserHolder.getUser().getName());
    	log.setStatus("失败");
    	log.setErrorLog(meg);
    	log.setRequestContent("");
    	log.setStr1(gw);
    	log.setStr2(bi.getModelType());
    	log.setStr3(bi.getName());
    	log.setStr4(bi.getCode());
    	commonDao.store(log);
	}
	public void addlog (String fileName,String fileType,String type,String meg) {
		InterfaceLog log=new InterfaceLog();
    	log.setDealTime(new Date());
    	log.setFileName(fileName);
    	log.setFileType(fileType);
    	log.setType(type);
    	log.setToSYS(UserHolder.getUser().getName());
    	if(meg!=null&&!meg.equals("")) {
    		log.setStatus("失败");
    	 }else {
    		 log.setStatus("成功");
    	 }
    	log.setErrorLog(meg);
    	log.setRequestContent("");
    	commonDao.store(log);
	}
	
	
	
	
	public void appPlanTLJ(List<Long> pickTicketIds) {
		for (Long id:pickTicketIds) {
			double unallocateQty=0;
			
			PlanAssembly ppd = commonDao.load(PlanAssembly.class, id);
			
			List<ProductionPlan> list1=commonDao.findByQuery(" from ProductionPlan b where b.planAssembly.id="+id+
					" and b.strExtend1 is null and b.OfflineDate>date_add(CURRENT_DATE(), interval 3 day)");
			List<AddOutPlanList> addlist=new ArrayList<AddOutPlanList>();
			if(list1.size()>0) {
				for(ProductionPlan pm:list1) {
					List<ItemList> list3=commonDao.findByQuery(" from ItemList p where "
							+ "p.bigItem.id="+pm.getBigItem().getId()+" and p.outType='CKD单点' ");
					if(list3.size()>0) {
						
//						for(ItemList l:list3) {
					
//							AddOutPlanList ptd =EntityFactory.getEntity(AddOutPlanList.class);
					
					double qty=1D;
//					ptd.setOrderQuantity(qty+ptd.getOrderQuantity());
//					ptd.setBigItem(l.getBigItem());
//					ptd.setPlanPickTicket(pt);
//					ptd.setInvStatus(l.getModelType());
//					ptd.setZone(l.getOutZone());
					
//						}
				}else {
					
//					throw new BusinessException("无完成品BOM清单!");
				}
				}
				
			}else {
				
			}
			
			
			if(list1.size()>0) {
				PlanPickTicket pt =EntityFactory.getEntity(PlanPickTicket.class);
				pt.setWarehouse(WarehouseHolder.getWarehouse());
				pt.setStatus(PickTicketStatus.OPEN);
				pt.setOrderDate(new Date());
				pt.setCode(this.bussinessCodeManager.getCodeForYm("ZS",3));
				
				if(pt.getZone()!=null){
					pt.setCompany(pt.getZone().getSupplier());
				}
				pt.setUserID(ppd.getId());
//				pt.setRelatedBill1(p.getCountry());
				pt.setRelatedBill2("拖拉机日计划");
				pt.setRelatedBill3("CDK单点");//CKD单点
				
				
				for(ProductionPlan pm:list1) {
					List<ItemList> list3=commonDao.findByQuery(" from ItemList p where "
							+ "p.bigItem.id="+pm.getBigItem().getId()+" and p.outType='CKD单点' ");
					if(list3.size()>0) {
						commonDao.store(pt);
						for(ItemList l:list3) {
					PlanPickDetail ptd =EntityFactory.getEntity(PlanPickDetail.class);
//					List<PlanPickDetail> list2=commonDao.findByQuery(" from PlanPickDetail p where "
//							+ "p.bigItem.id="+l.getBigItem().getId()+" and  p.invStatus='"+l.getModelType()+"'");
//					if(list2.size()>0) {
//						ptd=list2.get(0);
//					}
					double qty=1D;
					ptd.setOrderQuantity(qty+ptd.getOrderQuantity());
					ptd.setBigItem(l.getBigItem());
					ptd.setPlanPickTicket(pt);
					ptd.setInvStatus(l.getModelType());
					ptd.setZone(l.getOutZone());
					commonDao.store(ptd);
					pt.setOrderQuantity(qty+pt.getOrderQuantity());
					ptd.setNumberNo(pm.getNumberNo());
					ptd.setProcedure(l.getModelType());
					ptd.setOfflineDate(pm.getOfflineDate());
					ptd.setCode(pm.getCode());
					ptd.setName(pm.getName());
					ptd.setCountry(pm.getCountry());
					ptd.setModelType(pm.getModelType());
					ptd.setModelNo(pm.getModelNo());
					ptd.setModelName(pm.getModelName());
					ptd.setDescription(pm.getDescription());
					commonDao.store(pt);
					}
				}else {
					throw new BusinessException("无完成品BOM清单!");
				}
				}

		}else {
			throw new BusinessException("无计划明细!");
		}
		}
	}
	public String getByJhMap(Map map) {
//		Long inventoryId = (Long)map.get("b.id");
		String str="";
		List<ProductionPlan> list= commonDao.findByQuery(" from  ProductionPlan p where p.strExtend1 is null  order by longExtend1");
		if(list.size()>0) {
			ProductionPlan p=list.get(0);
			str=p.getModelNo();
		}
		return str;
	}
	
	
	//生成拖拉机出库单
	public void addProductionp(String tsr,String str1,double qty1,String procedure,String description) {
		if(tsr==null||tsr.equals("")) {
			throw new BusinessException("起始机号不能空");
		}
		List<ProductionPlan> list= commonDao.findByQuery(" from  ProductionPlan p where p.strExtend1 is null and p.procedure='"+procedure+"' and p.modelNo not in('"+description+"')  order by p.longExtend1,p.id ");
		
		if(list.size()>0) {
			int y=1;
			PickTicket pt=EntityFactory.getEntity(PickTicket.class);
			pt.setWarehouse(WarehouseHolder.getWarehouse());
			pt.setStatus(PickTicketStatus.OPEN);
			pt.setCode(this.bussinessCodeManager.getCodeForYm("ZS",3));
			String xb_code="";
			if(pt.getZone()!=null){
				xb_code=pt.getZone().getHckw().getCode();
			}else{
				xb_code=pt.getZone1().getHckw().getCode();
			}
			List<Location> locs=commonDao.findByQuery(" from Location b where b.code='"+xb_code+"'");// and b.warehouse.id="+WarehouseHolder.getWarehouse().getId());
			if(locs.size()>0) {
				pt.setDock(locs.get(0));
			}
//				if(pt.getZone()!=null){
					pt.setCompany(commonDao.load(Structure.class, 1002L));
//				}
				List<BillType> list2=commonDao.findByQuery(" from BillType b where b.code='SKD单点' ");
				BillType billType=null;
				if(list2.size()>0) {
					billType=list2.get(0);
					pt.setBillType(billType);
				}else {
					pt.setBillType(commonDao.load(BillType.class, 6L));
				}
				pt.setUserTracking();
				pt.setRelatedBill1("日出库单");
				pt.setRelatedBill2(null);
				pt.setRelatedBill3(procedure);
				pt.setZone(commonDao.load(WarehouseArea.class, 37L));
//				commonDao.store(pt);
			
			for(ProductionPlan ppd:list) {
				if((ppd.getModelNo().equals(tsr)||y>1)&&y<=qty1) {
					y++;
			String hql=" from BomAccount b where b.bigItem.id="+ppd.getBigItem().getId()+
				" and b.zone1.id= "+ppd.getZone2().getId()+" and  b.outType='"+ppd.getOutType()+"' and b.strExtend1='"+ppd.getProcedure()+"'";
		List<BomAccount> list1=commonDao.findByQuery(hql);
		System.out.println(hql);
		if(list1.size()>0) {
			pt.setZone1(ppd.getZone1());
			pt.setZone2(ppd.getZone2());
			pt.setOutType(ppd.getOutType());
			commonDao.store(pt);
			for(BomAccount b:list1) {
				
				List<PickTicketDetail> list3=new ArrayList<PickTicketDetail>();
				PickTicketDetail ptd=null;
				if(!pt.isNew()) {
					list3=commonDao.findByQuery(" from PickTicketDetail p where p.item.id="+b.getItem().getId()+" and p.pickTicket.id="+pt.getId());
				}
				if(list3.size()>0) {
					ptd=list3.get(0);
					System.out.println("重复SKU");
				}else {
					ptd=EntityFactory.getEntity(PickTicketDetail.class);
				}
				double quantity=1;
				
				double qty=Integer.parseInt(b.getSingle());//需求数量
				System.out.println("比"+b.getSingle()+"--数量"+qty);
				//需求数量
				ptd.setXqQty(ptd.getXqQty()+qty);//需要数量
				
				//订单数量
				ptd.setOrderQuantity(ptd.getOrderQuantity()+qty);
				ptd.setOrderQtyOfMasterUnit(ptd.getOrderQtyOfMasterUnit()+qty);
				ptd.setZone1(ppd.getZone1());
				ptd.setZone2(ppd.getZone2());
				System.out.println("需求"+ptd.getXqQty()+"--订单"+ptd.getOrderQuantity());
				
				pt.setOrderDate(new Date());
				pt.setQuantity3(pt.getQuantity3()+qty);
				pt.setOrderQuantity(pt.getOrderQuantity()+qty);
				if(pt.getCompany()==null) {
				pt.setCompany(b.getItem().getCompany());
			   }
				ptd.setPickTicket(pt);
				ptd.setItem(b.getItem());
				ptd.setSOI(b.getProphase());
				//查询在途数量
//				List<Double> li2=commonDao.findByQuery("select sum(p.orderQuantity-p.shippedQuantity) from  PickTicketDetail p wher p.pickTicket.relatedBill1='日出库单' and p.item.id="+b.getItem().getId());
//				if(li2.size()>0) {
//					ptd.setRejectZTQuantity(li2.get(0));
//				}
				//查询线边数量
//				List<Double> li3=commonDao.findByQuery("select sum(p.qtyOfMasterPack) from  Inventory p wher p.barCode='XB' and p.itemKey.item.id="+b.getItem().getId());
//				if(li3.size()>0) {
//					ptd.setKcQty(li3.get(0));
//					ptd.setOrderQuantity(ptd.getq);
//				}
				commonDao.store(pt);
				commonDao.store(ptd);
				refpickQty(pt);
				ppd.setStrExtend2(pt.getCode());
				commonDao.store(ppd);
			}
			}
			}
		}
		}else {
			throw new BusinessException("无成品BOM清单!");
		}
		
	}
	public void refpickQty(PickTicket p) {
		
		List<Double> list=commonDao.findByQuery("select sum(p.orderQuantity) from PickTicketDetail p where p.pickTicket.id="+p.getId());
		if(list.size()>0) {
		p.setOrderQuantity(list.get(0));
		}
		List<Double> list1=commonDao.findByQuery("select sum(p.xqQty) from PickTicketDetail p where p.pickTicket.id="+p.getId());
		if(list1.size()>0) {
		p.setQuantity3(list1.get(0));
		}
		commonDao.store(p);
	}
	
	
	public void appPlanLDJ(List<Long> pickTicketIds) {
		for (Long id:pickTicketIds) {
			double unallocateQty=0;
			
			PlanAssembly ppd = commonDao.load(PlanAssembly.class, id);
			
			List<ModelPlan> list1=commonDao.findByQuery(" from ModelPlan b where b.planAssembly.id="+id+" and b.strExtend1 is null ");
			if(list1.size()>0) {
				PlanPickTicket pt =EntityFactory.getEntity(PlanPickTicket.class);
				pt.setWarehouse(WarehouseHolder.getWarehouse());
				pt.setStatus(PickTicketStatus.OPEN);
				pt.setOrderDate(new Date());
				pt.setCode(this.bussinessCodeManager.getCodeForYm("ZS",3));
				
				if(pt.getZone()!=null){
					pt.setCompany(pt.getZone().getSupplier());
				}
				pt.setUserID(ppd.getId());
//				pt.setRelatedBill1(p.getCountry());
				pt.setRelatedBill2("履带机日计划");
//				pt.setRelatedBill3("拖拉机日计划");
				
				commonDao.store(pt);
				for(ModelPlan pm:list1) {
					List<ItemList> list3=commonDao.findByQuery(" from ItemList p where "
							+ "p.bigItem.id="+pm.getBigItem().getId());
					if(list3.size()>0) {
						for(ItemList l:list3) {
					
					
					PlanPickDetail ptd =EntityFactory.getEntity(PlanPickDetail.class);
					List<PlanPickDetail> list2=commonDao.findByQuery(" from PlanPickDetail p where "
							+ "p.bigItem.id="+l.getBigItem().getId()+" and  p.invStatus='"+l.getModelType()+"'");
					if(list2.size()>0) {
						ptd=list2.get(0);
					}
					double qty=1D;
					ptd.setOrderQuantity(qty+ptd.getOrderQuantity());
					ptd.setBigItem(l.getBigItem());
					ptd.setPlanPickTicket(pt);
					ptd.setInvStatus(l.getModelType());
					ptd.setZone(l.getOutZone());
					commonDao.store(ptd);
					pt.setOrderQuantity(qty+pt.getOrderQuantity());
					commonDao.store(pt);
						}
				}else {
					throw new BusinessException("无完成品BOM清单!");
				}
				}

		}else {
			throw new BusinessException("无计划明细!");
		}
		}
	}
	public void pickoutConfirm(List<Long> pickTicketIds) {
		for(Long id:pickTicketIds) {
			PickTicket pt =commonDao.load(PickTicket.class, id);
			List<Long> list=new ArrayList<Long>();
			list.add(id);
			pickoutConfirm(list,pt.getZone1().getId());
		}
	}
	
	
	public void pickoutConfirm(List<Long> pickTicketIds,Long zid) {
		for(Long id :pickTicketIds) {
			PickTicket pt =commonDao.load(PickTicket.class, id);
			WarehouseArea zone=commonDao.load(WarehouseArea.class, zid);
			if(zone==null) {
				throw new BusinessException("入库库区没有值，请选择库区");
			}
//			//线边库位
//			List<Location> ls=this.commonDao.findByQuery("from Location l where l.code='"+SysCode.XB_LOC+"'");
//			if(ls.size()<=0){
//				throw new BusinessException("请维护代码是"+SysCode.XB_LOC+"的久保田线边库位");
//			}
//			Location xb_loc=ls.get(0);
			
			if(zone.getHckw()==null){
				throw new BusinessException("维护库区对应线边待投料库位");
			}
			Location xb_loc=zone.getHckw();
		
		   List<PickTicketDetail>	list1=commonDao.findByQuery(" from  PickTicketDetail p where p.pickTicket.id="+id+" and p.pickedQuantity>0");
		   for(PickTicketDetail ptd:list1) {
			   if(ptd.getItemKey()!=null&&!ptd.isOldRecord()) {
				  String hql=" from Inventory  i where i.itemKey.id="+ptd.getItemKey().getId()+
					 " and i.zone.id="+zone.getId()+" and  i.barCode='XB'  and i.location.id="+xb_loc.getId()+" and i.zzkw.id="+ptd.getZzkw().getId();
				 List<Inventory> list2 =commonDao.findByQuery(hql);
				 Inventory inv=null;
				 if(list2.size()>0) {
					 inv =list2.get(0);
					 inv.setLocation(xb_loc);
					 inv.setQtyOfMasterPack(inv.getQtyOfMasterPack()+ptd.getPickedQuantity());
					 inv.setQuantity(inv.getQtyOfMasterPack());
					 commonDao.store(inv);
				 }else {
					 inv=EntityFactory.getEntity(Inventory.class);
					 inv.setLocation(xb_loc);
					 inv.setZzkw(ptd.getZzkw());
					 inv.setItemKey(ptd.getItemKey());
					 inv.setQtyOfMasterPack(ptd.getPickedQuantity());
					 inv.setQuantity(ptd.getPickedQuantity());
					 inv.setZone(zone);
					 inv.setBarCode("XB");
					 commonDao.store(inv);
				 }
				 ptd.setShippedQuantity(ptd.getPickedQuantity());
				 ptd.setNorejectQuantity(ptd.getShippedQuantity());
				 ptd.setOldRecord(true);
				 commonDao.store(ptd);
				 InventoryLog log2 = new InventoryLog(InventoryLogType.PROCESS_UP, 1, pt.getCode(), null, xb_loc, null, inv.getItemKey(), 
							new Date(), pt.getCode(), ptd.getPickedQuantity(), null, null, inv.getId(), null,inv.getZone());
				 commonDao.store(log2);
			   }
		   }
		   
//		   List<Double> list3=commonDao.findByQuery("select sum(p.invQty) from PickTicketDetail p  where  p.pickTicket.id="+pt.getId());
//			if(list1.size()>0) {
				pt.setPackageQuantity(pt.getShippedQuantity());
//				pt.setQuantity1(list3.get(0));
				pt.setStatus("CLOSE");
				commonDao.store(pt);
//			}
		}
	}
	
	public void shipConfirmKAMS(List<Long> pickIds) {
		String operator=UserHolder.getUser().getName();
		for(Long pickId:pickIds) {
			PickTicket pt=this.commonDao.get(PickTicket.class, pickId);
			if(pt.getStatus().equals(PickTicketStatus.PICK_ALL)||pt.getStatus().equals(PickTicketStatus.SHIP_PART)){
				pt.setShipDate(new Date());
				pt.setStatus(PickTicketStatus.SHIP_ALL);
				pt.setShippedQuantity(pt.getPickedQuantity());
	//			pt.setRelatedBill2(this.bussinessCodeManager.getCodeForYm("CK",5));
				this.commonDao.store(pt);
			}else{
				throw new BusinessException(pt.getCode()+"状态不正确");
			}
			List<PickTicketDetail> pds=this.commonDao.findByQuery("from PickTicketDetail d where d.pickTicket.id="+pt.getId()+" and d.allocatedQuantity>0");
			for(PickTicketDetail pd:pds){
				if(pd.getPickedQuantity()<pd.getAllocatedQuantity()){
					throw new BusinessException(pt.getCode()+"状态不正确");
				}
				if(pt.getPickedQuantity()>0){
					double shipQty=pd.getPickedQuantity()-pd.getShippedQuantity();
	//				List<Inventory> news=this.commonDao.findByQuery("from Inventory inv where  inv.itemKey.item.id="+pd.getItem().getId()+
	//						" and inv.zone.id="+pd.getZone2().getId()+ " and inv.location.type='SHIP'");
					Inventory inv=findInventory(pd.getItemKey(), pd.getZone2(), null, pt.getCode(), SysCode.CK_FY1);
					double qty1=inv.getQtyOfMasterPack();
					inv.setQtyOfMasterPack(inv.getQtyOfMasterPack()-shipQty);
					if(inv.getQtyOfMasterPack()<0){
						inv.setQtyOfMasterPack(0);
					}
					inv.setQuantity(inv.getQtyOfMasterPack());
					this.commonDao.store(inv);
					addInventoryLog(InventoryLogType.SHIPPING, -1, pd.getZone2(), inv.getLocation(), pt.getCode(), pd.getItemKey(),shipQty, null, operator, inv.getId(), (int)qty1+"变为"+(int)inv.getQtyOfMasterPack(),null,null);
					pd.setShippedQuantity(pd.getPickedQuantity());
					this.commonDao.store(pd);
				}
			}
			List<Double> list1=commonDao.findByQuery("select COALESCE(sum(p.shippedQuantity),0) from PickTicketDetail p  where  p.pickTicket.id="+pt.getId());
			if(list1.size()>0) {
				pt.setShippedQuantity(list1.get(0));
				commonDao.store(pt);
			}
		}
	}
	
	
	public void confirmShipKAMS(List<Long> pickIds) {
		for(Long pickId:pickIds) {
		PickTicket pt=this.commonDao.get(PickTicket.class, pickId);
		if(pt.getStatus().equals(PickTicketStatus.PICK_ALL)||pt.getStatus().equals(PickTicketStatus.PICKUP)){
			pt.setShipDate(new Date());
			pt.setStatus(PickTicketStatus.SHIP_ALL);
			pt.setShippedQuantity(pt.getPickedQuantity());
//			pt.setRelatedBill2(this.bussinessCodeManager.getCodeForYm("CK",5));
			this.commonDao.store(pt);
			//扣库存
			Location loc=null;
			if(pt.getDock()!=null) {
				loc=pt.getDock();
			}else {
			 loc=this.commonDao.get(Location.class, 525l);
			}
			String billCode=pt.getRelatedBill2()==null?pt.getCode():pt.getRelatedBill2();
			
		}
		List<PickTicketDetail> pds=this.commonDao.findByQuery("from PickTicketDetail d where d.pickTicket.id="+pt.getId());
		for(PickTicketDetail pd:pds){
			List<Inventory> news=this.commonDao.findByQuery("from Inventory inv where  inv.itemKey.item.id="+pd.getItem().getId()+
					" and inv.zone.id="+pd.getZone2().getId()+ " ");
			//未发运数量
			double qtyinv=pd.getPickedQuantity()-pd.getShippedQuantity();
			double qty2=0D;
			for(Inventory inv:news){
				
				qty2=inv.getQtyOfMasterPack()-qtyinv;
				if(qty2==0) {
					InventoryLog log2 = new InventoryLog(InventoryLogType.SHIPPING, -1, pt.getCode(), null, pt.getDock(), null, inv.getItemKey(), 
							new Date(), pt.getCode(), qtyinv, null, null, inv.getId(), null,inv.getZone());
					commonDao.store(log2);
					this.commonDao.delete(inv);
				}else if(qty2>0) {
					
					inv.setQtyOfMasterPack(inv.getQtyOfMasterPack()-qtyinv);
					inv.setQuantity(inv.getQtyOfMasterPack());
					commonDao.store(inv);
					InventoryLog log2 = new InventoryLog(InventoryLogType.SHIPPING, -1, pt.getCode(), null, pt.getDock(), null, inv.getItemKey(), 
							new Date(), pt.getCode(), qtyinv, null, null, inv.getId(), null,inv.getZone());
					commonDao.store(log2);
				}else {
					qtyinv=qtyinv-inv.getQtyOfMasterPack();
					InventoryLog log2 = new InventoryLog(InventoryLogType.SHIPPING, -1, pt.getCode(), null, pt.getDock(), null, inv.getItemKey(), 
							new Date(), pt.getCode(), inv.getQtyOfMasterPack(), null, null, inv.getId(), null,inv.getZone());
					commonDao.store(log2);
					this.commonDao.delete(inv);
					continue;
				}
			}
			
			pd.setShippedQuantity(pd.getShippedQuantity()+qtyinv);
			
			this.commonDao.store(pd);
		}
		List<Double> list1=commonDao.findByQuery("select COALESCE(sum(p.shippedQuantity),0) from PickTicketDetail p  where  p.pickTicket.id="+pt.getId());
		if(list1.size()>0) {
			pt.setShippedQuantity(list1.get(0));
			commonDao.store(pt);
		}
		refPlanPick(pt.getId(),null);
		
	}
	}
	
	//备货操作，出库操作审核
	public void activeKAMSAll(List<Long> pickTicketIds) {
		String errMsg = "";
		for (Long id : pickTicketIds) {
			PickTicket pickTicket = commonDao.load(PickTicket.class, id);
				for(PickTicketDetail d:pickTicket.getPickTicketDetails()){
					String hql="FROM Inventory i WHERE  i.itemKey.item.id="+d.getItem().getId()+" and i.zone.id="+d.getZone2().getId();
					hql+=" and ( i.location.type!='SHIP')";
//					hql+=" and ( i.location.type!='SHIP')";
					List<Inventory> invs =  commonDao.findByQuery(hql);
					//只针对CKD课稅和保税仓库
					double unallocateQty=d.getUnallocateQuantity();
					if(unallocateQty<=0) {
						continue;
					}
					double quantity=unallocateQty;
					if(invs.size()==0) {
						errMsg+=d.getItem().getCode()+"没有库存";
					}
					for(Inventory i:invs){
						double b=i.getQtyOfMasterPack()-i.getQueuedQuantity();
						if(unallocateQty>=0) {
							if (quantity > i.getAvaliableQuantity()) {
								quantity = i.getAvaliableQuantity();
							}
							if (quantity > unallocateQty) {
								quantity = unallocateQty;
							}
							unallocateQty -= quantity;
							if(i.getLocation()==null){
								i.setLocation(i.getItemKey().getPinfan().getLocation());
							}
							if(i.getLocation()==null){
								throw new BusinessException(d.getItem().getCode()+"对应品番关联库位为空");
							}
							Task t=pickTicket.allocate(null,d, i, quantity);
							i.allocate(quantity, null, null);
							refreshPickWeightInfo(pickTicket.getId());
						}else {
							  break;
						}
						if(unallocateQty>0) {
							errMsg+=d.getItem().getCode()+"库存不足,";
						}
						d.setPf(i.getItemKey().getPinfan());
					}
					if(d.getQuantity()>0){
						d.setCaCoefficient(d.getAllocatedQuantity());
					}else{
						d.setCaCoefficient(Math.ceil(d.getAllocatedQuantity()/d.getQuantity()));
					}
				
					 //分配不足orderQuantity！=orderQuantity 需要设变
					 sheChange(pickTicket,d);	
				}
				//生效时预分配，如果预分配失败则不进行拣货分配
//				if (pickTicket.getPickTicketDetails() != null || pickTicket.getPickTicketDetails().size() > 0) {
//					autoAllocator.prePlanAllocate(pickTicket.getPickTicketDetails());
//				}
			
//					if(pickTicket.getPreAllocatedQuantity()<pickTicket.getOrderQuantity()){
//						pickTicket.setStatus(PickTicketStatus.OPEN);
//						errMsg+=pickTicket.getCode()+"库存不足";
//						continue;
//					}
			    if(pickTicket.getAllocatedQuantity()>0) {
				pickTicket.setStatus(PickTicketStatus.ALLOCATE);
				pickTicket.setShipDateStart(new Date());
			    }else{
			    	pickTicket.setStatus(PickTicketStatus.OPEN);
			    }
//				pickTicket.setDescription(errMsg);
				commonDao.store(pickTicket);
				errMsg+=pickTicket.getCode()+" 发货单激活成功;";
				LocalizedMessage.addLocalizedMessage(errMsg);
				refPlanPick(pickTicket.getId(),null);
		}
	}
	
//	public void sheChange(PickTicketDetail ptd){
//		if(ptd.getOrderQuantity()!=ptd.getAllocatedQuantity()&&ptd.getOrderQuantity()>0){
//			String sql=" FROM DesignList dl "
//			+ " where 1=1 "
//			+ " and dl.oldItem.code='"+ptd.getItem().getCode()+"' ";
//			List<DesignList> DesignLists =  commonDao.findByQuery(sql);
//			if(DesignLists.size()>0){
//				DesignList designList=DesignLists.get(0);
//				ptd.setDesignList(designList);
//				commonDao.store(ptd);
//			}
//		}
//	}
	
	public void sheChange(PickTicket pt,PickTicketDetail ptd){
		if(ptd.getOrderQuantity()!=ptd.getAllocatedQuantity()&&ptd.getOrderQuantity()>0){
			SimpleDateFormat ymd = new SimpleDateFormat("yyyyMM");
			String dqy=ymd.format(new Date());
			String sql=" FROM DesignList dl "
			+ " where 1=1  and dl.oldItemCode='"+ptd.getItem().getCode()+"'";// and putDate like '%"+dqy+"%'";
			List<DesignList> DesignLists =  commonDao.findByQuery(sql);
			if(DesignLists.size()>0){
				DesignList designList=DesignLists.get(0);
				ptd.setDesignList(designList);
				commonDao.store(ptd);
				pt.setPriority(1);
				this.commonDao.store(pt);
			}
		}
	}
	public void deleteProduction(List<Long> ids) {
		for(Long id:ids) {
			ProductionPlan p=commonDao.load(ProductionPlan.class, id);
			if(p.getStrExtend1().equals("未消耗")) {
				commonDao.delete(p);
			}else {
				throw new BusinessException("已消耗不能删除");
			}
		}
	}
	
	public void saveProductionPlan(List<Long> pIds ,String p,Long spId) {
		SpareParts sp=null;
		for(Long id:pIds) {
			ProductionPlan pp=commonDao.load(ProductionPlan.class, id);
			if(p.equals("已耗用")){
				if(pp.getStrExtend1().equals("已耗用")){
					throw new BusinessException(pp.getId()+"选中数据包含已耗用");
				}
				if(spId==null||spId.equals(new Long("0"))){
					sp=createSpareParts(pp, null, null, pIds.size());
					sp.setStr1(pp.getModelNo());
					spId=sp.getId();
					sp.setDescription("单一耗用");
					pp.setSpId(spId);
				}
//				if(sp!=null){
//					sp.setStr2(pp.getModelNo());
//					this.commonDao.store(sp);
//				}
			}
			pp.setStrExtend1(p);
			pp.setHyTime(new Date());
			commonDao.store(pp);
			
		}
	}

	public void addpickTicketPlan_zs(Long planid,String rd,Long id, Double sum) {
		List<BillType> list2=commonDao.findByQuery(" from BillType b where b.code='手工成套' ");
		BillType bt=null;
		if(list2.size()>0) {
			bt=list2.get(0);
		}else {
			bt=commonDao.load(BillType.class, 11L);
		}
		addpickTicketPlan(planid, rd, id, sum, "指示单",bt);
	}
	public void addpickTicketPlan_bh(Long planid,String rd,Long id, Double sum) {
		List<BillType> list2=commonDao.findByQuery(" from BillType b where b.code='CKD单点' ");
		BillType bt=null;
		if(list2.size()>0) {
			bt=list2.get(0);
		}else {
			bt=commonDao.load(BillType.class, 6L);
		}
		addpickTicketPlan(planid, rd, id, sum, "日出库单",bt);
	}
	
	public void checkCtPick(List<Long> pIds) {
		String meg="";
		String ptdIds=StringUtils.strip(pIds.toString(),"[]");
		List<Long> ptIds=commonDao.findByQuery("select distinct(p.planPickTicket.id) from PlanPickDetail p where p.id in ("+ptdIds+")");
		if(ptIds.size()>1){
			throw new BusinessException("只能选择一张计划审核"); 
		}else{
			PlanPickTicket ppt=this.commonDao.get(PlanPickTicket.class, ptIds.get(0));
			List<PlanPickDetail> pds=commonDao.findByQuery(" from PlanPickDetail p where p.planPickTicket.id="+ppt.getId()+" and p.orderQuantity>0");
			Boolean cw=Boolean.FALSE;
			for(PlanPickDetail pd:pds){
				String hql1=" from BomAccount b where b.bigItem.id="+pd.getBigItem().getId() +" and b.bonded='课税' and b.outType='CKD成套' and b.strExtend1='"+ppt.getRelatedBill3()+"'";
				List<BomAccount> list1=commonDao.findByQuery(hql1);
				String hql2=" from BomAccount b where b.bigItem.id="+pd.getBigItem().getId() +" and b.bonded='保税' and b.outType='CKD成套' and b.strExtend1='"+ppt.getRelatedBill3()+"'";
				List<BomAccount> list2=commonDao.findByQuery(hql2);
				if(list1.size()<=0&&list2.size()<=0){
					addlog(ppt.getCode(), "无BOM工位清单", pd.getBigItem(), ppt.getRelatedBill3());
					cw=Boolean.TRUE;
				}
				pd.setAllocatedQuantity(pd.getOrderQuantity());
				this.commonDao.store(pd);
			}
			if(cw){
				LocalizedMessage.addLocalizedMessage("无BOM工位清单");
				return;
			}else{
				PlanPickTicket pk=createPlanPick("课税", ppt);
				PlanPickTicket pb=createPlanPick("保税", ppt);
			}
			
		}
	}
	
	public void cancelCtPick(List<Long> pIds) {
		String meg="";
		String ptdIds=StringUtils.strip(pIds.toString(),"[]");
		List<Long> ptIds=commonDao.findByQuery("select distinct(p.planPickTicket.id) from PlanPickDetail p where p.id in ("+ptdIds+")");
		if(ptIds.size()>1){
			throw new BusinessException("只能选择一张计划取消审核"); 
		}else{
			Long pt_id=ptIds.get(0);
			List<PlanPickDetail> ds=this.commonDao.findByQuery("from PlanPickDetail d where d.planPickTicket.userID="+pt_id);
			PlanPickTicket ppt=null;
			for(PlanPickDetail d:ds){
				 ppt=d.getPlanPickTicket();
				 if(d.getAllocatedQuantity()>0){
					 throw new BusinessException("明细已出单，不能删除"); 
				 }
				 this.commonDao.delete(d);
			}
			if(ds.size()>0){
				this.commonDao.delete(ppt);
			}
			PlanPickTicket p=this.commonDao.get(PlanPickTicket.class, pt_id);
			p.setStatus("OPEN");
			this.commonDao.store(p);
			List<PlanPickDetail> pds=commonDao.findByQuery(" from PlanPickDetail p where p.planPickTicket.id="+p.getId()+" and p.orderQuantity>0");
			for(PlanPickDetail d:pds){
				d.setAllocatedQuantity(0);
				this.commonDao.store(d);
			}
		}
			
	}
	
	protected PlanPickTicket createPlanPick(String bonded, PlanPickTicket ppt){
		String hql="select max(b.id), sum(b.single*pptd.orderQuantity),max(pptd.description) "
				+ " from BomAccount b,PlanPickDetail pptd "
				+ " where pptd.planPickTicket.id="+ppt.getId()+" and b.bigItem.id=pptd.bigItem.id and b.outType='CKD成套' "
				+ " and b.strExtend1='"+ppt.getRelatedBill3()+"' and b.bonded='"+bonded+"'"
				+ " group by b.zzkw.id, b.item.id";
		
		List<Object[]> list1=commonDao.findByQuery(hql);
		if(list1.size()>0){
			PlanPickTicket p=EntityFactory.getEntity(PlanPickTicket.class);
			p.setWarehouse(WarehouseHolder.getWarehouse());
			p.setStatus(PickTicketStatus.OPEN);
			p.setBillType(ppt.getBillType());
			p.setCode(this.bussinessCodeManager.getCodeForYm("ZS",3));
			p.setRelatedBill1("指示单");
			p.setOrderDate(new Date());
			p.setCompany(ppt.getCompany());
			p.setUserID(ppt.getId());
			p.setOutType(ppt.getCode());
			//new_ppt.setOrderQuantity(ppt.getOrderQuantity());
			this.commonDao.store(p);
			int hh=1;
			for(Object[] obj:list1) {
				Long bId=(Long) obj[0];
				double orderQuantity=(Double) obj[1];
				String description=obj[2]==null?null:obj[2].toString();
				BomAccount ba=this.commonDao.get(BomAccount.class, bId);
				PlanPickDetail ppd=EntityFactory.getEntity(PlanPickDetail.class);
				ppd.setItem(ba.getItem());
				ppd.setZone(ba.getZone());
				ppd.setZone1(ba.getZone());
				ppd.setZone2(ba.getZone1());
				ppd.setZzkw(ba.getZzkw());
				ppd.setOrderQuantity(orderQuantity);
				ppd.setDescription(description);
				List<Pinfan> pf1=commonDao.findByQuery(" from Pinfan p where p.item.id="+ppd.getItem().getId()+" and p.zone.id="+ppd.getZone2().getId());
				if(pf1.size()>0) {
					Pinfan pf=pf1.get(0);
					ppd.setBonded(pf.getBonded());
					ppd.setSpecs(pf.getSpecs());
					ppd.setContent(pf.getContent());
					ppd.setHezi(pf.getHezi());
				}
				ppd.setPlanPickTicket(p);
				commonDao.store(ppd);
				p.setZone1(ba.getZone());
				p.setZone2(ba.getZone1());
				p.setOrderQuantity(p.getOrderQuantity()+orderQuantity);
				this.commonDao.store(p);
			}
			ppt.setStatus(PickTicketStatus.ALLOCATE);
			this.commonDao.store(ppt);
			return p;
		}else{
			return null;
		}
	}
	
	public void addpickTicketPlan_ctbh(Long planid,String rd,Long id, Double sum) {
		List<BillType> list2=commonDao.findByQuery(" from BillType b where b.code='手工成套' ");
		BillType bt=null;
		if(list2.size()>0) {
			bt=list2.get(0);
		}else {
			bt=commonDao.load(BillType.class, 6L);
		}
		addpickTicketPlan(planid, rd, id, sum, "手工成套",bt);
	}
	public void copypickTicketPlan_bh(Long planid,String rd,List<Long> ids) {
		List<BillType> list2=commonDao.findByQuery(" from BillType b where b.code='CKD单点' ");
		BillType bt=null;
		if(list2.size()>0) {
			bt=list2.get(0);
		}else {
			bt=commonDao.load(BillType.class, 6L);
		}
		List<PlanPickTicket> list1=commonDao.findByQuery(" from PlanPickTicket p where p.code='"+rd+"'");
		PlanPickTicket pt=null;
		if(list1.size()>0) {
			pt=list1.get(0);
		}else{
			pt=EntityFactory.getEntity(PlanPickTicket.class);
			pt.setWarehouse(WarehouseHolder.getWarehouse());
			pt.setStatus(PickTicketStatus.OPEN);
			pt.setCode(this.bussinessCodeManager.getCodeForYm("ZS",3));
			pt.setCompany(commonDao.load(Structure.class, 1002L));
			pt.setBillType(bt);
			pt.setRelatedBill1("日出库单");
			pt.setOrderDate(new Date());
			commonDao.store(pt);
		}
		for(Long id:ids){
			PlanPickDetail ppd_o=commonDao.get(PlanPickDetail.class, id);
			if(pt.getRelatedBill3()!=null&&!ppd_o.getProcedure().equals(pt.getRelatedBill3())){
				throw new BusinessException("和单据工位"+pt.getRelatedBill3()+"不一致！");
			}
			PlanPickDetail ppd=EntityFactory.getEntity(PlanPickDetail.class);
			ppd.setBigItem(ppd_o.getBigItem());
			ppd.setProcedure(ppd_o.getProcedure());
			ppd.setOrderQuantity(ppd_o.getOrderQuantity());
			ppd.setPlanPickTicket(pt);
			ppd.setModelName(ppd_o.getModelName());
			ppd.setDescription("复制");
			pt.setRelatedBill3(ppd_o.getProcedure());
			pt.setOrderQuantity(pt.getOrderQuantity()+ppd.getOrderQuantity());
			commonDao.store(ppd);
			System.out.println("---"+ppd.getId());
		}
	}
	public void addpickTicketPlan(Long planid,String rd,Long id, Double sum,String relatedBill1,BillType bt) {
		BomAccount b=this.load(BomAccount.class, id);
		List<PlanPickTicket> list1=commonDao.findByQuery(" from PlanPickTicket p where p.code='"+rd+"'");
		PlanPickTicket pt=null;
		if(list1.size()>0) {
			pt=list1.get(0);
		}
		if(pt==null) {
			pt=EntityFactory.getEntity(PlanPickTicket.class);
			pt.setWarehouse(WarehouseHolder.getWarehouse());
			pt.setStatus(PickTicketStatus.OPEN);
			pt.setCode(this.bussinessCodeManager.getCodeForYm("CT",3));
			pt.setCompany(commonDao.load(Structure.class, 1002L));
			pt.setBillType(bt);
			pt.setRelatedBill1(relatedBill1);
			pt.setRelatedBill2("");
			pt.setRelatedBill3("");
			pt.setOrderDate(new Date());
			if(relatedBill1.equals("指示单")){
				pt.setZone(commonDao.load(WarehouseArea.class, 37L));
				pt.setZone1(b.getZone());
				pt.setZone2(b.getZone1());
			}else{
				pt.setRelatedBill3(b.getStrExtend1());
			}
			commonDao.store(pt);
		}
		if(relatedBill1.equals("指示单")){
			List<BomAccount> bas=commonDao.findByQuery(" from BomAccount b where b.bigItem.id="+b.getBigItem().getId()+" and b.strExtend1='"+b.getStrExtend1()+"'");
			for(BomAccount ba:bas) {
				List<PlanPickDetail> list2=commonDao.findByQuery(" from PlanPickDetail p where p.item.id="+ba.getItem().getId()+" and p.planPickTicket.id="+pt.getId());
				PlanPickDetail ppd=EntityFactory.getEntity(PlanPickDetail.class);
				if(list2.size()>0) {
					ppd=list2.get(0);
				}
				double qty=Integer.parseInt(ba.getSingle());//需求数量
				ppd.setBigItem(ba.getBigItem());
				ppd.setQty2(sum);//成套数量
				ppd.setItem(ba.getItem());
				ppd.setProcedure(ba.getProphase());
				ppd.setOrderQuantity(ppd.getOrderQuantity()+sum*qty);
				ppd.setZone1(ba.getZone());
				ppd.setZone2(ba.getZone1());
				ppd.setZzkw(ba.getZzkw());
//				List<Pinfan> pf1=commonDao.findByQuery(" from Pinfan p where p.item.id="+pd.getItem().getId()+" and p.zone.id="+ppd.getZone2().getId());
//				if(pf1.size()>0) {
//					Pinfan pf=pf1.get(0);
//					ppd.setBonded(pf.getBonded());
//					ppd.setSpecs(pf.getSpecs());
//					ppd.setContent(pf.getContent());
//					ppd.setHezi(pf.getHezi());
//				}
				ppd.setPlanPickTicket(pt);
				pt.setOrderQuantity(ppd.getOrderQuantity());
				ppd.setSpecs(ba.getSpecs());
				ppd.setContent(ba.getContent());
				ppd.setBonded(ba.getBonded());
				ppd.setSingle(ba.getSingle());
				ppd.setDescription(ba.getStrExtend1());
				commonDao.store(ppd);
				System.out.println("---"+ppd.getId());
			}
		}else{
			if(!b.getStrExtend1().equals(pt.getRelatedBill3())){
				throw new BusinessException("和单据工位"+pt.getRelatedBill3()+"不一致！");
			}
			PlanPickDetail ppd=EntityFactory.getEntity(PlanPickDetail.class);
			ppd.setBigItem(b.getBigItem());
			ppd.setProcedure(b.getStrExtend1());
			ppd.setOrderQuantity(sum);
			ppd.setPlanPickTicket(pt);
			ppd.setModelName(b.getName());
			pt.setOrderQuantity(pt.getOrderQuantity()+ppd.getOrderQuantity());
			commonDao.store(ppd);
			System.out.println("---"+ppd.getId());
		}
		
		
		
		/*List<Long> ids=new ArrayList<Long>();
		ids.add(addpptid);
		appPlanAssembly(ids);*/
	}
	public void appPlanPickzd(List<Long> pickTicketIds) {
		PlanPickTicket pt=EntityFactory.getEntity(PlanPickTicket.class);
		for(Long pit:pickTicketIds) {
			PlanPickDetail ppt=commonDao.load(PlanPickDetail.class, pit);
		if(pt.isNew()) {
			pt.setWarehouse(WarehouseHolder.getWarehouse());
			pt.setStatus(PickTicketStatus.OPEN);
			pt.setCode(this.bussinessCodeManager.getCodeForYm("ZS",3));
			pt.setCompany(commonDao.load(Structure.class, 1002L));
			List<BillType> list2=commonDao.findByQuery(" from BillType b where b.code='其他出库单' ");
			BillType billType=null;
			if(list2.size()>0) {
				billType=list2.get(0);
				pt.setBillType(billType);
			}else {
				pt.setBillType(commonDao.load(BillType.class, 6L));
			}
			pt.setRelatedBill1("指示单");
			pt.setRelatedBill2("");
			pt.setRelatedBill3("");
			pt.setOrderDate(new Date());
			pt.setZone(commonDao.load(WarehouseArea.class, 37L));
			pt.setZone1(ppt.getZone1());
			pt.setZone2(ppt.getZone2());
			commonDao.store(pt);
		}
		List<BomAccount> boms=commonDao.findByQuery(" from BomAccount b where b.bigItem.id="+ppt.getBigItem().getId()
				+" and b.strExtend1='"+ppt.getProcedure()+"'");
		for(BomAccount b:boms) {
		PlanPickDetail ppd=EntityFactory.getEntity(PlanPickDetail.class);
	List<PlanPickDetail>	list2=commonDao.findByQuery("  from PlanPickDetail p where p.item.id="+b.getItem().getId()
				+" ");
	double qty=Integer.parseInt(b.getSingle());//需求数量
		ppd.setBigItem(b.getBigItem());
		ppd.setProcedure(b.getProphase());
		ppd.setOrderQuantity(ppd.getOrderQuantity()+qty*ppt.getOrderQuantity());
		ppd.setZone1(b.getZone());
		ppd.setZone2(b.getZone1());
		ppd.setPlanPickTicket(pt);
		
		ppd.setContent(b.getContent());
		ppd.setSpecs(b.getSpecs());
		ppd.setBonded(b.getBonded());
		ppd.setHezi("");//赫兹
		ppd.setSingle(b.getSingle());//单用
		commonDao.store(ppd);
		
		
		}
		}
		
	}
	
	@Override
	public void addpickTicketSCRJHPageer(Long id,double sum) {
		BomAccount b=this.load(BomAccount.class, id);
		double unallocateQty=0;
		PickTicket pt=EntityFactory.getEntity(PickTicket.class);
		PickTicket pts=EntityFactory.getEntity(PickTicket.class);
		pt.setWarehouse(WarehouseHolder.getWarehouse());
		pt.setStatus(PickTicketStatus.OPEN);
		pt.setCode(this.bussinessCodeManager.getCodeForYm("BH",3));
		pts.setWarehouse(pt.getWarehouse());
		pts.setStatus(pt.getStatus());
		pts.setCode(this.bussinessCodeManager.getCodeForYm("BH",3));
		List<Location> locs=commonDao.findByQuery(" from Location b where b.type='SHIP' and b.warehouse.id="+WarehouseHolder.getWarehouse().getId());
		if(locs.size()>0) {
			pt.setDock(locs.get(0));
		}
		pt.setCompany(commonDao.load(Structure.class, 1002L));
		List<BillType> list2=commonDao.findByQuery(" from BillType b where b.code='其他出库单' ");
		BillType billType=null;
		if(list2.size()>0) {
			billType=list2.get(0);
			pt.setBillType(billType);
		}else {
			pt.setBillType(commonDao.load(BillType.class, 6L));
		}
		pt.setUserTracking();
		pt.setRelatedBill1("其他出库单");
		pt.setRelatedBill2(null);
		pt.setRelatedBill3("");
		pt.setZone(commonDao.load(WarehouseArea.class, 37L));
		pts.setDock(pt.getDock());
		pts.setCompany(pts.getCompany());
		pts.setBillType(pt.getBillType());
		pts.setUserTracking();
		pts.setRelatedBill1(pt.getRelatedBill1());
		pts.setRelatedBill2(null);
		pts.setRelatedBill3(pt.getRelatedBill3());
		pts.setZone(pt.getZone());
		PlanPickDetail ppd=EntityFactory.getEntity(PlanPickDetail.class);
		ppd.setBigItem(b.getBigItem());
		PlanPickTicket pa=EntityFactory.getEntity(PlanPickTicket.class);
		pa.getRelatedBill2();
		pa.getRelatedBill3();
		
		appPlamAssemblys(pt,b,"课税","");
		appPlamAssemblys(pts,b,"保税","");
	}
	public void appPlamAssemblys(PickTicket pt,BomAccount bomAccount,String bonded,String meg){
		String hql=" from BomAccount b where b.bigItem.id="+bomAccount.getBigItem().getId()+
				"  and b.strExtend1='"+bomAccount.getStrExtend1()+"' and b.bonded='"+bonded+"'";
		List<BomAccount> list1=commonDao.findByQuery(hql);
		System.out.println(hql);
		if(list1.size()>0) {
			if(list1.size()==1) {
				commonDao.store(pt);
			}
			for(BomAccount b:list1) {
				List<PickTicketDetail> list3=new ArrayList<PickTicketDetail>();
				PickTicketDetail ptd=null;
				if(!pt.isNew()) {
					list3=commonDao.findByQuery(" from PickTicketDetail p where p.item.id="+b.getItem().getId()+" and p.pickTicket.id="+pt.getId());
				}
				if(list3.size()>0) {
					ptd=list3.get(0);
					System.out.println("重复SKU");
				}else {
					ptd=EntityFactory.getEntity(PickTicketDetail.class);
					List<PickTicketDetail> list4=commonDao.findByQuery(" from PickTicketDetail p where  p.pickTicket.id="+pt.getId());
					int hh=1;
					if(list4.size()>0) {
						hh=list4.size()+1;
					}
					ptd.setLineNumber(hh+"");
				}				
				double qty=Integer.parseInt(b.getSingle());//需求数量
				System.out.println("比"+b.getSingle()+"--数量"+qty);
				//需求数量
				ptd.setXqQty(ptd.getXqQty()+qty);//需要数量
				//纯需要数量
				ptd.setRejectQuantity(ptd.getRejectQuantity()+qty);
				//备货数量
				ptd.setOrderQuantity(ptd.getOrderQuantity()+qty);
				ptd.setOrderQtyOfMasterUnit(ptd.getOrderQtyOfMasterUnit()+qty);
				ptd.setZone1(b.getZone());
				ptd.setZone2(b.getZone1());
				System.out.println("需求"+ptd.getXqQty()+"--备货需求"+ptd.getOrderQuantity());
				pt.setOrderDate(new Date());
				pt.setQuantity3(pt.getQuantity3()+qty);
				pt.setOrderQuantity(pt.getOrderQuantity()+qty);
				pt.setBOLQuantity(pt.getBOLQuantity()+qty);
				pt.setCompany(b.getItem().getCompany());
				pt.setZone1(b.getZone());
				pt.setZone2(b.getZone1());
				ptd.setPickTicket(pt);
				ptd.setItem(b.getItem());
				ptd.setSOI(b.getProphase());
				ptd.setSpecs(b.getSpecs());
				ptd.setSingle(b.getSingle());
				ptd.setBonded(b.getBonded());
				ptd.setContent(b.getContent());
				String hql2=" from  Pinfan p where p.item.id="+b.getItem().getId();
				if(b.getBonded()!=null&&!b.getBonded().equals("")) {
					hql2=hql2+" and p.bonded='"+b.getBonded()+"'";
				}else {
					hql2=hql2+" and p.bonded is null";
				}
				List<Pinfan> fan1=commonDao.findByQuery(hql2);
				if(fan1.size()>0) {
					Pinfan f=fan1.get(0);
					ptd.setHezi(f.getHezi());
					ptd.setQuantity(f.getQuantity());
				}		
				commonDao.store(pt);
				commonDao.store(ptd);
			}
			shuapick(pt.getId());
		}else {
			meg=meg+"无成品BOM清单!";
		}
		addlog("","生成备货操作","生产顺序计划",meg);//日志
	
	}
	public void addInstructions(String pickCode,Long billTypeid,
			PlanPickDetail pd) {
		List<PlanPickTicket> list=new ArrayList<PlanPickTicket>();
		if(pd.getZone1()==null||pd.getZone2()==null){
			throw new BusinessException("库区必填");
		}
		
		if(pickCode!=null&&!pickCode.equals("")) {
			list=commonDao.findByQuery(" from  PlanPickTicket p where p.code='"+pickCode+"'");
		}
			PlanPickTicket p=null;
			BillType bill=commonDao.load(BillType.class, billTypeid);
			if(list.size()>0) {
				p=list.get(0);
				if(!p.getZone1().getId().equals(pd.getZone1().getId())){
					throw new BusinessException("指示单收货仓库需保持一致");
				}
				if(!p.getZone2().getId().equals(pd.getZone2().getId())){
					throw new BusinessException("指示单出货仓库需保持一致");
				}
			}else {
				p=EntityFactory.getEntity(PlanPickTicket.class);
				p.setWarehouse(WarehouseHolder.getWarehouse());
				p.setStatus(PickTicketStatus.OPEN);
				p.setBillType(bill);
				if(pickCode!=null&&!pickCode.equals("")) {
					p.setCode(pickCode);
				}else {
					p.setCode(this.bussinessCodeManager.getCodeForYm("ZS",3));
				}
				p.setRelatedBill1("指示单");
                p.setZone1(pd.getZone1());
                p.setZone2(pd.getZone2());
                p.setOrderDate(new Date());
				if(p.getCompany()==null) {
					p.setCompany(commonDao.load(Structure.class, 1002L));
				}
			}
			commonDao.store(p);
			List<Pinfan> pf1=commonDao.findByQuery(" from Pinfan p where p.item.id="+pd.getItem().getId()+" and p.zone.id="+pd.getZone2().getId());
			if(pf1.size()>0) {
				Pinfan pf=pf1.get(0);
				pd.setBonded(pf.getBonded());
				pd.setSpecs(pf.getSpecs());
				pd.setContent(pf.getContent());
				pd.setHezi(pf.getHezi());
			}
			pd.setPlanPickTicket(p);
			commonDao.store(pd);
//		}else {
//			throw new BusinessException("指示单号不能为空!");
//		}
	}
	
	public void deletePlanAll(List<Long> pickIds) {
		for(Long id:pickIds) {
			
			commonDao.delete(commonDao.load(PlanPickDetail.class,id));
			
		}
	}
	
	public void appzs(List<Long> pickIds) {
		System.out.println("1");
		PickTicket pt=EntityFactory.getEntity(PickTicket.class);
		List<Long> ptdIds=new ArrayList<Long>();
		for(Long id:pickIds) {
			PlanPickDetail	pdd=commonDao.load(PlanPickDetail.class,id);
			PlanPickTicket p=commonDao.load(PlanPickTicket.class, pdd.getPlanPickTicket().getId());
			System.out.println("2");
			List<PlanPickDetail> list1=commonDao.findByQuery(" from PlanPickDetail  p where p.orderQuantity-p.allocatedQuantity>0 and p.planPickTicket.id="+p.getId());
			if(list1.size()<=0){
				return;
			}
			if(p!=null) {
				if(pt.isNew()) {
				pt.setCode(bussinessCodeManager.getCodeForYm("BH",3));
				
				pt.setWarehouse(WarehouseHolder.getWarehouse());
				pt.setStatus(PickTicketStatus.OPEN);
				if(pt.getDock()==null) {
					List<Location> locs=commonDao.findByQuery(" from Location b where b.type='SHIP' and b.warehouse.id="+WarehouseHolder.getWarehouse().getId());
					Location l =locs.get(0);
					 pt.setDock(l);
				}
				pt.setRelatedBill3(p.getCode());
				pt.setBillType(p.getBillType());
				pt.setRelatedBill1("成套出库");
				pt.setOrderDate(new Date());
				pt.setCompany(commonDao.load(Structure.class, 1002L));
				pt.setUserTracking();
				pt.setSourceId(p.getId()+"");
				pt.setShipDateStart(new Date());
				this.commonDao.store(pt);
				}
				System.out.println("3");
					int i=1;
					for(PlanPickDetail pd:list1) {
					Item item=commonDao.load(Item.class, pd.getItem().getId()); 
					System.out.println("手工指示明细"+pd.getId());
					List<Double> invs=commonDao.findByQuery("select COALESCE(sum(i.quantity-i.queuedQuantity),0) "
							+ "from Inventory i where i.itemKey.item.id="+item.getId()
													+" and i.zone.id="+pd.getZone2().getId() +" and i.location.type!='SHIP'");
					if(invs.size()>0) {
						PickTicketDetail ptd=EntityFactory.getEntity(PickTicketDetail.class);
						ptd.setPickTicket(pt);
						ptd.setItem(pd.getItem());
						ptd.setZone1(pd.getZone1());
						ptd.setZone(pd.getZone2());
						ptd.setZone2(pd.getZone2());
						double inv_qty=invs.get(0);
						if(inv_qty>0) {
						double wchuk=pd.getOrderQuantity()-pd.getAllocatedQuantity();
						double bc_ck=0;
						if(wchuk>inv_qty){
							bc_ck=inv_qty;
						}else{
							bc_ck=wchuk;
						}
						ptd.setQuantity(bc_ck);
						ptd.setOrderQuantity(bc_ck);
						ptd.setOrderQtyOfMasterUnit(bc_ck);
						pd.setAllocatedQuantity(pd.getAllocatedQuantity()+bc_ck);
						pd.setQty1(bc_ck);
						pt.setOrderQuantity(bc_ck+pt.getOrderQuantity());
						ptd.setApplyDocDetailId(pd.getId());
						ptd.setLineNumber(++i+"");
						p.setStatus("ACTIVE");
						p.setPackType2(pt.getCode());
						commonDao.store(p);
						commonDao.store(ptd);
						System.out.println("ptd"+ptd.getId());
						ptdIds.add(ptd.getId());
						pt.getPickTicketDetails().add(ptd);
						pt.setZone1(pd.getZone1());
						pt.setZone(pd.getZone());
						pt.setZone2(pd.getZone2());
						commonDao.store(pt);
						commonDao.store(pd);
						System.out.println("pd出单数量"+pd.getAllocatedQuantity());
						}
					}
					
				}
					if(pt!=null) {
						List<Long> ids=new ArrayList<Long>();
						ids.add(pt.getId());
						activeKAMSAll(ids);
						
					}
					if(pt.getOrderQuantity()==0) {
						commonDao.delete(pt);
					}
					for(Long ptdId:ptdIds){
						PickTicketDetail d=this.commonDao.get(PickTicketDetail.class, ptdId);
						d.setOrderQuantity(d.getOrderQtyOfMasterUnit());
						d.setPickTicket(pt);
						this.commonDao.store(d);
					}
					
			}
		}
	}
	public void refPlanPick(List<Long> ids) {
		for(Long id:ids){
			refPlanPick(id,null) ;
		}
	}
	
	public void refPlanPick(Long id,Long itemId) {
		PickTicket pt =commonDao.load(PickTicket.class, id);
		if(pt!=null) {
			//刷新出库明细上的数量
			List<PickTicketDetail> PickTicketDetails =commonDao.findByQuery(" from PickTicketDetail p where p.pickTicket.id="+pt.getId());
			if(PickTicketDetails.size()>0) {
				double orderQuantity=0;
				double allocatedQuantity=0;	
				for(PickTicketDetail ptd:PickTicketDetails) {
					List<Task> ts=this.commonDao.findByQuery("from Task t where t.pickTicketDetail.id="+ptd.getId());
					double allocatedQuantity_d=0;
					for(Task t:ts){
						allocatedQuantity_d+=t.getPlanQuantity();
					}
					ptd.setAllocatedQuantity(allocatedQuantity_d);
					this.commonDao.store(ptd);
					orderQuantity+=ptd.getOrderQuantity();
					allocatedQuantity+=ptd.getAllocatedQuantity();
				}
				if(orderQuantity-allocatedQuantity>0){
					commonDao.store(pt);
				}
			}
			if(pt.getSourceId()!=null){
				List<Long> ptIds=commonDao.findByQuery("select distinct(d.planPickTicket.id) from PlanPickDetail d where d.id in "
						+ "( select p.applyDocDetailId from  PickTicketDetail p where p.pickTicket.id ="+id+")");
				String ids=StringUtils.strip(ptIds.toString(),"[]");
				if(ids!=null&&ids.length()>2){
					String hqlp=" from PlanPickDetail p where p.planPickTicket.id in("+ids+")";
					if(itemId!=null){
						hqlp+=" and p.item.id="+itemId;
					}
					List<PlanPickDetail> ppds =commonDao.findByQuery(hqlp);
					if(ppds.size()>0) {
						for(PlanPickDetail ppd:ppds) {
							List<Object> object=commonDao.findByQuery("select COALESCE(sum(p.orderQuantity),0),COALESCE(sum(p.allocatedQuantity),0),"
									+ "COALESCE(sum(p.pickedQuantity),0),COALESCE(sum(p.shippedQuantity),0) "
									+ "from PickTicketDetail p where p.applyDocDetailId="+ppd.getId());
							if(object.size()>0) {
								Object[] obj=(Object[])object.get(0);
								ppd.setAllocatedQuantity(Double.parseDouble(obj[1].toString()));
								ppd.setPickedQuantity(Double.parseDouble(obj[2].toString()));
								ppd.setShippedQuantity(Double.parseDouble(obj[3].toString()));
								commonDao.store(ppd);
							}
						}
					}
				}
			}
			
			
		}
	}
	
	public  void deleteProductionPlan(Long id,String tsr,double qty,String procedure) {
		List<ProductionPlan> pps=commonDao.findByQuery(" from  ProductionPlan p where p.modelNo='"+tsr+"' and p.procedure='"+procedure+"'");
		String str1=null;
		String str2=null;
		if(pps.size()>0&&qty>0) {
			ProductionPlan p=pps.get(0);
			List<ProductionPlan> ppts=commonDao.findByQuery(" from  ProductionPlan p where p.strExtend1='未消耗' "
					+ " and p.longExtend1>="+p.getLongExtend1()+" and p.procedure='"+p.getProcedure()+"' order by p.longExtend1 ");
			if(ppts.size()>0) {
				List<Long> ids=new ArrayList<Long>();
				for(int i=0;i<ppts.size();i++) {
					ProductionPlan pp=ppts.get(i);
					if(qty<=i) {
						break;
					}
					if(i==0){
						str1=pp.getModelNo();
					}
					ids.add(pp.getId());
					str2=pp.getModelNo();
				}
//				Object[] hyids=ids.toArray();
				if(ids.size()>0){
					String hyids=StringUtils.strip(ids.toString(),"[]");
					List<ProductionPlan> hys=commonDao.findByQuery(" from  ProductionPlan p where p.id in ("+hyids+") "
							+ " order by p.bigItem.code asc,p.longExtend1 asc");
					String oldCode="";
					SpareParts sp=null;
					for(ProductionPlan hy:hys){
						if(!hy.getBigItem().getCode().equals(oldCode)){
							sp=createSpareParts(hy, hy.getLongExtend1()+"", hy.getLongExtend1()+"", 1);
							sp.setDescription("生产计划耗用");
						}else{
							sp.setStr2(hy.getLongExtend1()+"");
							sp.setOrderQuantity(sp.getOrderQuantity()+1);
						}
						oldCode=hy.getBigItem().getCode();
						this.commonDao.store(sp);
						hy.setSpId(sp.getId());
						this.commonDao.store(hy);
						oldCode=hy.getBigItem().getCode();
						System.out.println(hy.getBigItem().getCode()+"====="+hy.getLongExtend1());
					}
				}
				saveProductionPlan(ids, "已耗用",new Long("1"));
			}
			
		}else {
			System.out.println("无耗用数量");
		}
	}
	//耗用线边库存
	public void hyInv(List<Long> ids) {
//		List<Location> ls=this.commonDao.findByQuery("from Location l where l.code='"+SysCode.XB_LOC+"'");
//		if(ls.size()<=0){
//			throw new BusinessException("请维护代码是"+SysCode.XB_LOC+"的久保田线边库位");
//		}
//		Location xb_loc=ls.get(0);
		String hyId=StringUtils.strip(ids.toString(),"[]");
		List<String> gwCode=commonDao.findByQuery("select code from SpareParts p where  p.status='未消耗' and p.id in ("+hyId+") group by p.code");
		for(String code:gwCode){
			List<SpareParts> sps=commonDao.findByQuery("from SpareParts p where  p.status='未消耗' and p.code='"+code+"'");
			for(SpareParts sp:sps){
				hySpareParts(sp);
			}
		}
	}
	public void hySpareParts(SpareParts sp){
		if(sp.getStatus().equals("未消耗")) {
			List<BomAccount>	bas=commonDao.findByQuery(" from BomAccount b where b.bigItem.id="+sp.getBigItem().getId()
			+" and b.strExtend1='"+sp.getCode()+"' ");
			if(bas.size()<=0){
				throw new BusinessException(sp.getBigItem().getCode()+"请维护BOM清单");
			}
			for(BomAccount b:bas) {
				WarehouseArea zone=b.getZone();
				if(zone.getHckw()==null){
					throw new BusinessException("维护库区对应线边待投料库位");
				}
				Location xb_loc=zone.getHckw();
				System.out.println("品番"+b.getItem().getCode());
				if(b.getSingle()!=null&&!b.getSingle().equals("")) {
					String hql=" from Inventory i where i.barCode='XB' and i.zone.id="+b.getZone().getId()
							+" and i.itemKey.item.id="+b.getItem().getId()+" and i.zzkw.id="+xb_loc.getId();
//					if(b.getSpecs()!=null&&!b.getSpecs().equals("")) {
//						hql+=" and i.itemKey.pinfan.specs='"+b.getSpecs()+"' ";
//					}
//					if(b.getContent()!=null&&!b.getContent().equals("")) {
//						hql+=" and i.itemKey.pinfan.content='"+b.getContent()+"' ";
//					}
//					if(b.getBonded()!=null&&!b.getBonded().equals("")) {
//						hql+=" and i.itemKey.pinfan.bonded='"+b.getBonded()+"' ";
//					}
					hql+=" order by i.id ";
					List<Inventory> invs=commonDao.findByQuery(hql);
					if(invs.size()>0) {
						Inventory inv=invs.get(0);
						double qty=Double.parseDouble(b.getSingle())*sp.getOrderQuantity();
//						for(Inventory inv:invs) {
						inv.setQtyOfMasterPack(inv.getQtyOfMasterPack()-qty);	
						inv.setQuantity(inv.getQtyOfMasterPack());
						inv.setLocation(xb_loc);
						commonDao.store(inv);
						//inv.getItemKey().getPinfan().getLocation();
						InventoryLog log2 = new InventoryLog(InventoryLogType.PROCESS_DOWN, -1, sp.getBigItem().getCode(), null, xb_loc, null, inv.getItemKey(), 
							new Date(), sp.getBigItem().getCode(), qty, null, null, inv.getId(), sp.getOrderQuantity()+"套"+sp.getId(),inv.getZone());
						commonDao.store(log2);
//						}
					}else {
						//生成库存记录
						Inventory inv=EntityFactory.getEntity(Inventory.class);
						double qty=Double.parseDouble(b.getSingle())*sp.getOrderQuantity();
//						for(Inventory inv:invs) {
						inv.setQtyOfMasterPack(inv.getQtyOfMasterPack()-qty);	
						inv.setQuantity(inv.getQtyOfMasterPack());
						inv.setLocation(xb_loc);
						//判断税别
						String pf_hql="from Pinfan f where f.item.id="+b.getItem().getId();
						if(b.getBonded().equals("课税")){
							pf_hql+=" and f.zone.code='"+SysCode.W_KS+"'";;
						}else if(b.getBonded().equals("保税")){
							pf_hql+=" and f.zone.code='"+SysCode.W_BS+"'";
						}
						List<Pinfan> pfs=this.commonDao.findByQuery(pf_hql);
						if(pfs.size()<=0){
							throw new BusinessException(b.getItem().getCode()+"未找到品番关联信息");
						}
						ItemKey key = this.itemManager.getItemKey(new ItemKey("",
								b.getItem(), pfs.get(0)), Boolean.TRUE,null);
						inv.setItemKey(key);
						inv.setZone(b.getZone());
						inv.setBarCode("XB");
						commonDao.store(inv);
						//inv.getItemKey().getPinfan().getLocation();
						InventoryLog log2 = new InventoryLog(InventoryLogType.PROCESS_DOWN, -1, sp.getBigItem().getCode(), null, xb_loc, null, inv.getItemKey(), 
							new Date(), sp.getBigItem().getCode(), qty, null, null, inv.getId(), sp.getOrderQuantity()+"套"+sp.getId(),inv.getZone());
						commonDao.store(log2);
						//System.out.println("无库存记录");
					}
				}else {
					throw new BusinessException(sp.getBigItem().getCode()+"请维护BOM清单");
				}
			}
			sp.setStatus("已耗用");
			this.commonDao.store(sp);
		}
	}
	//生成零件表
	public SpareParts createSpareParts(ProductionPlan p,String str1,String str2,int size) {
		//写到零件表
		SpareParts sp=EntityFactory.getEntity(SpareParts.class);
		sp.setCode(p.getProcedure());//工位
		sp.setAllocateTime(new Date());//下线日期
		sp.setName(p.getBigItem().getName());//型式名
		sp.setModelType(p.getBigItem().getCode());//型号品番
		sp.setOrderQuantity(size);//数量
		sp.setUserDate(new Date());
		sp.setUserName(UserHolder.getUser().getName());
		sp.setStr1(str1);//开始机号
		sp.setStr2(str2);//终止机号
		sp.setBigItem(p.getBigItem());
		sp.setStatus("未消耗");
		this.commonDao.store(sp);
		return sp;
	}

	@Override
	public void addSpareParts(SpareParts spareParts) {
		if(spareParts.isNew()){
			spareParts.setStatus("未消耗");
			spareParts.setUserName(UserHolder.getUser().getName());
			spareParts.setUserDate(new Date());
			commonDao.store(spareParts);
		}else{
			commonDao.store(spareParts);
		}
	}

	@Override
	public void copySpareParts(List<Long> ids) {
		for(Long id:ids){
			SpareParts spareParts= this.load(SpareParts.class, id);
			SpareParts newspareParts=EntityFactory.getEntity(SpareParts.class);
			newspareParts.setCode(spareParts.getCode());
			newspareParts.setBigItem(spareParts.getBigItem());
			newspareParts.setName(spareParts.getName());
			newspareParts.setModelType(spareParts.getName());
			newspareParts.setOrderQuantity(spareParts.getOrderQuantity());
			newspareParts.setAllocateTime(spareParts.getAllocateTime());
			newspareParts.setUserName(UserHolder.getUser().getLoginName());
			newspareParts.setUserDate(new Date());
			newspareParts.setStatus("未消耗");
			newspareParts.setStr1(spareParts.getStr1());
			newspareParts.setStr2(spareParts.getStr2());
			newspareParts.setDescription("复制");
			commonDao.store(newspareParts);
		}
	}

	@Override
	public void deletSpareParts(List<Long> ids) {
		for(Long id:ids){
			SpareParts spareParts= this.load(SpareParts.class, id);
			if(spareParts.getStatus().equals("未消耗")){
				List<ProductionPlan> pps=this.commonDao.findByQuery("from ProductionPlan p where p.spId="+id);
				for(ProductionPlan p:pps){
					p.setSpId(null);
					p.setHyTime(null);
					p.setStrExtend1("未消耗");
					this.commonDao.store(p);
				}
				String objectIds=spareParts.getStr5();
				commonDao.delete(spareParts);
				
				if(spareParts.getDescription().equals("下线数据")){
					List<OfflineData> OfflineDatas=this.commonDao.findByQuery("from OfflineData p where p.hyId1="+id);
//					if(objectIds!=null&&objectIds.length()>0){
//						List<OfflineData> OfflineDatas=this.commonDao.findByQuery(" from OfflineData o where o.id in ("+objectIds+") ");
						for(OfflineData od:OfflineDatas){
							od.setStatus("未消耗");
							od.setHyId1(null);
							od.setHyDate(null);
							od.setHyBy(null);
							commonDao.store(od);
						}
//					}
					
				}else if(spareParts.getDescription().equals("吊装数据")){
//					if(objectIds!=null&&objectIds.length()>0){
						if(spareParts.getCode().equals("LDB")){
							List<HoistingData> HoistingDatas=this.commonDao.findByQuery("from HoistingData p where p.hyId2="+id);
							for(HoistingData hd:HoistingDatas){
								hd.setStatus("未消耗");
								hd.setHyId2(null);
								hd.setHyDate(null);
								hd.setHyBy(null);
								commonDao.store(hd);
							}
						}else{
							List<HoistingData> HoistingDatas=this.commonDao.findByQuery("from HoistingData p where p.hyId1="+id);
							for(HoistingData hd:HoistingDatas){
								hd.setStatus("未消耗");
								hd.setHyId1(null);
								hd.setHyDate(null);
								hd.setHyBy(null);
								commonDao.store(hd);
							}
						}
						
//						List<HoistingData> HoistingDatas=this.commonDao.findByQuery(" from HoistingData h where h.id in ("+objectIds+") ");
						
//					}
				}
			}else{
				throw new BusinessException("删除失败,状态错误！");
			}
		}
	}

	@Override
	public double getInvQtyMap(Map map) {
		double invQty=0;
		Long id=(Long) map.get("pickTicketDetail.id");
		if(id>0){
			PickTicketDetail ptd=this.load(PickTicketDetail.class, id);
			DesignList dl=ptd.getDesignList();
			if(dl!=null && dl.getNewItem()!=null){
				invQty= (Double) commonDao.findByQuery("select COALESCE(sum(inv.quantity-inv.queuedQuantity),0) "
						+ "from Inventory inv where inv.itemKey.item.code='"+dl.getNewItemCode()+"'"
						+ " and inv.zone.id="+ptd.getZone2().getId()
						+" and inv.quantity>0 ").get(0);
			}
		}
		return invQty;
	}

	@Override
	public double getQuantityMap(Map map) {
		double quantity=0;
		Long id=(Long) map.get("pickTicketDetail.id");
		if(id>0){
			PickTicketDetail ptd=this.load(PickTicketDetail.class, id);
			quantity=ptd.getOrderQuantity()-ptd.getAllocatedQuantity();
		}	
		return quantity;
	}

	@Override
	public void designList(long pickTicketDetailId, double qty) {
		if(pickTicketDetailId>0){
			PickTicketDetail ptd=this.load(PickTicketDetail.class, pickTicketDetailId);
			PickTicket pickTicket =ptd.getPickTicket();
			//旧品番-根据当前明细备货需求数量-设变数量
			Item oldItem=this.load(Item.class, ptd.getItem().getId());
			ptd.setOrderQuantity(ptd.getOrderQuantity()-qty);
			ptd.setOrderQtyOfMasterUnit(ptd.getOrderQuantity());
			commonDao.store(ptd);
			//新品番-根据设变数量分配库存
			Item newItem=null;
			List<Item> newItems=this.commonDao.findByQuery("from Item it where it.code='"+ptd.getDesignList().getNewItemCode()+"'");
			if(newItems.size()<=0){
				throw new BusinessException("新品番未维护");
			}else{
				newItem=newItems.get(0);
			}
			//this.load(Item.class, ptd.getDesignList().getNewItem().getId());
			PickTicketDetail newptd=EntityFactory.getEntity(PickTicketDetail.class);
			newptd.setItem(newItem);
			newptd.setOrderQuantity(qty);
			newptd.setOrderQtyOfMasterUnit(qty);
			newptd.setPickTicket(pickTicket);
			commonDao.store(newptd);
			//分配。
			List<Inventory> Inventorys =  commonDao.findByQuery("FROM Inventory i WHERE  i.itemKey.item.id=:code and i.zone.id=:zone_id and i.quantity>0  and ( i.location.type!='SHIP')",
					new String[] { "code","zone_id"},new Object[] {newItem.getId(),ptd.getZone2().getId()});
			double unallocateQty=newptd.getUnallocateQuantity();
			if(unallocateQty<=0) {
				return;
			}
			double quantity=unallocateQty;
			for(Inventory i:Inventorys){
				ItemKey itemKey=i.getItemKey();
				double b=i.getQtyOfMasterPack()-i.getQueuedQuantity();
				if(unallocateQty>=0) {
					if (quantity > i.getAvaliableQuantity()) {
						quantity = i.getAvaliableQuantity();
					}
					if (quantity > unallocateQty) {
						quantity = unallocateQty;
					}
					unallocateQty -= quantity;
					pickTicket.allocate(null,newptd, i, quantity);
					i.allocate(quantity, null, null);
					newptd.setItemKey(itemKey);
					newptd.setSpecs(itemKey.getPinfan().getSpecs());
					newptd.setContent(itemKey.getPinfan().getContent());
					newptd.setBonded(itemKey.getPinfan().getBonded());
					newptd.setQuantity(itemKey.getPinfan().getQuantity());
					newptd.setHezi(itemKey.getPinfan().getHezi());
					newptd.setXqQty(quantity);
					newptd.setPf(itemKey.getPinfan());
					newptd.setZone(ptd.getZone());
					newptd.setZone1(ptd.getZone1());
					newptd.setZone2(ptd.getZone2());
					//制造库位
					List<BomAccount> bls=this.commonDao.findByQuery("from BomAccount l where l.item.id="+itemKey.getItem().getId()+" and l.strExtend1='"+pickTicket.getRelatedBill3()+"'");
					if(bls.size()<=0){
						throw new BusinessException(itemKey.getItem().getCode()+"未找到制造库位");
					}
					newptd.setZzkw(bls.get(0).getZzkw());
					commonDao.store(newptd);
					refreshPickWeightInfo(pickTicket.getId());
				}else {
					  continue;
				}
			}
			
		}
	}

	@Override
	public boolean sheChangeColor(long pickTicketId) {
		boolean change=false;
		Session session = ((HibernateDaoSupport)this.commonDao).getSessionFactory().openSession();
		try {
			String sql="select ptd.id from pick_ticket_detail ptd "
			+ " left join pick_ticket pt on pt.id=ptd.PICK_TICKET_ID "
			+ " where 1=1 "
			+ " and pt.id="+pickTicketId+" "
			+ " and ptd.designList_ID>0 "
			+ " and pt.status='ALLOCATE' ";
			Query   query   =   session.createSQLQuery(sql); 
			if(query.list().size()>0){
				change=true;
			}else{
				PickTicketDetail ptd =this.load(PickTicketDetail.class, pickTicketId);
				if(ptd!=null&&ptd.getDesignList()!=null){
					change=true;
				}
			}
		} catch (Exception e) {
			e.getMessage();
		}finally{
			session.close();
		}
		return change;
	}
	//查找库存存不存在
	public Inventory findInventory(ItemKey itemkey,WarehouseArea zone,Location location,String billCode,String type){
		//type 1备货，2备货确认-1，3备货确认+1，4备货-1，5备货+1，5发运，6取消发运
		String hql="from Inventory inv where inv.itemKey.id="+itemkey.getId()+" "
				+ " and inv.zone.id="+zone.getId();
		//type 1.VMI正常入库，2.KAMS入库，3.线边入库，4.备货入库
		if(zone.getCode().indexOf("-SL")>0) {
			hql+=" and inv.barCode='XB' ";
			//线边固定放在线边库位,目前数据没有放，等刷新
			//hql+=" and inv.location.code='"+SysCode.XB_LOC+"'";
		}
		//备货固定放在备货库位
		if(type.equals(SysCode.CK_FP2)){
			if(location!=null){
				hql+=" and inv.location.id="+location.getId()+" and inv.location.type!='SHIP'";
			}
		}else if(type.equals(SysCode.CK_TH1)){
			if(location!=null){
				hql+=" and inv.location.id="+location.getId()+" and inv.location.type='SHIP'";
			}
		}else if(type.equals(SysCode.CK_TH2)){
			if(location!=null){
				hql+=" and inv.location.id="+location.getId()+" and inv.location.type!='SHIP'";
			}
		}else if(type.equals(SysCode.CK_BH1)){
			if(location!=null){
				hql+=" and inv.location.id="+location.getId()+" and inv.location.type!='SHIP' and inv.quantity>0";// and inv.queuedQuantity>0 ";
			}
		}else if(type.equals(SysCode.CK_BH2)){
			if(location!=null){
				hql+=" and inv.location.id="+location.getId()+" and inv.location.type='SHIP'";
			}
		}else if(type.equals(SysCode.CK_FY1)){
			if(location!=null){
				hql+=" and inv.location.id="+location.getId()+" and inv.location.type='SHIP'";
			}else{
				hql+=" and inv.location.type='SHIP'";
			}
		}else if(type.equals(SysCode.CK_FY2)){
			if(location!=null){
				hql+=" and inv.location.id="+location.getId()+" and inv.location.type!='SHIP'";
			}else{
				hql+=" and inv.location.type!='SHIP'";
			}
		}else if(type.equals(SysCode.RK_SH1)){
			if(location!=null){
				hql+=" and inv.location.id="+location.getId()+" and inv.location.type!='SHIP'";
			}
		}else if(type.equals(SysCode.RK_SH2)){
			if(location!=null){
				hql+=" and inv.location.id="+location.getId()+" and inv.location.type!='SHIP'";
			}
		}
		List<Inventory> invs=this.commonDao.findByQuery(hql);
		if(invs.size()>0){
			Inventory inv=invs.get(0);
			if(invs.get(0).getLocation()==null){
				inv.setLocation(location);
				this.commonDao.store(inv);
			}
			return inv;
		}else{
			if(type.equals(SysCode.RK_SH1)){
				Inventory dbInv=EntityFactory.getEntity(Inventory.class);
				dbInv.setLocation(location);
				dbInv.setItemKey(itemkey);
				dbInv.setZone(zone);
				dbInv.setZzkw(this.commonDao.get(Location.class, new Long("5124")));
				if(zone.getCode().indexOf("-SL")>0) {
					dbInv.setBarCode("XB");
				}
				itemkey.getInventories().add(dbInv);
				this.commonDao.store(dbInv);
				return dbInv;
			}else{
				return null;
			}
		}
	}
	
	public InventoryLog addInventoryLog(String logType, int incOrDec, WarehouseArea zone,Location location,String relatedBill, 
			 ItemKey itemKey,  double occurQuantity, String LP,String operator,Long referenceLog, String description,String bhr,String cph) {
		InventoryLog log=EntityFactory.getEntity(InventoryLog.class);
		log.setWarehouse(zone.getWarehouse());
		log.setZone(zone);
		log.setLogType(logType);
		log.setIncOrDec(incOrDec);
		log.setRelatedBill(relatedBill);
		log.setLocation(location);
		log.setItemKey(itemKey);
		log.setOccurQuantity(occurQuantity);
		log.setTph(LP);
		log.setBhr(bhr);
		log.setCph(cph);
		log.setReferenceLog(referenceLog);
		log.setOperator(operator);
		log.setOccurTime(new Date());
		log.setDescription(description);
		this.commonDao.store(log);
		return log;
	}
	
	private void addTaskLog(Task t,ItemKey itemKey, Location srcLoc, String srcLp, Location dstLoc, String barcode, double quantity, Worker worker,String oper) {
		TaskLog tasklog = EntityFactory.getEntity(TaskLog.class);
		tasklog.setTask(t);
		tasklog.setItemKey(itemKey);
		tasklog.setDstLoc(dstLoc);
		tasklog.setSrcLoc(srcLoc);
		tasklog.setSrcLPCode(srcLp);
		tasklog.setBarCode(barcode);
		tasklog.setMovedQuantity(quantity);
		tasklog.setWorker(worker);
		tasklog.setRecordTime(new Date());
		tasklog.setSOI(oper);
		tasklog.setDescription("移位确认");
//		if (t.getLogs() == null) {
//			t.setLogs(new HashSet<TaskLog>());
//		}
		this.commonDao.store(tasklog);
//		t.getLogs().add(tasklog);
		t.setMovedQuantityMU(t.getMovedQuantityMU()+quantity);
		this.commonDao.store(t);
	}
	
	
	
}