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

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;


import org.apache.commons.lang.StringUtils;
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;
import com.dev.swms.server.model.abstractEntity.AutoProduction;
import com.dev.swms.server.model.abstractEntity.AutoProductionLog;
import com.dev.swms.server.model.abstractEntity.BigItem;
import com.dev.swms.server.model.abstractEntity.BomAccount;
import com.dev.swms.server.model.abstractEntity.DesignList;
import com.dev.swms.server.model.abstractEntity.HoistingData;
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.BillType;
import com.dev.swms.server.model.base.Item;
import com.dev.swms.server.model.base.ItemKey;
import com.dev.swms.server.model.base.Location;
import com.dev.swms.server.model.base.Structure;
import com.dev.swms.server.model.base.SysCode;
import com.dev.swms.server.model.base.WarehouseArea;
import com.dev.swms.server.model.count.CommonCode;
import com.dev.swms.server.model.count.Consumables;
import com.dev.swms.server.model.count.Contract;
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.Stock;
import com.dev.swms.server.model.inventory.Task;
import com.dev.swms.server.model.inventory.TaskLog;
import com.dev.swms.server.model.shipping.BOL;
import com.dev.swms.server.model.shipping.MasterBOL;
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.PrintXppRecord;
import com.dev.swms.server.model.shipping.RkEwmRecord;
import com.dev.swms.server.service.base.ItemManager;
import com.dev.swms.server.service.count.CommonCodeManager;
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.PickKamsManager;
import com.dev.swms.server.service.task.AllocateManager;
import com.dev.swms.server.utils.DateUtil;
import com.dev.swms.server.utils.DateUtils;
import com.dev.swms.server.web.filter.WarehouseHolder;

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



public class DefaultPickKamsManager extends DefaultBaseManager implements PickKamsManager{
	
	protected final ItemManager itemManager;
	protected final InventoryManager inventoryManager;
	protected final AutoAllocator autoAllocator;
	private final BussinessCodeManager bussinessCodeManager;
	protected final InterfaceLogManager logManager;
	protected final AllocateManager allocateManager;
	
	public DefaultPickKamsManager(ItemManager manager,
			InventoryManager manager2, AutoAllocator autoAllocator,
			BussinessCodeManager manager3, InterfaceLogManager manager4,AllocateManager allocateManager) {
		super();
		this.itemManager = manager;
		this.inventoryManager = manager2;
		this.autoAllocator = autoAllocator;
		this.bussinessCodeManager = manager3;
		this.logManager = manager4;
		this.allocateManager=allocateManager;
	}
	@Override
	public void storePickTicket(PickTicket pickTicket) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void activeAll(List<Long> pickTicketIds) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void appPlamAssemblys(PickTicket pt, BomAccount bomAccount, String bonded, String meg) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void activeAll(Long pickTicketId) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void inactiveAllTask(List<Long> pickTicketIds) {
		System.out.println("XIN 方法");
		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);//+" and d.allocatedQuantity>0");
			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,null);
					inv.setQueuedQuantity(inv.getQueuedQuantity()-t.getPlanQuantityMU());
					if(inv.getQueuedQuantity()<0){
						inv.setQueuedQuantity(0);
					}
					this.commonDao.store(inv);
					this.commonDao.delete(t);
				}
				d.setAllocatedQuantity(0);
				this.commonDao.store(d);
				//删除现品票
				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);
			pickTicket.setPriority(0);
			refreshPick(id);
		}
		LocalizedMessage.addLocalizedMessage(errMsg);
	}
	@Override
	public void deleteAll(List<Long> pickTicketIds) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void cancelPlanPick(List<Long> ids) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void cancelAll(List<Long> pickTicketIds) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void addPickTicketDetail(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());
//		}
		
		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)));
				}
			}
			ptd.setOrderQtyOfMasterUnit(ptd.getOrderQuantity());
			ptd=lockInvKAMS(pickTicket,ptd);
			if(ptd.getAllocatedQuantity()<ptd.getOrderQuantity()){
				throw new BusinessException(ptd.getItem().getCode()+"库存不足"+ptd.getUnallocateQuantity());
			}
		}else{
			PickTicketDetail old=commonDao.get(PickTicketDetail.class, ptd.getId());
			if(ptd.getOrderQtyOfMasterUnit()!=ptd.getOrderQuantity()){
				old.setOrderQuantity(ptd.getOrderQuantity());
				old.setOrderQtyOfMasterUnit(ptd.getOrderQuantity());
				//先取消，后分配
				List<Task> ts=this.commonDao.findByQuery("from Task t where t.pickTicketDetail.id="+ptd.getId());
				for(Task t:ts){
					Inventory inv=findInventory(t.getItemKey(), t.getZone(), t.getSrcLoc(), pickTicket.getCode(), SysCode.CK_FP2,null);
					inv.setQueuedQuantity(inv.getQueuedQuantity()-t.getPlanQuantityMU());
					if(inv.getQueuedQuantity()<0){
						inv.setQueuedQuantity(0);
					}
					this.commonDao.store(inv);
					this.commonDao.delete(t);
				}
				old.setAllocatedQuantity(0);
				old=lockInvKAMS(pickTicket,old);
				if(old.getAllocatedQuantity()<old.getOrderQuantity()){
					throw new BusinessException(old.getItem().getCode()+"库存不足"+old.getUnallocateQuantity());
				}
				this.commonDao.store(old);
			}
		}
		refreshPick(pickTicket.getId());//刷新毛重体
		//if(pickTicket.getAllocatedQuantity()>0){
			pickTicket.setStatus(PickTicketStatus.OPEN);
		//}
		commonDao.store(pickTicket);
		
	}
	
	PickTicketDetail lockInvKAMS(PickTicket pickTicket,PickTicketDetail ptd){
		String hql="FROM Inventory i WHERE  i.itemKey.item.id="+ptd.getItem().getId()+" and i.zone.id="+pickTicket.getZone().getId();
		hql+=" and ( i.location.type!='SHIP') and i.itemKey.pinfan.bonded='"+ptd.getBonded()+"'";
		
		if(pickTicket.getZone()!=null&&pickTicket.getZone().getCode().indexOf("-SL")>0&&ptd.getZzkw()!=null){
			hql+=" and i.zzkw.id="+ptd.getZzkw().getId();
		}
		if(ptd.getItem().isBeWeight()){
			hql+=" order by  i.itemKey.lotInfo.propC3 asc ";
		}
		//只针对CKD课稅和保税仓库
		double unallocateQty=ptd.getUnallocateQuantity();
		if(unallocateQty<=0) {
			return ptd;
		}
		List<Inventory> invs =  commonDao.findByQuery(hql);
		double kjQty=unallocateQty;
		double syqty=unallocateQty;
		if(invs.size()==0) {
			return ptd;
		}
		for(Inventory inv:invs){
			if(syqty>0){
				if(inv.getQuantity()>0){
					ItemKey itemKey=inv.getItemKey();
					if((inv.getQuantity()-inv.getQueuedQuantity())<syqty){
						kjQty=(inv.getQuantity()-inv.getQueuedQuantity());
					}else{
						kjQty=syqty;
					}
					syqty=syqty-kjQty;
					Task t=pickTicket.allocate(null,ptd, inv, kjQty);
					inv.setQueuedQuantity(inv.getQueuedQuantity()+kjQty);
					this.commonDao.store(inv);
//					ptd.setAllocatedQuantity(ptd.getAllocatedQuantity()+kjQty);
					ptd.setZone(inv.getZone());
					ptd.setAllocateTime(new Date());
					ptd.setPf(itemKey.getPinfan());
					ptd.setItemKey(itemKey);
					ptd.setLocation(inv.getLocation());
					ptd.setQuantity(inv.getItemKey().getPinfan().getQuantity());
					this.commonDao.store(ptd);
				}else{
					continue;
				}
			}else{
				break;
			}
		}
		return ptd;
		
	}
	@Override
	public void addPickTicketDetails(Long pickTicketId, List<Long> ids) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void removePickTicketDetail(Long pickTicketId, List<Long> pickTicketDetailIds) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void removePlanPickTicketDetail(Long pickTicketId, List<Long> planPickTicketDetailIds) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void unallocate(List<Long> pickTicketIds) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void storeBOL(BOL BOL) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public MasterBOL getMasterBOLbyCode(String code) {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public void pickConfirm(Long taskId, Long srcLocId, String srcLp, String lot, Long packageUnitId,
			double pickedQuantity, double weight, Long workerId) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void pickKamsForSys(Long taskId, double pickedQuantity, Long workerId) {
		// TODO Auto-generated method stub
		
	}
	
	@Override
	public JSONObject pickKamsForApp(Long ptId, String xpp,String operator,String tph,String bhr) {
		String pfh=null;
		String ac=null;
		double pick_qty=0;
		PickTicket pt=this.commonDao.get(PickTicket.class, ptId);
		if(xpp!=null&&!xpp.equals("")&&xpp.length()==88){
    		pfh=xpp.substring(3, 13);
			ac=xpp.substring(13, 16);
			String nrs=xpp.substring(46, 52);
			pick_qty=Double.parseDouble(nrs);
		}else{
			throw new BusinessException("现品票长度不对");
		}
		if(tph==null||tph.equals("")){
			throw new BusinessException("托盘号必填");
		}else if(xpp==null||xpp.equals("")){
			throw new BusinessException("现品票必填");
		}
		List<String> qt_its=this.commonDao.findByQuery("select srcLPCode from TaskLog l where l.srcLPCode!='"+tph+"' and l.itemKey.item.code='"+pfh+"'"
				+ " and l.task.pickTicketDetail.pickTicket.id="+ptId);
		if(qt_its.size()>0){
			throw new BusinessException(pfh+"在其他托盘");
		}
		List<PrintXppRecord> prs=this.commonDao.findByQuery(" from PrintXppRecord r where r.xpp='"+xpp+"'");
		PrintXppRecord pr=null;
		String zzkw_code="";
		String loc_code="";
		if(prs.size()>0){
			pr=prs.get(0);
			pick_qty=pr.getShsl();
			if(pr.getTaskLog()!=null){
				throw new BusinessException("现品票已出库");
			}
			if(pr.getPtd().getZzkw()!=null){
				zzkw_code=pr.getPtd().getZzkw().getCode();
			}
			loc_code=pr.getCgkw();
		}
		String hql="from Task t where t.pickTicketDetail.pickTicket.id="+pt.getId()+" and t.itemKey.item.code='"+pfh+"'"
				+ " and t.planQuantityMU>0 and t.pickTicketDetail.allocatedQuantity>t.pickTicketDetail.pickedQuantity";
		if(zzkw_code!=null&&!zzkw_code.equals("")){
			hql+=" and t.pickTicketDetail.zzkw.code='"+zzkw_code+"'";
		}
		if(loc_code!=null&&!loc_code.equals("")){
			hql+=" and t.srcLoc.code like '%"+loc_code+"'";
		}
		List<Task> ts=this.commonDao.findByQuery(hql);
		if(ts.size()<=0){
			throw new BusinessException(pfh+"该品番不需要出库");
		}
		Task t=ts.get(0);
		PickTicketDetail ptd=t.getPickTicketDetail();
		TaskLog log= pickScan(pt, t, pick_qty, tph, operator, xpp, bhr, pr,null);
		refreshPlanPickQty(ptId,ptd.getItem().getId());
		JSONObject obj = new JSONObject();
		obj.put("item_code", ptd.getItem().getCode());
		obj.put("item_name", ptd.getItem().getName());
		obj.put("kysl", pick_qty);
		obj.put("ybhs",(int)pt.getPickedQuantity());
		obj.put("srs", ptd.getQuantity());
		obj.put("src_loc", t.getSrcLoc().getCode());
		String sql="select t.id from TaskLog t where  t.task.pickTicketDetail.pickTicket.id="+ptId;
		obj.put("cds",pt.getAllocatedQuantity());
		obj.put("ybhs",pt.getPickedQuantity());
		obj.put("ybhxs",commonDao.findByQuery(sql).size());
		obj.put("xpp_id", pr.getId());
		obj.put("log_id", log.getId());
		return obj;
	}
	
	@Override
	public JSONObject pickKamsForFdj(Long ptId, String ewm,String operator,String bhr) {
		String pfh=null;
		String ac=null;
		double pick_qty=1;//发动机数量1
		PickTicket pt=this.commonDao.get(PickTicket.class, ptId);
		RkEwmRecord rkr=null;
		String pcy=null;
		if(ewm!=null&&!ewm.equals("")){
    		List<RkEwmRecord> rs=this.commonDao.findByQuery("from RkEwmRecord r where r.ewm='"+ewm+"'");
    		if(rs.size()>=0){
    			rkr=rs.get(0);
    			pcy=rkr.getRky();
    			pfh=rkr.getItem().getCode();
    			if(rkr.getTaskLog()!=null){
    				throw new BusinessException("该条码已出库");
    			}
    		}else{
    			throw new BusinessException("二维码入库未采集");
    		}
		}else{
			throw new BusinessException("发动机二维码不能为空");
		}
		List<Task> ts=this.commonDao.findByQuery("from Task t where t.pickTicketDetail.pickTicket.id="+pt.getId()+" and t.itemKey.item.code='"+pfh+"'"
				+ " and t.itemKey.lotInfo.propC3='"+pcy+"'" 
				+" and t.planQuantityMU>0 and t.planQuantityMU>t.movedQuantityMU");
		if(ts.size()<=0){
			throw new BusinessException(pfh+"该品番不需要出库");
		}
		Task t=ts.get(0);
		PickTicketDetail ptd=t.getPickTicketDetail();
		pickScan(pt, t, pick_qty, null, operator, ewm, bhr, null,rkr);
		JSONObject obj = new JSONObject();
		obj.put("item_code", ptd.getItem().getCode());
		obj.put("item_name", ptd.getItem().getName());
		obj.put("kysl", pick_qty);
		obj.put("ybhs",(int)pt.getPickedQuantity());
		obj.put("srs", ptd.getQuantity());
		obj.put("src_loc", t.getSrcLoc().getCode());
		obj.put("pcy", pcy);
		obj.put("fdj", rkr.getFdj());
		String sql="select t.id from TaskLog t where  t.task.pickTicketDetail.pickTicket.id="+ptId;
		obj.put("cds",pt.getAllocatedQuantity());
		obj.put("ybhs",pt.getPickedQuantity());
		obj.put("ybhxs",commonDao.findByQuery(sql).size());
//		obj.put("xpp_id", pr.getId());
//		obj.put("log_id", log.getId());
		return obj;
	}
	
	public TaskLog  pickScan(PickTicket pt,Task t,double pick_qty,String tph,String operator,String ewm,String bhr,PrintXppRecord pr,RkEwmRecord rkr){
//		Location zzkw=ptd.getZzkw();
		ItemKey itemKey=t.getItemKey();
		Item it=itemKey.getItem();
		if((t.getPlanQuantityMU()-t.getMovedQuantityMU())<pick_qty){
			throw new BusinessException(it.getCode()+"剩余备货数量不足"+pick_qty);
		}
		//库存移位处理
		Inventory inv1=findInventory(t.getItemKey(), t.getZone(), t.getSrcLoc(), t.getBillCode(), SysCode.CK_BH1,null);
		if(inv1==null){
			throw new BusinessException("move.inventory.none");
		}
		
		double srcQty1=inv1.getQtyOfMasterPack();
		inv1.setQueuedQuantity(inv1.getQueuedQuantity()-pick_qty);
		if(inv1.getQueuedQuantity()<0){
			inv1.setQueuedQuantity(0);
		}
		if(pt.getRelatedBill2()==null||pt.getRelatedBill2().equals("")){
			pt.setShipDateEnd(new Date());
			pt.setRelatedBill2(this.bussinessCodeManager.getCodeForYm("CK",3));
		}
		
		this.commonDao.store(pt);
		inv1.remove(pick_qty, 0, 0);
		this.commonDao.store(inv1);
		String tp_tm=ewm;
		if(tph!=null&&!tph.equals("")){
			tp_tm= tph+"/"+ewm;
		}
		//减少
		addInventoryLog(InventoryLogType.PICK_DOWN, -1,  t.getZone(), t.getSrcLoc(), t.getBillCode(), t.getItemKey(), pick_qty, tp_tm, operator, inv1.getId(), (int)srcQty1+"变为"+(int)inv1.getQtyOfMasterPack(),bhr,null,null);
		t.setBeBh(Boolean.TRUE);
		//addTaskLog(task, itemKey,  task.getSrcLoc(), tph, task.getDstLoc(), key, pickedQuantity, null, operator);
		this.commonDao.store(t);
		//ptd.pickConfirm(pickedQuantity*1,0);
//		this.movedQuantityMU += pickedQuantity;//*unit.getConvertFigure();
//		task.pickConfirm(itemKey, task.getSrcLoc(), 
//				inv1.getLP(), task.getDstLoc(), task.getDstLP(), inv1.getStatus(),
//				inv1.getStorageDate(), inv1.getSOI(), 
//				null, pickedQuantity, null);
		TaskLog log=t.pickConfirm(itemKey, t.getSrcLoc(), 
				inv1.getLP(), t.getDstLoc(), t.getDstLP(), inv1.getStatus(),
				inv1.getStorageDate(), inv1.getSOI(), 
				null, pick_qty, null);
		log.setSrcLPCode(tph);
		log.setBarCode(ewm);
		log.setSOI(operator);
		this.commonDao.store(log);
		
		if(pr!=null){
			pr.setTaskLog(log);
			pr.setBhBy(operator);
			pr.setBhDate(new Date());
			this.commonDao.store(pr);
		}
		if(rkr!=null){//如果为发动机
			rkr.setTaskLog(log);
			rkr.setBhBy(operator);
			rkr.setBhDate(new Date());
			this.commonDao.store(rkr);
		}
		Inventory inv2 =findInventory(t.getItemKey(), t.getZone(), t.getDstLoc(), t.getBillCode(), SysCode.CK_BH2,null);
		if(inv2==null){
			inv2=EntityFactory.getEntity(Inventory.class);
			inv2.setLocation(t.getDstLoc());
			inv2.setItemKey(t.getItemKey());
			inv2.setZone(t.getZone());
//			t.getItemKey().getInventories().add(inv2);
			this.commonDao.store(inv2);
		}
		double srcQty2=inv2.getQtyOfMasterPack();
		inv2.add(pick_qty,0,0);
		this.commonDao.store(inv2);
		//增加
		addInventoryLog(InventoryLogType.PICK_DOWN, 1,  t.getZone(), t.getDstLoc(), t.getBillCode(), t.getItemKey(), pick_qty, tp_tm, operator, inv2.getId(), (int)srcQty2+"变为"+(int)inv2.getQtyOfMasterPack(),bhr,null,null);
		return log;
	}
	@Override
	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.getPickedQuantity()>=pt.getAllocatedQuantity()){
				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<Long> ids=this.commonDao.findByQuery("select id from TaskLog  l where l.task.pickTicketDetail.pickTicket.id="+pt.getId()+" and l.movedQuantity>0 and l.shipQuantity<=0");
			shipConfirmTphKAMS(pickId, ids, null, UserHolder.getUser().getName());
//			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,null);
//					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,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);
//			}
//			refreshPlanPick(pt.getId());
			if(pt.getSourceId()!=null){
				refreshPlanPickQty(pt.getId(),null);
			}
		}
	}
	
	public void shipConfirmTphKAMS(Long pt_id,List<Long> ids,String cph,String oper) {
		PickTicket pt=this.commonDao.get(PickTicket.class, pt_id);
		if(pt.getPickedQuantity()<pt.getAllocatedQuantity()){
			throw new BusinessException(pt.getCode()+"未备货完成");
		}
		if(pt.getShippedQuantity()<pt.getPickedQuantity()){
			if(pt.getRelatedBill2()==null){
				pt.setRelatedBill2(this.bussinessCodeManager.getCodeForYm("CK",5));
			}
			pt.setShipDate(new Date());
			this.commonDao.store(pt);
		}else{
			throw new BusinessException(pt.getCode()+"状态不正确");
		}
		for(Long logId:ids) {
			TaskLog log=this.commonDao.get(TaskLog.class, logId);
			Task t=log.getTask();
			PickTicketDetail ptd=t.getPickTicketDetail();
			Inventory inv=findInventory(t.getItemKey(), ptd.getZone2(), log.getDstLoc(), pt.getCode(), SysCode.CK_FY1,null);
			double qty1=inv.getQtyOfMasterPack();
			double shipQty=log.getMovedQuantity();
			inv.setQtyOfMasterPack(inv.getQtyOfMasterPack()-shipQty);
			if(inv.getQtyOfMasterPack()<0){
				inv.setQtyOfMasterPack(0);
			}
			inv.setQuantity(inv.getQtyOfMasterPack());
			this.commonDao.store(inv);
			addInventoryLog(InventoryLogType.SHIPPING, -1, ptd.getZone2(), inv.getLocation(), pt.getCode(), t.getItemKey(),shipQty, log.getSrcLPCode(), oper, inv.getId(), (int)qty1+"变为"+(int)inv.getQtyOfMasterPack(),null,cph,null);
			log.setShipQuantity(shipQty);
			log.setDstLPCode(cph);
			log.setFhBy(oper);
			log.setFhDate(new Date());
			this.commonDao.store(log);
			ptd.setShippedQuantity(ptd.getShippedQuantity()+log.getShipQuantity());
			this.commonDao.store(ptd);
			List<PrintXppRecord> rs=this.commonDao.findByQuery("from PrintXppRecord xxp where xxp.xpp='"+log.getBarCode()+"'");
			if(rs.size()>0){
				PrintXppRecord r=rs.get(0);
				r.setFhBy(oper);
				r.setFhDate(new Date());
				r.setTaskLog(log);
				this.commonDao.store(r);
			}
			
			List<RkEwmRecord> rrs=this.commonDao.findByQuery("from RkEwmRecord r where r.ewm='"+log.getBarCode()+"'");
			if(rrs.size()>0){
				RkEwmRecord r=rrs.get(0);
				r.setFhBy(oper);
				r.setFhDate(new Date());
				r.setTaskLog(log);
				this.commonDao.store(r);
			}
			
		}
		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));
			if(pt.getShippedQuantity()>=pt.getPickedQuantity()){
				pt.setStatus(PickTicketStatus.SHIP_ALL);
			}else{
				pt.setStatus(PickTicketStatus.SHIP_PART);
			}
			pt.setLicenseNO(cph);
			commonDao.store(pt);
		}
		refreshPlanPickQty(pt_id,null);
	}
	@Override
	public void pickConfirm(Long taskId, double pickedQuantity, Long workerId) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void pickConfirm(Long pickTicketId, Long workerId) {
		// TODO Auto-generated method stub
		
	}
	
	@Override
	public void willShip(List<Long> ids, Long dockId, Date shipDateStart, Date shipDateEnd) {
		// TODO Auto-generated method stub
		
	}
	@Override
	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}));
		String operator= UserHolder.getUser().getName();
		for(TaskLog l:logs){
			pickedBack(pickTicketId, l.getId(),0d, operator, null);
		}
		
	}
	@Override
	public void pickedBack(Long pickTicketId, List<Long> taskLogIds) {
		for(Long id:taskLogIds){
//			Task t=this.commonDao.get(Task.class, id);
			pickedBack(pickTicketId,id,0d,  UserHolder.getUser().getName(), null);
		}
		
	}
	public void pickedBackForSys(Long pickTicketId, Long taskLogId, Double movedQuantity) {
		pickedBack(pickTicketId,taskLogId,movedQuantity,  UserHolder.getUser().getName(), null,Boolean.FALSE);
		//pickedBack(pickTicketId, taskLogId, movedQuantity, UserHolder.getUser().getName(),null);
	}
	
	@Override
	public void pickedBackXpp(Long pickTicketId, List<Long> taskLogIds) {
		for(Long id:taskLogIds){
//			Task t=this.commonDao.get(Task.class, id);
			pickedBack(pickTicketId,id,0d,  UserHolder.getUser().getName(), null,Boolean.TRUE);
		}
		
	}
	@Override
	public void pickedBack(Long pickTicketId, Long taskLogId, Double pickQty,String operator,Long xpp_id) {
		pickedBack(pickTicketId,taskLogId,pickQty, operator, null,Boolean.FALSE);
	}
	
	public void pickedBack(Long pickTicketId, Long taskLogId, Double pickQty,String operator,Long xpp_id,Boolean cancelXpp) {
		TaskLog log = this.commonDao.load(TaskLog.class, taskLogId);
    	Task t=log.getTask();
    	PickTicketDetail ptd=t.getPickTicketDetail();
    	Double pickBackQty = log.getMovedQuantity()-pickQty;
    	if(pickBackQty < 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,ptd.getZzkw());
    			double srcQty1=inv1.getQtyOfMasterPack();
    			inv1.remove(pickBackQty,0,0);
    			this.commonDao.store(inv1);
    			//减少
    			addInventoryLog(InventoryLogType.PICK_CANCEL, -1,  t.getZone(), t.getDstLoc(), t.getBillCode(), ik, pickBackQty, t.getSrcLPCode(), operator, inv1.getId(), (int)srcQty1+"变为"+(int)inv1.getQtyOfMasterPack(),null,null,null);
    			Inventory inv2 =findInventory(ik, t.getZone(), t.getSrcLoc(), t.getBillCode(), SysCode.CK_TH2,ptd.getZzkw());
    			double srcQty2=inv2.getQtyOfMasterPack();
    			inv2.add(pickBackQty,0,0);
    			if(cancelXpp){
    				inv2.setQueuedQuantity(inv2.getQueuedQuantity()+pickBackQty);
    			}
    			this.commonDao.store(inv2);
    			//增加
    			addInventoryLog(InventoryLogType.PICK_CANCEL, 1,  t.getZone(), t.getSrcLoc(), t.getBillCode(), ik, pickBackQty, null, operator, inv2.getId(), (int)srcQty2+"变为"+(int)inv2.getQtyOfMasterPack(),null,null,null);
    			t.setBeBh(Boolean.FALSE);
    			this.commonDao.store(t);
    		}else {
				throw new BusinessException("moveDoc.pickBackLoc.none");
			}
    		if(cancelXpp){
    			log.setMovedQuantity(log.getMovedQuantity()-pickBackQty);
    			this.commonDao.store(log);
				t.setMovedQuantityMU(t.getMovedQuantityMU()-pickBackQty);
				this.commonDao.store(t);
				ptd.setPickedQuantity(ptd.getPickedQuantity()-pickBackQty);
				PickTicket pt =ptd.getPickTicket();
				pt.setPickedQuantity(pt.getPickedQuantity()-pickBackQty);
				pt.setStatus(PickTicketStatus.PICKUP);
				if(pt.getPickedQuantity()==0){
					pt.setStatus(PickTicketStatus.ALLOCATE);
				}
				this.commonDao.store(pt);
			}else{
				log.pickBack(pickBackQty);
			}
    	}
    	if(xpp_id!=null){
    		PrintXppRecord x=this.commonDao.get(PrintXppRecord.class, xpp_id);
    		x.setShsl(pickQty.intValue());
    		x.setUpdateBy(operator);
    		x.setUpdateDate(new Date());
    		this.commonDao.store(x);
    	}
    	if(log.getMovedQuantity()==0){
    		List<PrintXppRecord> xs=this.commonDao.findByQuery("from PrintXppRecord x where x.taskLog.id="+log.getId());
    		for(PrintXppRecord x:xs){
    			x.setTaskLog(null);
    			x.setBhBy(null);
    			x.setBhDate(null);
    			this.commonDao.store(x);
    		}
    		List<RkEwmRecord> rs=this.commonDao.findByQuery("from RkEwmRecord x where x.taskLog.id="+log.getId());
    		for(RkEwmRecord r:rs){
    			r.setTaskLog(null);
    			r.setBhBy(null);
    			r.setBhDate(null);
    			this.commonDao.store(r);
    		}
    		this.commonDao.delete(log);
    	}
    	if(t.getPlanQuantityMU()==0){
    		this.commonDao.delete(t);
    	}
    	refreshPlanPickQty(ptd.getPickTicket().getId(),ptd.getItem().getId());
		
	}
	@Override
	public void multiPickConfirm(List<Long> ids) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void multiPickConfirmForBOL(List<Long> ids) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void shipconfirm(List<Long> ids, double fytps, String shipmentType, String cphorkddh, Date shipDate) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void cancellAllocate(List<Long> ids) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void returnGoods(Long pickTicketId, Map map) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void importPickTicket(File file) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void importPickTicketKAMS(Long pickId, File file) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void appAllocate(List<Long> pickTicketIds) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void confirmShip(Long pickId, Map qtys) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void confirmKAMSShip(Long pickId, Map qtys) {
		// TODO Auto-generated method stub
		
	}
	@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<Task> ts=this.commonDao.findByQuery("from Task t where t.pickTicketDetail.id="+pd.getId()+" and t.planQuantity>0 ");
				if(ts.size()>0){
					for(Task t:ts){
						//扣库存
						Location zzkw=pd.getZzkw();
						Inventory inv=findInventory(t.getItemKey(), pd.getZone(), t.getSrcLoc(), pt.getCode(), SysCode.CK_BH1, zzkw);
//						if(pd.getItem().getCode().equals("1J04531000")){
//							System.out.println(pd.getId()+"---"+pd.getItem().getCode()+"===="+t.getPlanQuantity()+"===="+pd.getAllocatedQuantity());
//						}
						double srcQty=inv.getQtyOfMasterPack();
						inv.setQueuedQuantity(inv.getQueuedQuantity()-t.getPlanQuantity());
						inv.setQtyOfMasterPack(inv.getQtyOfMasterPack()-t.getPlanQuantity());
						inv.setQuantity(inv.getQtyOfMasterPack());
						InventoryLog log2 =inventoryManager.addInventoryLog(InventoryLogType.SHIPPING_ADJUST, -1, inv.getZone(), inv.getLocation(), pt.getCode(),
								inv.getItemKey(), t.getPlanQuantity(), null, UserHolder.getUser().getName(), 
								 inv.getId(), srcQty+"减少后"+inv.getQtyOfMasterPack(), pt.getDescription(), null, null, zzkw);
						commonDao.store(log2);
						this.commonDao.store(inv);
						t.setMovedQuantityMU(t.getPlanQuantity());
						this.commonDao.store(t);
					}
//					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);
				}else{
					//扣库存
					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);
				}
			
			}
		}
		
	}
	
	public void cancelShipKamsQt(Long pickId) {
		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,pd.getZzkw());
				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);
		}
		refreshPick(pt.getId());
	}
	@Override
	public void confirmShip(Long pickId) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void confirmKAMSShip(Long pickId) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void cancelPick(Long pickId) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void cancelShip(Long pickId) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void appPlanPickTicket(List<Long> pickTicketIds) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void storePlanPickTicket(PlanPickTicket p) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void addpick(Map clientParams, List<Long> id) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void addPlanPick(Map clientParams, List<Long> id) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void appPlanAssembly(List<Long> pickTicketIds, int fs1, int fs2, int fs3) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void addpickTicketSCRJHPageer(Long id, double qty1) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void appPlanTLJ(List<Long> pickTicketIds) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public String getByJhMap(Map map) {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public void deleteProductionPlan(Long id, String tsr, double qty, String procedure) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void addpickTicketPlan_zs(Long planid, String rd, Long id, Double sum) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void addpickTicketPlan_bh(Long planid, String rd, Long id, Double sum) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void copypickTicketPlan_bh(Long planid, String rd, List<Long> ids) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void appPlanPickzd(List<Long> pickTicketIds) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void addProductionp(String tsr, String str1, double qty, String procedure, String description) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void appPlanLDJ(List<Long> pickTicketIds) {
		// TODO Auto-generated method stub
		
	}
	
	@Override
	public void xbjsSys(List<Long> pickTicketIds){
		 for(Long ptId:pickTicketIds){
			PickTicket pt =commonDao.load(PickTicket.class, ptId);
			if(pt.getShippedQuantity()<pt.getPickedQuantity()){
				throw new BusinessException(pt.getCode()+"没有全部出库，不能接收");
			}
			 List<Long> logIds=this.commonDao.findByQuery("select id from TaskLog l where l.task.pickTicketDetail.pickTicket.id="+ptId+" and l.xbQuantity<=0 and l.shipQuantity>0");
			 this.xbjs(ptId, null, logIds, UserHolder.getUser().getName());
		 }
	 }
	
	@Override
	public void xbjs(Long pt_id,String tph,List<Long> logIds,String oper) {
		PickTicket pt =commonDao.load(PickTicket.class, pt_id);
		WarehouseArea zone=pt.getZone1();
		if(zone==null) {
			throw new BusinessException(pt.getCode()+"入库库区没有值，请选择库区");
		}
		if(zone.getHckw()==null){
			throw new BusinessException(pt.getCode()+"维护库区对应线边待投料库位");
		}
		if(pt.getPackageQuantity()>=pt.getShippedQuantity()){
			throw new BusinessException(pt.getCode()+"全部接收完成");
		}
	    Location xb_loc =zone.getHckw();
	    double t_xb_qty=0;
	    for(Long logId:logIds){
	    	TaskLog l=this.commonDao.get(TaskLog.class, logId);
	    	if(l.getXbQuantity()>0){
	    		continue;
	    	}
	    	Task t=l.getTask();
	    	l.setXbQuantity(l.getShipQuantity());
	    	l.setSlDate(new Date());
	    	l.setSlBy(oper);
	    	this.commonDao.store(l);
	    	List<PrintXppRecord> rs=this.commonDao.findByQuery("from PrintXppRecord xxp where xxp.xpp='"+l.getBarCode()+"'");
	    	if(rs.size()>0){
	    		PrintXppRecord r=rs.get(0);
	    		r.setSlBy(oper);
	    		r.setSlDate(new Date());
	    		r.setSlkw(xb_loc);
	    		r.setTaskLog(l);
	    		this.commonDao.store(r);
	    	}
	    	PickTicketDetail ptd=t.getPickTicketDetail();
			Inventory inv=findInventory(t.getItemKey(), zone, xb_loc, pt.getCode(), SysCode.XB1, ptd.getZzkw());
			double xb_qty=l.getShipQuantity();
			t_xb_qty+=xb_qty;
			double srcQty1=0;
//					 inv =list2.get(0);
			 inv.setZzkw(ptd.getZzkw());
			 inv.setLocation(xb_loc);
			 srcQty1=inv.getQtyOfMasterPack();
			 inv.setQtyOfMasterPack(inv.getQtyOfMasterPack()+xb_qty);
			 inv.setQuantity(inv.getQtyOfMasterPack());
			 commonDao.store(inv);
				
			 ptd.setShippedQuantity(ptd.getPickedQuantity());
			 ptd.setNorejectQuantity(ptd.getNorejectQuantity()+xb_qty);
			 ptd.setOldRecord(true);
			 commonDao.store(ptd);
			 this.addInventoryLog(InventoryLogType.PROCESS_UP, 1, zone, inv.getLocation(), pt.getCode(), inv.getItemKey(), xb_qty, 
					 tph,oper, inv.getId(), (int)srcQty1+"变为"+(int)inv.getQtyOfMasterPack(), null, null, ptd.getZzkw());
		  }
	    pt.setSlDate(new Date());
	    pt.setSlBy(oper);
		pt.setPackageQuantity(pt.getPackageQuantity()+t_xb_qty);
//				pt.setQuantity1(list3.get(0));
		pt.setStatus("CLOSE");
		commonDao.store(pt);
	}
	
	@Override
	public void xbjs(List<Long> pickTicketIds) {
		for(Long id:pickTicketIds) {
			PickTicket pt =commonDao.load(PickTicket.class, id);
			WarehouseArea zone=pt.getZone1();
			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=findInventory(ptd.getItemKey(), zone, xb_loc, pt.getCode(), SysCode.XB1, ptd.getZzkw());
				 double srcQty1=0;
				 if(inv!=null) {
//					 inv =list2.get(0);
					 inv.setZzkw(ptd.getZzkw());
					 inv.setLocation(xb_loc);
					 srcQty1=inv.getQtyOfMasterPack();
					 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);
				 this.addInventoryLog(InventoryLogType.PROCESS_UP, 1, zone, inv.getLocation(), pt.getCode(), inv.getItemKey(), ptd.getShippedQuantity(), 
						 null, UserHolder.getUser().getName(), inv.getId(), (int)srcQty1+"变为"+(int)inv.getQtyOfMasterPack(), null, null, ptd.getZzkw());
			   }
		   }
//		   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);
		}
	}
	@Override
	public void confirmShipKAMS(List<Long> pickIds) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void manualAllocate(List<Long> pickIds) {
		// TODO Auto-generated method stub
		
	}
	@Override
	//备货操作，出库操作审核
	public void activeKAMSAll(List<Long> pickTicketIds) {
		System.out.println("XIN 方法");
		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+" "
					+ "and d.allocatedQuantity<d.orderQtyOfMasterUnit");
			for(PickTicketDetail d:ds){//pickTicket.getPickTicketDetails()){
				Long zoneId=null;
				if(!pickTicket.getBillType().getName().equals("其他出库单")){
					zoneId=d.getZone2().getId();
				}else{
					zoneId=pickTicket.getZone().getId();
				}
				
				String hql="FROM Inventory i WHERE  i.itemKey.item.id="+d.getItem().getId()+" and i.zone.id="+zoneId;
				hql+=" and ( i.location.type!='SHIP')";
				if(d.getItem().isBeWeight()){
					hql+=" order by  i.itemKey.lotInfo.propC3,i.location.code asc ";
				}else{
					hql+=" order by i.location.code asc ";
				}
				List<Inventory> invs =  commonDao.findByQuery(hql);
				List<Inventory> pxInvs=new ArrayList<Inventory>();
			
				//只针对CKD课稅和保税仓库
				double unallocateQty=d.getUnallocateQuantity();
				if(unallocateQty<=0) {
					continue;
				}
				double kjQty=unallocateQty;
				double syqty=unallocateQty;
				//把库存进行排序，先找默认库存
				if(invs.size()==0) {
					errMsg+=d.getItem().getCode()+"没有库存";
				}
				if(invs.size()>1&&!d.getItem().isBeWeight()){
					for(Inventory inv:invs){
						if(inv.getItemKey().getPinfan().getLocation().getId().equals(inv.getLocation().getId())){
							pxInvs.add(inv);
						}
					}
					for(Inventory inv:invs){
						if(!inv.getItemKey().getPinfan().getLocation().getId().equals(inv.getLocation().getId())){
							pxInvs.add(inv);
						}
					}
				}else{
					pxInvs=invs;
				}
				for(Inventory inv:pxInvs){
					if(syqty>0){
						if(inv.getQuantity()>0){
							ItemKey itemKey=inv.getItemKey();
							if((inv.getQuantity()-inv.getQueuedQuantity())<syqty){
								kjQty=(inv.getQuantity()-inv.getQueuedQuantity());
							}else{
								kjQty=syqty;
							}
							syqty=syqty-kjQty;
							Task t=pickTicket.allocate(null,d, inv, kjQty);
							inv.setQueuedQuantity(inv.getQueuedQuantity()+kjQty);
							this.commonDao.store(inv);
//							d.setAllocatedQuantity(d.getAllocatedQuantity()+kjQty);
							d.setZone(inv.getZone());
							d.setAllocateTime(new Date());
							d.setPf(itemKey.getPinfan());
							d.setItemKey(itemKey);
							d.setLocation(inv.getLocation());
							d.setQuantity(inv.getItemKey().getPinfan().getQuantity());
							this.commonDao.store(d);
						}else{
							continue;
						}
					}else{
						break;
					}
				}
				
				if(syqty>0) {
					errMsg+=d.getItem().getCode()+"库存不足,";
					sheChange(pickTicket,d);	
				}
			}
		    if(pickTicket.getAllocatedQuantity()>0) {
				pickTicket.setStatus(PickTicketStatus.ALLOCATE);
				pickTicket.setShipDateStart(new Date());
		    }else{
		    	pickTicket.setStatus(PickTicketStatus.OPEN);
		    }
		    pickTicket.setLineName(errMsg);
			commonDao.store(pickTicket);
			errMsg+=pickTicket.getCode()+" 发货单激活成功;";
			LocalizedMessage.addLocalizedMessage(errMsg);
			refreshPick(pickTicket.getId());
			//createXpp(pickTicket);
		}
		
	}
	
	public void createXpp(PickTicket pickTicket){
		//生成现品票
		List<Task> ts=this.commonDao.findByQuery("from Task t where t.pickTicketDetail.pickTicket.id="+pickTicket.getId());
		int fzh=1;
		for(Task t:ts){
			PickTicketDetail d=t.getPickTicketDetail();
			int fs=(int) Math.ceil(t.getPlanQuantityMU()/d.getQuantity());
			int sysl=(int)t.getPlanQuantityMU();
			for(int i=1;i<=fs;i++){
				PrintXppRecord r=EntityFactory.getEntity(PrintXppRecord.class);
				if(sysl>d.getQuantity()){
					r.setShsl((int)d.getQuantity());
				}else{
					r.setShsl(sysl);
				}
				sysl-=r.getShsl();
				r.setWarehouse(WarehouseHolder.getWarehouse());
				r.setAc(d.getSpecs());
				r.setPf(d.getPf());
				r.setDdbh(pickTicket.getCode());
				r.setItem(d.getItem());
				r.setSrs((int)d.getQuantity());
				r.setCgkw(r.getPf().getLocation().getCode());
				r.setFzh(fzh++);
				r.setPtd(d);
				r.setRemark(d.getZzkw().getCode());
				StringBuffer sb=new StringBuffer();
				sb.append("JR1");
				sb.append(d.getItem().getCode());
				sb.append(r.getAc());
				sb.append(String.format("%21s", pickTicket.getCode()));
				sb.append("20230426");
				sb.append(String.format("%07d", r.getShsl()));
				sb.append("J-WL");
				sb.append(String.format("%20s", r.getRemark()));
				if(r.getCgkw().length()>6){
					sb.append(String.format("%6s", r.getCgkw().substring(0,6)));
				}else{
					sb.append(String.format("%6s", r.getCgkw()));
				}
				sb.append(String.format("%06d", r.getFzh()));
				r.setXpp(sb.toString());
				System.out.println(r.getXpp()+"==="+r.getXpp().length());
				this.commonDao.store(r);
			}
		}
	}
	@Override
	public void saveProductionPlan(List<Long> pickTicketIds, String p, Long spId) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void deleteProduction(List<Long> pickTicketIds) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void addInstructions(String pickTicketId, Long billTypeid, PlanPickDetail planPickTicketDetail) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void deletePlanAll(List<Long> pickIds) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void createPickTicket1(List<Long> pickIds) {
		createPickTicketSGZS(pickIds,"ALL");
	}
	@Override
	public void createPickTicket2(List<Long> pickIds) {
		createPickTicketSGZS(pickIds,"MULTI");
	}
	public void createPickTicketSGZS(List<Long> pickIds,String type) {
		PickTicket pt=null;
		String pptdIds=StringUtils.strip(pickIds.toString(),"[]");
		List<Long> ptIds=commonDao.findByQuery("select distinct(p.planPickTicket.id) from PlanPickDetail p where p.id in ("+pptdIds+")");
		String zsdh="";
		String rzone="";
		String czone="";
//		PlanPickTicket ppt=null;
		for(Long id:ptIds){
			PlanPickTicket ppt=this.commonDao.get(PlanPickTicket.class, id);
			if(!rzone.equals("")&&!rzone.equals(ppt.getZone1().getCode())){
				throw new BusinessException("选择单据收货库区不一致"); 
			}
			if(!czone.equals("")&&!czone.equals(ppt.getZone2().getCode())){
				throw new BusinessException("选择单据出库库区不一致"); 
			}
			rzone=ppt.getZone1().getCode();
			czone=ppt.getZone2().getCode();
			zsdh+=ppt.getCode()+";";
			ppt.setStatus("ACTIVE");
//			ppt.setPackType2(pt.getCode());
			commonDao.store(ppt);
		}
		String pptIds=StringUtils.strip(ptIds.toString(),"[]");;
//		if(ptIds.size()>1){
		if(false){
			throw new BusinessException("只能选择一张手工指示单"); 
		}else{
			PlanPickTicket ppt=this.commonDao.get(PlanPickTicket.class, ptIds.get(0));
			List<PlanPickDetail> ppds=null;
			if(type.equals("ALL")){
//				ppds=commonDao.findByQuery(" from PlanPickDetail  p where p.orderQuantity-p.allocatedQuantity>0 and p.planPickTicket.id="+ppt.getId());
				ppds=commonDao.findByQuery(" from PlanPickDetail  p where p.orderQuantity-p.allocatedQuantity>0 and p.planPickTicket.id in("+pptIds+")");
			}else if(type.equals("MULTI")){
				ppds=commonDao.findByQuery(" from PlanPickDetail  p where p.orderQuantity-p.allocatedQuantity>0 and p.id in ("+pptdIds+") order by p.planPickTicket.orderDate asc ");
			}
			int i=1;
			for(PlanPickDetail pd:ppds) {
				//判断明细是否有库存，进行库存锁定
				List<Double> invQtys=commonDao.findByQuery("select COALESCE(sum(i.quantity-i.queuedQuantity),0) "
						+ "from Inventory i where i.itemKey.item.id="+pd.getItem().getId()
												+" and i.zone.id="+pd.getZone2().getId() +" and i.location.type!='SHIP'");
				if(invQtys.size()>0){
					Double invQty=invQtys.get(0);
					if(invQty<=0){
						continue;
					}
					double wck=pd.getOrderQuantity()-pd.getAllocatedQuantity();//未出单数量
					double bccd=wck;//本次出单
					if(wck>invQty){
						bccd=invQty;
					}
					if(pt==null){
						pt=EntityFactory.getEntity(PickTicket.class);
						pt.setWarehouse(WarehouseHolder.getWarehouse());
						pt.setStatus(PickTicketStatus.OPEN);
						pt.setCode(this.bussinessCodeManager.getCodeForYm("BH",3));
//						pt.setWaveCode(ppt.getCode());
						pt.setWaveCode(zsdh);
						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));
						pt.setBillType(ppt.getBillType());
						pt.setUserTracking();
						pt.setRelatedBill1("成套出库");
						pt.setRelatedBill3(ppt.getRelatedBill3());
						pt.setZone(commonDao.load(WarehouseArea.class, 37L));
//						pt.setSourceId(ppt.getId()+"");
						pt.setSourceId(pptIds);
						pt.setShipDateStart(new Date());
						pt.setOrderDate(new Date());
						pt.setDescription(ppt.getDescription());
						this.commonDao.store(pt);
					}
					//生成明细
					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());
					ptd.setQuantity(bccd);
					ptd.setOrderQuantity(bccd);
					ptd.setOrderQtyOfMasterUnit(bccd);
					pt.setOrderQuantity(bccd+pt.getOrderQuantity());
					ptd.setLineNumber((i++)+"");
					ptd.setZzkw(pd.getZzkw());
					ptd.setApplyDocDetailId(pd.getId());
					ptd.setApplyDoc(pd.getPlanPickTicket().getCode());//直接存单据数据
					commonDao.store(ptd);
					pd.setAllocatedQuantity(pd.getAllocatedQuantity()+bccd);
					pd.setQty1(bccd);
					this.commonDao.store(pd);
					System.out.println("ptd"+ptd.getId());
					pt.getPickTicketDetails().add(ptd);
					pt.setZone1(ptd.getZone1());
					pt.setZone(ptd.getZone());
					pt.setZone2(ptd.getZone2());
				
					if(pt.getRelatedBill3()==null){
						pt.setRelatedBill3(pd.getZone1().getGw());
						if(pd.getZone2().getCode().indexOf("课")>0){
							pt.setApplyDoc("课税");
						}else if(pd.getZone2().getCode().indexOf("保")>0){
							pt.setApplyDoc("保税");
						}
					}
					commonDao.store(pt);
				}else{
					continue;
				}
			}
			if(pt!=null) {
				List<Long> ids=new ArrayList<Long>();
				ids.add(pt.getId());
				activeKAMSAll(ids);
				refreshPlanPickQty(pt.getId(),null);
//				refreshPlanPick(pt.getId());
			}
		}
	}
	@Override
	public void addSpareParts(SpareParts spareParts) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void copySpareParts(List<Long> ids) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void deletSpareParts(List<Long> ids) {
		// TODO Auto-generated method stub
		
	}
	@Override
	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);
//		if(zone.getHckw()==null){
//			throw new BusinessException("维护库区对应线边待投料库位");
//		}
//	    Location xb_loc =zone.getHckw();
		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){
				if(sp.getStatus().equals("未消耗")) {
					hySpareParts(sp);
				}
			}
		}
	}
	
	public void hySpareParts(SpareParts sp){
		List<BomAccount>	bas=commonDao.findByQuery(" from BomAccount b where b.bigItem.id="+sp.getBigItem().getId()
				+" and b.strExtend1='"+sp.getCode()+"'");
		if(bas.size()<=0){
			sp.setDescription(sp.getDescription()==null?"":sp.getDescription()+"  无BOM清单，实际未耗用");
			sp.setStatus("已耗用");
			this.commonDao.store(sp);
			return;
//					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();
			if(zone.isBeZzHy()){
				xb_loc=b.getZzkw();
				if(xb_loc==null){
					throw new BusinessException(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="+b.getZzkw().getId();
				if(b.getBonded()!=null&&!b.getBonded().equals("")) {
					hql+=" and i.itemKey.pinfan.bonded='"+b.getBonded()+"' ";
					hql+=" and i.itemKey.pinfan.zone.id!=77 ";
				}
				hql+=" and i.location.id="+xb_loc.getId()+" order by i.itemKey.lotInfo.propC3";
//						hql+=" order by i.id ";
				List<Inventory> invs=commonDao.findByQuery(hql);
				double srcQty1=0;
				if(invs.size()>0) {
					double qty=Double.parseDouble(b.getSingle())*sp.getOrderQuantity();
					//如果为发动机，则按照批次耗用
					if(b.getItem().isBeWeight()){
						int i=0;
						for(Inventory inv:invs){
							if(qty<=0){
								break;
							}
							i++;
							if(i<invs.size()&&inv.getQtyOfMasterPack()<=0){
								continue;
							}
							srcQty1=inv.getQtyOfMasterPack();
							double hyQty=0;
							if(inv.getQtyOfMasterPack()>qty||i==invs.size()){
								hyQty=qty;
								qty-=hyQty;
							}else{
								hyQty=inv.getQtyOfMasterPack();
								qty-=hyQty;
							}
							inv.setQtyOfMasterPack(inv.getQtyOfMasterPack()-hyQty);	
							inv.setQuantity(inv.getQtyOfMasterPack());
							commonDao.store(inv);
							this.addInventoryLog(InventoryLogType.PROCESS_DOWN, -1, b.getZone(), inv.getLocation(), sp.getBigItem().getCode(), inv.getItemKey(),
									hyQty, null, UserHolder.getUser().getName(), null,  (int)srcQty1+"变为"+(int)inv.getQtyOfMasterPack()+"hy"+sp.getId(), null, null, b.getZzkw());
						}
					}else{
						Inventory inv=invs.get(0);
						srcQty1=inv.getQtyOfMasterPack();
	
						inv.setQtyOfMasterPack(inv.getQtyOfMasterPack()-qty);	
						inv.setQuantity(inv.getQtyOfMasterPack());
						commonDao.store(inv);
						this.addInventoryLog(InventoryLogType.PROCESS_DOWN, -1, b.getZone(), inv.getLocation(), sp.getBigItem().getCode(), inv.getItemKey(),
								qty, null, UserHolder.getUser().getName(), null,  (int)srcQty1+"变为"+(int)inv.getQtyOfMasterPack()+"hy"+sp.getId(), null, null, b.getZzkw());
					}
				}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");
					inv.setZzkw(b.getZzkw());
					commonDao.store(inv);
					//inv.getItemKey().getPinfan().getLocation();
					this.addInventoryLog(InventoryLogType.PROCESS_DOWN, -1, b.getZone(), inv.getLocation(), sp.getBigItem().getCode(), inv.getItemKey(),
							qty, null, UserHolder.getUser().getName(), null,  (int)srcQty1+"变为"+(int)inv.getQtyOfMasterPack()+"hy"+sp.getId(), null, null, b.getZzkw());
					//System.out.println("无库存记录");
				}
			}else {
				throw new BusinessException(sp.getBigItem().getCode()+"请维护BOM清单");
			}
		}
		sp.setStatus("已耗用");
		this.commonDao.store(sp);
	}
	@Override
	public void confirmPickKAMS(Long pickId, Map qtys) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void designList(long pickTicketDetailId, double quantity) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public boolean sheChangeColor(long pickTicketId) {
		// TODO Auto-generated method stub
		return false;
	}
	//制造库位
	public void manualMoveZzkw(Long srcInventoryId, Long destLocationId,double quantity, Long workerId) {
		Inventory srcInv = commonDao.load(Inventory.class, srcInventoryId);
		Location zzkw = commonDao.load(Location.class, destLocationId);
		double quantityMU = quantity;
		if (quantityMU > srcInv.getAvaliableQuantity()) {
			throw new BusinessException("inventory.quantity.insufficient");
		}
		Inventory inv=findInventory(srcInv.getItemKey(), srcInv.getZone(), srcInv.getLocation(), null, SysCode.ZZKW_TRAN, zzkw);
		double srcQty1=inv.getQtyOfMasterPack();
		inv.setQuantity(inv.getQuantity()+quantity);
		inv.setQtyOfMasterPack(inv.getQtyOfMasterPack()+quantity);
		this.commonDao.store(inv);
		this.addInventoryLog(InventoryLogType.ZZKW_TRANS, 1, inv.getZone(), inv.getLocation(), null, inv.getItemKey(),
				quantity, null, UserHolder.getUser().getName(), null,  (int)srcQty1+"变为"+(int)inv.getQtyOfMasterPack()+"制造库位"+inv.getId(), null, null, inv.getZzkw());
		double srcQty2=srcInv.getQtyOfMasterPack();
		srcInv.setQuantity(srcInv.getQuantity()-quantity);
		srcInv.setQtyOfMasterPack(srcInv.getQtyOfMasterPack()-quantity);
		this.commonDao.store(srcInv);
		this.addInventoryLog(InventoryLogType.ZZKW_TRANS, -1, srcInv.getZone(), srcInv.getLocation(), null, srcInv.getItemKey(),
				quantity, null, UserHolder.getUser().getName(), null,  (int)srcQty2+"变为"+(int)srcInv.getQtyOfMasterPack()+"制造库位"+srcInv.getId(), null, null, srcInv.getZzkw());
	}
	public void invZzkwTlSys(Long srcInventoryId, Long destLocationId,double quantity) {
		invZzkwTl(srcInventoryId, destLocationId, quantity,  UserHolder.getUser().getName());
	}
	
	
	//投料制造库位
	public void invZzkwTl(Long srcInventoryId, Long destLocationId,double quantity,String oper) {
		Inventory srcInv = commonDao.load(Inventory.class, srcInventoryId);
		Location zzkw = commonDao.load(Location.class, destLocationId);
		double quantityMU = quantity;
		if (quantityMU > srcInv.getAvaliableQuantity()) {
			throw new BusinessException("inventory.quantity.insufficient");
		}
		Inventory inv=findInventory(srcInv.getItemKey(), srcInv.getZone(), zzkw, null, SysCode.ZZ_TL, zzkw);
		double srcQty1=inv.getQtyOfMasterPack();
		inv.setQuantity(inv.getQuantity()+quantity);
		inv.setQtyOfMasterPack(inv.getQtyOfMasterPack()+quantity);
		this.commonDao.store(inv);
		this.addInventoryLog(InventoryLogType.MOVE_ZZKW, 1, inv.getZone(), zzkw, null, inv.getItemKey(),
				quantity, null, oper, null,  (int)srcQty1+"变为"+(int)inv.getQtyOfMasterPack()+"投料"+inv.getId(), null, null, inv.getZzkw());
		double srcQty2=srcInv.getQtyOfMasterPack();
		srcInv.setQuantity(srcInv.getQuantity()-quantity);
		srcInv.setQtyOfMasterPack(srcInv.getQtyOfMasterPack()-quantity);
		this.commonDao.store(srcInv);
		this.addInventoryLog(InventoryLogType.MOVE_ZZKW, -1, srcInv.getZone(), srcInv.getLocation(), null, srcInv.getItemKey(),
				quantity, null, oper, null,  (int)srcQty2+"变为"+(int)srcInv.getQtyOfMasterPack()+"投料"+srcInv.getId(), null, null, srcInv.getZzkw());
	}
	
	@Override
	//查找库存存不存在
	public Inventory findInventory(ItemKey itemkey,WarehouseArea zone,Location location,String billCode,String type,Location zzkw){
		//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(zone.getHckw()==null){
				throw new BusinessException("维护库区对应线边待投料库位");
			}
//			hql+=" and inv.location.id='"+zone.getHckw().getId()+"'";
//			if(!type.equals(SysCode.CK_FP2)){
//				hql+=" and inv.zzkw.id="+zzkw.getId();
//			}
		}
		hql+=" and inv.location.id="+location.getId();
		//备货固定放在备货库位
		if(type.equals(SysCode.CK_FP2)){
			hql+=" and inv.location.type!='SHIP'";
		}else if(type.equals(SysCode.CK_TH1)){
			hql+=" and inv.location.type='SHIP'";
		}else if(type.equals(SysCode.CK_TH2)){
			hql+=" and inv.location.type!='SHIP'";
		}else if(type.equals(SysCode.CK_BH1)){
			hql+=" and inv.location.type!='SHIP' and inv.quantity>0";// and inv.queuedQuantity>0 ";
			if(zone.getCode().indexOf("-SL")>0) {
				hql+=" and inv.zzkw.id="+zzkw.getId();
			}
		}else if(type.equals(SysCode.CK_BH2)){
			hql+=" and inv.location.type='SHIP'";
			if(zone.getCode().indexOf("-SL")>0) {
				hql+=" and inv.zzkw.id="+zzkw.getId();
			}
		}else if(type.equals(SysCode.CK_FY1)){
			hql+=" and inv.location.type='SHIP'";
			if(zone.getCode().indexOf("-SL")>0) {
				hql+=" and inv.zzkw.id="+zzkw.getId();
			}
		}else if(type.equals(SysCode.CK_FY2)){
			hql+=" and inv.location.type!='SHIP'";
			if(zone.getCode().indexOf("-SL")>0) {
				hql+=" and inv.zzkw.id="+zzkw.getId();
			}
		}else if(type.equals(SysCode.RK_SH1)||type.equals(SysCode.RK_SH2)){
			hql+=" and inv.location.type!='SHIP' ";
			if(zone.getCode().indexOf("-SL")>0) {
				hql+=" and inv.zzkw.id="+zzkw.getId();
			}
		}else if(type.equals(SysCode.XB1)||type.equals(SysCode.XB2)){
			hql+=" and  inv.location.type!='SHIP' and inv.zzkw.id="+zzkw.getId();
		}else if(type.equals(SysCode.ZZKW_TRAN)){
			hql+=" and inv.zzkw.id="+zzkw.getId();
		}
		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)||type.equals(SysCode.ZZKW_TRAN)||type.equals(SysCode.ZZ_TL)||type.equals(SysCode.XB1)){
				Inventory dbInv=EntityFactory.getEntity(Inventory.class);
				dbInv.setLocation(location);
				dbInv.setItemKey(itemkey);
				dbInv.setZone(zone);
				if(zone.getCode().indexOf("-SL")>0) {
					dbInv.setBarCode("XB");
					dbInv.setZzkw(zzkw);
				}
				itemkey.getInventories().add(dbInv);
				this.commonDao.store(dbInv);
				return dbInv;
			}else{
				return null;
			}
		}
	}
	
	@Override
	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,Location zzkw) {
		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);
		log.setZzkw(zzkw);
		this.commonDao.store(log);
		return log;
	}
	
	//刷新出库单的重量体积
	private void refreshPick(Long id){
		PickTicket pt = commonDao.load(PickTicket.class, id);
		Object[] objs = (Object[])commonDao.findByQuery("select sum(d.orderQuantity),sum(d.allocatedQuantity),sum(d.pickedQuantity),sum(d.shippedQuantity) "
				+ " from PickTicketDetail d where d.pickTicket.id=:id", new String[]{"id"}, new Object[]{id}).get(0);
		double orderQuantity=(Double)(objs[0]==null?0D:objs[0]);
		double allocatedQuantity=(Double)(objs[1]==null?0D:objs[1]);
		double pickedQuantity=(Double)(objs[2]==null?0D:objs[2]);
		double shippedQuantity=(Double)(objs[3]==null?0D:objs[3]);
		pt.setOrderQuantity(orderQuantity);
		pt.setAllocatedQuantity(allocatedQuantity);
		pt.setPickedQuantity(pickedQuantity);
		pt.setShippedQuantity(shippedQuantity);
		this.commonDao.store(pt);
	}
	
//	public void refreshPlanPick(Long id) {
//		PickTicket pt =commonDao.load(PickTicket.class, id);
//		if(pt!=null) {
//		List<PlanPickDetail> ppds =commonDao.findByQuery(" from PlanPickDetail p where p.planPickTicket.id="+pt.getSourceId());
//			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 refreshPlanPickQty(Long id,Long itemId) {
//		PickTicket pt =commonDao.load(PickTicket.class, id);
		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+")");
		if(ptIds.size()>0){
			String ids=StringUtils.strip(ptIds.toString(),"[]");
			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 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);
				ptd.setBeSb(Boolean.TRUE);
				commonDao.store(ptd);
				pt.setPriority(1);
				this.commonDao.store(pt);
			}
		}
	}
	
	public void deletePlanAssembly(List<Long> ids) {
		for (Long id : ids) {
			PlanAssembly p = commonDao.load(PlanAssembly.class, id);
//			if(!d.getPlanPickTicket().getStatus().equals(PickTicketStatus.OPEN)){
//				throw new BusinessException("已加入备货计划，不能删除");
//			}else{
//				PlanPickTicket pt=d.getPlanPickTicket();
//				this.commonDao.delete(d);
				List<ProduceMonthPlan> ds=this.commonDao.findByQuery("from ProduceMonthPlan d where d.planAssembly.id="+p.getId());
				if(ds.size()>0){
					this.commonDao.deleteAll(ds);
				}
				this.commonDao.delete(p);
//			}
		}
	}
	
	public void importMoveLocation(File file){
		Workbook workbook;
		try {
			workbook = Workbook.getWorkbook(file);
			Sheet sheet = workbook.getSheet(0);//得到excel第一页的内容
			SimpleDateFormat yy = new SimpleDateFormat("yyyyMMdd");
			for (int i = 1; i <sheet.getRows(); i++) {
				System.out.println(i);
			 	String id=sheet.getCell(0,i).getContents().trim();
			 	String loc_code=sheet.getCell(1,i).getContents().trim();
				List<Location> locs=this.commonDao.findByQuery("from Location l where l.code='"+loc_code+"'");
				if(locs.size()>0){ 
					Location l=locs.get(0);
					Inventory inv=this.commonDao.get(Inventory.class, new Long(id));
					if(inv==null){
						throw new BusinessException("第"+(i+1)+"行库存不存在");
					}else{
						if(inv.getQueuedQuantity()<=0){
							addInventoryLog(InventoryLogType.MOVE, -1, inv.getZone(), inv.getLocation(), null, inv.getItemKey(),
									inv.getQuantity(), null, UserHolder.getUser().getName(), inv.getId(), "导入调整", null, null, inv.getZzkw());
							addInventoryLog(InventoryLogType.MOVE, 1, inv.getZone(), l, null, inv.getItemKey(),
									inv.getQuantity(), null, UserHolder.getUser().getName(), inv.getId(), "导入调整", null, null, inv.getZzkw());
							inv.setLocation(l);
							this.commonDao.store(inv);
						}else{
							throw new BusinessException("第"+(i+1)+"行库存被占用");
						}
					}
				}else{
					throw new BusinessException("第"+(i+1)+"行库位代码"+loc_code+"不存在");
				}
			 }
		} catch (BiffException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	public void checkAutoProduction(List<Long> ids) {
		List<BillType> list2=commonDao.findByQuery(" from BillType b where b.code='CKD单点' ");
		BillType billType=null;
		if(list2.size()>0) {
			billType=list2.get(0);
		}else {
			billType=commonDao.load(BillType.class, 6L);
		}
		for(Long id:ids){
			AutoProduction ap=this.commonDao.get(AutoProduction.class, id);
			AutoProductionLog log=EntityFactory.getEntity(AutoProductionLog.class);
			log.setAutoProduction(ap);
			log.setFxQty(ap.getFxQty());
			log.setPlanQty(ap.getPlanQty());
			log.setZone1(ap.getZone1());
			log.setCreateBy(UserHolder.getUser().getName());
			log.setCreateDate(new Date());
			this.commonDao.store(log);
			//生成耗用数据
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
			String xxrq=sdf.format(new Date());//下线日期
			double hyQty=0;
			if(ap.getProcedure().equals("TLQ")||ap.getProcedure().equals("TLB")){//吊装
				itemManager.getDzData(new Date());
				List<Object[]> objs =  commonDao.findByQuery("select t.modelType,count(*) from HoistingData t where t.status='未消耗' and t.allocateTime='"+xxrq+"'"
						+ " and t.code='620001' group by t.modelType");
				for(Object[] obj:objs){
					String modelType=obj[0].toString();//形式名
					String quantity= obj[1].toString();//数量
					createAutoHy("吊装数据", "620001", "TLQ", modelType, quantity, xxrq, new Date(),"自动计划");
				}
				List<SpareParts> sps=commonDao.findByQuery("from SpareParts p where  p.status='未消耗' and p.code='"+ap.getProcedure()+"' "
						+ "and p.autoCode is not null");
				for(SpareParts sp:sps){
					hySpareParts(sp);
					hyQty+=sp.getOrderQuantity();
				}
			}else if(ap.getProcedure().equals("TLH")){//下线
				itemManager.getXxData(new Date());
				List<Object[]> objs =  commonDao.findByQuery("select t.modelType,count(*) from OfflineData t where t.status='未消耗' and t.allocateTime='"+xxrq+"'"
						+ " and t.code='620611' group by t.modelType");
				for(Object[] obj:objs){
					String modelType=obj[0].toString();//形式名
					String quantity= obj[1].toString();//数量
					createAutoHy("下线数据", "620611", "TLH", modelType, quantity, xxrq, new Date(),"自动计划");
				}
				List<SpareParts> sps=commonDao.findByQuery("from SpareParts p where  p.status='未消耗' and p.code='"+ap.getProcedure()+"' "
						+ "and p.autoCode ='自动计划'");
				for(SpareParts sp:sps){
					hySpareParts(sp);
					hyQty+=sp.getOrderQuantity();
				}
			}
			List<ProductionPlan> ps= commonDao.findByQuery("from ProductionPlan p where (p.strExtend1 is null or p.strExtend1='未消耗')  and p.procedure='"+ap.getProcedure()+"'  order by p.longExtend1,p.id ");
			int count;
			if (ps.size()>ap.getFxQty()+ap.getPlanQty()){
				count =  ap.getFxQty().intValue()+ ap.getPlanQty().intValue();
			}else{
				count = ps.size();
			}
			String scsx=null;
			if(count>0){
				PlanPickTicket pt =EntityFactory.getEntity(PlanPickTicket.class);
				pt.setWarehouse(WarehouseHolder.getWarehouse());
				pt.setStatus(PickTicketStatus.OPEN);
				pt.setOrderDate(new Date());
	//			pt.setCode(this.bussinessCodeManager.getCodeForYm("SC",5));
				pt.setWarehouse(WarehouseHolder.getWarehouse());
				pt.setStatus(PickTicketStatus.OPEN);
				pt.setCode(this.bussinessCodeManager.getCodeForYm("ZS",3));
				pt.setCompany(commonDao.load(Structure.class, 1002L));
				pt.setBillType(billType);
				pt.setRelatedBill1("日出库单");
				pt.setRelatedBill2("");
				pt.setRelatedBill3(ap.getProcedure());
				pt.setZone(commonDao.load(WarehouseArea.class, 37L));
				pt.setZone1(ap.getZone1());
				commonDao.store(pt);
				for(int i=0;i<count;i++){
					ProductionPlan p=ps.get(i);
					PlanPickDetail ptd=createPlanPickDetail(pt, p, ap.getProcedure());
					p.setAutoProductionLog(log);
					p.setAutoProductionLog(log);
					this.commonDao.store(p);
					scsx=","+p.getId();
				}
				scsx.replaceFirst(",", "");
				pt.setDescription("自动计划"+log.getId());
				this.commonDao.store(pt);
				ap.setScsx(scsx);
				
			}
			ap.setHyQty(hyQty);
			ap.setCheckBy(UserHolder.getUser().getName());
			ap.setCheckDate(new Date());
			ap.setCreateBy(UserHolder.getUser().getName());
			ap.setCreateDate(new Date());
			ap.setStatus("已审核");
			ap.setSjQty(count+0d);
			this.commonDao.store(ap);
			log.setScsx(scsx);
			log.setSjQty(count+0d);
			log.setHyQty(ap.getHyQty());
			this.commonDao.store(log);
		}
	}
	
	private long addpptid;
	@Override
	public void addProductionPlan(Long pid,String tsr,String str1,double qty1,String procedure,String description,String modelName) {
		if(tsr==null||tsr.equals("")) {
			throw new BusinessException("起始机号不能空");
		}
		String meg="";
		List<ProductionPlan> pps=commonDao.findByQuery(" from  ProductionPlan p where p.modelNo='"+tsr+"'");
		if(pps.size()==0) {
			meg=tsr+"该起始机号错误！";
		}
	//	List<ProductionPlan> list= commonDao.findByQuery(" from  ProductionPlan p where (p.strExtend1 is null or p.strExtend1='未消耗') and p.procedure='"+procedure+"' and p.modelNo not in('"+description+"')  order by p.longExtend1,p.id ");
		
		String hql=" from  ProductionPlan p where (p.strExtend1 is null or p.strExtend1='未消耗') and p.procedure='"+procedure+"' and p.modelNo not in('"+description+"')";
		if(modelName!=null&&!modelName.equals("")){
			String[] ms=modelName.split(","); 
			for(int i=0;i<ms.length;i++){
				hql+=" and p.modelType!='"+ms[i]+"' ";
			}
		}
		hql+=" order by p.longExtend1,p.id ";
		List<ProductionPlan> list= commonDao.findByQuery(hql);

		if(list.size()>0&&meg.equals("")) {
			int y=1;
			PlanPickTicket pt =EntityFactory.getEntity(PlanPickTicket.class);
			pt.setWarehouse(WarehouseHolder.getWarehouse());
			pt.setStatus(PickTicketStatus.OPEN);
			pt.setOrderDate(new Date());
//			pt.setCode(this.bussinessCodeManager.getCodeForYm("SC",5));
			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='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.setRelatedBill2("");
			pt.setRelatedBill3(procedure);
			pt.setDescription("生产顺序计划");
			pt.setZone(commonDao.load(WarehouseArea.class, 37L));
			commonDao.store(pt);
			for(ProductionPlan p:list) {
				if((p.getModelNo().equals(tsr)||y>1)&&y<=qty1) {
					y++;
					PlanPickDetail ptd=createPlanPickDetail(pt, p, procedure);
				}
			}
			this.addpptid=pt.getId();
		}
		InterfaceLog log=new InterfaceLog();
	    	log.setDealTime(new Date());
	    	log.setFileName("生成备货计划");
	    	log.setFileType("手工生成");
	    	log.setType("生产顺序计划");
	    	log.setToSYS(UserHolder.getUser().getName());
	    	if(meg!=null&&!meg.equals("")) {
	    		log.setStatus("失败");
	    	 }else {
	    		 log.setStatus("成功");
	    	 }
	    	log.setErrorLog(meg);
	    	log.setRequestContent("");
	    	commonDao.store(log);
	}
	//生成明细
	public PlanPickDetail createPlanPickDetail(PlanPickTicket pt,ProductionPlan p,String procedure){
		PlanPickDetail ptd =null;
		List<PlanPickDetail> pdts=commonDao.findByQuery(" from PlanPickDetail p where p.planPickTicket.id="+pt.getId()+" and p.bigItem.id="+p.getBigItem().getId());
		if(pdts.size()>0) {
			ptd=pdts.get(0);
		}else {
			ptd=EntityFactory.getEntity(PlanPickDetail.class);
			ptd.setStrExtend3(p.getModelNo());
		}
		double qty=1D;
		ptd.setOrderQuantity(qty+ptd.getOrderQuantity());
		ptd.setBigItem(p.getBigItem());
		ptd.setPlanPickTicket(pt);
		ptd.setInvStatus(p.getModelType());
//				ptd.setZone(p.getOutZone());
		pt.setOrderQuantity(qty+pt.getOrderQuantity());
		ptd.setNumberNo(p.getNumberNo());
		ptd.setProcedure(procedure);
		ptd.setOfflineDate(p.getOfflineDate());
		ptd.setCode(p.getCode());
		ptd.setName(p.getName());
		ptd.setCountry(p.getCountry());
		ptd.setModelType(p.getModelType());
		ptd.setModelNo(p.getModelNo());
		ptd.setModelName(p.getModelName());
		ptd.setDescription(p.getDescription());
		commonDao.store(pt);
		commonDao.store(ptd);
		p.setStrExtend2(pt.getCode());
		commonDao.store(p);
		return ptd;
	}
	
	//生成耗用数据
			public void createAutoHy(String type,String code,String gwxx,String modelType,String qty,String xxrq,Date xxDate,String apCode) {
				List<BigItem> BigItems =  commonDao.findByQuery(" from BigItem bt where bt.code='"+modelType+"'");
				List<OfflineData> ods = commonDao.findByQuery(" from OfflineData t where t.status='未消耗' and t.allocateTime='"+xxrq+"' "
						+ " and  t.modelType='"+modelType+"' and t.code='620611'");
				List<HoistingData> hds =  commonDao.findByQuery(" from HoistingData t where t.status='未消耗' and t.allocateTime='"+xxrq+"'"
						+ " and  t.modelType='"+modelType+"' and t.code='620001'");
				if(BigItems.size()>0){
					BigItem bigItem=BigItems.get(0);
					if(code.equals("620001")){
						gwxx="TLQ";
					}else if(code.equals("620611")){
						gwxx="TLH";
					}
					SpareParts sp1=EntityFactory.getEntity(SpareParts.class);
					sp1.setCode(gwxx);
					sp1.setAllocateTime(xxDate);
					sp1.setBigItem(bigItem);
					sp1.setOrderQuantity(Double.parseDouble(qty));
					sp1.setStatus("未消耗");
					sp1.setUserDate(new Date());
					sp1.setUserName(UserHolder.getUser().getName());
					sp1.setDescription(type);//备注
					sp1.setAutoCode(apCode);
					commonDao.store(sp1);
					SpareParts sp2=null;
					if(type.equals("吊装数据")){
						sp2=EntityFactory.getEntity(SpareParts.class);
						sp2.setCode("TLB");
						sp2.setAllocateTime(xxDate);
						sp2.setBigItem(bigItem);
						sp2.setOrderQuantity(Double.parseDouble(qty));
						sp2.setStatus("未消耗");
						sp2.setUserDate(new Date());
						sp2.setUserName(UserHolder.getUser().getName());
						sp2.setDescription(type);//备注
						sp2.setAutoCode(apCode);
						commonDao.store(sp2);
					}
					//刷新状态
					if(type.equals("下线数据")){
						for(OfflineData hd:ods){
							hd.setStatus("已耗用");
							hd.setHyBy(UserHolder.getUser().getName());
							hd.setHyDate(new Date());
							hd.setHyId1(sp1.getId());
							commonDao.store(hd);
							//生产顺序耗用
							List<ProductionPlan> ps=this.commonDao.findByQuery("from ProductionPlan p where p.code='"+hd.getStr1()+"' and p.strExtend1='未消耗'"
									+ " and procedure='TLH' ");
							if(ps.size()>0){
								for(ProductionPlan p:ps){
									p.setStrExtend1("已耗用");
									p.setHyTime(new Date());
									if(p.getProcedure().equals("TLB")){
										p.setSpId(sp2.getId());
									}else{
										p.setSpId(sp1.getId());
									}
									this.commonDao.store(p);
								}
							}else{
								hd.setHyDes(hd.getStr1()+"找不到耗用或已经耗用");
								this.commonDao.store(hd);
								System.out.println(hd.getStr1()+"找不到耗用或已经耗用");
							}
						}
					}else if(type.equals("吊装数据")){
						for(HoistingData hd:hds){
							hd.setStatus("已耗用");
							hd.setHyBy(UserHolder.getUser().getName());
							hd.setHyDate(new Date());
							hd.setHyId1(sp1.getId());
							if(sp2!=null){
								hd.setHyId2(sp2.getId());
							}
							commonDao.store(hd);
							//生产顺序耗用
							List<ProductionPlan> ps=this.commonDao.findByQuery("from ProductionPlan p where p.code='"+hd.getStr1()+"' and p.strExtend1='未消耗'"
									+ " and procedure in ('TLQ','TLB') ");
							if(ps.size()>0){
								for(ProductionPlan p:ps){
									p.setStrExtend1("已耗用");
									p.setHyTime(new Date());
									if(p.getProcedure().equals("TLB")){
										p.setSpId(sp2.getId());
									}else{
										p.setSpId(sp1.getId());
									}
									this.commonDao.store(p);
								}
							}else{
								hd.setHyDes(hd.getStr1()+"找不到耗用或已经耗用");
								this.commonDao.store(hd);
								System.out.println(hd.getStr1()+"找不到耗用或已经耗用");
							}
						}
					}
				}else{
					//continue;
					if(code.equals("620611")){
						for(OfflineData od:ods){
							od.setHyDes("无对应完成品品番");
							commonDao.store(od);
						}
					}else if(code.equals("620001")){
						for(HoistingData hd:hds){
							hd.setHyDes("无对应完成品品番");
							commonDao.store(hd);
						}
					}
				}
				
				
				
			}
	
	
}
