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

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.dev.swms.client.ui.page.CustomEntity;
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.Location2;
import com.dev.swms.server.model.base.LocationStatus;
import com.dev.swms.server.model.base.LocationTaskMode;
import com.dev.swms.server.model.base.LocationType;
import com.dev.swms.server.model.base.LpBarCode;
import com.dev.swms.server.model.base.Position;
import com.dev.swms.server.model.base.RackType;
import com.dev.swms.server.model.base.Stowage;
import com.dev.swms.server.model.base.WarehouseArea;
import com.dev.swms.server.model.interfaceLog.InterfaceLog;
import com.dev.swms.server.model.inventory.Inventory;
import com.dev.swms.server.model.inventory.Task;
import com.dev.swms.server.model.rules.PickItemRule;
import com.dev.swms.server.model.rules.PutRackRule;
import com.dev.swms.server.service.base.LocationManager;
import com.dev.swms.server.utils.DateUtil;
import com.dev.swms.server.utils.DoubleUtils;
import com.dev.swms.server.web.filter.WarehouseHolder;

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

import com.dev.energy.server.exception.BusinessException;
import com.dev.energy.server.model.EntityFactory;
import com.dev.energy.server.model.exception.ExceptionLog;
import com.dev.energy.server.service.pojo.DefaultBaseManager;
import com.dev.energy.server.util.LocalizedMessage;
import com.dev.energy.server.web.security.UserHolder;

public class DefaultLocationManager extends DefaultBaseManager implements
		LocationManager {

	public void deleteAll(List<Long> locationIds) {
		String errMsg = "";
		for (Long id : locationIds) {
			String hql="SELECT COUNT(inv.id) FROM Inventory inv WHERE inv.location.id = :locationId and inv.quantity>0";
			Long count = Long.valueOf(String.valueOf(commonDao.findByQuery(hql, new String[] {"locationId"}, new Long[] {id}).get(0)));
//			Long count = Long.valueOf(String.valueOf(commonDao.findByNamedQueryUniqueResult("getInventoryLogCountByLocationId", new String[] {"locationId"}, new Long[] {id})));
			Location location = commonDao.load(Location.class, id);
			if (count == 0) {
				location.setDisabled(true);
				errMsg+=location.getCode()+" 库位失效成功;";
			}
			else
				errMsg+=location.getCode()+" 库位失效失败,还有库存数据;";
		}
		LocalizedMessage.addLocalizedMessage(errMsg);
	}
	public void storeLpBarCode(String prefix,int start,int end){
//		Date date=new Date();
//		String d=DateUtil.formatDateYYMMDDToStr(new Date());
		if(start <=end&&end<=1000){
			for (int i = start; i <= end; i++) {
				LpBarCode l=EntityFactory.getEntity(LpBarCode.class);
				l.setPrefix(prefix);
				l.setCode(prefix+String.format("%05d", i));
				l.setCreateDate(new Date());
				l.setWarehouse(WarehouseHolder.getWarehouse());
				l.setCreateName(UserHolder.getUser().getName());
				this.commonDao.store(l);
			}
		}
	}
	
	public void storeLpBarCode(LpBarCode lp){
		if(lp.isNew()){
				lp.setCreateDate(new Date());
				lp.setWarehouse(WarehouseHolder.getWarehouse());
				lp.setCreateName(UserHolder.getUser().getName());
		}
		this.commonDao.store(lp);
	}
	public void storeLocation(Location location) {
		//备货库位要设置为件拣货库位
//		if (location.getType().equals(LocationType.READY) || 
//				location.getType().equals(LocationType.PROCESS)) {
//			location.setMuPick(1);
//		}
		if (location.isNew()) {
			location.setWarehouse(WarehouseHolder.getWarehouse());
			location.setCountLock(Location.VALID);
			location.setInLock(Location.VALID);
			location.setOutLock(Location.VALID);
			location.setStatus(Location.EMPTY);
			location.setFlagStatus(Location.WAIT_ADD);
			location.setUpdateCode(location.getCode());
			
			if (LocationType.STORAGE.equals(location.getType())) {
				if (location.getAisle()!=0 && location.getLine()!=0 && location.getRow()!=0 && location.getCol()!=0) {
					//判断道排层列是否在库区层面不重复
					Location checkLoc = (Location)commonDao.findByNamedQueryUniqueResult("checkLocationInZoneIsNotRepeat",new String[]{"zoneId","aisle","line","row","col"},
							new Object[]{location.getZone().getId(),location.getAisle(),location.getLine(),location.getRow(),location.getCol()});
					if(null != checkLoc){
						LocalizedMessage.addLocalizedMessage(location.getCode()+"库位物理坐标信息重复;");
						
					}
					
					if (location.getSortIndex() == 0) {
						location.setSortIndex(Integer.valueOf(""+location.getAisle()+location.getLine()+location.getCol()+location.getRow()));
					}
				}
			}
			if(location.getStatus().equals("-")|| location.getStatus()==null){
				location.setStatus(LocationStatus.EMPTY);
			}
			this.store(location);
		} else {
			Location dbLoc = commonDao.load(Location.class, location.getId());
//			dbLoc.setCode(location.getCode());
			dbLoc.setFlagStatus(Location.WAIT_UPDATE);
			dbLoc.setUpdateCode(location.getCode());
			dbLoc.setName(location.getName());
			dbLoc.setType(location.getType());
			dbLoc.setZone(commonDao.load(WarehouseArea.class, location.getZone().getId()));
//			if (location.getStowage() != null && location.getStowage().getId() != 0) {
//				dbLoc.setStowage(commonDao.load(Stowage.class, location.getStowage().getId()));
//			} else {
//				dbLoc.setStowage(null);
//			}
			dbLoc.setRackType(location.getRackType());
			dbLoc.setMuPick(location.getMuPick());
			dbLoc.setMixItem(location.isMixItem());
			dbLoc.setMixLot(location.isMixLot());
			dbLoc.setAisle(location.getAisle());
			dbLoc.setLine(location.getLine());
			dbLoc.setCol(location.getCol());
			dbLoc.setRow(location.getRow());
//			if (location.getSortIndex() == 0) {
//				dbLoc.setSortIndex(Integer.valueOf(""+location.getAisle()+location.getLine()+location.getCol()+location.getRow()));
//			} else {
//				dbLoc.setSortIndex(location.getSortIndex());
//			}
//			dbLoc.setTaskMode(location.getTaskMode());
//			if (location.getPickBackLoc() != null && location.getPickBackLoc().getId() != 0) {
//				dbLoc.setPickBackLoc(commonDao.load(Location.class, location.getPickBackLoc().getId()));
//			} else {
//				dbLoc.setPickBackLoc(null);
//			}
			commonDao.store(dbLoc);
		}
	}
	//测试方法
	public void storeLocation2(Location2 location) {
		//备货库位要设置为件拣货库位
		if (location.getType().equals(LocationType.READY) || 
				location.getType().equals(LocationType.PROCESS)) {
			location.setMuPick(1);
		}
		if (location.isNew()) {
			location.setWarehouse(WarehouseHolder.getWarehouse());
			location.setCountLock(Location.VALID);
			location.setInLock(Location.VALID);
			location.setOutLock(Location.VALID);
			location.setStatus(Location.EMPTY);
			
			if (LocationType.STORAGE.equals(location.getType())) {
				if (location.getAisle()!=0 && location.getLine()!=0 && location.getRow()!=0 && location.getCol()!=0) {
					//判断道排层列是否在库区层面不重复
					Location checkLoc = (Location)commonDao.findByNamedQueryUniqueResult("checkLocationInZoneIsNotRepeat",new String[]{"zoneId","aisle","line","row","col"},
							new Object[]{location.getZone().getId(),location.getAisle(),location.getLine(),location.getRow(),location.getCol()});
					if(null != checkLoc){
						LocalizedMessage.addLocalizedMessage(location.getCode()+"库位物理坐标信息重复;");
						
					}
					
					if (location.getSortIndex() == 0) {
						location.setSortIndex(Integer.valueOf(""+location.getAisle()+location.getLine()+location.getCol()+location.getRow()));
					}
				}
			}
			this.store(location);
		} else {
			Location dbLoc = commonDao.load(Location.class, location.getId());
			dbLoc.setCode(location.getCode());
			dbLoc.setName(location.getName());
			dbLoc.setType(location.getType());
			dbLoc.setZone(commonDao.load(WarehouseArea.class, location.getZone().getId()));
			if (location.getStowage() != null && location.getStowage().getId() != 0) {
				dbLoc.setStowage(commonDao.load(Stowage.class, location.getStowage().getId()));
			} else {
				dbLoc.setStowage(null);
			}
			dbLoc.setRackType(location.getRackType());
			dbLoc.setMuPick(location.getMuPick());
			dbLoc.setMixItem(location.isMixItem());
			dbLoc.setMixLot(location.isMixLot());
			dbLoc.setAisle(location.getAisle());
			dbLoc.setLine(location.getLine());
			dbLoc.setCol(location.getCol());
			dbLoc.setRow(location.getRow());
			if (location.getSortIndex() == 0) {
				dbLoc.setSortIndex(Integer.valueOf(""+location.getAisle()+location.getLine()+location.getCol()+location.getRow()));
			} else {
				dbLoc.setSortIndex(location.getSortIndex());
			}
			dbLoc.setTaskMode(location.getTaskMode());
			if (location.getPickBackLoc() != null && location.getPickBackLoc().getId() != 0) {
				dbLoc.setPickBackLoc(commonDao.load(Location.class, location.getPickBackLoc().getId()));
			} else {
				dbLoc.setPickBackLoc(null);
			}
			commonDao.store(dbLoc);
		}
	}
	
	
	
	public void deleteStowages(List<Long> stowageIds) {
		String errMsg = "";
		for (Long id : stowageIds) {
			Stowage stowage = commonDao.load(Stowage.class, id);
			if (!stowage.inUse()) {
				stowage.setDisabled(true);
				errMsg+=stowage.getCode()+" 类型失效成功;";
			}
			else
				errMsg+=stowage.getCode()+" 类型失效失败;";
			
		}
		LocalizedMessage.addLocalizedMessage(errMsg);
	}

	public void lock(List<Long> locationIds, String lockIn, String lockOut, String reason) {
		List<Location> locs = commonDao.loadAll(Location.class, locationIds.toArray(new Long[locationIds.size()]));
		String opMessage = "";
		for (Location location : locs) {
			if (LocationType.STORAGE.equals(location.getType())) {
				if (!location.beInLock() && lockIn.equalsIgnoreCase("true")) {
					location.setInLock(reason);
				}
				if (!location.beOutLock() && lockOut.equalsIgnoreCase("true")) {
					location.setOutLock(reason);
				}
				opMessage += location.getCode() + "已成功锁定!";
			} else {
				opMessage += location.getCode() + "锁定失败!";
			}
		}
		LocalizedMessage.addLocalizedMessage(opMessage);
	}

	public void unlock(List<Long> locationIds, String lockIn, String lockOut) {
		List<Location> locs = commonDao.loadAll(Location.class, locationIds.toArray(new Long[locationIds.size()]));
		for (Location location : locs) {
			if (location.beInLock() && lockIn.equalsIgnoreCase("true")) {
				location.setInLock(Location.VALID);
			}
			if (location.beOutLock() && lockOut.equalsIgnoreCase("true")) {
				location.setOutLock(Location.VALID);
			}
		}
	}

	public void active(List<Long> locationIds) {
		for (Long id : locationIds) {
			Location location = this.commonDao.load(Location.class,id);
			location.setDisabled(false);
		}
		
	}
	
	public void pass(List<Long> locationIds) {
		for (Long id : locationIds) {
			Location location = this.commonDao.load(Location.class,id);
//			if(location.getFlagStatus().equals(Location.WAIT_UPDATE)){
//				List<Location> ls=this.commonDao.findByQuery("from Location l where l.code='"+location.getUpdateCode()+"'");
//			}
			location.setCode(location.getUpdateCode());
			location.setFlagStatus(Location.PASS);
			this.commonDao.store(location);
		}
		
	}
	
	public void noPass(List<Long> locationIds) {
		for (Long id : locationIds) {
			Location location = this.commonDao.load(Location.class,id);
			location.setFlagStatus(Location.NO_PASS);
			this.commonDao.store(location);
		}
		
	}

	public void activeStowages(List<Long> stowageIds) {
		for (Long id : stowageIds) {
			Stowage stowage = this.commonDao.load(Stowage.class,id);
			stowage.setDisabled(false);
		}
		
	}

	public void storeStowage(Stowage stowage) {
		if (stowage.isNew()) {
			stowage.setWarehouse(WarehouseHolder.getWarehouse());
		}
		this.store(stowage);
	}

	public void storeBatchLocation(Location location, Integer aisleEnd, Integer lineEnd, Integer colEnd, Integer rowEnd, String frontString, Integer aisleCount, String aisleString, Integer lineCount, String lineString, Integer colCount, String colString, Integer rowCount) {	
		    //得到除去前缀的编码位数
			int numberCountWhihoutFront = aisleCount + lineCount + colCount + rowCount + frontString.length();
			if((aisleCount+lineCount+colCount+rowCount) > numberCountWhihoutFront){
				throw new BusinessException("numberCount.not.enough");
			}
			//算出要创建的库位
			int aisleStart = location.getAisle();
			int lineStart = location.getLine();
			int colStart = location.getCol();
			int rowStart = location.getRow();
			String errCode = "";
			String repeatCode = "";
			if(aisleStart > aisleEnd || lineStart > lineEnd || colStart > colEnd || rowStart > rowEnd){
				throw new BusinessException("startNumber.gt.endNumber");
			}
			for(int aisleSum = aisleStart;aisleSum <= aisleEnd;aisleSum++){
				for(int lineSum = lineStart;lineSum <= lineEnd;lineSum++){
					for(int colSum = colStart;colSum <= colEnd;colSum++){
						for(int rowSum = rowStart;rowSum <= rowEnd;rowSum++){
							//生成CODE
							String s1 = "", s2 = "", s3 = "", s4 = "", code = "";
							if(aisleCount > 0){
								s1 = String.format("%1$0"+aisleCount+"d",aisleSum);
								code = code + s1 + aisleString;
							}
							if(lineCount > 0){
								s2 = String.format("%1$0"+lineCount+"d",lineSum);
								code = code + s2 + lineString;
							}
							if(colCount > 0){
								s3 = String.format("%1$0"+colCount+"d",colSum);
								code = code + s3 + colString;
							}
							if(rowCount > 0){
								s4 = String.format("%1$0"+rowCount+"d",rowSum);
								code += s4;
							}		
							
							Location checkLoc = (Location)commonDao.findByNamedQueryUniqueResult("getLocationByCode",new String[]{"code","warehouseId"},new Object[]{code,WarehouseHolder.getWarehouse().getId()});
							if(null != checkLoc){
								errCode += code + ".";
								continue;
							}
							Location newLoc = EntityFactory.getEntity(Location.class);
							//默认拆箱级别为1
							newLoc.setSortIndex(Integer.parseInt((s1+s2+s3+s4).trim()));
							newLoc.setWarehouse(WarehouseHolder.getWarehouse());
							newLoc.setCountLock(Location.VALID);
							newLoc.setInLock(Location.VALID);
							newLoc.setOutLock(Location.VALID);
							newLoc.setStatus(Location.EMPTY);
							newLoc.setCode(frontString+code);
							if (StringUtils.isEmpty(location.getName())) {
								newLoc.setName(newLoc.getCode());
							} else {
								newLoc.setName(location.getName());
							}
							newLoc.setType(location.getType());
							newLoc.setZone(commonDao.load(WarehouseArea.class, location.getZone().getId()));
							newLoc.setRackType(location.getRackType());
							newLoc.setMuPick(location.getMuPick());
							newLoc.setMixItem(location.isMixItem());
							newLoc.setMixLot(location.isMixLot());
							newLoc.setAisle(aisleSum);
							newLoc.setLine(lineSum);
							newLoc.setCol(colSum);
							newLoc.setRow(rowSum);
							newLoc.setStowage(commonDao.load(Stowage.class, location.getStowage().getId()));
							newLoc.setTaskMode(location.getTaskMode());
							//判断道排层列是否在库区层面不重复
//							Location checkRepeatLoc = (Location)commonDao.findByNamedQueryUniqueResult("checkLocationInZoneIsNotRepeat",new String[]{"zoneId","aisle","line","row","col"},
//									             new Object[]{newLoc.getZone().getId(),newLoc.getAisle(),newLoc.getLine(),newLoc.getRow(),newLoc.getCol()});
//							if(null != checkRepeatLoc){
//								repeatCode += code + ".";
//								continue;
//							}
							this.commonDao.store(newLoc);
						}
					}
				}
			}	
			if(errCode.length() > 0){
				LocalizedMessage.addMessage("location.not.success", new String[] {errCode});
			}
			if(repeatCode.length() > 0){
				LocalizedMessage.addLocalizedMessage(repeatCode+"库位重复;");
			}
		}

	public void editBatchLocations(Location location, List<Long> ids) {
		for(Long id : ids){
			Location loc = this.commonDao.load(Location.class,id);
			if (StringUtils.isEmpty(location.getName())) {
				loc.setName(loc.getCode());
			} else {
				loc.setName(location.getName());
			}
			loc.setType(location.getType());
			loc.setZone(commonDao.load(WarehouseArea.class, location.getZone().getId()));
			loc.setRackType(location.getRackType());
			loc.setMixItem(location.isMixItem());
			loc.setMixLot(location.isMixLot());
			loc.setTaskMode(location.getTaskMode());
			loc.setMuPick(location.getMuPick());
			loc.setStowage(commonDao.load(Stowage.class, location.getStowage().getId()));
			this.store(loc);
		}
	}

	public void deleteBatchLocations(List<Long> locationIds) {
		int i = 0;
		for (Long id : locationIds) {
			Long count = Long.valueOf(String.valueOf(commonDao.findByNamedQueryUniqueResult("getInventoryLogCountByLocationId", new String[] {"locationId"}, new Long[] {id})));
			if (count == 0) {
				this.commonDao.delete(commonDao.load(Location.class, id));
				i++;
			}
		}
		if (i>0) {
			LocalizedMessage.addMessage("batchlocations.delete.success", new String[] {String.valueOf(i)});
		} else {
			LocalizedMessage.addMessage("batchLocationsRecord.delete.none");
		}
	}

	public String locationAnalyze(Map map) {
		String result = "";
		Long locationId = (Long) map.get("location.id");
		Location loc = commonDao.load(Location.class, locationId);
		List<Long> positionIds = new ArrayList<Long>();
		
		String posList = "";
		if (!StringUtils.isEmpty(loc.getPositionIds())) {
			String[] positions = StringUtils.split(loc.getPositionIds(), "<");
			for (int i=0;i<positions.length;i++) {
				Long posId = Long.valueOf(positions[i].replace(">", ""));
				positionIds.add(posId);
				Position position = commonDao.load(Position.class, posId);
				posList += position.getName() + ",";
			}
			posList = posList.substring(0, posList.length()-1);
		}

		result += "库位编码："+loc.getCode()+"\r\n";
		result += "所属库区：" + loc.getZone().getName() + "[" 
			+ loc.getAisle() + "道" 	+ loc.getLine() + "排" + loc.getCol() + "列" + loc.getRow() + "层]\r\n";
		result += "\r\n";
		
		result += "物理特性：\r\n";
		result += "------------------------------------------------------------\r\n";
		result += "长*宽*高：" + loc.getStowage().getLength() + "×" + loc.getStowage().getWidth() + "×" +loc.getStowage().getHeight() + "\r\n";
		result += "承载重量：" + (loc.getStowage().getWeight() == 0 ? "无限制" : loc.getStowage().getWeight()+"") + "\r\n";
		result += "承载体积：" + (loc.getStowage().getVolume() == 0 ? "无限制" : loc.getStowage().getVolume()+"") + "\r\n";
		if (loc.getStowage().getLpLimit() > 0) {
			result += "托盘库位[承载托数]：" + loc.getStowage().getLpLimit() + "\r\n";
		} else {
			result += "普通库位[承载件数]：" + (loc.getStowage().getQuantity() == 0 ? "无限制" : loc.getStowage().getQuantity()+"") + "\r\n";
		}
		result += "满载率：" + loc.getStowage().getFullRate() + "\r\n"; 
		result += "\r\n";
		
		result += "库位分类：\r\n";
		result += "------------------------------------------------------------\r\n";
		result += "库位类型：" + LocalizedMessage.getLocalizedMessage("LocationType."+loc.getType(), UserHolder.getReferenceModel(), UserHolder.getLanguage()) + "\r\n";
		result += "承载类型：" + loc.getStowage().getName() + "\r\n";
		result += "货架类型：" + LocalizedMessage.getLocalizedMessage("RackType."+loc.getRackType(), UserHolder.getReferenceModel(), UserHolder.getLanguage()) + "\r\n";
		result += "作业模式：" + LocalizedMessage.getLocalizedMessage("LocationTaskMode."+loc.getTaskMode(), UserHolder.getReferenceModel(), UserHolder.getLanguage()) + "\r\n";
		result += "库位定位分类：" + posList + "\r\n";
		result += "\r\n";

		result += "相关上架策略：\r\n";
		result += "------------------------------------------------------------\r\n";
		List<PutRackRule> prrs = commonDao.findByQuery("from PutRackRule prr where prr.position.id " +
				" in (:positionIds) or prr.defaultLocation.id = :locationId",
				new String[] {"positionIds", "locationId"},
				new Object[] {positionIds, loc.getId()});
		for (PutRackRule prr : prrs) {
			result += prr.toStringForDis(new CustomEntity()) + "-->" + (prr.getPosition()!=null ? prr.getPosition().getName() : prr.getDefaultLocation().getCode()) + "\r\n";
		}
		result += "\r\n";

		result += "相关拣货策略：\r\n";
		result += "------------------------------------------------------------\r\n";
		List<PickItemRule> pirs = commonDao.findByQuery("from PickItemRule pir where pir.position.id " +
				" in (:positionIds) or pir.pickLocation.id = :locationId",
				new String[] {"positionIds", "locationId"},
				new Object[] {positionIds, loc.getId()});
		for (PickItemRule pir : pirs) {
			result += pir.toStringForDis(new CustomEntity()) + "-->" + (pir.getPosition()!=null ? pir.getPosition().getName() : pir.getPickLocation().getCode()) + "\r\n";
		}
		result += "\r\n";
		
		result += "混放信息：\r\n";
		result += "------------------------------------------------------------\r\n";
		result += (loc.isMixItem() ? 
					((loc.isMixLot() ? "允许货品批次混放" : "允许货品混放")) 
					: "不允许货品混放") + "\r\n";
		Item item = (loc.getCurrentItem() == null ? null : commonDao.load(Item.class, loc.getCurrentItem()));
		ItemKey itemKey = (loc.getCurrentLot() == null ? null : commonDao.load(ItemKey.class, loc.getCurrentLot()));
		result += "最后一次放置货品：" + (item == null ? "无" : 
				"货主[" + item.getCompany().getCode() + " - " + item.getCompany().getName() + "]"
				+ "货品[" + item.getCode() + " - " + item.getName() + "]") + "\r\n";
		result += "最后一次放置批次：" + (itemKey == null ? "无" : 
				"[批次号：" + itemKey.getLot() + " - 批次属性：" + itemKey.getContent() + "]") + "\r\n";
		result += "\r\n";
		
		result += "锁定状态：\r\n";
		result += "------------------------------------------------------------\r\n";
		result += "入锁：" + (StringUtils.isEmpty(loc.getInLock()) ? "无" : loc.getInLock()) + "\r\n";
		result += "出锁：" + (StringUtils.isEmpty(loc.getInLock()) ? "无" : loc.getOutLock()) + "\r\n";
		result += "盘点锁：" + (StringUtils.isEmpty(loc.getInLock()) ? "无" : loc.getCountLock()) + "\r\n";
		result += "\r\n";

		result += "库存信息：\r\n";
		result += "------------------------------------------------------------\r\n";
		result += "[托盘号]-[批次号]-[货主]-[货品]-[数量]-[重量]-[体积]\r\n"; 
		result += "------------------------------------------------------------\r\n";
		for (Inventory inv : loc.getInventories()) {
			result += "[" + (inv.getLP() == null ? "" : inv.getLP().getLP()) + "]-" 
				+ "[" + inv.getItemKeyInventory().getItemKey().getLot() + "]-"
				+ "[" + inv.getItemKeyInventory().getItemKey().getItem().getCompany().getName() + "]-"
				+ "[" + inv.getItemKeyInventory().getItemKey().getItem().getName() + "]-"
				+ "[" + inv.getQuantity()+inv.getPackageUnit().getUnit() + "]-"
				+ "[" + DoubleUtils.formatByPrecision(inv.getQuantity()*inv.getPackageUnit().getWeight(), 4) + "]-"
				+ "[" + DoubleUtils.formatByPrecision(inv.getQuantity()*inv.getPackageUnit().getVolume(), 4) + "]"
				+ "\r\n";
		}
		result += "总数量：" + DoubleUtils.formatByPrecision(loc.getTotalQuantity(), 4) + "\r\n";
		result += "总重量：" + DoubleUtils.formatByPrecision(loc.getTotalWeight(), 4) + "\r\n";
		result += "总体积：" + DoubleUtils.formatByPrecision(loc.getTotalVolume(), 4) + "\r\n";
		result += "总托数：" + DoubleUtils.formatByPrecision(loc.getTotalLP(), 0) + "\r\n";
		result += "\r\n";
		
		result += "待上架信息：\r\n";
		result += "------------------------------------------------------------\r\n";
		result += "[托盘号]-[批次号]-[货主]-[货品]-[数量]-[重量]-[体积]\r\n"; 
		result += "------------------------------------------------------------\r\n";
		List<Task> tasks = commonDao.findByQuery("FROM Task task WHERE task.dstLoc.id = " + loc.getId() + " AND task.planQuantityMU > task.movedQuantityMU");
		for (Task task :tasks) {
			double unMoveQty = task.getPlanQuantityMU() - task.getMovedQuantityMU();
			double packQty = 0;
			if (task.getPackageUnit().getPrecision() == 0) {
				packQty = Math.ceil(unMoveQty/task.getPackageUnit().getConvertFigure());
			} else {
				packQty = DoubleUtils.formatByPrecision(unMoveQty / task.getPackageUnit().getConvertFigure(), 
						task.getPackageUnit().getPrecision());
			}
			
			result += "[" + (task.getDstLP() == null ? "" : task.getDstLP().getLP()) + "]-" 
			+ "[" + task.getItemKey().getLot() + "]-"
			+ "[" + task.getItemKey().getItem().getCompany().getName() + "]-"
			+ "[" + task.getItemKey().getItem().getName() + "]-"
			+ "[" + packQty+task.getPackageUnit().getUnit() + "]-"
			+ "[" + DoubleUtils.formatByPrecision(packQty*task.getPackageUnit().getWeight(), 4) + "]-"
			+ "[" + DoubleUtils.formatByPrecision(packQty*task.getPackageUnit().getVolume(), 4) + "]"
			+ "\r\n";
		}
		result += "待上架数量：" + DoubleUtils.formatByPrecision(loc.getQueuedQuantity(), 4) + "\r\n";
		result += "待上架重量：" + DoubleUtils.formatByPrecision(loc.getQueuedWeight(), 4) + "\r\n";
		result += "待上架体积：" + DoubleUtils.formatByPrecision(loc.getQueuedVolume(), 4) + "\r\n";
		result += "待上架托数：" + DoubleUtils.formatByPrecision(loc.getQueuedLP(), 0) + "\r\n";

		return result;
	}
	
	public Location getLocation(String locationCode){
		String hql = "FROM Location l where l.type = 'RECEIVE' and l.code = '" + locationCode + "'";
		List<Location> locations = commonDao.findByQuery(hql);
		if(locations.isEmpty()){
			return null;
		}
		return locations.get(0);
	}


	/**添加库位到库位定位*/
	@Override
	public void addlocationToPosition(Long positionid,List<Long> parentIds,Long zid,String type,Long sid,String rackType) {
	    /*type-库位类型  zone-所属库区 stowage-库位承载类型 rackType-货架类型*/
		Position position = commonDao.load(Position.class,positionid);
		for(Long id:parentIds) {
			Location l =this.load(Location.class, id);
			WarehouseArea w =this.load(WarehouseArea.class, zid);
			Stowage s=this.load(Stowage.class, sid);
			l.setType(type);
			l.setZone(w);
			l.setStowage(s);
			l.setStatus(rackType);
			l.setPosition(position);
			commonDao.store(l);
		}
		
		 
		
	}
	
	/**刪除库位定位中的库位*/
	@Override
	public void deletelocationFromPosition(List<Long> ids) {
		for(Long id :ids) {
			Location l =this.load(Location.class, id);
			this.delete(l);
		}
		
	}

	public void imporLocation(File file) {
		//库区名称 库区编码 库位  库位类型
		imporLocationVIM(file);
	}
	public void imporLocationVIM(File file) {
		try {
			Workbook workbook = Workbook.getWorkbook(file);
			Sheet sheet = workbook.getSheet(0);
			Stowage st=this.commonDao.get(Stowage.class, new Long("2"));
			WarehouseArea z=this.commonDao.get(WarehouseArea.class, new Long("19"));
			 for (int i = 1; i <sheet.getRows(); i++) {
				 String code=sheet.getCell(0,i).getContents();//库位代码
				 if(code==null||code.equals("")){
					 break;
				 }
				 Location l =null;
				 List<Location> ls=commonDao.findByQuery("from Location l where l.code=:code ", new String[]{"code"},new Object[]{code});
				 if(ls.size()>0){
					 l=ls.get(0);
					 l.setCode(code);
					 l.setFlagStatus(Location.WAIT_ADD);
					 commonDao.store(l);
				 }else{
					 l=EntityFactory.getEntity(Location.class);
					 l.setZone(z);//所属库区
					 l.setStowage(st);//库位承载类型
					 l.setWarehouse(WarehouseHolder.getWarehouse());
					 l.setFlagStatus(Location.WAIT_UPDATE);
					 l.setUpdateCode(code);
				 }
				 	 l.setType(LocationType.STORAGE);//默认类型
					 l.setStatus("EMPTY");
					 l.setTaskMode(LocationTaskMode.FORKLIFTWORK);//作业模型
					 l.setName(code);//库位说明
					 l.setRackType(RackType.NORMAL);//货架类型
					 l.setMixItem(true);//允许产品混放
					 l.setMixLot(true);//允许批次混放
					 commonDao.store(l);
			 }
		} catch (BiffException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	
	public void imporLocationUpdate(File file) {
		try {
			Workbook workbook = Workbook.getWorkbook(file);
			Sheet sheet = workbook.getSheet(0);
			 for (int i = 1; i <sheet.getRows(); i++) {
				 String oldCode=sheet.getCell(0,i).getContents();//库位代码
				 String newCode=sheet.getCell(1,i).getContents();//库位代码
				 if(oldCode==null||oldCode.equals("")){
					 break;
				 }
				 Location l =null;
				
				 List<Location> ls2=commonDao.findByQuery("from Location l where l.code=:newCode", new String[]{"newCode"},new Object[]{newCode});
				 if(ls2.size()>0){
					 ExceptionLog log=EntityFactory.getEntity(ExceptionLog.class);
					 log.setOperPageId("库位更新");
					 log.setOperDate(new Date());
					 log.setOperException((i+1)+"行"+newCode+"已经存在");
					 log.setOperUserName(UserHolder.getUser().getName());
					 log.setOperComponentName("导入日志");
					 this.commonDao.store(log);
				 }else{
					 List<Location> ls=commonDao.findByQuery("from Location l where l.code=:oldCode", new String[]{"oldCode"},new Object[]{oldCode});
					 if(ls.size()>0){
						 l=ls.get(0);
						 l.setCode(newCode);
						 l.setRemarks(oldCode+"变为"+newCode);
						 commonDao.store(l);
					 }else{
	//					 l=EntityFactory.getEntity(Location.class);
						 ExceptionLog log=EntityFactory.getEntity(ExceptionLog.class);
						 log.setOperPageId("库位更新");
						 log.setOperDate(new Date());
						 log.setOperException((i+1)+"行"+oldCode+"不存在");
						 log.setOperUserName(UserHolder.getUser().getName());
						 log.setOperComponentName("导入日志");
						 this.commonDao.store(log);
					 }
				 }
					
			 }
		} catch (BiffException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	public void importUpdate(File file) {
		try {
			Workbook workbook = Workbook.getWorkbook(file);
			Sheet sheet = workbook.getSheet(0);
			 for (int i = 1; i <sheet.getRows(); i++) {
				 String oldCode=sheet.getCell(0,i).getContents();//库位代码
				 String barCode=sheet.getCell(1,i).getContents();//库位代码
				 if(oldCode==null||oldCode.equals("")){
					 break;
				 }
				 Location l =null;
				 List<Location> ls2=commonDao.findByQuery("from Location l where l.code=:barCode", new String[]{"barCode"},new Object[]{barCode});
				 if(ls2.size()>0){
					 ExceptionLog log=EntityFactory.getEntity(ExceptionLog.class);
					 log.setOperPageId("库位更新");
					 log.setOperDate(new Date());
					 log.setOperException((i+1)+"行"+barCode+"已经存在");
					 log.setOperUserName(UserHolder.getUser().getName());
					 log.setOperComponentName("导入日志");
					 this.commonDao.store(log);
				 }else{
					 List<Location> ls=commonDao.findByQuery("from Location l where l.code=:oldCode", new String[]{"oldCode"},new Object[]{oldCode});
					 if(ls.size()>0){
						 l=ls.get(0);
						 l.setBarCode(barCode);
						 commonDao.store(l);
					 }else{
	//					 l=EntityFactory.getEntity(Location.class);
						 ExceptionLog log=EntityFactory.getEntity(ExceptionLog.class);
						 log.setOperPageId("库位更新");
						 log.setOperDate(new Date());
						 log.setOperException((i+1)+"行"+oldCode+"不存在");
						 log.setOperUserName(UserHolder.getUser().getName());
						 log.setOperComponentName("导入日志");
						 this.commonDao.store(log);
					 }
				 }
					
			 }
		} catch (BiffException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	public void imporLocation2(File file) {
		//库区名称 库区编码 库位  库位类型
		try {
			Workbook workbook = Workbook.getWorkbook(file);
			Sheet sheet = workbook.getSheet(0);
			 for (int i = 1; i <sheet.getRows(); i++) {
				 String zone=sheet.getCell(0,i).getContents();//库区名称
				 String code=sheet.getCell(1,i).getContents();//库位代码
				 String name=sheet.getCell(2,i).getContents();//库位名称
				 String rackType=sheet.getCell(3,i).getContents();//货架类型				 
				 String strMixItem=sheet.getCell(4,i).getContents();//货品混放
				 int mixItem=0;//货品混放
				 if(strMixItem.equals("混放")) {
					 mixItem = 1;
				 }
				 String strMixLot=sheet.getCell(5,i).getContents();//mixLot
				 int mixLot=0;//货品混放
				 if(strMixItem.equals("混放")) {
					 mixLot = 1;
				 }			 
				 String remarks=sheet.getCell(6,i).getContents();//库区编码
				 
				 
				 Location l =null;
				 List<Location> ls=commonDao.findByQuery("from Location l where l.code=:code ",
	        	 new String[]{"code"},new Object[]{code});
				 if(ls.size()>0){
					 l=ls.get(0);
					 commonDao.store(l);
				 }else{
					 l=EntityFactory.getEntity(Location.class);
				 }
				 	 l.setType(LocationType.STORAGE);//默认类型
					 l.setCode(code);
					 l.setStatus("EMPTY");
					 
					 List<WarehouseArea> w=this.commonDao.findByQuery("from WarehouseArea w where w.warehouse.id=:id and w.code=:code",
				    			new String[]{"id","code"},new Object[]{WarehouseHolder.getWarehouse().getId(),zone});
					 if(w.size()>0) {
						 WarehouseArea wha=w.get(0);
						 l.setZone(wha);//所属库区
					 }
					 List<Stowage> s=this.commonDao.findByQuery("from Stowage s where s.warehouse.id=:id",
				    			new String[]{"id"},new Object[]{WarehouseHolder.getWarehouse().getId()});
					 if(s.size()>0) {
						 Stowage stowage=s.get(0);
						 l.setStowage(stowage);//库位承载类型
					 }
					 l.setTaskMode(LocationTaskMode.FORKLIFTWORK);//作业模型
					 l.setName(code);//库位说明
					 l.setRackType(RackType.NORMAL);//货架类型
					 l.setMixItem(true);//允许产品混放
					 l.setMixLot(true);//允许批次混放
					 l.setWarehouse(WarehouseHolder.getWarehouse());
					 commonDao.store(l);
					 System.out.println(i);
				 
				 
			 }
		} catch (BiffException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	public int getInt(String str){
		try {
			return Integer.parseInt(str);
		} catch (Exception e) {
			return 0;
		}
	}
	
	public void storeItem(Item item) throws Exception { 
		Boolean temp=item.isNew();
		//先保存商品
		item.setWarehouse(WarehouseHolder.getWarehouse());
		commonDao.store(item);
		if(item.getWarehouse().getId().equals(1020L)){
			List<Inventory> invs=this.commonDao.findByQuery("from Inventory inv where inv.itemKey.item.id="+item.getId() +" "
					+ " and inv.zone.id!=20");
			String loc_code=item.getStrExtend1();
			Location newL=null;
			Location oldL=item.getLocation();
			List<Location> ls=this.commonDao.findByQuery("from Location where code='"+loc_code+"'");
			if(ls.size()>0){
				newL=ls.get(0);
			}else{
				newL=EntityFactory.getEntity(Location.class);
				newL.setCode(item.getStrExtend1());
				newL.setName(item.getStrExtend1());
				newL.setWarehouse(WarehouseHolder.getWarehouse());
		    	//查找对应的库区
		    	List<WarehouseArea> areas=this.commonDao.findByQuery("from WarehouseArea z where z.supplier.id ="+item.getCompany().getId()+" order by id asc ") ;
		    	if(areas.size()>0){
		    		newL.setZone(areas.get(0));
		    	}else{
		    		throw new BusinessException("请先维护供应商库区"); 
		    	}
		    	newL.setType("STORAGE");
		    	newL.setMixItem(true);
		    	newL.setMixLot(true);
		    	newL.setRackType("CW");
		    	newL.setTaskMode("MIXWORK");
		    	newL.setStowage(commonDao.load(Stowage.class, 1L));
		    	newL.setUpdateCode(item.getStrExtend1());
		    	newL.setFlagStatus(Location.WAIT_ADD);
		    	commonDao.store(newL);
		    	item.setLocation(newL);
			}
			if(!temp){
				if(!newL.getId().equals(oldL.getId())){
					for(Inventory inv:invs){
						oldL=inv.getLocation();
						if(!oldL.getId().equals(newL.getId())){
							inv.setLocation(newL);
							this.commonDao.store(inv);
						}
					}
					//
					if(!newL.getId().equals(oldL.getId())){
						InterfaceLog log=EntityFactory.getEntity(InterfaceLog.class);
						log.setDealTime(new Date());
						log.setRequest(item.getCode()+"品番原库位"+oldL.getCode()+"更改"+newL.getCode());
						log.setRequestTime(new Date());
						log.setFromSYS(UserHolder.getUser().getName());
						this.commonDao.store(log);
					}
				}
			}
			item.setLocation(newL);
			commonDao.store(item);
		}

		commonDao.store(item);
		LocalizedMessage.addMessage("item.save.success", new String[] {item.getCode()});
	}
}
