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

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
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.TimeZone;
import java.util.Map.Entry;
import java.util.Set;

import jxl.CellType;
import jxl.DateCell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import com.dev.energy.client.utils.StringUtils;
import com.dev.energy.server.exception.BusinessException;
import com.dev.energy.server.model.Entity;
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.interfaces.ItemJobLauncher;
import com.dev.swms.server.model.abstractEntity.Pinfan;
import com.dev.swms.server.model.base.BillType;
import com.dev.swms.server.model.base.CompanyCode;
import com.dev.swms.server.model.base.Item;
import com.dev.swms.server.model.base.ItemKey;
import com.dev.swms.server.model.base.LPFormat;
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.PackageUnit;
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.Warehouse;
import com.dev.swms.server.model.base.WarehouseArea;
import com.dev.swms.server.model.base.Worker;
import com.dev.swms.server.model.fee.Fee;
import com.dev.swms.server.model.interfaces.InterfaceWmsDownload;
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.StockType;
import com.dev.swms.server.model.inventory.Task;
import com.dev.swms.server.model.receiving.ASN;
import com.dev.swms.server.model.receiving.ASNDetail;
import com.dev.swms.server.model.receiving.ASNStatus;
import com.dev.swms.server.model.receiving.MoveDoc;
import com.dev.swms.server.model.receiving.MoveDocDetail;
import com.dev.swms.server.model.receiving.MoveDocStatus;
import com.dev.swms.server.model.receiving.ReceivedDoc;
import com.dev.swms.server.model.receiving.ReceivedRecord;
import com.dev.swms.server.model.receiving.ReceivingDoc;
import com.dev.swms.server.model.receiving.ReceivingDocDetail;
import com.dev.swms.server.model.receiving.ReceivingDocStatus;
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.RkEwmRecord;
import com.dev.swms.server.service.GlobalParamUtils;
import com.dev.swms.server.service.base.ItemManager;
import com.dev.swms.server.service.base.WarehouseManager;
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.receiving.ASNManager;
import com.dev.swms.server.service.receiving.MoveDocManager;
import com.dev.swms.server.service.receiving.PutawayAllocator;
import com.dev.swms.server.service.sequence.BussinessCodeManager;
import com.dev.swms.server.service.shipping.PickKamsManager;
import com.dev.swms.server.service.shipping.PickTicketManager;
import com.dev.swms.server.utils.DateUtil;
import com.dev.swms.server.utils.DoubleUtils;
import com.dev.swms.server.web.filter.WarehouseHolder;
import com.sun.org.apache.bcel.internal.generic.SIPUSH;

/**
 * @author dev
 * 
 */
@SuppressWarnings("unchecked")
public class DefaultASNManager extends DefaultBaseManager implements ASNManager {
	protected final ItemManager itemManager;
	protected final InventoryManager inventoryManager;
	protected final BussinessCodeManager bussinessCodeManager;
	protected final PutawayAllocator putawayAllocator;
	protected final WarehouseManager warehouseManager;
	protected final InterfaceLogManager logManager;
	protected final PickTicketManager pickTicketManager;
	protected final MoveDocManager moveDocManager;
	protected final FeeManager feeManager;
	protected final PickKamsManager pickKamsManager;

	public DefaultASNManager(ItemManager manager, InventoryManager manager2,
			BussinessCodeManager manager3, PutawayAllocator putawayAllocator,
			WarehouseManager manager4, InterfaceLogManager manager5,
			PickTicketManager pickTicketManager, MoveDocManager moveDocManager,
			FeeManager feeManager,PickKamsManager pickKamsManager) {
		super();
		itemManager = manager;
		this.inventoryManager = manager2;
		this.bussinessCodeManager = manager3;
		this.putawayAllocator = putawayAllocator;
		this.warehouseManager = manager4;
		this.logManager = manager5;
		this.pickTicketManager = pickTicketManager;
		this.moveDocManager = moveDocManager;
		this.feeManager = feeManager;
		this.pickKamsManager=pickKamsManager;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.dev.swms.server.service.receive.ASNManager#addASNDetail(java.lang
	 * .Long, com.dev.swms.server.model.receiving.ASNDetail)
	 */
	public void addASNDetail(Long asnId, ASNDetail asnDetail) {
		ASN asn = commonDao.load(ASN.class, asnId);
		if (asnDetail.getDock() == null || asnDetail.getDock().getId() == 0) {
			asnDetail.setDock(null);
		} else {
			asnDetail.setDock(this.load(Location.class, asnDetail.getDock()
					.getId()));
		}
		PackageUnit unit = null;
		List<PackageUnit> PackageUnits = commonDao.findByQuery(
				" from PackageUnit o where o.item.id=:id ", new String[] { "id" },
				new Object[] { asnDetail.getItem().getId() });
//		List<PackageUnit> PackageUnits = commonDao.findByQuery(" from PackageUnit o where o..id=:id ",
//				new String[] { "id" }, new Object[] { asnDetail.getItem().getId() });
//		List<PackageUnit> PackageUnits = commonDao.findByQuery(" from PackageUnit o where o.item.id=:id ",
//				new String[] { "id" }, new Object[] { asnDetail.getItem().getId() });
		if (PackageUnits.size() > 0) {
			unit = PackageUnits.get(0);
		}
		asnDetail.setExpectedQuantity(asnDetail.getExpectedQuantity());
		asnDetail.setExpectedQtyOfMasterUnit(asnDetail.getExpectedQuantity());
		if (asnDetail.getExpectedQuantity() <= 0) {
			throw new BusinessException("docDetail.add.quantityError");
		}

		Item item = this.commonDao
				.load(Item.class, asnDetail.getItem().getId());
		// asnDetail.setLotInfo(convertLot(asn.getCompany().getCode(),asnDetail.getLotInfo()));
		itemManager.formatLotInfo(item, asnDetail.getLotInfo(), Boolean.FALSE);
		if (ASNStatus.OPEN.equals(asn.getStatus())||ASNStatus.ACTIVE.equals(asn.getStatus())) {
			ASNDetail dbDetail = asn.geASNDetailByCondition(asnDetail.getPO(),
					asnDetail.getLineNo(), asnDetail.getItem(),
					asnDetail.getLotInfo(), asnDetail.getPackageUnit());

			if (asnDetail.isNew()) {
				if (dbDetail != null) {
					throw new BusinessException("docDetail.add.uniqueError");
				}
				asnDetail.setLineNo(asn.getAsnDetails().size() + 1);
				asnDetail.setPackageUnit(unit);
				asn.addASNDetail(asnDetail);
				asnDetail.setCaCoefficient(item.getCAcoefficient() == null ? 0
						: item.getCAcoefficient());
			} else {
				if (dbDetail == null) {
					dbDetail = commonDao.load(ASNDetail.class,
							asnDetail.getId());

				}
				if (!dbDetail.getId().equals(asnDetail.getId())) {
					throw new BusinessException("docDetail.add.uniqueError");
				}
				asn.setExpectedQuantity(asn.getExpectedQuantity()
						- dbDetail.getExpectedQtyOfMasterUnit());
				dbDetail.setPackageUnit(unit);
				dbDetail.setItem(item);
				dbDetail.setExpectedQuantity(asnDetail.getExpectedQuantity());
				dbDetail.setExpectedQtyOfMasterUnit(asnDetail
						.getExpectedQtyOfMasterUnit());
				dbDetail.setPO(asnDetail.getPO());
				dbDetail.setTemperature(asnDetail.getTemperature());
				dbDetail.setLineNo(asnDetail.getLineNo());
				dbDetail.setLotInfo(asnDetail.getLotInfo());
				dbDetail.setDock(asnDetail.getDock());
				dbDetail.setCaCoefficient(item.getCAcoefficient() == null ? 0
						: item.getCAcoefficient());
				asn.setExpectedQuantity(asn.getExpectedQuantity()
						+ dbDetail.getExpectedQtyOfMasterUnit());
				if (dbDetail.getExpectedQuantity() <= 0) {
					asn.getAsnDetails().remove(dbDetail);
				}
				

			}
			if(dbDetail!=null){
				asn.setSourceId(dbDetail.getLotInfo()==null?null:dbDetail.getLotInfo().getPropC1());
			}
			asn.setTemperature("");
			commonDao.store(asn);
		}

		refreshweightandvolume(asnId);// 刷新

	}

	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);

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.dev.swms.server.service.receive.ASNManager#removeASNDetail(java.lang.
	 * Long, java.util.List)
	 */
	public void removeASNDetail(Long asnId, List<Long> ASNDetailIds) {
		ASN asn = commonDao.load(ASN.class, asnId);
		for(Long id:ASNDetailIds){
			ASNDetail d=this.commonDao.get(ASNDetail.class, id);
			this.commonDao.delete(d);
		}
//		asn.removeDetails(ASNDetailIds);
		if (asnId != null) {
			refreshweightandvolume(asnId);
		}

	}

	/*
	 * 整单收货
	 * 
	 * @see
	 * com.dev.swms.server.service.receive.ASNManager#confirmReceiving(java.
	 * lang. Long, java.lang.Long)
	 */
	@SuppressWarnings("unchecked")
	public void confirmReceiving(Long asnId, Date receiveDate,String qualityCode, Long workerId, Long zoneId) {
		List<Long> asnDetailIds = commonDao.findByNamedQuery(
				"getASNDetailIdsByASNID", new String[] { "asnId" },
				new Object[] { asnId });
		this.confirmReceiving(asnId, asnDetailIds, receiveDate, qualityCode,
				workerId, zoneId);
	}
	
	@SuppressWarnings("unchecked")
	public void confirmReceivingVIM(Long asnId, String qualityCode, Long workerId, Long zoneId) {
		List<Long> asnDetailIds = commonDao.findByNamedQuery(
				"getASNDetailIdsByASNID", new String[] { "asnId" },
				new Object[] { asnId });
		ASN asn=this.commonDao.get(ASN.class, asnId);
		this.confirmReceiving(asnId, asnDetailIds, asn.getReceivedDate(), qualityCode,
				workerId, zoneId);
	}

	/*
	 * 批量收货
	 * 
	 * @see
	 * com.dev.swms.server.service.receive.ASNManager#comfireASN(java.lang.Long,
	 * java.util.List, java.lang.Long)
	 */
	public void confirmReceiving(Long asnId, List<Long> asnDetailIds,Date receiveDate, String qualityCode, Long workerId,
			Long zoneId) {
		if (zoneId == null) {
			throw new BusinessException("选择库区");
		}
		ASN asn = commonDao.load(ASN.class, asnId);
		if(asn.getZone()!=null){
			zoneId=asn.getZone().getId();
		}
		Worker worker = this.load(Worker.class, workerId);
		if (worker != null) {
			asn.setInputWorker(worker);
		}
		for (ASNDetail asnDetail : asn.getAsnDetails()) {
//			if (asnDetailIds.contains(asnDetail.getId())) {
			if (asnDetail.getUnReceivedQuantity()>0) {
				Item it=asnDetail.getItem();
				Location location=it.getLocation();
				if (location == null) {
					throw new BusinessException(it.getCode()+"所属库位为空");
				}
				// 不允许收取超过订单数量的库存
				double availableQty = asnDetail.getUnReceivedQuantity();
				commonDao.store(asnDetail);
				if (availableQty > 0) {
//					LotInfo lotinfo=asnDetail.getLotInfo();
//					if(lotinfo==null){
//						lotinfo=new LotInfo();
//					}
//					lotinfo.setPropL2(zoneId);
					ItemKey key = this.itemManager.getItemKey(new ItemKey("",
							asnDetail.getItem(), asnDetail.getLotInfo(),
							receiveDate, asn.getRelatedBill1(),null), Boolean.TRUE,asnDetail.getRemark());
					// 收货
					receive(asn, asnDetail, key, location, availableQty,
							asnDetail.getPackageUnit(), null, null, 0, 0,
							receiveDate, qualityCode, worker);
				}
			}
		}
	}
	
	public void confirmAsnReceivingKams(List<Long> asnIds,String myfs,Date receiveDate, String receivingstatus,
			Long zoneId) {
		for(Long id:asnIds){
			List<Long> ids=this.commonDao.findByQuery("select id from ASNDetail d where d.asn.id="+id +" and d.receivedQuantity<d.expectedQtyOfMasterUnit");
			WarehouseArea zone=commonDao.load(WarehouseArea.class, zoneId);
			Location loc=null;
			if(zone.getCode().indexOf("-SL")>0) {
//				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+"的久保田线边库位");
//				}
//				loc=ls.get(0);
				if(zone.getHckw()==null){
					throw new BusinessException("维护库区对应线边待投料库位");
				}
				loc=zone.getHckw();
			}
			confirmReceivingKams(ids, myfs,receiveDate,  receivingstatus,zoneId,loc);
		}
	}
	public void confirmReceivingAllKams(Long asnId,Date receiveDate, String receivingstatus,
			Long zoneId) {
		List<Long> ids=this.commonDao.findByQuery("select id from ASNDetail d where d.asn.id="+asnId +" and d.receivedQuantity<=0");
		WarehouseArea zone=commonDao.load(WarehouseArea.class, zoneId);
		Location loc=null;
		if(zone.getCode().indexOf("-SL")>0) {
//			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+"的久保田线边库位");
//			}
//			loc=ls.get(0);
			if(zone.getHckw()==null){
				throw new BusinessException("维护库区对应线边待投料库位");
			}
			loc=zone.getHckw();
		}
		confirmReceivingKams(ids, null,receiveDate,  receivingstatus,zoneId,loc);
	}
	
	public void confirmReceivingKams(List<Long> asnDetailIds,String myfs,Date receiveDate, String receivingstatus,
			Long zoneId,Location loc) {
		if (zoneId == null) {
			throw new BusinessException("选择库区");
		}
		ASN asn = null;
		for (Long id:asnDetailIds) {
			ASNDetail asnDetail=this.commonDao.get(ASNDetail.class, id);
			asn=asnDetail.getAsn();
			String str=asnDetail.getLotInfo()==null?null:asnDetail.getLotInfo().getPropC1();
			if(!asn.getBillType().getCode().equals("QTRK")) {
				if(myfs!=null&&!myfs.equals("")) {
					if(str.equals("进料对口")) {
						str="保税";
					}else if("一般贸易".equals(str)) {
						str="课税";
					}else if("暂时进出货物".equals(str)) {
						str="保税";
					}else if("其他进出口免费".equals(str)) {
						str="课税";
					}
					if(!str.equals(myfs)) {
					throw new BusinessException("贸易方式选择的跟入库单不一致");
					}
				}
			}else{
				str=asnDetail.getTemperature();
			}
			if(str==null||str.equals("")){
				throw new BusinessException("税别有误");
			}else{
				if(!str.equals("课税")&&!str.equals("保税")) {
					throw new BusinessException("税别有误");
				}
			}
//			asn.setSourceId(str);
			asn.setTemperature(myfs);
//			if(receivingstatus==null||receivingstatus.equals("")) {
//				receivingstatus=asnDetail.getRemark();
//			}
			
//			if (asnDetailIds.contains(asnDetail.getId())) {
			WarehouseArea zone=commonDao.load(WarehouseArea.class, zoneId);
			
			if (asnDetail.getUnReceivedQuantity()>0) {
				Item it=asnDetail.getItem();
				String hql="from Pinfan f where f.item.id="+it.getId();
				if(zone.getCode().indexOf("-SL")>0) {
					if(str.equals("保税")||str.equals("进料对口")) {
						hql+="  and f.zone.code='"+SysCode.W_BS+"'";
					}else {
						hql+="  and f.zone.code='"+SysCode.W_KS+"'";
					}
				}else{
					hql+="  and f.zone.id="+zoneId;
				}
				List<Pinfan> pfs=this.commonDao.findByQuery(hql);
				if(pfs.size()<=0){
					asnDetail.setMyfs("未关联品番");
					asnDetail.setChTate(new Date());
					commonDao.store(asnDetail);
					continue;
//					throw new BusinessException(it.getCode()+"未找到品番关联信息");
				}
				if(zone.getCode().indexOf("-SL")<=0) {
					loc=pfs.get(0).getLocation();
					if (loc == null) {
						asnDetail.setMyfs(it.getCode()+"关联品番无库位");
						asnDetail.setChTate(new Date());
						commonDao.store(asnDetail);
						continue;
//						throw new BusinessException(it.getCode()+"所属库位为空");
					}
				}
				// 不允许收取超过订单数量的库存
				double availableQty = asnDetail.getUnReceivedQuantity();
				asnDetail.setMyfs("");
				commonDao.store(asnDetail);
				if (availableQty > 0) {
					ItemKey key = this.itemManager.getItemKey(new ItemKey("",
							asnDetail.getItem(), pfs.get(0)), Boolean.TRUE,null);
					this.commonDao.store(key);
					// 收货
					receive(asn, asnDetail, key, loc, availableQty,
							asnDetail.getPackageUnit(), zoneId, null, 0, 0,
							receiveDate, receivingstatus, null);
				}
			}
		}
	}
	
	public void confirmReceivingKamsAppFdjs(Long detailId,Long pfId,String location_code,String barCodes,String oper) {
		ASNDetail asnDetail=this.commonDao.get(ASNDetail.class, detailId);
		String[] strs=barCodes.split(",");
		for(int i=0;i<strs.length;i++ ){
			String barCode=asnDetail.getItem().getCode()+strs[i];
			this.confirmReceivingKamsApp(detailId, location_code, pfId, 1, barCode, new Date(), oper);
		}
	}
	
	
	public void confirmReceivingKamsApp(Long detailId,String location_code,Long pfId,double qty,String barCode,Date receiveDate,String oper) {
		ASNDetail asnDetail=this.commonDao.get(ASNDetail.class, detailId);
		ASN asn=asnDetail.getAsn();
		Pinfan pf=commonDao.get(Pinfan.class, pfId);
		if(asnDetail.getLotInfo()!=null){
			asn.setSourceId(asnDetail.getLotInfo().getPropC1());
		}
		asn.setTemperature(pf.getBonded());
		WarehouseArea zone=pf.getZone();
		if (asnDetail.getUnReceivedQuantity()>0) {
			Item it=asnDetail.getItem();
			Location location=pf.getLocation();
			List<Location> ls=commonDao.findByQuery("from Location l where (l.code='"+location_code+"' or l.barCode='"+location_code+"' )  and l.id!=7104  and l.flagStatus!='WAIT_ADD'  "
					+ " and l.warehouse.id="+asn.getWarehouse().getId());
			if(ls.size()>0){
				location=ls.get(0);
			}
			if (location == null) {
				asnDetail.setMyfs("未关联库位");
				commonDao.store(asnDetail);
				asnDetail.setChTate(new Date());
//				location=commonDao.load(Location.class, 2594L);
//				continue;
				throw new BusinessException(it.getCode()+"所属库位为空");
			}
			// 不允许收取超过订单数量的库存
			double availableQty = asnDetail.getUnReceivedQuantity();
			if(qty>availableQty){
				throw new BusinessException(it.getCode()+"数量大于未收货数量");
			}
			asnDetail.setMyfs("");
			commonDao.store(asnDetail);
			if (qty > 0) {
				String pcy="";
				String hql=" from ItemKey ik where ik.item.id="+asnDetail.getItem().getId()+" and ik.pinfan.id="+pfId ;
				if(it.isBeWeight()){
					pcy=DateUtil.formatDateYMToStr(new Date());
					hql+=" and ik.lotInfo.propC3='"+pcy+"'";
				}
				List<ItemKey> iks=this.commonDao.findByQuery(hql);
				ItemKey ik =null;
				if(iks.size()>0){
					ik=iks.get(0);
				}else{
					ik=EntityFactory.getEntity(ItemKey.class);
					String lot = bussinessCodeManager.getCodeForYm("",5);
					ik.setLot(lot);
					ik.setPinfan(pf);
					ik.setItem(asnDetail.getItem());
					LotInfo lotInfo=new LotInfo();
					lotInfo.setPropC3(pcy);
					if(it.isBeWeight()){
						lotInfo.setPropD1(new Date());
					}
					ik.setLotInfo(lotInfo);
					commonDao.store(ik);
				}
				Inventory inv=pickTicketManager.findInventory(ik, zone, location, asn.getCode(), SysCode.RK_SH1);
				double qty1=inv.getQtyOfMasterPack();
				inv.add(qty, 0, 0);
				this.commonDao.store(inv);
				pickTicketManager.addInventoryLog(InventoryLogType.RECEIVING, 1, zone, location, asn.getCode(), ik, qty, barCode, oper, inv.getId(), (int)qty1+"变为"+(int)inv.getQtyOfMasterPack(),null,null);
				// 收货
				Worker worker=null;
				ReceivedRecord rd=asnDetail.addReceivedRecord(zone, location, ik, qty, barCode, receiveDate, null, worker, oper);
				this.commonDao.store(rd);
				if(it.isBeWeight()){
					//保存二维码采集表
					RkEwmRecord e=EntityFactory.getEntity(RkEwmRecord.class);
					e.setPf(pf);
					e.setItem(it);
					e.setRky(pcy);
					e.setRd(rd);
					e.setWarehouse(asn.getWarehouse());
					String fdj=barCode.substring(10, barCode.length());
					if(barCode.indexOf("1J81420000")>0){
						//样例： PIN MD1J81420000 SN7PM0642 WGN EMC ESN
						 fdj=barCode.substring(19, 26);;
					}
					e.setEwm(barCode);
					e.setFdj(fdj);
					e.setAc(pf.getSpecs());
					e.setHz(pf.getHezi());
					e.setJgzx(pf.getContent());
					e.setSrs((int)pf.getQuantity());
					e.setShsl(1);
					e.setCreateBy(oper);
					e.setCreateDate(new Date());
					this.commonDao.store(e);
				}

				refreshReceAsn(asn);
			}
		}
	}
	//刷新入库单的数据
	public void refreshReceAsn(ASN asn){
		List<Double> objs=this.commonDao.findByQuery("select sum(receivedQuantity) from ReceivedRecord r where r.asn.id="+asn.getId());
		if(objs.size()>0){
			asn.setReceivedQuantity(objs.get(0));
			asn.setReceivedDate(new Date());
			if(asn.getReceivedQuantity()<asn.getExpectedQuantity()){
				asn.setStatus(ASNStatus.RECEIVING);
			}else{
				asn.setStatus(ASNStatus.RECEIVED);
			}
		}else{
			asn.setStatus(ASNStatus.ACTIVE);
		}
		this.commonDao.store(asn);
	}

	public void yjshConfirmReceiving(List<Long> asnIds, Date receiveDate,
			Long locationId) {
		for (Long id : asnIds) {
			ASN asn = commonDao.load(ASN.class, id);
			for (ASNDetail asnDetail : asn.getAsnDetails()) {
				Location location = this.commonDao.get(Location.class,
						locationId);
				// 不允许收取超过订单数量的库存
				double availableQty = asnDetail.getUnReceivedQuantity();
				if (availableQty > 0) {
					ItemKey key = this.itemManager.getItemKey(new ItemKey("",
							asnDetail.getItem(), asnDetail.getLotInfo(),
							receiveDate, asn.getCode(),null), Boolean.TRUE,asnDetail.getRemark());
					// 收货
					receive(asn, asnDetail, key, location, availableQty,
							asnDetail.getPackageUnit(), null, null, 0, 0,
							receiveDate, null, null);
				}
			}
		}
	}

	// public void

	/**
	 * asn收货确认时根据asnDetail中的po和lineNo反查对应的收货单及其明细，如果找到，则更新收货单及其明细的收货数量，
	 * 并设置收货单状态为RECEIVING（收货中），如果收货单的订单数量等于收货数量，则自动关闭收货单；
	 * 
	 * @param asnDetail
	 * @param quantity
	 *            （基本单位数量）
	 */
	private void dealReceivingDoc(ASNDetail asnDetail, Double quantity) {
		ReceivingDocDetail recDetail = (ReceivingDocDetail) commonDao
				.findByNamedQueryUniqueResult(
						"getReceivingDocDetailByPOAndLineNo",
						new String[] { "po", "lineNo" },
						new Object[] { asnDetail.getPO(), asnDetail.getLineNo() });
		if (recDetail == null) {
			return;
		}
		ReceivingDoc doc = recDetail.getReceivingDoc();
		recDetail.setReceivedQuantity(recDetail.getReceivedQuantity()
				+ quantity);
		// if (recDetail.getReceivedQuantity() >
		// recDetail.getExpectedQtyOfMasterUnit()
		if (DoubleUtils.compareByPrecision(recDetail.getReceivedQuantity(),
				recDetail.getExpectedQtyOfMasterUnit(), recDetail
						.getPackageUnit().getPrecision()) > 0
				&& !doc.getCompany().isBeRevLimit()) {
			throw new BusinessException("receiving.quantity.error");
		}
		doc.setReceivedQuantity(doc.getReceivedQuantity() + quantity);
		if (doc.isAllReceived() && !doc.getCompany().isBeRevLimit()) {
			doc.setStatus(ReceivingDocStatus.CLOSE);
		} else {
			doc.setStatus(ReceivingDocStatus.RECEIVING);
		}
		this.commonDao.store(doc);
	}

	/*
	 * 单一收货
	 * 
	 * @see
	 * com.dev.swms.server.service.receive.ASNManager#confirmReceiving(java.
	 * lang. Long, java.lang.Long, com.dev.swms.server.model.base.ItemKey,
	 * java.lang.Long, double, java.lang.Long)
	 */
	// 单一明细收货确认
	public void confirmReceiving(Long asnId, Long asnDetailId, LotInfo lotInfo,
			 double puQty, Date receiveDate, String qualityCode,
			 Long workerId, Long zoneId, ASNDetail detail) {
		ASN asn = commonDao.load(ASN.class, asnId);
		ASNDetail asnDetail = commonDao.load(ASNDetail.class, asnDetailId);
		// 提取ASN收货月台作为收货库位
		Location location = asnDetail.getDock();
		if (location == null) {
			throw new BusinessException("receiving.dock.error");
		}
		PackageUnit receivingPack = asnDetail.getPackageUnit();// commonDao.load(PackageUnit.class,
																// receivingPackId);
		double quantity =puQty;
		double availableQty = asnDetail.getExpectedQtyOfMasterUnit()
				- asnDetail.getReceivedQuantity();
		commonDao.store(asnDetail);
		ReceivedRecord receivedRecord = null;
		// 如果ASN货主不允许多收, 则不能收取超过订单数量的库存
		if (asn.getCompany().isBeRevLimit()
				|| (!asn.getCompany().isBeRevLimit() && availableQty >= (quantity * receivingPack
						.getConvertFigure()))) {
			Stock stock = null;
			ItemKey key = this.itemManager.getItemKey(
					new ItemKey("", asnDetail.getItem(), lotInfo, receiveDate,
							asn.getCode(),null), Boolean.TRUE,asnDetail.getRemark());
			Worker worker = this.load(Worker.class, workerId);
			receivedRecord = receive(asn, asnDetail, key, location, quantity
					* receivingPack.getConvertFigure(), receivingPack,
					stock == null ? null : stock.getId(), null,
					0, 0, receiveDate, qualityCode, worker);
		} else {
			throw new BusinessException("receiving.quantity.error");
		}

	}


	/**
	 * 收货动作
	 * 
	 * @param asn
	 * @param asnDetail
	 * @param location
	 * @param receiveQty
	 *            (基本单位数量)
	 * @param LP
	 */

	public ReceivedRecord receive(ASN asn, ASNDetail asnDetail,
			ItemKey itemKey, Location location, double receiveQty,
			PackageUnit receivingPack, Long zone_id, String barCode,
			double weight, double volume, Date receiveDate, String receivingstatus,
			Worker worker) {
		zone_id=zone_id==null?asn.getZone().getId():zone_id;
		WarehouseArea zone=this.commonDao.get(WarehouseArea.class, zone_id);
		// 当该ASN单货主允许收货质检, 则无论质损代码如何都设置为"质检"
		if (barCode != null && barCode.equals("")) {
			barCode = null;
		}
//		if (asn.getCompany().isBeAsnQuality()) {
//			receivingstatus = Inventory.STATUS_QUALITY;
//		}
		// 获取入库单
//		ReceivedDoc receivedDoc = this.createReceivedDoc(asn);
		ReceivedDoc receivedDoc = null;
//		Boolean reject = Boolean.FALSE;
//		if (asn.getBillType().getName().equals("不良品退货收货单")) {
//			reject = Boolean.TRUE;  
//		}
//		inventoryManager.receiving(location.getId(), itemKey, receiveQty,
//				null, zone_id, barCode, weight, volume,
//				asn.getCode(), receivingstatus, receiveDate, asn.getBillType(),
//				Boolean.FALSE, reject);
		Location zzkw=null;
		if(zone.getCode().indexOf("-SL")>0) {
			zzkw=asnDetail.getZzkw();
			if(zzkw==null){
				throw new BusinessException("线边仓制造库位必填");
			}
		}
		Inventory inv=pickKamsManager.findInventory(itemKey, zone, location, asn.getCode(), SysCode.RK_SH1, zzkw);
		double srcQty1=inv.getQtyOfMasterPack();
		inv.setQtyOfMasterPack(inv.getQtyOfMasterPack()+receiveQty);
		inv.setQuantity(inv.getQtyOfMasterPack());
		this.commonDao.store(inv);
		String str1=InventoryLogType.RECEIVING;
		if(asn.getBillType()!=null&&asn.getBillType().getCode().equals("QTRK")) {
			str1=InventoryLogType.RECEIVING_ADJUST;
		}
		
		inventoryManager.addInventoryLog(str1, 1, zone,location, asn.getCode(), itemKey, receiveQty, null, UserHolder.getUser().getName(), inv.getId(), (int)srcQty1+"变为"+(int)inv.getQtyOfMasterPack(),asn.getDescription(),null,null,zzkw);
		Stock stock =null;
		ReceivedRecord receivedRecord = asn.receiving(asnDetail, location,
				itemKey, receiveQty, receivingPack, stock, barCode, weight,
				volume, receiveDate, receivedDoc, worker, receivingstatus);
		receivedRecord.setZone(zone);
		Set<ReceivedRecord> l = asn.getReceivedRecords();
		l.add(receivedRecord);
		asn.setZone(zone);
		commonDao.store(asn);
		// 检查是否创建上架计划, 当货主不需要收货质检, 货主不允许多收时而且收货完成, 则收货完毕自动创建上架计划
		if ( asn.isAllReceived()) {
			List<Long> asnIds = new ArrayList();
			asnIds.add(asn.getId());
			// this.createMoveDocByASN(asnIds);
			asn.setStatus(ASNStatus.CLOSE);
//			feeManager.autoAsnFee(asn.getId());
			// 调用接口发送收货确认消息
			// logManager.asnReceiveResponse(asn);
		}
		// // 处理收货单和收货单明细
		dealReceivingDoc(asnDetail, receiveQty);
		return receivedRecord;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.dev.swms.server.service.receive.ASNManager#storeASN(com.dev.swms.
	 * server. model.receiving.ASN)
	 */
	public void storeASN(ASN asn) {
		// 保存收货单
		if (asn.isNew()) {
			// asn.setCode(this.bussinessCodeManager.getCodeByBillType(asn.getBillType(),
			// WarehouseHolder.getWarehouse().getId()));
			if(asn.getCompany()==null) {
				asn.setCompany(commonDao.load(Structure.class, 1002L));
			}
			asn.setCode(this.bussinessCodeManager.getCodeForYm("RK", 3));
			asn.setWarehouse(WarehouseHolder.getWarehouse());
			asn.setStatus(ASNStatus.ACTIVE);
			asn.setBillType(this.load(BillType.class, asn.getBillType().getId()));
		} 
		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();
		if(asn.getZone()!=null&&!asn.getWarehouse().getId().equals(new Long("1"))){
			asn.setCompany(asn.getZone().getSupplier());
		}
		commonDao.store(asn);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.dev.swms.server.service.receive.ASNManager#deleteAll(java.util.List)
	 */
	public void deleteAll(List<Long> asnIds) {
		String errMsg = "";
		for (Long id : asnIds) {
			ASN asn = commonDao.load(ASN.class, id);
			if (ASNStatus.OPEN.equals(asn.getStatus())
					|| ASNStatus.ACTIVE.equals(asn.getStatus())) {
				commonDao.delete(asn);
				errMsg += asn.getCode() + " 单据删除成功;";
			} else
				errMsg += asn.getCode() + " 单据删除失败;";
		}
		LocalizedMessage.addLocalizedMessage(errMsg);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.dev.swms.server.service.receiving.ASNManager#cancelAll(java.util.
	 * List)
	 */
	public void cancelAll(List<Long> asnIds) {
		String errMsg = "";
		for (Long id : asnIds) {
			ASN asn = commonDao.load(ASN.class, id);
			if (asn.cancel()) {
				errMsg += asn.getCode() + " 单据取消成功;";
			} else
				errMsg += asn.getCode() + " 单据取消失败;";
		}
		LocalizedMessage.addLocalizedMessage(errMsg);
	}

	public void receiveBack(List<Long> receivedRecordIds) {
		String barCode = null;
		double weight = 0;
		double volume = 0;
		Set<String> moveDocs = new HashSet<String>();
		for (Long id : receivedRecordIds) {
			ReceivedRecord receivedRecord = commonDao.load(
					ReceivedRecord.class, id);
			// 已上架则不能取消收货
			if (receivedRecord.isBeMoved()) {
				continue;
			}
			// 待退拣数量（MU）
			double revQty = receivedRecord.getReceivedQuantityMU()- receivedRecord.getQualityQty();
			if (receivedRecord.getMoveDocCode() != null
					&& !moveDocs.contains(receivedRecord.getMoveDocCode())) {
				moveDocs.add(receivedRecord.getMoveDocCode());
				MoveDoc moveDoc = (MoveDoc) this.commonDao
						.findByNamedQueryUniqueResult(
								"getMoveDocByCodeAndRelateBillCode",
								new String[] { "code", "relateBillCode",
										"warehouseId", "companyId", "asnTypeId" },
								new Object[] {
										receivedRecord.getMoveDocCode(),
										receivedRecord.getAsn().getCode(),
										receivedRecord.getAsn().getWarehouse()
												.getId(),
										receivedRecord.getAsn().getCompany()
												.getId(),
										receivedRecord.getAsn().getBillType()
												.getId() });
				if (MoveDocStatus.OPEN.equals(moveDoc.getStatus())
						|| MoveDocStatus.ACTIVE.equals(moveDoc.getStatus())
						|| MoveDocStatus.ALLOCATE.equals(moveDoc.getStatus())) {
					if (MoveDocStatus.OPEN.equals(moveDoc.getStatus())) {
						putawayAllocator.unallocate(moveDoc);
					}

					// 已质检登记的数量不能回退
					receivedRecord.getAsnDetail().receiveBack(receivedRecord,
							moveDoc);

					inventoryManager.receivingAdjust(receivedRecord
							.getLocation().getId(),
							receivedRecord.getItemKey(), revQty, receivedRecord
									.getPackageUnit().getId(), null, barCode,
							weight, volume, receivedRecord.getQualityCode(),
							receivedRecord.getReceiveDate(), receivedRecord
									.getAsn().getRelatedBill1(), receivedRecord
									.getAsn().getBillType(), Boolean.FALSE,
							Boolean.FALSE);

					moveDoc.setStatus(MoveDocStatus.CANCEL);
					this.commonDao.store(moveDoc);
				} else {
					throw new BusinessException("receivedRecord.moveDoc.moved");
				}
			} else {
				receivedRecord.getAsnDetail().receiveBack(receivedRecord, null);

				inventoryManager.receivingAdjust(receivedRecord.getLocation()
						.getId(), receivedRecord.getItemKey(), revQty,
						0L, receivedRecord.getSrcLP() == null ? null : receivedRecord
								.getSrcLP().getId(), barCode, weight, volume,
						receivedRecord.getQualityCode(), receivedRecord
								.getReceiveDate(), receivedRecord.getAsn()
								.getRelatedBill1(), receivedRecord.getAsn()
								.getBillType(), Boolean.FALSE, Boolean.FALSE);
			}
			dealReceivingDoc(receivedRecord.getAsnDetail(), revQty);
			feeManager.deleteBillFee(receivedRecord.getAsn().getId(), "ASN");
		}
		moveDocs.clear();
	}

	public void receiveBackKams(List<Long> receivedRecordIds) {
		for (Long id : receivedRecordIds) {
			ReceivedRecord rd = commonDao.load(ReceivedRecord.class, id);
			Pinfan pf=rd.getItemKey().getPinfan();
			ASN asn=rd.getAsn();
			List<Inventory> invs=this.commonDao.findByQuery("from Inventory inv where inv.itemKey.id="+rd.getItemKey().getId()+" "
					+ " and  inv.zone.id="+rd.getZone().getId()+" and inv.location.id="+rd.getLocation().getId());
			double cancelQty=rd.getReceivedQuantity();
			for(Inventory inv:invs){
				double kyQty=inv.getAvaliableQuantity();
				if(kyQty>=cancelQty){
					inv.setQuantity(inv.getQuantity()-cancelQty);
					inv.setQtyOfMasterPack(inv.getQtyOfMasterPack()-cancelQty);
					this.commonDao.store(inv);
					InventoryLog log2 = new InventoryLog(InventoryLogType.RECEIVING_CANCEL, -1, asn.getCode(), null, pf.getLocation(), null, rd.getItemKey(), 
							new Date(), asn.getCode(), cancelQty, null, null, inv.getId(), null,inv.getZone());
					commonDao.store(log2);
					cancelQty=0;
					break;
				}else{
					inv.setQuantity(inv.getQuantity()-kyQty);
					inv.setQtyOfMasterPack(inv.getQtyOfMasterPack()-kyQty);
					this.commonDao.store(inv);
					InventoryLog log2 = new InventoryLog(InventoryLogType.RECEIVING_CANCEL, -1, asn.getCode(), null, pf.getLocation(), null, rd.getItemKey(), 
							new Date(), asn.getCode(), kyQty, null, null, inv.getId(), null,inv.getZone());
					commonDao.store(log2);
					cancelQty-=kyQty;
					continue;
				}
			}
			if(cancelQty>0){
				throw new BusinessException(rd.getItemKey().getItem().getCode()+"库存数量不足");
			}
			ASNDetail ad=rd.getAsnDetail();
			ad.setReceivedQuantity(ad.getReceivedQuantity()-rd.getReceivedQuantity());
			this.commonDao.store(ad);
			asn.setReceivedQuantity(asn.getReceivedQuantity()-rd.getReceivedQuantity());
			List<RkEwmRecord> res=this.commonDao.findByQuery("from RkEwmRecord e where e.rd.id="+rd.getId());
			if(res.size()>0){
				this.commonDao.deleteAll(res);
			}
			this.commonDao.delete(rd);
			if(asn.getReceivedQuantity()==0){
				asn.setStatus(ASNStatus.ACTIVE);
			}else if(asn.getReceivedQuantity()<asn.getExpectedQuantity()){
				asn.setStatus(ASNStatus.RECEIVING);
			}
			this.commonDao.store(asn);
		}
	}
	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.dev.swms.server.service.receiving.ASNManager#getLeftQuantityByDetail
	 * (java .lang.Long)
	 */
	public String getExpectedQuantityByDetail(Map map) {
		Long asnDetailId = (Long) map.get("asnDetail.id");
		if (asnDetailId == null) {
			return "0";
		}
		ASNDetail detail = commonDao.load(ASNDetail.class, asnDetailId);
		Item item = detail.getItem();
		PackageUnit packageUnit = commonDao.load(PackageUnit.class, detail
				.getPackageUnit().getId());
		double returnQty = 0;
		// 取包装数量
		if (packageUnit.getPrecision() == 0) {
			// 向上取整，得到整包装数量
			returnQty = Math.ceil(detail.getUnReceivedQuantity()
					/ detail.getPackageUnit().getConvertFigure());
		} else {
			// 根据包装精度计算包装数量
			returnQty = DoubleUtils.formatByPrecision(
					detail.getUnReceivedQuantity()
							/ detail.getPackageUnit().getConvertFigure(),
					packageUnit.getPrecision());
		}
		String caseName = item.getCAname() == null ? "箱" : item.getCAname();
		if (item.getCAcoefficient() == null || item.getCAcoefficient() == 0) {
			return '0' + caseName + detail.getUnReceivedQuantity()
					+ packageUnit.getUnit();
		} else {
			int caseQty = (int) (detail.getUnReceivedQuantity()
					/ item.getCAcoefficient() == 0 ? 1 : item
					.getCAcoefficient());
			int puQty = (int) (detail.getUnReceivedQuantity() - caseQty
					* item.getCAcoefficient());
			return caseQty + caseName + puQty + packageUnit.getUnit() + "/"
					+ returnQty + packageUnit.getUnit();
		}
		// return returnQty+packageUnit.getUnit();
	}

	public int getCaseQty(Map map) {
		// Long asnDetailId = (Long) map.get("asnDetail.id");
		// if (asnDetailId == null) {
		// return 0;
		// }
		// ASNDetail detail = commonDao.load(ASNDetail.class, asnDetailId);
		// Item item = detail.getItem();
		// if (item.getCAcoefficient() == null || item.getCAcoefficient() == 0)
		// {
		// return 0;
		// } else {
		// int caseQty = (int) (detail.getUnReceivedQuantity() /
		// item.getCAcoefficient());
		// return caseQty;
		// }
		return 0;
	}

	public int getPuQty(Map map) {
		Long asnDetailId = (Long) map.get("asnDetail.id");
		if (asnDetailId == null) {
			return 0;
		}
		ASNDetail detail = commonDao.load(ASNDetail.class, asnDetailId);
		// Item item = detail.getItem();
		// if (item.getCAcoefficient() == null || item.getCAcoefficient() == 0)
		// {
		// return (int) detail.getUnReceivedQuantity();
		// } else {
		// int caseQty = (int) (detail.getUnReceivedQuantity() /
		// item.getCAcoefficient());
		// int puQty = (int) (detail.getUnReceivedQuantity() - caseQty *
		// item.getCAcoefficient());
		// return puQty;
		// }
		return (int) detail.getUnReceivedQuantity();
	}
	
	public String getZoneMap(Map map) {
		Long asnId=(Long) map.get("asn.id");
		String code="";
		if(asnId!=null&&asnId.longValue()>0){
			ASN asn = commonDao.load(ASN.class, asnId);
			code=asn.getCompany().getCode();
		}
		return code;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.dev.swms.server.service.receiving.ASNManager#activeAll(java.util.
	 * List)
	 */
	public void activeAll(List<Long> asnIds) {
		String errMsg = "";
		for (Long id : asnIds) {
			ASN asn = commonDao.load(ASN.class, id);
			asn.setReceiveDateEnd(new Date());
			if (asn.active()) {
				commonDao.store(asn);
				errMsg += asn.getCode() + " 单据到货激活成功;";
			} else {
				errMsg += asn.getCode() + " 单据到货激活失败;";
			}
		}
		LocalizedMessage.addLocalizedMessage(errMsg);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.dev.swms.server.service.receiving.ASNManager#inactiveAll(java.util
	 * .List)
	 */
	public void inactiveAll(List<Long> asnIds) {
		String errMsg = "";
		for (Long id : asnIds) {
			ASN asn = commonDao.load(ASN.class, id);
			asn.setReceiveDateEnd(null);
			if (asn.inactive()) {
				commonDao.store(asn);
				errMsg += asn.getCode() + " 单据到货反激活成功;";
			} else
				errMsg += asn.getCode() + " 单据反激活失败;";
		}
		LocalizedMessage.addLocalizedMessage(errMsg);
	}

	public ASN getASNByCode(String code) {
		List result = commonDao.findByNamedQuery("getASNByCode",
				new String[] { "code" }, new String[] { code });
		if (result.size() >= 1) {
			return (ASN) result.get(0);
		}
		return null;
	}

	public ASNDetail getASNDetailByItem(Long asnId, String itemCode, int type) {
		ASN asn = commonDao.load(ASN.class, asnId);
		for (ASNDetail detail : asn.getAsnDetails()) {
			if (detail.getItem().getCode().equals(itemCode)) {
				if (type == 0) {
					return detail;
					// } else if
					// (detail.getExpectedQtyOfMasterUnit()-detail.getReceivedQuantity()>0)
					// {
				} else if (DoubleUtils.compareByPrecision(detail
						.getExpectedQtyOfMasterUnit(), detail
						.getReceivedQuantity(), detail.getPackageUnit()
						.getPrecision()) > 0) {
					return detail;
				}
			}
		}
		return null;
	}

	public PackageUnit getUnit(Long detailId) {
		ASNDetail detail = commonDao.load(ASNDetail.class, detailId);
		PackageUnit unit = commonDao.load(PackageUnit.class, detail
				.getPackageUnit().getId());
		return unit;
	}

	public ReceivedDoc getReceivedDocByCode(String code, String receivedCode,
			int type) {
		List result = null;
		if (type == 1) {
			result = commonDao.findByNamedQuery("getReceivedDocByREVCode",
					new String[] { "REVCode", "receivedCode" }, new String[] {
							code, receivedCode });
		} else {
			result = commonDao.findByNamedQuery("getReceivedDocByASNCode",
					new String[] { "ASNCode", "receivedCode" }, new String[] {
							code, receivedCode });
		}
		if (result.size() >= 1) {
			return (ReceivedDoc) result.get(0);
		}
		return null;
	}

	private ReceivedDoc createReceivedDoc(ASN asn) {
		ReceivedDoc receivedDoc = null;
		// Map params = ;//generateASNReceiveGroupCode(asn.getCode());
		List<ReceivedDoc> docs = this.commonDao
				.findByQuery("from ReceivedDoc where asn.id=" + asn.getId());
		if (docs.size() > 0) {
			receivedDoc = docs.get(0);
		} else {
			receivedDoc = EntityFactory.getEntity(ReceivedDoc.class);
			receivedDoc.setCode(bussinessCodeManager.getCodeForYm("AG", 4));
			receivedDoc.setCreateDate(new Date());
			receivedDoc.setAsn(asn);
			commonDao.store(receivedDoc);
		}
		return receivedDoc;
	}

	private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

	public void createMoveDocByASN(List<Long> asnIds) {
		for (Long id : asnIds) {
			ASN asn = commonDao.load(ASN.class, id);
			if (ASNStatus.RECEIVING.equals(asn.getStatus())
					|| ASNStatus.RECEIVED.equals(asn.getStatus())) {
				BillType billType = (BillType) this.commonDao
						.findByNamedQueryUniqueResult(
								"getBillTypeByCompanyAndCode",
								new String[] { "code" },
								new Object[] { MoveDoc.MV_ASN });
				if (billType == null) {
					throw new BusinessException("无此单据类型!");
				}
				String code = this.bussinessCodeManager.getCodeForYm("MV", 5);
				MoveDoc moveDoc = EntityFactory.getEntity(MoveDoc.class);
				moveDoc.setWarehouse(WarehouseHolder.getWarehouse());
				moveDoc.setCompany(asn.getCompany());
				moveDoc.setCode(code);
				moveDoc.setBillType(billType);
				moveDoc.setAsnType(asn.getBillType());
				moveDoc.setCreateDate(new Date());
				moveDoc.setStatus(MoveDocStatus.OPEN);
				moveDoc.setRelateBillCode(asn.getCode());
				moveDoc.setRelatedBill1(asn.getRelatedBill1());// 客户订单号
				moveDoc.setDescription(asn.getDescription());// 备注
				moveDoc.setUserTracking();

				for (ReceivedRecord record : asn.getReceivedRecords()) {
					// 直接收货上架的记录不再加入上架计划明细
					if (!LocationType.RECEIVE.equals(record.getLocation()
							.getType())) {
						continue;
					}
					double qty = record.getReceivedQuantityMU()
							- record.getQualityQty();
					if (StringUtils.isEmpty(record.getMoveDocCode())
							&& qty != 0) {
						Item item = record.getItemKey().getItem();
						if ((item.getSuggest() > 0 || asn.getCompany()
								.getCode().equals(CompanyCode.HLX))
								&& record.getSrcLP() == null) {
							int ca = item.getCAcoefficient() == null ? 1 : item
									.getCAcoefficient().intValue();
							if (!asn.getCompany().getCode()
									.equals(CompanyCode.HLX)) {
								ca = item.getSuggest() * ca;
							}
							int i = 0;
							if (ca == 0) {
								i = (int) ((int) qty / 1);
							} else {
								i = (int) ((int) qty / ca);
							}
							for (int j = 0; j < i; j++) {
								createDetail(moveDoc, record, ca + 0d);
							}
							double unQty = qty - i * ca;
							if (unQty > 0) {
								createDetail(moveDoc, record, unQty);
							}
						} else {
							createDetail(moveDoc, record, qty);
						}

					}
				}
				if (moveDoc.getDetails().size() > 0) {
					commonDao.store(moveDoc);
					asn.setStatus(ASNStatus.PUTAWAY);
				}
			}
		}
	}

	public MoveDocDetail createDetail(MoveDoc moveDoc, ReceivedRecord record,
			Double qty) {
		// 增加明细
		MoveDocDetail detail = EntityFactory.getEntity(MoveDocDetail.class);
		detail.setMoveDoc(moveDoc);
		detail.setItemKey(record.getItemKey());
		detail.setPackageUnit(record.getPackageUnit());
		detail.setSrcLoc(record.getLocation());
		detail.setSrcLP(record.getSrcLP());
		detail.setSrcLPCode(record.getSrcLPCode());
		detail.setLineNo(moveDoc.getDetails().size() + 1);
		try {
			detail.setStorageDate(format.parse(format.format(record
					.getReceiveDate())));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		detail.setSOI(record.getAsn().getCode());
		detail.setInventoryStatus(record.getQualityCode());
		// if (moveDoc.getDetails() != null &&
		// moveDoc.getDetails().contains(detail)) {
		// for (MoveDocDetail mdd : moveDoc.getDetails()) {
		// if (mdd.equals(detail)) {
		// mdd.add(qty);
		// break;
		// }
		// }
		// } else {
		// detail.add(qty);
		// moveDoc.getDetails().add(detail);
		// }
		detail.add(qty);
		moveDoc.getDetails().add(detail);
		record.setMoveDocCode(moveDoc.getCode());
		commonDao.store(record);
		return detail;
	}

	public void input(Long asnId, String vehicle, Date inputDate, Long workerId) {
		ASN asn = this.load(ASN.class, asnId);
		asn.setVehicle(vehicle);
		asn.setInputDate(new Date());
		asn.setStoreType("INPUT");
		asn.setInputWorker(this.load(Worker.class, workerId));
	}

	public void output(Long asnId, Date inputDate, Long workerId) {
		ASN asn = this.load(ASN.class, asnId);
		asn.setOutputDate(new Date());
		asn.setStoreType("OUTPUT");
		asn.setOutputWorker(this.load(Worker.class, workerId));
	}

	public void willReceive(List<Long> ids, Long dock_id, Date estimateDate,
			String vehicle) {
		for (Long asnId : ids) {
			ASN asn = this.load(ASN.class, asnId);
			if (!asn.getStatus().equals(ASNStatus.OPEN)) {
				throw new BusinessException("asn.willreceive.error");
			}
			if (dock_id != null) {
				Location l = commonDao.load(Location.class, dock_id);
				asn.setDock(l);
			}
			asn.setVehicle(vehicle);
			// asn.setReceiveDateStart(receiveDateStart);
			asn.setEstimateDate(estimateDate);
			// asn.setReceiveDateEnd(receiveDateEnd);

			commonDao.store(asn);
		}
	}

	public void receiveBackAll(Long asnId) {
		ASN asn = this.load(ASN.class, asnId);
		List<Long> receivedRecordIds = new ArrayList();
		for (ReceivedRecord receivedRecord : asn.getReceivedRecords()) {
			if (!receivedRecord.isBeMoved()) {
				receivedRecordIds.add(receivedRecord.getId());
			}
		}
		receiveBack(receivedRecordIds);
	}

	public void virInOutputStock(List<Long> ids) {
		for (Long id : ids) {
			ASN asn = this.load(ASN.class, id);
			if (asn.getBillType().getCode().equals(ASN.PO_STRAIGHT)) {
				asn.setStatus(ASNStatus.CLOSE);
				asn.setUserTracking();
				for (ASNDetail detail : asn.getAsnDetails()) {
					detail.addReceivedQuantity(detail
							.getExpectedQtyOfMasterUnit());
					// 创建入库库存日志
					this.createInventoryLog(asn, detail, 1,
							InventoryLogType.RECEIVING);
					// 创建出库库存日志
					this.createInventoryLog(asn, detail, -1,
							InventoryLogType.SHIPPING);
				}
				pickTicketManager.createBOLByASN(asn);
			}
			commonDao.store(asn);
		}
	}

	public void receiveOver(List<Long> ids) {
		// 创建上架计划
		this.createMoveDocByASN(ids);
		// 处理ASN收货单信息
		for (Long id : ids) {
			ASN asn = this.load(ASN.class, id);
			// 关闭ASN
			asn.setStatus(ASNStatus.CLOSE);
			feeManager.autoAsnFee(asn.getId());
			// 调用接口发送收货确认消息
			// logManager.asnReceiveResponse(asn);
			commonDao.store(asn);
		}
	}

	@SuppressWarnings("unchecked")
	public void asnMoveTo(List<Long> ids) {
		for (Long id : ids) {
			ASN asn = this.load(ASN.class, id);
			List<Task> tasks = commonDao.findByQuery(
					"FROM Task task WHERE task.billCode = '" + asn.getCode()
							+ "'", new String[] {}, new Long[] {});
			for (Task task : tasks) {
				// if (task.getPlanQuantity() > task.getMovedQuantityMU()) {
				if (DoubleUtils.compareByPrecision(task.getPlanQuantity(), task
						.getMovedQuantityMU(), task.getPackageUnit()
						.getPrecision()) > 0) {
					Worker worker = (Worker) commonDao
							.findByNamedQueryUniqueResult("getWorkerByUserId",
									new String[] { "userId" },
									new Long[] { UserHolder.getUser().getId() });
					this.moveDocManager.moveTo(task, worker.getId());
				}
			}
		}
	}

	@SuppressWarnings("unchecked")
	public void asnQuality(ASN asn, Map inventories) {
		ASN dbASN = commonDao.load(ASN.class, asn.getId());
		// 判断ASN的货主是否为允许收货质检, 只有允许收货质检的货主的ASN才能作质检登记
		if (!dbASN.getCompany().isBeAsnQuality()) {
			throw new BusinessException("company.is.not.asnQuality");
		}
		// 获取已定义库位列表(如果存在)
		List<Location> destLocs4Quality = commonDao.findByNamedQuery(
				"getLocationsByType", new String[] { "type", "warehouseId" },
				new Object[] { LocationType.QUALITY,
						dbASN.getWarehouse().getId() });
		// 判断是否定义质检库位
		if (destLocs4Quality == null || destLocs4Quality.isEmpty()) {
			throw new BusinessException("quality.location.none");
		}
		// 质检登记
		for (Iterator it = inventories.entrySet().iterator(); it.hasNext();) {
			Map.Entry entry = (Entry) it.next();
			Long inventoryId = (Long) entry.getKey();
			Inventory inventory = commonDao.load(Inventory.class, inventoryId);
			List value = (List) entry.getValue();
			Double quantity = Double.valueOf(String.valueOf(value.get(0)));
			// 如果质检登记数量大于库存数量则终止操作
			// if (quantity > inventory.getAvaliableQuantity()) {
			if (DoubleUtils.compareByPrecision(quantity, inventory
					.getAvaliableQuantity(), inventory.getPackageUnit()
					.getPrecision()) > 0) {
				throw new BusinessException("quality.quantity.error");
			}

			inventoryManager.inventoryQuality(inventory, quantity, inventory
					.getMasterPackUnit().getId());
		}
	}

	public void transitInStock(List<Long> ids) {
		for (Long id : ids) {
			ASN asn = this.load(ASN.class, id);
			if (asn.getBillType().getCode().equals(ASN.PO_TRANSFER)) {
				String barCode = null;
				double weight = 0;
				double volume = 0;
				asn.setStatus(ASNStatus.RECEIVED);
				asn.setUserTracking();
				for (ASNDetail detail : asn.getAsnDetails()) {
					detail.addReceivedQuantity(detail
							.getExpectedQtyOfMasterUnit());
					ItemKey itemKey = itemManager.getItemKey(
							new ItemKey("", detail.getItem(), detail
									.getLotInfo(), asn.getUpdateTime(), asn
									.getCode(),null), Boolean.FALSE,null);
					Location location = null;
					List result = commonDao.findByQuery(
							"from Location where type = '"
									+ LocationType.TRANSIT + "'",
							new String[] {}, new Long[] {});
					if (result.size() >= 1) {
						location = (Location) result.get(0);
					} else {
						throw new BusinessException("location.transit.none");
					}
					PackageUnit packageUnit = detail.getPackageUnit();
					double receiveQty = detail.getExpectedQtyOfMasterUnit();
					Boolean reject = Boolean.FALSE;
					if (asn.getBillType().equals("不良品退货收货单")) {
						reject = Boolean.TRUE;
					}
					// 普通收货流程
					inventoryManager.receiving(location.getId(), itemKey,
							receiveQty, packageUnit.getId(), null, barCode,
							weight, volume, asn.getCode(),
							Inventory.STATUS_VALID, new Date(),
							asn.getBillType(), Boolean.FALSE, reject);
				}
			}
			commonDao.store(asn);
		}

	}

	public void transitOutStock(List<Long> ids) {
		// 中转发货时自动创建BOL及其明细，并修改BOL状态为已发运，并记录发货库存日志，修改ASN状态为关闭
		for (Long id : ids) {
			ASN asn = this.load(ASN.class, id);
			if (asn.getBillType().getCode().equals(ASN.PO_TRANSFER)) {
				asn.setStatus(ASNStatus.CLOSE);
				asn.setUserTracking();
				Location location = null;
				List result = commonDao.findByQuery(
						"from Location where type = '" + LocationType.TRANSIT
								+ "'", new String[] {}, new Long[] {});
				if (result.size() >= 1) {
					location = (Location) result.get(0);
				} else {
					throw new BusinessException("location.transit.none");
				}
				// 根据ASN的CODE查找库存(不允许同一仓库出现相同的订单号)
				List<Inventory> inventories = commonDao.findByNamedQuery(
						"getInventoryBySoi", new String[] { "soi", "location",
								"type", "warehouseId" },
						new Object[] { asn.getCode(), location,
								LocationType.TRANSIT,
								WarehouseHolder.getWarehouse().getId() });
				// 对库存直接调用inventoryManager.ship()方法
				for (Inventory inventory : inventories) {
					// 普通发货流程
					inventoryManager.ship(location.getId(), inventory
							.getItemKeyInventory().getItemKey(), inventory
							.getQuantity(), inventory.getPackageUnit().getId(),
							inventory.getLP() == null ? null : inventory
									.getLP().getId(), inventory.getStatus(),
							inventory.getStorageDate(), inventory.getSOI(), asn
									.getCode(), asn.getBillType());
				}
				// 根据ASN创建BOL
				pickTicketManager.createBOLByASN(asn);
			}
			commonDao.store(asn);
		}
	}

	public void createInventoryLog(ASN asn, ASNDetail detail, int incOrDec,
			String locType) {
		ItemKey itemKey = itemManager.getItemKey(
				new ItemKey("", detail.getItem(), detail.getLotInfo(), asn
						.getUpdateTime(), asn.getCode(),null), Boolean.FALSE,detail.getRemark());
		// 在库存日志表上记录出入库日志
		InventoryLog invLog = EntityFactory.getEntity(InventoryLog.class);
		invLog.setWarehouse(asn.getWarehouse());
		invLog.setLogType(locType);
		invLog.setIncOrDec(incOrDec);
		invLog.setRelatedBill(asn.getCode());
		invLog.setItemKey(itemKey);
		invLog.setOccurQuantity(detail.getExpectedQuantity());
		invLog.setOccurTime(new Date());
		invLog.setOperator(UserHolder.getUser().getName());
		invLog.setStorageDate(new Date());
		invLog.setSOI(asn.getCode());
		invLog.setLP(null);
		List result = commonDao.findByQuery("from Location where type = '"
				+ LocationType.TRANSIT + "'", new String[] {}, new Long[] {});
		if (result.size() >= 1) {
			invLog.setLocation((Location) result.get(0));
		} else {
			throw new BusinessException("location.transit.none");
		}
		commonDao.store(invLog);
	}

	public void importReceiveConfirm(File file, Long asnId) {
		ASN asn = this.commonDao.load(ASN.class, asnId);
		Map<String, Double> maps = readDateByFile(file);
		for (ASNDetail detail : asn.getAsnDetails()) {
			if (maps.get(detail.getItem().getCode() + "_"
					+ detail.getLotInfo().getPropC5()) != null) {
				Location location = detail.getDock();
				if (location == null) {
					location = asn.getDock();
					if (location == null) {
						location = (Location) commonDao.findByNamedQuery(
								"getLocationsByType",
								new String[] { "type", "warehouseId" },
								new Object[] { LocationType.RECEIVE,
										asn.getWarehouse().getId() }).get(0);
						if (location == null) {
							throw new BusinessException("receiving.dock.error");
						}
					}
				}
				double quantity = maps.get(detail.getItem().getCode() + "_"
						+ detail.getLotInfo().getPropC5());
				Date receiveDate = new Date();
				if (quantity > 0) {
					ItemKey key = this.itemManager.getItemKey(new ItemKey("",
							detail.getItem(), detail.getLotInfo(), receiveDate,
							asn.getCode(),null), Boolean.TRUE,detail.getRemark());
					// 收货
					receive(asn, detail, key, location, quantity,
							detail.getPackageUnit(), null, null, 0, 0,
							receiveDate, Inventory.STATUS_VALID, null);
				}
			}
		}
	}

	private Map<String, Double> readDateByFile(File file) {
		if (file == null) {
			throw new BusinessException("no.csvfile.exists");
		} else {
			String fileName = StringUtils.substringBetweenFirstAndLast(
					file.getName(), "-", "-");
			if (fileName.indexOf(".csv") == -1) {
				throw new BusinessException("no.csvfile.exists");
			}
		}
		BufferedReader br = null;
		Map<String, Double> maps = new HashMap<String, Double>();
		try {
			br = new BufferedReader(new InputStreamReader(new FileInputStream(
					file), "GBK"));
			String line = br.readLine();
			while (line != null) {
				String[] strs = line.split(",");
				if (strs.length != 3) {
					line = br.readLine();
					continue;
				}
				if (strs[0] == null || "".equals(strs[0].trim())
						|| strs[2] == null || "".equals(strs[2].trim())) {
					line = br.readLine();
					continue;
				}
				String code = strs[0] + "_" + strs[2];
				Double receivedQuantity = .0;
				if (strs[1] != null && strs[1].length() > 1) {
					try {
						receivedQuantity = Double.valueOf(strs[1]);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				maps.put(code, receivedQuantity);
				line = br.readLine();
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new BusinessException("no.csvfile.exists");
		} finally {
			try {
				if (br != null) {
					br.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return maps;
	}

	public Double getReceivedQuantityByDetail(Map map) {
		Long asnDetailId = (Long) map.get("asnDetail.id");
		if (asnDetailId == null) {
			return .0;
		}
		ASNDetail detail = commonDao.load(ASNDetail.class, asnDetailId);
		PackageUnit packageUnit = commonDao.load(PackageUnit.class, detail
				.getPackageUnit().getId());
		Item item = detail.getItem();
		double returnQty = 0;
		// 取包装数量
		if (packageUnit.getPrecision() == 0) {
			// 向上取整，得到整包装数量
			returnQty = Math.ceil(detail.getUnReceivedQuantity()
					/ detail.getPackageUnit().getConvertFigure());
		} else {
			// 根据包装精度计算包装数量
			returnQty = DoubleUtils.formatByPrecision(
					detail.getUnReceivedQuantity()
							/ detail.getPackageUnit().getConvertFigure(),
					packageUnit.getPrecision());
		}
		return returnQty;
	}

	public boolean isExistReceiveASN(Long userId) {
		Long count = (Long) commonDao.findByNamedQueryUniqueResult(
				"getASNCountByASNDetailZone", new String[] { "userId" },
				new Object[] { userId });
		if (count == null || count == 0L) {
			count = (Long) commonDao.findByNamedQueryUniqueResult(
					"getASNCountByZone", new String[] { "userId" },
					new Object[] { userId });
		}
		return count != null && count > 0L;
	}

	public String getStockInfoByItemUnit(Long asnDetailId, String unit) {
		ASNDetail detail = commonDao.load(ASNDetail.class, asnDetailId);
		Item item = detail.getItem();
		PackageUnit packageUnit = detail.getPackageUnit();
		for (PackageUnit pu : item.getPackageUnits()) {
			if (pu.getUnit().equals(unit)) {
				packageUnit = pu;
				break;
			}
		}

		if (!packageUnit.isAllowLP()) {
			return "";
		} else {
			return packageUnit.getLpFormat1().getTierQty()
					+ packageUnit.getUnit() + "×"
					+ packageUnit.getLpFormat1().getStackHighQty() + "层";
		}
	}

	public <T extends Entity> List<T> load(Class<T> clazz, List<Long> id) {
		// TODO Auto-generated method stub
		return null;
	}

	public int rfReceive(Map<Object, Object> values) {
		return 0;
	}

	private Stock getStockWithNew(Location location, String lp,
			PackageUnit unit, double quantity) {
		Stock stock = null;
		if (!StringUtils.isEmpty(lp)) {
			stock = (Stock) commonDao.findByNamedQueryUniqueResult(
					"getStockByCode", new String[] { "warehouseId", "code" },
					new Object[] { location.getWarehouse().getId(), lp });
			if (stock == null) {
				// 创建托盘
				stock = new Stock();// EntityFactory.getEntity(Stock.class);
				stock.setWarehouse(location.getWarehouse());
				stock.setLocation(location);
				stock.setLP(lp);
				stock.setType(StockType.PALLET);
				stock.setItemQty(quantity * unit.getConvertFigure());
				stock.setWeight(quantity * unit.getWeight());
				stock.setVolume(quantity * unit.getVolume());
				stock.setLocationIndex(0);
				stock.setEnabled(true);
				stock.setInventoryQty(0);
				if (location.getStowage() != null) {
					LPFormat lpFormat = unit.getFitLPFormat(location
							.getStowage().getHeight());
					stock.setStackHighQty(lpFormat == null ? 0 : lpFormat
							.getStackHighQty());
					stock.setTierQty(lpFormat == null ? 0 : lpFormat
							.getStackHighQty());
				}
				commonDao.store(stock);
			} else {
				// location.
			}
		}
		return stock;
	}

	public void importASN(File file) {
		String filename = file.getName();	
		try {
			filename = URLDecoder.decode(filename, "GBK");
			if(filename.indexOf("大金")>=0){
				importASNdj(file);
			}else if(filename.indexOf("卡乐比")>=0){
				importASNklb(file);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	
	public void importASN2(File file) {
		Workbook workbook;
		try {
			//入库日期:	入库类别	收货方	入库单号	货品代码	生产日期	到期日期	库位	入 库数量/PCS
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
			workbook = Workbook.getWorkbook(file);
			Sheet sheet = workbook.getSheet(0);// 得到excel第一页的内容
			for (int i = 1; i < sheet.getRows(); i++) {
				String rkDate = sheet.getCell(0, i).getContents().trim();
				String billType = sheet.getCell(1, i).getContents().trim();
				String fromName = sheet.getCell(2, i).getContents().trim();
				String relatedBill1 = sheet.getCell(3, i).getContents().trim();
				String itemCode = sheet.getCell(4, i).getContents().trim();
				String scDate = sheet.getCell(5, i).getContents().trim();
				String dqDate = sheet.getCell(6, i).getContents().trim();
				String loc = sheet.getCell(7, i).getContents().trim();
				String quantity = sheet.getCell(8, i).getContents().trim();
				if(rkDate==null||rkDate.length()<=0){
					break;
				}
				Date orderDate=null;
				Date propD1=null;
				Date propD2=null;
				try {
					 orderDate=sdf.parse(rkDate);
					 propD1=sdf.parse(scDate);
					 propD2=sdf.parse(dqDate);
				} catch (ParseException e) {
					orderDate=new Date();
				}
				
				BillType bt=null;
				List<BillType> BillTypes =  commonDao.findByQuery(" from BillType bt where bt.name=:name ",
				new String[] { "name"},new Object[] {billType});
				if(BillTypes.size()>0){
					bt=BillTypes.get(0);
				}else{
					throw new BusinessException("第"+(i+1)+"行，"+billType+"单据类型不存在!");
				}
				
				Item item=null;
				List<Item> Items =  commonDao.findByQuery(" from Item i where upper(i.code)=upper(:code) ",
				new String[] { "code"},new Object[] {itemCode});
				if(Items.size()>0){
					item=Items.get(0);
				}else{
					throw new BusinessException("第"+(i+1)+"行，"+itemCode+"货品不存在!");
				}
				
				PackageUnit packageUnit=null;
				List<PackageUnit> PackageUnits =  commonDao.findByQuery(" from PackageUnit pu where pu.item.id=:id ",
				new String[] { "id"},new Object[] {item.getId()});
				if(PackageUnits.size()>0){
					packageUnit=PackageUnits.get(0);
				}
				
				
				Location location=null;
				List<Location> Locations =  commonDao.findByQuery(" from Location l where upper(l.code)=upper(:code) ",
				new String[] { "code"},new Object[] {loc});
				if(Locations.size()>0){
					location=Locations.get(0);
				}else{
					throw new BusinessException("第"+(i+1)+"行，"+loc+"库位不存在!");
				}
				
				ASN asn=null;
				List<ASN> ASNs =  commonDao.findByQuery(" from ASN a where a.relatedBill1=:relatedBill1 ",
				new String[] { "relatedBill1"},new Object[] {relatedBill1});
				if(ASNs.size()>0){
					asn=ASNs.get(0);
				}else{
					asn=EntityFactory.getEntity(ASN.class);
					Structure company=this.load(Structure.class, 1000L);
					asn.setCompany(company);
					asn.setOrderDate(orderDate);
					asn.setBillType(bt);
					asn.setFromName(fromName);
					asn.setRelatedBill1(relatedBill1);
					asn.setUserName(UserHolder.getUser().getName());
					asn.setUpdateTime(new Date());
					asn.setStatus(ASNStatus.OPEN);
					asn.setCode(this.bussinessCodeManager.getCodeForYm("RP", 3));
					asn.setWarehouse(WarehouseHolder.getWarehouse());
					Location dock=null;
					if(WarehouseHolder.getWarehouse().getId()==1){
						 dock=this.load(Location.class, 1L);//默认月台
					}else{
						 dock=this.load(Location.class, 296L);//默认月台
					}
					asn.setDock(dock);
					commonDao.store(asn);
				}
				ASNDetail ad = null;
				List<ASNDetail> ASNDetails =  commonDao.findByQuery(" from ASNDetail ad where ad.asn.id=:id and ad.item.id=:itemId and ad.lotInfo.propD1=:propD1 and ad.lotInfo.propD2=:propD2 and ad.dock.id=:dockId ",
				new String[] { "id","itemId","propD1","propD2","dockId"},new Object[] {asn.getId(),item.getId(),propD1,propD2,location.getId()});
				if(ASNDetails.size()>0){
					ad=ASNDetails.get(0);
					ad.setExpectedQuantity(ad.getExpectedQuantity()+Double.parseDouble(quantity));
					ad.setExpectedQtyOfMasterUnit(ad.getExpectedQuantity());
				}else{
					ad=EntityFactory.getEntity(ASNDetail.class);
					ad.setAsn(asn);
					ad.setItem(item);
					ad.setExpectedQuantity(Double.parseDouble(quantity));
					ad.setExpectedQtyOfMasterUnit(Double.parseDouble(quantity));
					LotInfo lotInfo=new LotInfo();
					lotInfo.setPropD1(propD1);
					lotInfo.setPropD2(propD2);
					ad.setLotInfo(lotInfo);
					ad.setDock(location);
					ad.setAsn(asn);
					ad.setPackageUnit(packageUnit);
					commonDao.store(ad);
					refreshweightandvolume(asn.getId());
				}
				
			}
			
		} catch (BiffException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	
	/**
	 * 导入大金制冷数据
	 * @param file 文件名
	 */
	public void importASNdj(File file) {
		Workbook workbook;
		try {
			workbook = Workbook.getWorkbook(file);
			Sheet sheet = workbook.getSheet(0);// 得到excel第一页的内容
			HashMap<String, String> map = new HashMap<String, String>();
			List<Location> ls = 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 = ls.get(0);
			String fromName = sheet.getCell(3, 2).getContents().trim();
			ASN asn = new ASN();
			List<Structure> companys = this.commonDao
					.findByQuery("from Structure");
			for (Structure compang : companys) {
				String name = compang.getName();
				if (fromName.indexOf(name) >= 0) {
					asn.setCompany(compang);
					break;
				}
			}
			asn.setWarehouse(WarehouseHolder.getWarehouse());
			// asn.setFromName(fromName);
			String strorderDate = sheet.getCell(0, 7).getContents().trim();
			Date orderDate = DateUtil.getDateFormat(strorderDate); // 日期
			asn.setOrderDate(orderDate);
			asn.setCode(this.bussinessCodeManager.getCodeForYm("RP", 3));
			List<BillType> bts = commonDao.findByQuery(" from BillType ");
			if (bts != null && bts.size() > 0) {
				asn.setBillType(bts.get(0));
			}
			asn.setStatus(ASNStatus.OPEN);
			asn.setUpdateTime(new Date());
			asn.setUserName(UserHolder.getUser().getName());
			commonDao.store(asn);

			List<ASNDetail> details = new ArrayList<ASNDetail>();
			for (int i = 6; i < sheet.getRows(); i++) {
				String strTotal = sheet.getCell(4, i).getContents().trim();
				if (strTotal.indexOf("合计") >= 0) {
					break;
				}
				ASNDetail detail = new ASNDetail();
				System.out.println("======" + i);
				if (i == 12) {
					System.out.println("test by 殷剑" + i);
				}
				detail.setAsn(asn);
				String strReceivedQuantity = sheet.getCell(3, i).getContents()
						.trim();
				double receivedQuantity = 0.0;
				if (!strReceivedQuantity.equals("")) {
					receivedQuantity = Double.parseDouble(strReceivedQuantity);
				}
				detail.setExpectedQuantity(receivedQuantity);
				detail.setExpectedQtyOfMasterUnit(detail.getExpectedQuantity());
				String item_code = sheet.getCell(1, i).getContents().trim();
				Item item=null;
				List<Item> items = this.commonDao
						.findByQuery("from Item i where i.code='" + item_code
								+ "'");
				if (items != null && items.size() > 0) {
					item = items.get(0);
					detail.setItem(item);
				}else{
					throw new BusinessException(item_code+"货品代码不存在!");
				}
				String batchCode = sheet.getCell(2, i).getContents().trim();
				LotInfo lotInfo = new LotInfo();
				lotInfo.setPropC1(batchCode);
				detail.setLotInfo(lotInfo);

				String unit = sheet.getCell(6, i).getContents().trim();
				PackageUnit packageUnit=null;
				List<PackageUnit> pus = this.commonDao
						.findByQuery("from PackageUnit p where p.item.id="+item.getId()+" ");
				if(pus.size()>0){
					packageUnit=pus.get(0);
					detail.setPackageUnit(packageUnit);
				}
				commonDao.store(detail);
				
			}
			refreshweightandvolume(asn.getId());
			
		} catch (BiffException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	
	public void importASNklb(File file) {
		Workbook workbook;
		try {
			workbook = Workbook.getWorkbook(file);
			Sheet sheet = workbook.getSheet(0);// 得到excel第一页的内容
			String companyName = sheet.getCell(1, 4).getContents().trim();
			String btName = sheet.getCell(1, 5).getContents().trim();
			String fromName = sheet.getCell(1, 6).getContents().trim();
			String relatedBill1 = sheet.getCell(1, 7).getContents().trim();
			String strOrderDate = sheet.getCell(4, 4).getContents().trim();
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
			SimpleDateFormat sdf2=new SimpleDateFormat("yyyy-M-d");
			ASN asn = new ASN();
			asn.setStatus(ASNStatus.OPEN);
			asn.setCode(this.bussinessCodeManager.getCodeForYm("RP", 3));
			asn.setWarehouse(WarehouseHolder.getWarehouse());
			List<Structure> companys = this.commonDao
					.findByQuery("from Structure s where s.name like '%"+companyName+"%'");
			if(companys!=null && companys.size()>0){
				asn.setCompany(companys.get(0));
			}else{
				throw new BusinessException(companyName+"货主不存在!");
			}
			Date orderDate=null;
			try {
				orderDate = sdf.parse(strOrderDate);
				asn.setOrderDate(orderDate);
			} catch (ParseException e) {
				throw new BusinessException(strOrderDate+"入库日期格式错误!");
			} 
			List<BillType> bts = this.commonDao
					.findByQuery("from BillType bt where bt.name='"+btName+"'");
			if(bts!=null && bts.size()>0){
				asn.setBillType(bts.get(0));
			}else{
				throw new BusinessException(btName+"入库类别错误!");
			}
			asn.setRelatedBill1(relatedBill1);
			asn.setUpdateTime(new Date());
			asn.setUserName(UserHolder.getUser().getName());
			asn.setFromName(fromName);
			commonDao.store(asn);
			for (int i = 10; i < sheet.getRows(); i++) {
				ASNDetail detail = new ASNDetail();
				String name = sheet.getCell(0, i).getContents().trim();
				String strScrq = sheet.getCell(1, i).getContents().trim();
				String strDqrq = sheet.getCell(2, i).getContents().trim();
				String locCode=sheet.getCell(3, i).getContents().trim();
				String strExpectedQtyOfMasterUnit = sheet.getCell(5, i).getContents().trim();
				if(name==null||name.length()<=0){
					break;
				}
				Item item =null;
				List<Item> items = this.commonDao
						.findByQuery("from Item i where i.name='" + name
								+ "'");
				if (items != null && items.size() > 0) {
					item = items.get(0);
					detail.setItem(item);
				}else{
					throw new BusinessException(name+"商品不存在!");
				}
				
				List<PackageUnit> PackageUnits = this.commonDao
						.findByQuery("from PackageUnit pu where pu.item.id=" + item.getId()
								+ " ");
				
				if(PackageUnits.size()>0){
					detail.setPackageUnit(PackageUnits.get(0));
				}else{
					throw new BusinessException("包装单位不存在!");
				}
				
				List<Location> Locations = this.commonDao
						.findByQuery("from Location l where (l.code='" + locCode+ "' or l.name='" + locCode+ "' ) ");
				if(Locations.size()>0){
					detail.setDock(Locations.get(0));
				}else{
					throw new BusinessException(locCode+"库位不存在!");
				}			
				
				LotInfo lif = new LotInfo();
				Date scrq=null;
				if (sheet.getCell(1, i).getType() == CellType.DATE) {
		    	    DateCell dc = (DateCell)sheet.getCell(1, i);
		    	    TimeZone zone = TimeZone.getTimeZone("GMT");
		    	    sdf.setTimeZone(zone);
		    	    try {
		    	    	scrq=sdf2.parse(sdf.format(dc.getDate()));
		    	    	lif.setPropD1(scrq);
					} catch (ParseException e1) {
						throw new BusinessException(strScrq+"生产日期格式错误!");
					}
		    	}
				
				
				Date dqrq=null;
				if (sheet.getCell(2, i).getType() == CellType.DATE) {
		    	    DateCell dc = (DateCell)sheet.getCell(2, i);
		    	    TimeZone zone = TimeZone.getTimeZone("GMT");
		    	    sdf.setTimeZone(zone);
		    	    try {
		    	    	dqrq=sdf2.parse(sdf.format(dc.getDate()));
		    	    	lif.setPropD2(dqrq);
					} catch (ParseException e1) {
						throw new BusinessException(strDqrq+"到期日期格式错误!");
					}
		    	}
				detail.setLotInfo(lif);
				double expectedQtyOfMasterUnit = Double.parseDouble(strExpectedQtyOfMasterUnit);
				detail.setExpectedQuantity(expectedQtyOfMasterUnit);
				detail.setExpectedQtyOfMasterUnit(expectedQtyOfMasterUnit);
				detail.setAsn(asn);
				commonDao.store(detail);
				System.out.println("======" + i);
			}
			refreshweightandvolume(asn.getId());
		} catch (BiffException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public void importASNGrounding(File file) {
		Workbook workbook;
		try {
			workbook = Workbook.getWorkbook(file);
			Sheet sheet = workbook.getSheet(0);// 得到excel第一页的内容
			HashMap<String, String> map = new HashMap<String, String>();

			for (int i = 1; i < sheet.getRows(); i++) {
				List<Location> ls = 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 = ls.get(0);

				// 订单号（ASN） 货品自编码 条码（用于王品） 数量 库位（如果输入库位，则直接入库上架） 批号 生产日期
				String relatedBill1 = sheet.getCell(0, i).getContents().trim();
				if (relatedBill1 == null || relatedBill1.equals("")) {
					return;
				}

				String item_code = sheet.getCell(1, i).getContents().trim();
				String itemtm = sheet.getCell(2, i).getContents().trim();

				String quantity = sheet.getCell(3, i).getContents().trim();
				if (quantity == null || quantity.equals("")) {
					quantity = "0";
				}
				String location = sheet.getCell(4, i).getContents().trim();
				if (location != null && !location.equals("")) {
					List<Location> Locations = commonDao
							.findByQuery(
									" from Location o where o.warehouse.id=:id  and o.code =:code and o.disabled=false",
									new String[] { "id", "code" },
									new Object[] {
											WarehouseHolder.getWarehouse()
													.getId(), location });
					if (Locations.size() > 0) {
						l = Locations.get(0);
					}
				}
				String propC1 = sheet.getCell(5, i).getContents().trim();
				String d1 = sheet.getCell(6, i).getContents().trim();
				// String remark=sheet.getCell(9,i).getContents().trim();
				List<Item> items = this.commonDao
						.findByQuery("from Item i where i.code='" + item_code
								+ "'");
				if (items.size() > 0) {
					List<ASN> asns = this.commonDao.findByQuery(
							"from ASN a where a.relatedBill1=:relatedBill1 ",
							new String[] { "relatedBill1" },
							new Object[] { relatedBill1 });
					ASN asn = null;
					Item item = items.get(0);
					if (asns.size() > 0) {
						asn = asns.get(0);
					}

					PackageUnit unit = item.getMinPackageUnit();
					List<ASNDetail> asnds = this.commonDao
							.findByQuery(
									"from ASNDetail a where a.item.id=:item_id and a.lotInfo.propC1=:propC1 and to_char(a.lotInfo.propD1,'yyyy-MM-dd')=:propD1",
									new String[] { "item_id", "propC1",
											"propD1" },
									new Object[] { item.getId(), propC1, d1 });
					double qty = Double.parseDouble(quantity);
					ASNDetail ad = EntityFactory.getEntity(ASNDetail.class);
					if (asnds.size() > 0) {
						ad = asnds.get(0);
						confirmReceiving(asn.getId(), ad.getId(),
								ad.getLotInfo(),  qty,
								new Date(),null, null,l.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();
		}
	}

	// 批量收货
	@Override
	public void confirmReceiving(Long asnId, Map locs) {
		Iterator it = locs.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			Long dId = (Long) entry.getKey();
			ASNDetail d = this.commonDao.get(ASNDetail.class, dId);
			List value = (List) entry.getValue();
			String locationCode = String.valueOf(value.get(0));
			if (locationCode != null && !locationCode.equals("-")) {
				locationCode = locationCode.toUpperCase();
				if (locationCode.substring(0, 1).equals("-")) {
					locationCode = locationCode.substring(1,
							locationCode.length());
				}
				List<Location> ls = this.commonDao
						.findByQuery("from Location l where upper(l.code)='"
								+ locationCode + "'");
				if (ls.size() > 0) {
					this.confirmReceiving(asnId, dId, d.getLotInfo(), 
							d.getUnReceivedQuantity(), new Date(), "", 
							null, ls.get(0).getId(), d);
				} else {
					throw new BusinessException(locationCode + "库位不存在");
				}
			} else {
				this.confirmReceiving(asnId, dId, d.getLotInfo(), 
						d.getUnReceivedQuantity(), new Date(), "", 
						null, new Long("0"), d);
			}

		}

	}

	public LotInfo convertLot(String cusCode, LotInfo 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(calendar.getTime());
				return lotInfo;
			} catch (Exception e) {
				throw new BusinessException(lot + "年周天格式有误，应为数字");
			}
		} else {
			return lotInfo;
		}
	}

	public void saveFee(Fee fee, Long asnid, String billObjectType) {
		if (fee.isNew()) {
			fee.setType(billObjectType);
			fee.setStatus("OPEN");
			fee.setCreatPeople(UserHolder.getUser().getName());
			fee.setCreatDate(new Date());
		}
		if (billObjectType.equals("ASN")) {
			ASN asn = commonDao.load(ASN.class, asnid);
			fee.setCompany(asn.getCompany());
			fee.setOrderId(asn.getId());
			fee.setOrderCode(asn.getCode());
		}
		if (billObjectType.equals("PICKTICKET")) {
			PickTicket p = commonDao.load(PickTicket.class, asnid);
			fee.setCompany(p.getCompany());
			fee.setOrderId(p.getId());
			fee.setOrderCode(p.getCode());
		}
		commonDao.store(fee);
	}

	public void deleteFee(List<Long> ids) {
		for (Long id : ids) {
			Fee f = commonDao.load(Fee.class, id);
			commonDao.delete(f);
		}

	}

	// 删除回单影像
	@Override
	public void deleteSignFile(List<Long> ids) {
		for (Long id : ids) {
			SignFile signFile = this.get(SignFile.class, id);
			ASN asn = signFile.getAsn();
			if (signFile != null) {
				commonDao.delete(signFile);
			} else {
				throw new BusinessException("待删除文件不存在！");
			}
			asn.removeFiles(signFile);// 移除关联
			// 删除对应的图片资料
			String fileUrl = GlobalParamUtils
					.getGloableStringValue("imageTarget")
					+ signFile.getFileName();
			File file = new File(fileUrl);
			file.delete();
			commonDao.store(asn);
		}
	}
	
	@Override
	public void cancelReceivedRecord(Long asnId) {
		ASN asn=this.commonDao.load(ASN.class, asnId);
		List<ReceivedRecord> ds=this.commonDao.findByQuery("from ReceivedRecord r where r.asn.id="+asnId);
		for(ReceivedRecord d:ds){
			ajustReceivedQty(asn, d, d.getReceivedQuantity(), 0);
		}
	}
	
	@Override
	public void cancelReceivedRecord(Long asnId, Map qtys) {
		Iterator it = qtys.entrySet().iterator();
		ASN asn=this.commonDao.load(ASN.class, asnId);
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			Long dId = (Long) entry.getKey();
			ReceivedRecord d = this.commonDao.get(ReceivedRecord.class, dId);
			List value = (List) entry.getValue();
			String qtystr = String.valueOf(value.get(0));
			ItemKey ik=d.getItemKey();
			double bhsl=0;
			if (qtystr != null ) {
				int qty=0;
				try {
					 qty=Integer.parseInt(qtystr);
					 bhsl=d.getReceivedQuantity()-qty;
				} catch (BusinessException e) {
					throw new BusinessException(ik.getItem().getCode()+"收货数量格式错误");
				}
				 if(qty<0){
					 throw new BusinessException(ik.getItem().getCode()+"收货数量不能负数");
				 }
				 if(bhsl==0){
					 continue;
				 }
				 ajustReceivedQty(asn, d, d.getReceivedQuantity(), qty);
			}
		}
	}
	
	void ajustReceivedQty(ASN asn,ReceivedRecord d,double oldQty,double tzQty){
		ItemKey ik=d.getItemKey();
		String hql="from Inventory inv where inv.itemKey.id="+ik.getId()+" and inv.zone.id="+asn.getZone().getId();
		if(asn.getWarehouse().getId().equals(new Long("1"))){
			hql+=" and inv.location.id="+d.getLocation().getId() ;
		}
//		if(ik.getPinfan().getLocation()==null){
//			hql+=" and (inv.location.id is null or inv.location.id="+d.getLocation().getId()+")";
//		}else{
//			hql+=" and (inv.location.id is null or inv.location.id="+d.getLocation().getId()+""
//					+ "  or inv.location.id="+ik.getPinfan().getLocation().getId()+")";
//		}
//		if(d.getLocation()!=null){
//			hql+=" and inv.location.id="+d.getLocation().getId();
//		}else{
//			hql+=" and inv.location.id is null";
//		}
//		List<Inventory> invs=this.commonDao.findByQuery(hql);
		Inventory inv=pickKamsManager.findInventory(ik, asn.getZone(), d.getLocation(), asn.getCode(), SysCode.RK_SH2, d.getAsnDetail().getZzkw());
		double bhsl=oldQty-tzQty;
//		if(invs.size()>0){
//			Inventory inv=invs.get(0);
			//增加或减少
			String billCode=asn.getCode();
			int incOrDec=1;
			if(bhsl>0){
				incOrDec=-1;
			}
			double srcQty1=inv.getQtyOfMasterPack();
//			Location loc=inv.getLocation()==null?ik.getPinfan().getLocation():inv.getLocation();
//			InventoryLog log = new InventoryLog(InventoryLogType.RECEIVING_CANCEL, incOrDec, billCode, null, loc, null, ik, 
//					new Date(), null, Math.abs(bhsl) , null, null, d.getId(), "收货数量由"+d.getReceivedQuantity()+"变成"+tzQty,inv.getZone());
//			commonDao.store(log);
			if(incOrDec<1){
				if(inv.getQuantity()-inv.getQueuedQuantity()<bhsl){
					 throw new BusinessException(ik.getItem().getCode()+"可取消库存不足");
				}
			}
			inv.setQuantity(inv.getQuantity()-bhsl);
			inv.setQtyOfMasterPack(inv.getQuantity());
			this.commonDao.store(inv);
			inventoryManager.addInventoryLog(InventoryLogType.RECEIVING_CANCEL, incOrDec, asn.getZone(),
					d.getLocation(), asn.getCode(), ik, bhsl, null, UserHolder.getUser().getName(), inv.getId(), (int)srcQty1+"变为"+(int)inv.getQtyOfMasterPack(),asn.getDescription(),null,null,d.getAsnDetail().
					getZzkw());
//			if(inv.getQuantity()==0){
//				this.commonDao.delete(inv);
//			}
//		}else{
//			 throw new BusinessException(ik.getItem().getCode()+"未找到相应库存");
//		}
		d.setReceivedQuantity(tzQty);
		d.setReceivedQuantityMU(tzQty);
		this.commonDao.store(d);
		ASNDetail ad=d.getAsnDetail();
		ad.setReceivedQuantity(ad.getReceivedQuantity()-bhsl);
		this.commonDao.store(ad);
		if(d.getReceivedQuantity()==0){
			List<RkEwmRecord> rs=this.commonDao.findByQuery("from RkEwmRecord r where r.rd.id="+d.getId());
			this.commonDao.deleteAll(rs);
			this.commonDao.delete(d);
		}
		asn.setReceivedQuantity(asn.getReceivedQuantity()-bhsl);
		if(asn.getReceivedQuantity()==0){
			asn.setStatus(ASNStatus.ACTIVE);
		}
		this.commonDao.store(asn);
	}
	
	public void importInvPDTZ(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++) {
				 //序号	库区名称	品番	货品名称	税别	批次	库存数	调整批次	调整库存数	备注
				Long id=Long.parseLong(sheet.getCell(0,i).getContents().trim());
				Inventory inv=this.commonDao.get(Inventory.class, id);
				if(inv!=null){
					Double tzQty=Double.parseDouble(sheet.getCell(8,i).getContents().trim());
					String tzbz=sheet.getCell(9,i).getContents().trim();
					double srcQty=inv.getQtyOfMasterPack();
					inv.setQtyOfMasterPack(tzQty);
					inv.setQuantity(tzQty);
					this.commonDao.store(inv);
					String des=(int)srcQty+"变为"+tzQty;
					int incOrDec=1;
					double fasl=srcQty-tzQty;;
					if(fasl==0){
						System.out.println(i+1+"行没有调整");
						continue;
					}
					if(fasl>0){
						incOrDec=-1;
					}
					InventoryLog log=pickKamsManager.addInventoryLog(InventoryLogType.INVENTORY_ADJUST, incOrDec, inv.getZone(), inv.getLocation(), null, inv.getItemKey(), 
							Math.abs(fasl), null, UserHolder.getUser().getName(), inv.getId(), des, null, null, inv.getZzkw());
					log.setOperDes(tzbz);
					this.commonDao.store(log);
					System.out.println(i+1+"行调整完成");
				}else{
					System.out.println(i+1+"行没找到");
					
				}
			 }
		} catch (BiffException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}
