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

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.charset.Charset;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.ParsePosition;
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.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.lang.StringEscapeUtils;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

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

import com.dev.swms.server.model.abstractEntity.AutoProduction;
import com.dev.swms.server.model.abstractEntity.BigItem;
import com.dev.swms.server.model.abstractEntity.BomAccount;
import com.dev.swms.server.model.abstractEntity.BomAccountLog;
import com.dev.swms.server.model.abstractEntity.BomList;
import com.dev.swms.server.model.abstractEntity.HoistingData;
import com.dev.swms.server.model.abstractEntity.ItemList;
import com.dev.swms.server.model.abstractEntity.ModelChange;
import com.dev.swms.server.model.abstractEntity.ModelPlan;
import com.dev.swms.server.model.abstractEntity.OfflineData;
import com.dev.swms.server.model.abstractEntity.Pinfan;
import com.dev.swms.server.model.abstractEntity.PlanAssembly;
import com.dev.swms.server.model.abstractEntity.ProduceMonthPlan;
import com.dev.swms.server.model.abstractEntity.ProductionPlan;
import com.dev.swms.server.model.abstractEntity.SpareParts;
import com.dev.swms.server.model.base.BOMComponent;
import com.dev.swms.server.model.base.BillType;
import com.dev.swms.server.model.base.Item;
import com.dev.swms.server.model.base.ItemKey;
import com.dev.swms.server.model.base.ItemRelation;
import com.dev.swms.server.model.base.Location;
import com.dev.swms.server.model.base.LocationType;
import com.dev.swms.server.model.base.LotInfo;
import com.dev.swms.server.model.base.NewLotInfo;
import com.dev.swms.server.model.base.SignFile;
import com.dev.swms.server.model.base.Stowage;
import com.dev.swms.server.model.base.Structure;
import com.dev.swms.server.model.base.PackageUnit;
import com.dev.swms.server.model.base.TempBOM;
import com.dev.swms.server.model.base.Warehouse;
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.receiving.ASN;
import com.dev.swms.server.model.receiving.ASNDetail;
import com.dev.swms.server.model.receiving.ASNStatus;
import com.dev.swms.server.model.rules.LotRule;
import com.dev.swms.server.service.GlobalParamUtils;
import com.dev.swms.server.service.base.ItemManager;
import com.dev.swms.server.service.sequence.BussinessCodeManager;
import com.dev.swms.server.utils.DateUtil;
import com.dev.swms.server.utils.DoubleUtils;
import com.dev.swms.server.web.filter.WarehouseHolder;
import com.mysql.jdbc.Connection;
import com.sun.org.apache.bcel.internal.generic.SIPUSH;
import com.dev.energy.server.exception.BusinessException;
import com.dev.energy.server.exception.OriginalBusinessException;
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;

public class DefaultItemManager extends DefaultBaseManager implements
		ItemManager {
	protected final BussinessCodeManager codeManager;
	private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

	public DefaultItemManager(BussinessCodeManager manager) {
		super();
		codeManager = manager;
	}

	public Connection getConnection() {
		String driverClassName ="com.mysql.jdbc.Driver";
		String url = "jdbc:mysql://139.196.165.224:53306/jr_interface?useUnicode=true&amp;characterEncoding=UTF-8&amp;useSSL=false";
		String usename = "guanheng";
		String password = "jrxt123456";
		Connection con=null;
		try {
			Class.forName(driverClassName);
			try {
				 con= (Connection) DriverManager.getConnection(url,usename,password);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			
		}
		return con;
	}
	
	@Override
	public void autoItem() {
		Connection con=getConnection();
		Statement stmt =null;
		ResultSet rs=null;
		 String ghjk=getPropertiesParm("ghjk.bz");
		try {
			stmt =con.createStatement();
			String sql="select ID,ERPGNO,ERPGNAME,ERPUNIT from copgoods_mid where 1=1 ";
			if(ghjk.equals("OPEN")){
				sql+=" and DT_READ is null";
			}else{
				sql+= " and DATE_FORMAT(DT_INSERT,'%Y-%m-%d')>='2022-05-01'";
			}
			rs = stmt.executeQuery(sql);
			int i=0;
			Structure st=this.commonDao.load(Structure.class, new Long("1002"));
			Warehouse w=this.commonDao.load(Warehouse.class, new Long("1"));
			while(rs.next()){
	            int  id= rs.getInt("ID");
	            String  goodType= rs.getString("ERPGNO");
	            String  code=goodType.replace("-", "");
	            String  name= rs.getString("ERPGNAME");
	            String  unit= rs.getString("ERPUNIT");
	            List<Item> its=this.commonDao.findByQuery("from Item it where it.code='"+code+"'");
	            Item it=null;
	            if(its.size()>0){
	            	it=its.get(0);
	            }else{
	            	it= EntityFactory.getEntity(Item.class);
	            }
	            it.setGoodType(goodType);
	            it.setCode(code);
	            it.setName(name);
	            it.setUnit(unit);
	            it.setSourceId(id+"");
	            it.setCompany(st);
	            it.setWarehouse(w);
	            it.setSourceId(id+"");
	            this.commonDao.store(it);
	            Statement stmt2 =con.createStatement();
	           
		    		if(ghjk.equals("OPEN")){
			        	stmt2.executeUpdate("update copgoods_mid set DT_READ=now() where id ="+id);
			        	stmt2.close();
		    		}
	        	System.out.println(new Date()+"读取行数:"+i++);
	           // Statement update =null;
	        }
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			 try {
				 if(rs!=null){
					 rs.close();
				 }
				 if(stmt!=null){
					 stmt.close();
				 }
				 if(con!=null){
					 con.close();
				 }
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	        
		}
		
	}
	
	@Override
	public void autoAsn() {
		String ghjk=getPropertiesParm("ghjk.bz");
		System.out.println(ghjk);
//		if(ghjk.equals("CLOSE")){
		Connection con=getConnection();
		Statement stmt =null;
		ResultSet rs=null;
		String ymd=DateUtil.formatDateYMDToStr(DateUtil.increaseDate(new Date(),"DAY",-3));
//		ymd="2023-03-17";
		try {
			String sql_h="select max(ID) ID,LISTBILLNO,max(REMARK) REMARK,"
					+ "max(INVOICENO) INVOICENO,sum(LOADQTY) LOADQTY,max(DT_INSERT) DT_INSERT,"
					+ "max(CONTAINERNO) CONTAINERNO "
					+ " from cuc_loadlist_v_s_mid where 1=1";
			if(ghjk.equals("OPEN")){
				sql_h+= " and DT_READ is null";
			}else{ 
				sql_h+= " and DATE_FORMAT(DT_INSERT,'%Y-%m-%d')>='"+ymd+"'";
			}
			sql_h+= " group by LISTBILLNO order by id asc ";
			stmt =con.createStatement();
			rs = stmt.executeQuery(sql_h);
			int i=0;
			Structure st=this.commonDao.load(Structure.class, new Long("1002"));
			Location loc=this.commonDao.load(Location.class, new Long("1"));
			BillType bt=this.commonDao.load(BillType.class, new Long("1"));
			while(rs.next()){
	            String  code= rs.getString("LISTBILLNO");
	            String  des= rs.getString("REMARK");
	            String  relatedBill1= rs.getString("INVOICENO");
	            double  qty= rs.getDouble("LOADQTY");//本次装柜数量
	            Date date=rs.getDate("DT_INSERT");
	            String  relatedBill2= rs.getString("CONTAINERNO");
	            List<ASN> asns=this.commonDao.findByQuery("from ASN asn where asn.code='"+code+"'");
	            ASN asn=null;
	            if(asns.size()>0){
	            		asn=asns.get(0);
	            }else{
		            	asn=EntityFactory.getEntity(ASN.class);
		            	asn.setCode(code);
		            	asn.setCompany(st);
		            	asn.setOrderDate(date);
		            	asn.setUpdateTime(new Date());
		            	asn.setUserName("sys");
		            	asn.setDock(loc);
		            	asn.setBillType(bt);
		            	asn.setStatus(ASNStatus.OPEN);
		            	asn.setWarehouse(WarehouseHolder.getWarehouse());
		         }
		            asn.setExpectedQuantity(qty);
		            asn.setRelatedBill1(relatedBill1);
		            asn.setRelatedBill2(relatedBill2);
		            asn.setDescription(des);
		            this.commonDao.store(asn);
	            Statement stmtd =con.createStatement();
	    		ResultSet rsd=null; 
	    		String sql_d="select max(ID) ID,LINENUM,max(BILLNO_PLAN) BILLNO_PLAN,max(TRADEMODE) TRADEMODE,"
	    				+ "max(ERPGNO) ERPGNO ,max(LOADQTY) LOADQTY,"
	    				+ "max(ERPUNIT) ERPUNIT,max(NETWT) NETWT,max(CONTAINERNO) CONTAINERNO,max(BOXNO) BOXNO,"
	    				+ "max(REMARK) REMARK"
						+ " from cuc_loadlist_v_s_mid where 1=1 ";
	    		if(ghjk.equals("OPEN")){
	    			sql_d+= " and DT_READ is null";
	    		}
	    		sql_d+= " and LISTBILLNO ='"+code+"'";
	    		sql_d+= " group by LINENUM,LISTBILLNO order by id asc";
	    		rsd = stmtd.executeQuery(sql_d);
	    		String myfs="";
	    		String dpm="";
				while(rsd.next()){
		            int  id= rsd.getInt("ID");
		            int  LINENUM= rsd.getInt("LINENUM");//行号
		            String  BILLNO_PLAN= rsd.getString("BILLNO_PLAN");//计划单据编号
		            String  TRADEMODE= rsd.getString("TRADEMODE");//贸易方式
		            String  ERPGNO= rsd.getString("ERPGNO");// 本企业货号
		            double  LOADQTY= rsd.getDouble("LOADQTY");//本次装柜数量
		            String  ERPUNIT= rsd.getString("ERPUNIT");//本企业计量单位
		            double  NETWT=rsd.getDouble("NETWT");//净重(KG)
		            String  CONTAINERNO= rsd.getString("CONTAINERNO");//集装箱号
		            String  BOXNO= rsd.getString("BOXNO");
		            String  REMARK= rsd.getString("REMARK");
		            dpm=REMARK;
		            myfs=TRADEMODE;
		            List<Item> its=this.commonDao.findByQuery("from Item it where it.goodType='"+ERPGNO+"'");
		            if(its.size()>0){
		            	List<ASNDetail> ads=this.commonDao.findByQuery("from ASNDetail ad where ad.asn.code='"+code+"' "
		            			+ " and ad.lineNo="+LINENUM);
		            	ASNDetail ad=null;
		            	if(ads.size()>0){
		            		ad=ads.get(0);
		            	}else{
		            		ad=EntityFactory.getEntity(ASNDetail.class);
		            	}
		            	ad.setLineNo(LINENUM);
		            	ad.setPO(BILLNO_PLAN);
		            	ad.setExpectedQtyOfMasterUnit(LOADQTY);
		            	ad.setTemperature(CONTAINERNO);
		            	ad.setWeight(NETWT);
		            	LotInfo lot=new LotInfo();
		            	lot.setPropC1(TRADEMODE);
		            	lot.setPropC2(BOXNO);
		            	ad.setLotInfo(lot);
		            	ad.setExpectedQuantity(LOADQTY);
		            	ad.setItem(its.get(0));
		            	ad.setRemark(REMARK);
		            	ad.setAsn(asn);
		            	ad.setSourceId(id+"");
		            	this.commonDao.store(ad);
		            	if(ghjk.equals("OPEN")){
			            	Statement stmt2 =con.createStatement();
				        	stmt2.executeUpdate("update cuc_loadlist_v_s_mid set DT_READ=now() where id ="+id);
				        	stmt2.close();
		            	}
			        	System.out.println(new Date()+"读取行数:"+i+++"==="+asn.getId());
		            }else{
		             	if(ghjk.equals("OPEN")){
				            	Statement stmt2 =con.createStatement();
					        	stmt2.executeUpdate("update cuc_loadlist_v_s_mid set DT_READ=now(),mes='货品不存在' where id ="+id);
					        	stmt2.close();
		             	}
			        	System.out.println(new Date()+"读取异常行数:"+i+++"==="+asn.getId());
		            }
		            List objs = commonDao.findByQuery(
		    						"select sum(d.expectedQuantity)  from ASNDetail d where d.asn.id=:id ",
		    						new String[] { "id" }, new Object[] { asn.getId() });
		    		if (objs.size() > 0) {
		    			//asn.setExpectedQuantity((Double) objs.get(0));
		    		}
		    		asn.setSourceId(myfs);
		    		asn.setSourceType(dpm);
		    		String str="";
		    		if(myfs!=null&&!myfs.equals("")) {
		    			if(myfs.equals("进料对口")||"暂时进出货物".equals(myfs)) {
							str="保税";
						}else if("一般贸易".equals(myfs)||"其他进出口免".equals(myfs)) {
							str="课税";
						}
		    		}
		    		asn.setTemperature(str);
		    		commonDao.store(asn);
				}
				stmtd.close();
				rsd.close();
	        }
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			 try {
				 if(rs!=null){
					 rs.close();
				 }
				 if(stmt!=null){
					 stmt.close();
				 }
				 if(con!=null){
					 con.close();
				 }
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	        
		}
//		}
		
	}
	
	public void autoAsn2() {
		String ghjk=getPropertiesParm("ghjk.bz");
		if(ghjk.equals("OPEN")){
		Connection con=getConnection();
		Statement stmt =null;
		ResultSet rs=null;
		try {
			stmt =con.createStatement();
			rs = stmt.executeQuery("select ID,LISTBILLNO ,DT_INSERT  "
					+ " from dec_trans_s_mid where "
//					+ " DT_READ is null"
					+ " ID >=651  ");
			int i=0;
			while(rs.next()){
				Long ID=rs.getLong("ID");
	            String  LISTBILLNO= rs.getString("LISTBILLNO");
	            Date date=rs.getDate("DT_INSERT");
	            List<ASN> asns=this.commonDao.findByQuery("from ASN asn where asn.code='"+LISTBILLNO+"'");
	            ASN asn=null;
	            if(asns.size()>0){
	            	asn=asns.get(0);
	            	asn.setStatus(ASNStatus.ACTIVE);
	            	asn.setReceiveDateEnd(date);
	            	System.out.println(ID+"===="+LISTBILLNO);
	            }else{
	            	System.out.println("===="+LISTBILLNO);
	            }
	            this.commonDao.store(asn);
	        }
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			 try {
				 if(rs!=null){
					 rs.close();
				 }
				 if(stmt!=null){
					 stmt.close();
				 }
				 if(con!=null){
					 con.close();
				 }
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		}
	}
	
	public void returnAsn(List<Long> ids) {
		//如果是测试，则不需要打开接口回传
		String ghjk=getPropertiesParm("ghjk.bz");
		if(ghjk.equals("OPEN")){
			Connection con=getConnection();
			ResultSet rs=null;
			try {
				for(Long id:ids){
					ASN asn=this.commonDao.get(ASN.class, id);
					Statement stmt1 =con.createStatement();
					ResultSet rs1 = stmt1.executeQuery("select ID  "
							+ " from dec_trans_s_mid where "
							+ " LISTBILLNO ='"+asn.getCode()+"'");
					Boolean temp=Boolean.TRUE;
					while(rs1.next()){
						//存在则update
						Long update_id=rs1.getLong("ID");
						temp=Boolean.FALSE;
			            	Statement stmt2 =con.createStatement();
				        	stmt2.executeUpdate("update dec_trans_s_mid set ARRDATE_FACT=now(),DT_READ=null where id ="+update_id);
				        	stmt2.close();
					}
					if(temp){
						String sql="insert into dec_trans_s_mid (DT_INSERT,LISTBILLNO,ARRDATE_FACT) "
								+ " values (now(),?,now())";
						PreparedStatement pstmt = con.prepareStatement(sql);
						pstmt.setString(1, asn.getCode());
		//				pstmt.setDate(2, (java.sql.Date) new Date()); 
						pstmt.executeUpdate();
						pstmt.close();
					}
					asn.setStatus(ASNStatus.ACTIVE);
					asn.setReceiveDateEnd(new Date());
					asn.setFromName(asn.getTemperature()+"=="+UserHolder.getUser().getName()+"==="+new Date());
					this.commonDao.store(asn);
					stmt1.close();
					rs1.close();
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally{
				 try {
					 if(rs!=null){
						 rs.close();
					 }
					 if(con!=null){
						 con.close();
					 }
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		        
			}
		}else{
			for(Long id:ids){
				ASN asn=this.commonDao.get(ASN.class, id);
				asn.setStatus(ASNStatus.ACTIVE);
				asn.setReceiveDateEnd(new Date());
				asn.setFromName(asn.getTemperature()+"=="+UserHolder.getUser().getName()+"==="+new Date());
				this.commonDao.store(asn);
			}
		}
		
	}
	/*
	 *  (non-Javadoc)
	 * @see com.dev.swms.server.service.base.ItemManager#storeItem(com.dev.swms.server.model.base.Item, com.dev.swms.server.model.base.PackageUnit)
	 */
	public void storeItem(Item item) throws Exception { 
//		autoAsn() ;
		//先保存商品
		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");
			Location newL=item.getLocation();
			Location oldL=item.getLocation();
			for(Inventory inv:invs){
				oldL=inv.getLocation();
				if(!oldL.getId().equals(newL.getId())){
					if(inv.getQueuedQuantity()>0){
						throw new BusinessException("库存有占用，需要先完成未出库数据");
					}
					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);
			}
		}
		
			
//		//刷新session中的商品
//		item = commonDao.load(Item.class, item.getId());
//		//判断商品是否已有最小包装，如没有则自动创建，如有则修改最小包装名称为当前包装名称
//		PackageUnit minUnit = item.getMinPackageUnit();
//		if (minUnit == null) {
//			//设置数字1为默认的拆箱级别
//			packageUnit.setLineNO(1);
//			packageUnit.setLength(item.getLength());
//			packageUnit.setWidth(item.getWidth());
//			packageUnit.setHeight(item.getHeight());
//			packageUnit.setWeight(item.getWeight());
//			packageUnit.setVolume(item.getVolume());
//			packageUnit.setArea(0);
//			packageUnit.setConvertFigure(1);
//			item.addPackageUnit(packageUnit);
//		} else {
//			minUnit.setUnit(packageUnit.getUnit());
//		}
//		if(item.getLotRule() == null){
//			item.setLotRule(null);
//		}
		
		commonDao.store(item);
		LocalizedMessage.addMessage("item.save.success", new String[] {item.getCode()});
	}
	public void storePinfan(Pinfan pinfan,String locCode) {
		if(pinfan.isNew()) {
			pinfan.setWarehouse(WarehouseHolder.getWarehouse());
		}
		if(locCode!=null&&!locCode.equals("")) {
			List<Location> list=commonDao.findByQuery("from Location l where l.code='" +locCode+"'");
		    if(list.size()>0) {
		    	pinfan.setLocation(list.get(0));
		    }else {
		    	Location l=EntityFactory.getEntity(Location.class);
		    	l.setCode(locCode);
		    	l.setName(locCode);
		    	l.setWarehouse(WarehouseHolder.getWarehouse());
		    	l.setZone(pinfan.getZone());
		    	l.setType(LocationType.STORAGE);
		    	l.setMixItem(true);
		    	l.setMixLot(true);
		    	l.setRackType("CW");
		    	l.setTaskMode("MIXWORK");
		    	l.setStowage(commonDao.load(Stowage.class, 1L));
		    	l.setUpdateCode(locCode);
		    	l.setFlagStatus(Location.WAIT_ADD);
		    	commonDao.store(l);
		    	pinfan.setLocation(l);
		    }
		}else{
			pinfan.setLocation(null);
		}
		pinfan.setItem(pinfan.getItem());
		pinfan.setCode(pinfan.getItem().getCode());
		pinfan.setName(pinfan.getItem().getName());
		pinfan.setStrExtend1(locCode);
		commonDao.store(pinfan);
	}
	public void storeItemRelation(ItemRelation ir) { 
		ir.setCreateBy(UserHolder.getUser().getName());
		ir.setCreateDate(new Date());
		commonDao.store(ir);
	}

	/*
	 *  (non-Javadoc)
	 * @see com.dev.swms.server.service.base.ItemManager#addPackageUnit(java.lang.Long, com.dev.swms.server.model.base.PackageUnit)
	 */
	public void addPackageUnit(Long itemId, PackageUnit packageUnit) {
		if (packageUnit.getLpFormat1()!=null && !packageUnit.getLpFormat1().verify()) {
			throw new BusinessException("pakcageUnit.fullLPQuantity.input");
		}
		if (packageUnit.getLpFormat2()!=null && !packageUnit.getLpFormat2().verify()) {
			throw new BusinessException("pakcageUnit.fullLPQuantity.input");
		}
		if (packageUnit.getLpFormat3()!=null && !packageUnit.getLpFormat3().verify()) {
			throw new BusinessException("pakcageUnit.fullLPQuantity.input");
		}

		Item item = commonDao.load(Item.class, itemId);
		//新增商品包装
		if (packageUnit.isNew()) {
			PackageUnit dbUnit = item.getPackageUnit(packageUnit);
			if (dbUnit == null) {
				item.addPackageUnit(packageUnit);
			} else {
				throw new BusinessException("packageUnit.hasConvertFigure.error");
			}
		} else {
			PackageUnit dbUnit = commonDao.load(PackageUnit.class, packageUnit.getId());
			PackageUnit cdUnit = item.getPackageUnit(packageUnit);
			if (cdUnit != null && !cdUnit.getId().equals(dbUnit.getId())){
				throw new BusinessException("packageUnit.hasConvertFigure.error");
			}
			//不能修改最小包装的折算系数
			if (dbUnit.getConvertFigure() == 1 && packageUnit.getConvertFigure() != 1) {
				throw new BusinessException("packageUnit.convertFigure.error");
			} else if (dbUnit.getConvertFigure() != 1 && packageUnit.getLineNO() == 1) {
				throw new BusinessException("packageUnit.lineNO.error");
			} else {
				dbUnit.setConvertFigure(packageUnit.getConvertFigure());
			}
			dbUnit.setUnit(packageUnit.getUnit());
			dbUnit.setLength(packageUnit.getLength());
			dbUnit.setWidth(packageUnit.getWidth());
			dbUnit.setHeight(packageUnit.getHeight());
			dbUnit.setWeight(packageUnit.getWeight());
			dbUnit.setVolume(packageUnit.getVolume());
			dbUnit.setArea(packageUnit.getArea());
			dbUnit.setAllowLP(packageUnit.isAllowLP());
			dbUnit.setAtLeastLPQty(packageUnit.getAtLeastLPQty());
			dbUnit.setPrecision(packageUnit.getPrecision());
			if (dbUnit.getConvertFigure() == 1) {
				//设置基本包装的拆箱级别默认为1
				dbUnit.setLineNO(1);
			} else {
				dbUnit.setLineNO(packageUnit.getLineNO());
			}

			dbUnit.setLpFormat1(packageUnit.getLpFormat1());
			dbUnit.setLpFormat2(packageUnit.getLpFormat2());
			dbUnit.setLpFormat3(packageUnit.getLpFormat3());
		}
		
		commonDao.store(item);
		LocalizedMessage.addMessage("item.packageUnit.add.success", new String[] {item.getCode(),packageUnit.getUnit()});
	}

	/*
	 *  (non-Javadoc)
	 * @see com.dev.swms.server.service.base.ItemManager#removePackageUnit(java.lang.Long, java.util.List)
	 */
	public void removePackageUnit(Long itemId, List<Long> packageUnitIds) {
		Item item = commonDao.load(Item.class, itemId);
		Long id = packageUnitIds.get(0);
		PackageUnit unit = commonDao.load(PackageUnit.class, id);
		if (unit.getConvertFigure() != 1) {
			Long count_rvd = Long.valueOf(String.valueOf(commonDao.findByNamedQueryUniqueResult("getASNDetailsCountByPackageUnitId", new String[] {"packageUnitId"}, new Long[] {id})));
			Long count_ptd = Long.valueOf(String.valueOf(commonDao.findByNamedQueryUniqueResult("getPickTicketDetailsCountByPackageUnitId", new String[] {"packageUnitId"}, new Long[] {id})));
			Long count_wdd = Long.valueOf(String.valueOf(commonDao.findByNamedQueryUniqueResult("getWaveDocDetailsCountByPackageUnitId", new String[] {"packageUnitId"}, new Long[] {id})));
			Long count_inv = Long.valueOf(String.valueOf(commonDao.findByNamedQueryUniqueResult("getInventoryCountByPackageUnitId", new String[] {"packageUnitId"}, new Long[] {id})));
			
			if ((count_rvd+count_ptd+count_wdd+count_inv) == 0) {
				item.getPackageUnits().remove(unit);
				commonDao.store(item);
				LocalizedMessage.addMessage("item.packageUnit.remove.success", new String[] {item.getCode(), unit.getUnit()});
			} else {
				throw new OriginalBusinessException("该包装使用中，不能删除！");
			}
		} else {
			throw new OriginalBusinessException("折算系数为[1]的货品包装单位不能删除！");
		}
	}

	/*
	 *  (non-Javadoc)
	 * @see com.dev.swms.server.service.base.ItemManager#getSmallestPackageUnit(java.util.Map)
	 */
	@SuppressWarnings("unchecked")
	public String getSmallestPackageUnit(Map map) {
		Long itemId = (Long) map.get("item.id");
		if(itemId == null){
			return "";
		}
		Item item = this.load(Item.class,itemId);
		if(item.getPackageUnits().size()==0 || item.getMinPackageUnit()==null){
			return "";
		}
		return item.getMinPackageUnit().getUnit();
	}

	/*
	 *  (non-Javadoc)
	 * @see com.dev.swms.server.service.base.ItemManager#deleteAll(java.util.List)
	 */
	public void deleteAll(List<Long> itemIds) {
		String errMsg = "";
		for (Long id : itemIds) {
			Long count_log = Long.valueOf(String.valueOf(commonDao.findByNamedQueryUniqueResult("getInventoryLogCountByItemId", new String[] {"itemId"}, new Long[] {id})));
			Long count_rvd = Long.valueOf(String.valueOf(commonDao.findByNamedQueryUniqueResult("getASNDetailsCountByItemID", new String[] {"itemId"}, new Long[] {id})));
			Long count_ptd = Long.valueOf(String.valueOf(commonDao.findByNamedQueryUniqueResult("getPickTicketDetailsCountByItemID", new String[] {"itemId"}, new Long[] {id})));
			Item item = commonDao.load(Item.class, id);
			
			if (item!=null) {
				item.setDisabled(true);
				errMsg+=item.getCode()+" 货品失效成功;";
			}
			else
				errMsg+=item.getCode()+" 货品失效失败;";
		}
		LocalizedMessage.addLocalizedMessage(errMsg);
	}

	/**
	 * 如果指定收货日期和收货单号，则检查重复批次属性时包含lotInfo+storageDate+soi
	 * @param itemKey
	 * @return
	 */
	public ItemKey getItemKey(ItemKey itemKey, Boolean verifyLot,String soi) {
		itemKey.setItem(this.commonDao.load(Item.class, itemKey.getItem().getId()));
		formatLotInfo(itemKey.getItem(), itemKey.getLotInfo(), verifyLot);
//        if(soi!=null&&!soi.equals("")) {
//        	itemKey.setSOI(soi);
//        }else {
//        	itemKey.setSOI(null);
//        }
//		itemKey.setItem(this.commonDao.load(Item.class, itemKey.getItem().getId()));
//		if(itemKey.getItem().getCompany().isCheckReceiveDate() && !itemKey.getItem().getCompany().isCheckReceiveCode()){
//			itemKey.setSOI(null);
//		}else if(!itemKey.getItem().getCompany().isCheckReceiveDate() && itemKey.getItem().getCompany().isCheckReceiveCode()){
//			itemKey.setStorageDate(null);
//		}else if(!itemKey.getItem().getCompany().isCheckReceiveDate() && !itemKey.getItem().getCompany().isCheckReceiveCode()){
//		}
		
//		String hql = getHqlByItemKey(itemKey);
//		
//		List<String> params = new ArrayList<String>();
//		List<Object> values = new ArrayList<Object>();
//		try {
//			if (itemKey.getLotInfo().getPropD1() != null) {
//				params.add("propD1");
//					values.add(sdf.parse(sdf.format(itemKey.getLotInfo().getPropD1())));
//			}
//			if (itemKey.getLotInfo().getPropD2() != null) {
//				params.add("propD2");
//				values.add(sdf.parse(sdf.format(itemKey.getLotInfo().getPropD2())));
//			}
//			if (itemKey.getLotInfo().getPropD3() != null) {
//				params.add("propD3");
//				values.add(sdf.parse(sdf.format(itemKey.getLotInfo().getPropD3())));
//			}
//			if (itemKey.getStorageDate() != null) {
//				params.add("storageDate");
//				values.add(sdf.parse(sdf.format(itemKey.getStorageDate())));
//			}
//		} catch (ParseException e) {
//			e.printStackTrace();
//		}
//
//		ItemKey dbKey = (ItemKey) commonDao.findByQueryUniqueResult(hql, 
//				params.toArray(new String[params.size()]), values.toArray(new Object[values.size()]));
		ItemKey dbKey=null;
//		List<ItemKey> ItemKeys =  commonDao.findByQuery(" from ItemKey ik where ik.item.id=:id and ik.lotInfo.propD1=:propD1 and ik.lotInfo.propD2=:propD2 ",
//		new String[] { "id","propD1","propD2"},new Object[] {itemKey.getItem().getId(),itemKey.getLotInfo().getPropD1(),itemKey.getLotInfo().getPropD2()});
		String hql=" from ItemKey ik where ik.item.id="+itemKey.getItem().getId() ;
//		if(itemKey.getLotInfo()!=null&&itemKey.getLotInfo().getPropL2()!=null){
//			hql+=" and ik.lotInfo.propL2="+itemKey.getLotInfo().getPropL2();
//		}else{
//			hql+=" and ik.lotInfo.propL2 is null";
//		}
//		if(itemKey.getSOI()!=null) {
//			 hql+=" and ik.SOI='"+soi+"'" ;
//		}else {
//			 hql+=" and ik.SOI is null";
//		}
		if(itemKey.getPinfan()!=null){
			 hql+=" and ik.pinfan.id="+itemKey.getPinfan().getId() ;
		}else{
			 hql+=" and ik.pinfan.id is null";
		}
		List<ItemKey> ItemKeys =  commonDao.findByQuery(hql);
		if(ItemKeys.size()>0){
			dbKey=ItemKeys.get(0);
			return dbKey;
		}	
		if (dbKey == null) {
			dbKey = new ItemKey();//EntityFactory.getEntity(ItemKey.class);
			String lot = codeManager.getCodeForYm("",5);//codeManager.generateLot();
			dbKey.setLot(lot);
			dbKey.setLotInfo(new LotInfo());
			if(itemKey.getLotInfo()!=null){
			dbKey.getLotInfo().setPropC1(itemKey.getLotInfo().getPropC1());
			dbKey.getLotInfo().setPropC2(itemKey.getLotInfo().getPropC2());
			dbKey.getLotInfo().setPropC3(itemKey.getLotInfo().getPropC3());
			dbKey.getLotInfo().setPropC4(itemKey.getLotInfo().getPropC4());
			dbKey.getLotInfo().setPropC5(itemKey.getLotInfo().getPropC5());
			dbKey.getLotInfo().setPropC6(itemKey.getLotInfo().getPropC6());
			dbKey.getLotInfo().setPropC7(itemKey.getLotInfo().getPropC7());
			dbKey.getLotInfo().setPropC8(itemKey.getLotInfo().getPropC8());
			dbKey.getLotInfo().setPropC9(itemKey.getLotInfo().getPropC9());
			dbKey.getLotInfo().setPropD1(itemKey.getLotInfo().getPropD1());
			dbKey.getLotInfo().setPropD2(itemKey.getLotInfo().getPropD2());
			dbKey.getLotInfo().setPropC9(itemKey.getLotInfo().getPropC9());
			dbKey.getLotInfo().setPropN1(itemKey.getLotInfo().getPropN1());
			dbKey.getLotInfo().setPropN2(itemKey.getLotInfo().getPropN2());
			dbKey.getLotInfo().setPropN3(itemKey.getLotInfo().getPropN3());
			dbKey.getLotInfo().setPropL1(itemKey.getLotInfo().getPropL1());
			dbKey.getLotInfo().setPropL2(itemKey.getLotInfo().getPropL2());
			dbKey.getLotInfo().setPropL3(itemKey.getLotInfo().getPropL3());
			dbKey.getLotInfo().setPropLC1(itemKey.getLotInfo().getPropLC1());
			dbKey.getLotInfo().setPropLC2(itemKey.getLotInfo().getPropLC2());
			dbKey.getLotInfo().setPropLC3(itemKey.getLotInfo().getPropLC3());
			try {
				dbKey.getLotInfo().setPropD1(itemKey.getLotInfo().getPropD1()==null ? null : sdf.parse(sdf.format(itemKey.getLotInfo().getPropD1())));
				dbKey.getLotInfo().setPropD2(itemKey.getLotInfo().getPropD2()==null ? null : sdf.parse(sdf.format(itemKey.getLotInfo().getPropD2())));
				dbKey.getLotInfo().setPropD3(itemKey.getLotInfo().getPropD3()==null ? null : sdf.parse(sdf.format(itemKey.getLotInfo().getPropD3())));
//				dbKey.setStorageDate(itemKey.getStorageDate()==null ? null : sdf.parse(sdf.format(itemKey.getStorageDate())));
			} catch (ParseException e) {
				e.printStackTrace();
			}
			}
			dbKey.setPinfan(itemKey.getPinfan());
			dbKey.setSOI(itemKey.getSOI());
			dbKey.setContent(itemKey.getContent());
			dbKey.setItem(commonDao.load(Item.class, itemKey.getItem().getId()));
			commonDao.store(dbKey);
		} 
		return dbKey;
	}
	/**
	 * 新的ItemKey必须根据itemB的批次规则进行生成。
	 */
	public ItemKey getItemKeyForCompanyTrans(ItemKey itemKey, Date receiveDate, String soi, Item itemB) {
		ItemKey itemKeyTemp = new ItemKey("",itemB, new LotInfo(), receiveDate, soi,itemKey.getPinfan());
		if(itemB.getDefaultLotRule()!=null){
			LotRule lotRule = itemB.getDefaultLotRule();
			if(lotRule.getLotRuleComponent().getTrackPropC1()){
				itemKeyTemp.getLotInfo().setPropC1(itemKey.getLotInfo().getPropC1());
			}
			if(lotRule.getLotRuleComponent().getTrackPropC2()){
				itemKeyTemp.getLotInfo().setPropC2(itemKey.getLotInfo().getPropC2());
			}
			if(lotRule.getLotRuleComponent().getTrackPropC3()){
				itemKeyTemp.getLotInfo().setPropC3(itemKey.getLotInfo().getPropC3());
			}
			if(lotRule.getLotRuleComponent().getTrackPropC4()){
				itemKeyTemp.getLotInfo().setPropC4(itemKey.getLotInfo().getPropC4());
			}
			if(lotRule.getLotRuleComponent().getTrackPropC5()){
				itemKeyTemp.getLotInfo().setPropC5(itemKey.getLotInfo().getPropC5());
			}
			if(lotRule.getLotRuleComponent().getTrackPropC6()){
				itemKeyTemp.getLotInfo().setPropC6(itemKey.getLotInfo().getPropC6());
			}
			if(lotRule.getLotRuleComponent().getTrackPropC7()){
				itemKeyTemp.getLotInfo().setPropC7(itemKey.getLotInfo().getPropC7());
			}
			if(lotRule.getLotRuleComponent().getTrackPropC8()){
				itemKeyTemp.getLotInfo().setPropC8(itemKey.getLotInfo().getPropC8());
			}
			if(lotRule.getLotRuleComponent().getTrackPropC9()){
				itemKeyTemp.getLotInfo().setPropC9(itemKey.getLotInfo().getPropC9());
			}
			
			if(lotRule.getLotRuleComponent().getTrackPropD1()){
				itemKeyTemp.getLotInfo().setPropD1(itemKey.getLotInfo().getPropD1());
			}
			if(lotRule.getLotRuleComponent().getTrackPropD2()){
				itemKeyTemp.getLotInfo().setPropD2(itemKey.getLotInfo().getPropD2());
			}
			if(lotRule.getLotRuleComponent().getTrackPropD3()){
				itemKeyTemp.getLotInfo().setPropD3(itemKey.getLotInfo().getPropD3());
			}
			
			if(lotRule.getLotRuleComponent().getTrackPropN1()){
				itemKeyTemp.getLotInfo().setPropN1(itemKey.getLotInfo().getPropN1());
			}
			if(lotRule.getLotRuleComponent().getTrackPropN2()){
				itemKeyTemp.getLotInfo().setPropN2(itemKey.getLotInfo().getPropN2());
			}
			if(lotRule.getLotRuleComponent().getTrackPropN3()){
				itemKeyTemp.getLotInfo().setPropN3(itemKey.getLotInfo().getPropN3());
			}
		}else{
			//throw new BusinessException("canTrans.itemB.lotRule.null",new String[]{itemB.getCode()});
		}
		
		return this.getItemKey(itemKeyTemp, Boolean.FALSE,null);
	}

	/**
	 * 不允许itemKey中出现空字符串
	 * @param itemKey
	 */
	public void formatLotInfo(Item item, LotInfo lotInfo, Boolean verifyLot) {
		item = commonDao.load(Item.class, item.getId());
		if(lotInfo!=null){
		if ("".equals(lotInfo.getPropC1())) {
			lotInfo.setPropC1(null);
		}
		if ("".equals(lotInfo.getPropC2())) {
			lotInfo.setPropC2(null);
		}
		if ("".equals(lotInfo.getPropC3())) {
			lotInfo.setPropC3(null);
		}
		if ("".equals(lotInfo.getPropC4())) {
			lotInfo.setPropC4(null);
		}
		if ("".equals(lotInfo.getPropC5())) {
			lotInfo.setPropC5(null);
		}
		if ("".equals(lotInfo.getPropC6())) {
			lotInfo.setPropC6(null);
		}
		if ("".equals(lotInfo.getPropC7())) {
			lotInfo.setPropC7(null);
		}
		if ("".equals(lotInfo.getPropC8())) {
			lotInfo.setPropC8(null);
		}
		if ("".equals(lotInfo.getPropC9())) {
			lotInfo.setPropC9(null);
		}
		
		//保质期处理
		if (item.getDefaultLotRule() != null && item.getDefaultLotRule().getLotRuleComponent().getTrackPropD1()) {
			if(lotInfo.getPropD1()==null){
				lotInfo.setInvaidStart(item); 
			}
			if(lotInfo.getPropD2()==null){
				lotInfo.setInvaidEnd(item); 										
			}
		}
		
		//校验批次属性是否符合管理要求
		if (verifyLot) {
			if(item.getDefaultLotRule()!=null && !lotInfo.verifyRequired(item.getDefaultLotRule())){
				//throw new BusinessException("lotInfo.notRequired.error");
			}
		}
		}
	}
	
	/**
	 * 不允许itemKey中出现空字符串
	 * @param itemKey
	 */
	public void formatNewLotInfo(NewLotInfo lotInfo) {
		if ("".equals(lotInfo.getPropC1())) {
			lotInfo.setPropC1(null);
		}
		if ("".equals(lotInfo.getPropC2())) {
			lotInfo.setPropC2(null);
		}
		if ("".equals(lotInfo.getPropC3())) {
			lotInfo.setPropC3(null);
		}
		if ("".equals(lotInfo.getPropC4())) {
			lotInfo.setPropC4(null);
		}
		if ("".equals(lotInfo.getPropC5())) {
			lotInfo.setPropC5(null);
		}
		if ("".equals(lotInfo.getPropC6())) {
			lotInfo.setPropC6(null);
		}
		if ("".equals(lotInfo.getPropC7())) {
			lotInfo.setPropC7(null);
		}
		if ("".equals(lotInfo.getPropC8())) {
			lotInfo.setPropC8(null);
		}
		if ("".equals(lotInfo.getPropC9())) {
			lotInfo.setPropC9(null);
		}
		if ("".equals(lotInfo.getPropL1())) {
			lotInfo.setPropL1(null);
		}
		if ("".equals(lotInfo.getPropL2())) {
			lotInfo.setPropL2(null);
		}
		if ("".equals(lotInfo.getPropL3())) {
			lotInfo.setPropL3(null);
		}
	}
	public void addComponents(Long BOMId,BOMComponent bomComponent){
		if(bomComponent.getQuantity()<=0){
			throw new BusinessException("componentQuantity.error");
		}
		//套件的子件不能包含自己
		if(bomComponent.getComponent().getId().equals(BOMId)){
			throw new BusinessException("component.containItself.error");
		}
		Item bom = commonDao.load(Item.class,BOMId);		
		if(bomComponent.isNew()){
			bomComponent.setBom(bom);
			bomComponent.setQuantity(bomComponent.getQuantity());
			bom.addComponent(bomComponent);
		}else{
			BOMComponent component = commonDao.load(BOMComponent.class,bomComponent.getId());
			component.setComponent(bomComponent.getComponent());
			component.setQuantity(bomComponent.getQuantity());
		}
		this.store(bom);
	}

	public void deleteComponents(Long BOMId, List<Long> ids) {
		Item bom = commonDao.load(Item.class,BOMId);
		for(Long id : ids){
			BOMComponent bomComponent = commonDao.load(BOMComponent.class,id);
			bom.deleteComponent(bomComponent);
		}
	}
    
	/*
	 *  (non-Javadoc)
	 * @see com.dev.swms.server.service.base.ItemManager#queryBOM(java.lang.Long, double)
	 */
	@SuppressWarnings("unchecked")
	public void queryBOM(Long BOMId, double quantity) {
        double newQTY=this.queryBOMInventory(BOMId,quantity);
        commonDao.executeByNamed("deleteTempBOM",new String[0],new Object[0]);
        if(newQTY>0){
            List<BOMComponent> components1=commonDao.findByNamedQuery("getBOMComponentByBOMId",new String[]{"BOMId"},new Object[]{BOMId});
        	for(BOMComponent component1:components1){
        		if(component1.getComponent().getIsBOM()){
        			double newQTY1=newQTY*(component1.getQuantity());
        			queryBOMComponent(component1.getComponent().getId(),newQTY1);
        		}else{
        			Long itemId=component1.getComponent().getId();
        			double deltaQTY=component1.getQuantity()*newQTY;
        			storeTempBOM(itemId,deltaQTY);	
        	    }
        	}
         }

    }
	
	/*
	 * 递归调用，计算出所有套件的缺失数量
	 */
	@SuppressWarnings("unchecked")
	private void queryBOMComponent(Long BOMId, double quantity) {
	     double newQTY=this.queryBOMInventory(BOMId,quantity);
	     if(newQTY>0){
	         List<BOMComponent> components1=commonDao.findByNamedQuery("getBOMComponentByBOMId",new String[]{"BOMId"},new Object[]{BOMId});
	         for(BOMComponent component1:components1){
	             if(component1.getComponent().getIsBOM()){
	        		double newQTY1=newQTY*(component1.getQuantity());
	        		queryBOMComponent(component1.getComponent().getId(),newQTY1);
	        	}else{
	        	    Long itemId=component1.getComponent().getId();
	        	    double deltaQTY=component1.getQuantity()*newQTY;
	        	    storeTempBOM(itemId,deltaQTY);	
	        	}
	         }
	     }
	}
    
	/*
	 * 计算库存中BOM的数量，返回不足的数量
	 */
	@SuppressWarnings("unchecked")
	private double queryBOMInventory(Long BOMId,double quantity){
        double leftQuantity=0;
        List<Inventory> list=commonDao.findByNamedQuery("getInventoryByItemId",new String[]{"itemId"},new Object[]{BOMId});
        for(Inventory inventory:list){
        	leftQuantity+=inventory.getAvaliableQuantity();
        }
        //如果库存中已有数量大于或者等于设置数量则将quantity＝0表示够用
        if(leftQuantity >= quantity) {
        	quantity = 0;
        } else {
        	quantity -= leftQuantity;
        }
		return quantity;
	}
	 
	/*
	 * 保存当前tempBOM
	 */
	@SuppressWarnings("unchecked")
	private void storeTempBOM(Long itemId,double quantity){
		Item item=commonDao.load(Item.class,itemId);
    	double leftQuantity = 0;
    	
 	    List<Inventory> list=commonDao.findByNamedQuery("getInventoryByItemId",new String[]{"itemId"},new Object[]{itemId});
        for(Inventory inventory:list){
   	       leftQuantity += inventory.getAvaliableQuantity();
        }
 	    double actualQty=leftQuantity-quantity;
        TempBOM tempBOM = EntityFactory.getEntity(TempBOM.class); 
        tempBOM.setComponent(item);
        if(actualQty<0){
    	    tempBOM.setIsLack(true);
    	    tempBOM.setLackQTY(actualQty);
        }else{
    	    tempBOM.setIsLack(false);
        }
        this.store(tempBOM);
	}

	public void activeItem(List<Long> itemIds) {
		for (Long id : itemIds) {
			Item item = this.commonDao.load(Item.class,id);
			item.setDisabled(false);
		}
		List<Item> is=this.commonDao.findByQuery("from Item i where i.id not in (select p.item.id from PackageUnit p)");
		for(Item i:is){
		    PackageUnit unit=EntityFactory.getEntity(PackageUnit.class);
		    unit.setLineNO(1);
		    unit.setUnit("件");
		    unit.setItem(i);
		    this.commonDao.store(unit);
		    i.addPackageUnit(unit);
		    this.commonDao.store(i);
		}
		
	}
	
	public void addSuppliers(List<Long> orgIds, Long itemId) {
		Item item = this.load(Item.class, itemId);
		//判断当前货品是否已与相应供应商关联
		if (item.getSuppliers() == null || item.getSuppliers().isEmpty()) {
			item.setSuppliers(new HashSet<Structure>());
		}
		for (Long orgId : orgIds) {
			item.getSuppliers().add(commonDao.load(Structure.class, orgId));
		}
	}
	
	public void delSuppliers(List<Long> orgIds, Long itemId) {
		Item item = this.load(Item.class, itemId);
		for (Long orgId : orgIds) {
			item.getSuppliers().remove(commonDao.load(Structure.class, orgId));
		}
	}

	@SuppressWarnings("unchecked")
	public List<Boolean> getLotRuleTackersByPageMap(Map map) {
		Long itemId = (Long) map.get("itemId");
		
		if(itemId == null) {
			itemId = (Long) map.get("asnDetail.item.id");
		}
		if (itemId == null) {
			itemId = (Long) map.get("pickTicketDetail.item.id");
		}
		if(itemId == null) {
			itemId = (Long) map.get("applyDetail.item.id");
		}
		if(itemId == null) {
			itemId = (Long) map.get("detail.itemKey.item.id");
		}
		return getLotRuleTackers(itemId);
	}

	public List<Boolean> getLotRuleTackers(Long itemId) {
		List<Boolean> results = new ArrayList<Boolean>();
		Item item = commonDao.load(Item.class, itemId);
		if (item != null) {
			results.add(item.getLotRule() == null ? (item.getCompany().getLotRule() == null ? Boolean.FALSE : item.getCompany().getLotRule().getLotRuleComponent().getTrackPropC1()) : item.getLotRule().getLotRuleComponent().getTrackPropC1());
//			results.add(item.getLotRule() == null ? (item.getCompany().getLotRule() == null ? Boolean.FALSE : item.getCompany().getLotRule().getLotRuleComponent().getTrackPropC2()) : item.getLotRule().getLotRuleComponent().getTrackPropC2());
//			results.add(item.getLotRule() == null ? (item.getCompany().getLotRule() == null ? Boolean.FALSE : item.getCompany().getLotRule().getLotRuleComponent().getTrackPropC3()) : item.getLotRule().getLotRuleComponent().getTrackPropC3());
//			results.add(item.getLotRule() == null ? (item.getCompany().getLotRule() == null ? Boolean.FALSE : item.getCompany().getLotRule().getLotRuleComponent().getTrackPropC4()) : item.getLotRule().getLotRuleComponent().getTrackPropC4());
//			results.add(item.getLotRule() == null ? (item.getCompany().getLotRule() == null ? Boolean.FALSE : item.getCompany().getLotRule().getLotRuleComponent().getTrackPropC5()) : item.getLotRule().getLotRuleComponent().getTrackPropC5());
//			results.add(item.getLotRule() == null ? (item.getCompany().getLotRule() == null ? Boolean.FALSE : item.getCompany().getLotRule().getLotRuleComponent().getTrackPropC6()) : item.getLotRule().getLotRuleComponent().getTrackPropC6());
//			results.add(item.getLotRule() == null ? (item.getCompany().getLotRule() == null ? Boolean.FALSE : item.getCompany().getLotRule().getLotRuleComponent().getTrackPropC7()) : item.getLotRule().getLotRuleComponent().getTrackPropC7());
//			results.add(item.getLotRule() == null ? (item.getCompany().getLotRule() == null ? Boolean.FALSE : item.getCompany().getLotRule().getLotRuleComponent().getTrackPropC8()) : item.getLotRule().getLotRuleComponent().getTrackPropC8());
//			results.add(item.getLotRule() == null ? (item.getCompany().getLotRule() == null ? Boolean.FALSE : item.getCompany().getLotRule().getLotRuleComponent().getTrackPropC9()) : item.getLotRule().getLotRuleComponent().getTrackPropC9());
			results.add(item.getLotRule() == null ? (item.getCompany().getLotRule() == null ? Boolean.FALSE : item.getCompany().getLotRule().getLotRuleComponent().getTrackPropD1()) : item.getLotRule().getLotRuleComponent().getTrackPropD1());
			results.add(item.getLotRule() == null ? (item.getCompany().getLotRule() == null ? Boolean.FALSE : item.getCompany().getLotRule().getLotRuleComponent().getTrackPropD1()) : item.getLotRule().getLotRuleComponent().getTrackPropD1());
//			results.add(item.getLotRule() == null ? (item.getCompany().getLotRule() == null ? Boolean.FALSE : item.getCompany().getLotRule().getLotRuleComponent().getTrackPropD3()) : item.getLotRule().getLotRuleComponent().getTrackPropD3());
//			results.add(item.getLotRule() == null ? (item.getCompany().getLotRule() == null ? Boolean.FALSE : item.getCompany().getLotRule().getLotRuleComponent().getTrackPropN1()) : item.getLotRule().getLotRuleComponent().getTrackPropN1());
//			results.add(item.getLotRule() == null ? (item.getCompany().getLotRule() == null ? Boolean.FALSE : item.getCompany().getLotRule().getLotRuleComponent().getTrackPropN2()) : item.getLotRule().getLotRuleComponent().getTrackPropN2());
//			results.add(item.getLotRule() == null ? (item.getCompany().getLotRule() == null ? Boolean.FALSE : item.getCompany().getLotRule().getLotRuleComponent().getTrackPropN3()) : item.getLotRule().getLotRuleComponent().getTrackPropN3());
//			results.add(item.getLotRule() == null ? (item.getCompany().getLotRule() == null ? Boolean.FALSE : item.getCompany().getLotRule().getLotRuleComponent().getTrackPropL1()) : item.getLotRule().getLotRuleComponent().getTrackPropL1());
//			results.add(item.getLotRule() == null ? (item.getCompany().getLotRule() == null ? Boolean.FALSE : item.getCompany().getLotRule().getLotRuleComponent().getTrackPropL2()) : item.getLotRule().getLotRuleComponent().getTrackPropL2());
//			results.add(item.getLotRule() == null ? (item.getCompany().getLotRule() == null ? Boolean.FALSE : item.getCompany().getLotRule().getLotRuleComponent().getTrackPropL3()) : item.getLotRule().getLotRuleComponent().getTrackPropL3());
		}

		return results;
	}
	
	private String getHqlByItemKey(ItemKey itemKey) {
		String hql = "FROM ItemKey itemKey where itemKey.item.id = " + itemKey.getItem().getId() +  
		" AND itemKey.lotInfo.propN1 = " + itemKey.getLotInfo().getPropN1() + 
		" AND itemKey.lotInfo.propN2 = " + itemKey.getLotInfo().getPropN2() +
		" AND itemKey.lotInfo.propN3 = " + itemKey.getLotInfo().getPropN3();
		
		if (itemKey.getLotInfo().getPropC1() == null) {
			hql += " AND itemKey.lotInfo.propC1 IS NULL ";
		} else {
			hql += " AND itemKey.lotInfo.propC1 = '" + itemKey.getLotInfo().getPropC1() + "'";
		}
		if (itemKey.getLotInfo().getPropC2() == null) {
			hql += " AND itemKey.lotInfo.propC2 IS NULL ";
		} else {
			hql += " AND itemKey.lotInfo.propC2 = '" + itemKey.getLotInfo().getPropC2() + "'";
		}
		if (itemKey.getLotInfo().getPropC3() == null) {
			hql += " AND itemKey.lotInfo.propC3 IS NULL ";
		} else {
			hql += " AND itemKey.lotInfo.propC3 = '" + itemKey.getLotInfo().getPropC3() + "'";
		}
		if (itemKey.getLotInfo().getPropC4() == null) {
			hql += " AND itemKey.lotInfo.propC4 IS NULL ";
		} else {
			hql += " AND itemKey.lotInfo.propC4 = '" + itemKey.getLotInfo().getPropC4() + "'";
		}
		if (itemKey.getLotInfo().getPropC5() == null) {
			hql += " AND itemKey.lotInfo.propC5 IS NULL ";
		} else {
			hql += " AND itemKey.lotInfo.propC5 = '" + itemKey.getLotInfo().getPropC5() + "'";
		}
		if (itemKey.getLotInfo().getPropC6() == null) {
			hql += " AND itemKey.lotInfo.propC6 IS NULL ";
		} else {
			hql += " AND itemKey.lotInfo.propC6 = '" + itemKey.getLotInfo().getPropC6() + "'";
		}
		if (itemKey.getLotInfo().getPropC7() == null) {
			hql += " AND itemKey.lotInfo.propC7 IS NULL ";
		} else {
			hql += " AND itemKey.lotInfo.propC7 = '" + itemKey.getLotInfo().getPropC7() + "'";
		}
		if (itemKey.getLotInfo().getPropC8() == null) {
			hql += " AND itemKey.lotInfo.propC8 IS NULL ";
		} else {
			hql += " AND itemKey.lotInfo.propC8 = '" + itemKey.getLotInfo().getPropC8() + "'";
		}
		if (itemKey.getLotInfo().getPropC9() == null) {
			hql += " AND itemKey.lotInfo.propC9 IS NULL ";
		} else {
			hql += " AND itemKey.lotInfo.propC9 = '" + itemKey.getLotInfo().getPropC9() + "'";
		}
	
		if (itemKey.getLotInfo().getPropD1() == null) {
			hql += " AND itemKey.lotInfo.propD1 IS NULL ";
		} else {
			hql += " AND itemKey.lotInfo.propD1 = :propD1";
		}
		if (itemKey.getLotInfo().getPropD2() == null) {
			hql += " AND itemKey.lotInfo.propD2 IS NULL ";
		} else {
			hql += " AND itemKey.lotInfo.propD2 =  :propD2";
		}
		if (itemKey.getLotInfo().getPropD3() == null) {
			hql += " AND itemKey.lotInfo.propD3 IS NULL ";
		} else {
			hql += " AND itemKey.lotInfo.propD3 = :propD3";
		}
		
		if (itemKey.getLotInfo().getPropL1() == null) {
			hql += " AND itemKey.lotInfo.propL1 IS NULL ";
		} else {
			hql += " AND itemKey.lotInfo.propL1 = " + itemKey.getLotInfo().getPropL1();
		}
		if (itemKey.getLotInfo().getPropL2() == null) {
			hql += " AND itemKey.lotInfo.propL2 IS NULL ";
		} else {
			hql += " AND itemKey.lotInfo.propL2 = " + itemKey.getLotInfo().getPropL2();
		}
		if (itemKey.getLotInfo().getPropL3() == null) {
			hql += " AND itemKey.lotInfo.propL3 IS NULL ";
		} else {
			hql += " AND itemKey.lotInfo.propL3 = " + itemKey.getLotInfo().getPropL3();
		}
	
		if (itemKey.getSOI() == null) {
			hql += " AND itemKey.SOI IS NULL ";
		} else {
			hql += " AND itemKey.SOI = '" + itemKey.getSOI() + "'";
		}
		if (itemKey.getStorageDate() == null) {
			hql += " AND itemKey.storageDate IS NULL ";
		} else {
			hql += " AND itemKey.storageDate =  :storageDate";
		}
		
		return hql;
	}
	
	public void addItemKey(ItemKey key) {
		getItemKey(key, true,null);
//		commonDao.store(key);
	}
	public void importItem3(File file){
		try {
			Workbook workbook = Workbook.getWorkbook(file);
		    Sheet sheet = workbook.getSheet(0);//得到excel第一页的内容
		    for (int i = 1; i <sheet.getRows(); i++) {
		     	String itemCode=sheet.getCell(1,i).getContents().trim();
		     	String locationCode=sheet.getCell(0,i).getContents().trim();
			    	if(null==itemCode || itemCode.equals("")){
			    		return;
			    	}
			    	Item item=null;
			    	List<Item> items=this.commonDao.findByQuery("from Item s where s.code=:code",new String[]{"code"},new Object[]{itemCode});
			    	if(items.size()>0){
			    		List<Location> ls=this.commonDao.findByQuery("from Location where code=:code",new String[]{"code"},new Object[]{locationCode});
			    		if(ls.size()>0){
			    			item=items.get(0);
			    			item.setLocation(ls.get(0));
			    			this.commonDao.store(item);
			    		}else{
			    			System.out.println(locationCode);
			    		}
			    	}else{
			    		System.out.println(itemCode);
			    	}
		    }
	}catch (Exception e) {
		// TODO: handle exception
	}
}
	public void importItem(File file){
		try {
			Workbook workbook = Workbook.getWorkbook(file);
		    Sheet sheet = workbook.getSheet(0);//得到excel第一页的内容
		 	for (int i = 1; i <sheet.getRows(); i++) {
		 		//客户名称	货品代码	货品名称	长（米）	宽（米）	高（米）	单位	子父规格	重量（kg)	产品规格
		    	String cus_code=sheet.getCell(0,i).getContents().trim();
		     	String itemCode=sheet.getCell(1,i).getContents().trim();
		     	String itemName=sheet.getCell(2,i).getContents().trim();
//		     	String c=sheet.getCell(2,i).getContents();
//		     	String k=sheet.getCell(3,i).getContents();
//		     	String g=sheet.getCell(4,i).getContents();
		     	String pu=sheet.getCell(3,i).getContents();
		     	String goodType=sheet.getCell(4,i).getContents();//接口
//		     	String weight=sheet.getCell(5,i).getContents();
//		     	String gg=sheet.getCell(8,i).getContents();
//		     	String cclx=sheet.getCell(9,i).getContents();
		     	Structure st=null;
		     	List<Structure> ss=this.commonDao.findByQuery("from Structure s where s.name=:code",new String[]{"code"},new Object[]{cus_code});
		     	if(null==itemCode || itemCode.equals("")){
			    		return;
			    	}
		     	double len=0;
		     	double width=0;
		     	double height=0;
		     	double xs=1;
		     	double wg=0;
//		     	if(c!=null&&!c.equals("")){
//		     		len=Double.parseDouble(c);
//		     	}
//		     	if(k!=null&&!k.equals("")){
//		     		width=Double.parseDouble(k);
//		     	}
//		     	if(g!=null&&!g.equals("")){
//		     		height=Double.parseDouble(g);
//		     	}
//		     	if(weight!=null&&!weight.equals("")){
//		     		wg=Double.parseDouble(weight);
//		     	}
//		     	if(ca!=null&&!ca.equals("")){
//		     		xs=Double.parseDouble(ca);
//		     	}
		     	
		     	if(ss.size()<=0){
		     		System.out.println(itemCode+"客户不存在"+cus_code+"行"+(i+1));
		     		continue;
//		     		st=EntityFactory.getEntity(Structure.class);
//		     		st.setCode(cus_code);
//		     		st.setName(cus_code);
//		     		st.setShortName(cus_code);
//		     		st.setBeCompany(Boolean.TRUE);
//		     		this.commonDao.store(st);
			    		//throw new BusinessException(i+1+"行货主"+cus_code+"不存在!");
			    }else{
			    		st=ss.get(0);
			    }
			    	Item item=null;
			    List<Item> items=this.commonDao.findByQuery("from Item i where i.code='"+itemCode+"' and i.company.id="+st.getId());
			    	if(items.size()>0){
			    		item=items.get(0);
			    		item.setCode(itemCode);
			    		
//			    		if(len>0){
//			    			item.setLength(len);
//			    		}
//			    		if(width>0){
//			    			item.setWidth(width);
//			    		}
//			    		if(height>0){
//			    			item.setHeight(height);
//			    		}
//			    		if(xs>1){
//			    			item.setCAcoefficient(xs);
//			    		}
//			    		if(item.getCAcoefficient()>0){
//			    			item.setVolume(DoubleUtils.formatByPrecision(item.getLength()*item.getWidth()*item.getHeight()/item.getCAcoefficient(),6));
//			    		}
//			    		if(wg>0){
//			    			item.setWeight(wg);
//			    			item.setRoughWeight(wg);
//			    		}
			    		this.commonDao.store(item);
			    		System.out.println(itemCode+"更新"+"行"+(i+1));
			    	}else{
			    		System.out.println(itemCode+"未找到"+"行"+(i+1));
//			    		continue;
			    		item=EntityFactory.getEntity(Item.class);
//			    		item.setCompany(st);
			    		item.setCode(itemCode);
			    		item.setName(itemName);
//			    		item.setValidPeriod(0);
//			    		item.setGoodType(null);
			    		item.setUnit(pu);
//			    		item.setCAname("箱");
//			    		item.setBeMarkWeight(true);
//			    		item.setCAcoefficient(Double.parseDouble("1"));
//			    		item.setBeWeight(true);
//			    		commonDao.store(item);
//			    		PackageUnit minUnit = item.getMinPackageUnit();
//			    		PackageUnit packageUnit=EntityFactory.getEntity(PackageUnit.class);
//			    		if (minUnit == null) {
//			    			//设置数字1为默认的拆箱级别
//			    			packageUnit.setLineNO(1);
//			    			packageUnit.setUnit(item.getUnit());
//			    			packageUnit.setLength(item.getLength());
//			    			packageUnit.setWidth(item.getWidth());
//			    			packageUnit.setHeight(item.getHeight());
//			    			packageUnit.setWeight(item.getWeight());
//			    			packageUnit.setVolume(item.getVolume());
//			    			packageUnit.setArea(0);
//			    			packageUnit.setConvertFigure(1);
//			    			packageUnit.setItem(item);
//			    			item.addPackageUnit(packageUnit);
//			    			commonDao.store(packageUnit);
//			    		} else {
//			    			minUnit.setUnit(item.getUnit());
//			    		}
			    		commonDao.store(item);
				    	}
			    	}
		} catch (BiffException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void importItem2(File file){
		try {
			Workbook workbook = Workbook.getWorkbook(file);
		    Sheet sheet = workbook.getSheet(0);//得到excel第一页的内容
		    SimpleDateFormat sdf=new SimpleDateFormat("yy-MM-dd");//小写的mm表示的是分钟  
		    for (int i = 1; i <sheet.getRows(); i++) {
		    	System.out.println(i);
		    	//货主名称	货品代码	货品名称	货品规格	基本单位	包装系数	包装单位 	托系数 保质期	 	
		    	//存储类型	品牌	内条码 	长	宽	高	重量 体积	 描述
		    	String customer=sheet.getCell(0,i).getContents().trim();
		    	String itemCode=sheet.getCell(1,i).getContents().trim();
	        	String itemName=sheet.getCell(2,i).getContents().trim();
	        	String gg=sheet.getCell(3,i).getContents().trim();
	        	String unit=sheet.getCell(4,i).getContents().trim();
	        	double ca=Double.parseDouble(sheet.getCell(5,i).getContents().trim().equals("")?"0":sheet.getCell(5,i).getContents().trim());
	        	String caName=sheet.getCell(6,i).getContents().trim();
	        	int txs=Integer.parseInt(sheet.getCell(7,i).getContents().trim().equals("")?"0":sheet.getCell(7,i).getContents().trim());
	        	int validPeriod=Integer.parseInt(sheet.getCell(8,i).getContents().trim().equals("")?"0":sheet.getCell(8,i).getContents().trim());
	        	String storageType=sheet.getCell(9,i).getContents().trim();
	        	String brand=sheet.getCell(10,i).getContents().trim();
	        	String barcode=sheet.getCell(11,i).getContents().trim();
	        	double length=Double.parseDouble(sheet.getCell(12,i).getContents().trim().equals("")?"0":sheet.getCell(12,i).getContents().trim());
	        	double width=Double.parseDouble(sheet.getCell(13,i).getContents().trim().equals("")?"0":sheet.getCell(13,i).getContents().trim());
	        	double height=Double.parseDouble(sheet.getCell(14,i).getContents().trim().equals("")?"0":sheet.getCell(14,i).getContents().trim());
	        	double weight=Double.parseDouble(sheet.getCell(15,i).getContents().trim().equals("")?"0":sheet.getCell(15,i).getContents().trim());
	        	double volume=Double.parseDouble(sheet.getCell(16,i).getContents().trim().equals("")?"0":sheet.getCell(16,i).getContents().trim());
	        	String description=sheet.getCell(17,i).getContents().trim();
	        	
	        	List<Structure> ss=this.commonDao.findByQuery("from Structure s where s.name=:name",new String[]{"name"},new Object[]{customer});
	        	if(ss.size()>0){
	        		Structure s=ss.get(0);
	        		Item item=EntityFactory.getEntity(Item.class);
	        		List<Item> items=commonDao.findByQuery("from Item t where t.code=:itemCode and t.disabled=0 and t.company.id=:id",
	    			new String[]{"itemCode","id"},new Object[]{itemCode,s.getId()});
	        		if(items.size()>0){
			    		item=items.get(0);
			    		Integer convertFigure=1;
			    		PackageUnit pu=null;
		        		List<PackageUnit> units=new ArrayList<PackageUnit>();
		        		units=commonDao.findByQuery("from PackageUnit unit where convertFigure=:convertFigure and unit.item.id=:itemId",
	        					new String[]{"convertFigure","itemId"},new Object[]{convertFigure,item.getId()});
				    	if(units.size()>0){
				    		pu=units.get(0);
				    	}

			    	}
	        		if(storageType.equals("常温")){
			    		storageType="ROOM_TEMPERATURE";
			    	}else if(storageType.equals("冷冻")){
			    		storageType="FREEZING";
			    	}else if(storageType.equals("冷藏")){
			    		storageType="COLD_STORAGE";
			    	}else if(storageType.equals("恒温")){
			    		storageType="OTHER";
			    	}else if(storageType == null || storageType.length()<=0){
			    		storageType="";
			    	}
			    		item.setCompany(s);
			    		item.setCode(barcode);
			    		item.setName(itemName);
			    		item.setSpecs(gg);
			    		item.setUnit(unit);
			    		item.setCAcoefficient(ca);
			    		item.setCAname(caName);
			    		item.setBalanceNumber(txs);
			    		item.setBarcode(barcode);
			    		item.setLength(length);
			    		item.setWidth(width);
			    		item.setHeight(height);
			    		item.setWeight(weight);
			    		item.setVolume(volume);
			    		item.setValidPeriod(validPeriod);
			    		item.setStorageType(storageType);
			    		item.setBrand(brand);
			    		item.setDisabled(false);
			    		item.setDescription(description);
			    		commonDao.store(item);
			    		PackageUnit minUnit = item.getMinPackageUnit();
			    		PackageUnit packageUnit=EntityFactory.getEntity(PackageUnit.class);
			    		if (minUnit == null) {
			    			//设置数字1为默认的拆箱级别
			    			packageUnit.setLineNO(1);
			    			packageUnit.setUnit(item.getUnit());
			    			packageUnit.setLength(item.getLength());
			    			packageUnit.setWidth(item.getWidth());
			    			packageUnit.setHeight(item.getHeight());
			    			packageUnit.setWeight(item.getWeight());
			    			packageUnit.setVolume(item.getVolume());
			    			packageUnit.setArea(0);
			    			packageUnit.setConvertFigure(1);
			    			packageUnit.setItem(item);
			    			item.addPackageUnit(packageUnit);
			    			commonDao.store(packageUnit);
			    		} else {
			    			minUnit.setUnit(item.getUnit());
			    			minUnit.setLength(item.getLength());
			    			minUnit.setWidth(item.getWidth());
			    			minUnit.setHeight(item.getHeight());
			    			minUnit.setWeight(item.getWeight());
			    			minUnit.setVolume(item.getVolume());
			    			commonDao.store(minUnit);
			    		}
			    	commonDao.store(item);
					LocalizedMessage.addMessage("item.save.success", new String[] {item.getCode()});
        			System.out.println(i);
	        	}else{
	        		throw new BusinessException(i+1+"行货主,"+""+"不存在!");
	        	}
		    }
		}catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public String getLeaveDueDay(Map map) throws Exception {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String days=null;
		Set<Map.Entry<Long, List>> itor = map.entrySet();
		Long itemId = (Long) map.get("item.id");
		Calendar calendar=Calendar.getInstance();
		Date now = new Date();
		Item item = commonDao.load(Item.class, itemId);
		Date dueDate=sdf.parse(sdf.format(item.getDueDate())); //到期日期
		if(!dueDate.equals("")||!dueDate.equals("-")){
			Date newDate=sdf.parse(sdf.format(new Date())); //当前日期
			calendar.setTime(dueDate);    
			long time1 = calendar.getTimeInMillis(); 
			calendar.setTime(newDate);  
			long time2 = calendar.getTimeInMillis();  
			long day=(time1-time2)/(1000*3600*24); 
			days = String.valueOf(day);
			int a=Integer.valueOf(days);
			item.setAlertLeadingDays(a);
			this.commonDao.store(item);
			if(day<0){
				return "0";
			}else{
				return String.valueOf(a);
			}
		}
		return days;
		
			
	}
	// 删除回单影像
	@Override
	public void deleteSignFile(List<Long> ids) {
		for (Long id : ids) {
			SignFile signFile = this.get(SignFile.class, id);
			Item item = signFile.getItem();
			if (signFile != null) {
				commonDao.delete(signFile);
			} else {
				throw new BusinessException("待删除文件不存在！");
			}
			item.removeFiles(signFile);// 移除关联
			// 删除对应的图片资料
			String fileUrl = GlobalParamUtils
					.getGloableStringValue("imageTarget")
					+ signFile.getFileName();
			File file = new File(fileUrl);
			file.delete();
			commonDao.store(item);
		}
	}
	
	public double fourDecimal(double sum){
		BigDecimal  b = new BigDecimal(sum);  
		double   f1   =   b.setScale(4,BigDecimal.ROUND_HALF_UP).doubleValue(); 
		return f1;
	}

	@Override
	public void packChange(Item item) {
		if(item.getCAcoefficient()>0&&item.getPackNumber()>0){
			String result="";
			double small=item.getCAcoefficient();
			double big=item.getPackNumber();
			if(big%small==0){
				double number=big/small;
				result=number+item.getCAname();
			}else{
				double mo=big%small;//余数
				double shang=Math.floor(big/small);
				result=shang+item.getCAname()+mo+ item.getMinPackageUnit().getUnit();
			}
			item.setStrExtend4(result);
			commonDao.store(item);
			System.out.println(result);
		}else{
			throw new BusinessException("小单位货大单位系数不能为0!");
		}
	}
	
	public void  importPinfan(File file,String type){
		try {
			Workbook workbook = Workbook.getWorkbook(file);
		    Sheet sheet = workbook.getSheet(0);//得到excel第一页的内容
		    String strmes="";
		    SimpleDateFormat sdf=new SimpleDateFormat("yy-MM-dd");//小写的mm表示的是分钟  
		    for (int i = 1; i <sheet.getRows(); i++) {
		    	System.out.println(i);
		    	
		    	//No	品番	品名	A/C	加工内容	保税	仓库	库位	收容数	荷姿	库存计量单位	备注 	
		    	String numberNo=sheet.getCell(0,i).getContents().trim();
		    	String code=sheet.getCell(1,i).getContents().trim();
	        	String name=sheet.getCell(2,i).getContents().trim();
	        	String specs=sheet.getCell(3,i).getContents().trim();
	        	String content=sheet.getCell(4,i).getContents().trim();
	        	String bonded=sheet.getCell(5,i).getContents().trim();
	        	String ck=sheet.getCell(6,i).getContents().trim();
	        	String locCode=sheet.getCell(7,i).getContents().trim();
	        	double quantity=Double.parseDouble(sheet.getCell(8,i).getContents().trim().equals("")?"0":sheet.getCell(8,i).getContents().trim());
	        	String hezi=sheet.getCell(9,i).getContents().trim();
	        	String unit=sheet.getCell(10,i).getContents().trim();
	        	String description=sheet.getCell(11,i).getContents().trim();
	        	List<Item> Items=this.commonDao.findByQuery("from Item zone where zone.code=:code",new String[]{"code"},new Object[]{code});
	        	Item item=null;
	        	if(Items.size()>0) {
	        		item=Items.get(0);
	        	}else {
	        		 strmes=code+",";
	        		continue;
//	        		throw new BusinessException(code+":部品基础资料没有");
	        	}
	        	List<WarehouseArea> zones=this.commonDao.findByQuery("from WarehouseArea zone where zone.name=:name",new String[]{"name"},new Object[]{ck});
	        	WarehouseArea zneo=null;
	        	if(zones.size()>0) {
	        		zneo=zones.get(0);
	        	}else {
	        		zneo=EntityFactory.getEntity(WarehouseArea.class);
	        		zneo.setCode(ck);
	        		zneo.setName(ck);
	        		zneo.setWarehouse(WarehouseHolder.getWarehouse());
	        		commonDao.store(zneo);
//	        		throw new BusinessException(ck+":仓库基础资料没有");
	        	}
	        	
	        	List<Pinfan> Pinfans=this.commonDao.findByQuery("from Pinfan  p where p.code=:name and p.zone.id=:zoneId  and p.bonded=:bonded",
	        			new String[]{"name","zoneId","bonded"},new Object[]{code,zneo.getId(),bonded});
	        	Pinfan p=null;
	        	if(Pinfans.size()>0) {
	        		p=Pinfans.get(0);
	        	}else {
	        		p=EntityFactory.getEntity(Pinfan.class);
	        	}
	        	List<Location> locs=this.commonDao.findByQuery("from Location  s where s.code=:name",new String[]{"name"},new Object[]{locCode});
	        	Location loc=null;
	        	if(locs.size()>0){
	        		loc=locs.get(0);
	        	}else{
	        		loc=EntityFactory.getEntity(Location.class);
	        		loc.setCode(locCode);
	        		loc.setName(name);
	        		loc.setZone(zneo);
	        		loc.setWarehouse(WarehouseHolder.getWarehouse());
	        		loc.setType("STORAGE");
	        		loc.setStowage(commonDao.load(Stowage.class, 1L));
	        		loc.setRackType("CW");
	        		loc.setTaskMode("MIXWORK");
	        		loc.setMixItem(true);
	        		loc.setMixLot(true);
	        		loc.setUpdateCode(locCode);
	        		loc.setFlagStatus(Location.WAIT_ADD);
	        		commonDao.store(loc);
	        	}	
	        		p.setNumberNo(numberNo);
	        		p.setItem(item);
		    		p.setCode(code);
		    		p.setName(name);
		    		p.setSpecs(specs);
		    		p.setContent(content);
		    		p.setBonded(bonded);
		    		p.setQuantity(quantity);
		    		p.setHezi(hezi);
		    		p.setUnit(unit);
		    		p.setLocation(loc);
		    		p.setZone(zneo);
		    		p.setWarehouse(WarehouseHolder.getWarehouse());
		    		p.setDescription(description);
		    		commonDao.store(p);
		    }
		    System.out.println(strmes);
		}catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	public void  importPinfanSx(File file){
		try {
			Workbook workbook = Workbook.getWorkbook(file);
		    Sheet sheet = workbook.getSheet(0);//得到excel第一页的内容
		    for (int i = 1; i <sheet.getRows(); i++) {
		    	//No	品番	品名	A/C	加工内容	保税	仓库	库位	收容数	荷姿	库存计量单位	备注 	
		    	String id=sheet.getCell(0,i).getContents().trim();
		    	Pinfan pf=this.commonDao.get(Pinfan.class, new Long(id));
		    	if(pf!=null){
		    		pf.setDisabled(Boolean.TRUE);
		    		this.commonDao.store(pf);
		    	}else{
		    		throw new BusinessException((i+1)+"行不存在");
		    	}
		    }
		} catch (BiffException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	public void  importCbYb(File file){
		try {
			Workbook workbook = Workbook.getWorkbook(file);
		    Sheet sheet = workbook.getSheet(0);//得到excel第一页的内容
		    for (int i = 1; i <sheet.getRows(); i++) {
		    	//序号 品番 常备，预备
		    	String id=sheet.getCell(0,i).getContents().trim();
		    	Pinfan pf=this.commonDao.get(Pinfan.class, new Long(id));
		    	String cb=sheet.getCell(2,i).getContents().equals("")?"0":sheet.getCell(2,i).getContents();
		    	String yb=sheet.getCell(3,i).getContents().trim();
		    	if(pf!=null){
		    		pf.setCbQty(Integer.parseInt(cb));
		    		if(yb.equals("是")){
		    			pf.setBeYb(Boolean.TRUE);
		    		}else{
		    			pf.setBeYb(Boolean.FALSE);
		    		}
		    		this.commonDao.store(pf);
		    	}else{
		    		throw new BusinessException((i+1)+"行不存在");
		    	}
		    }
		} catch (BiffException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	public void storeBomList(BomList bl) {
		commonDao.store(bl);
	}
	
	public void  importBomList(File file){
		try {
			Workbook workbook = Workbook.getWorkbook(file);
		    Sheet sheet = workbook.getSheet(0);//得到excel第一页的内容
		    for (int i = 1; i <sheet.getRows(); i++) {
		    	System.out.println(i);
		    	//No	品番	品名	A/C	加工内容	保税	仓库	库位	收容数	荷姿	库存计量单位	备注 	
		    	String modelType=sheet.getCell(0,i).getContents().trim();
		    	String procedure1=sheet.getCell(1,i).getContents().trim();
	        	String procedure2=sheet.getCell(2,i).getContents().trim();
	        	String procedure3=sheet.getCell(3,i).getContents().trim();
	        	String procedure4=sheet.getCell(4,i).getContents().trim();
	        	String procedure5=sheet.getCell(5,i).getContents().trim();
	        	String procedure6=sheet.getCell(6,i).getContents().trim();
//	        	String description=sheet.getCell(7,i).getContents().trim();
	        	
	        	List<BomList> bls=this.commonDao.findByQuery("from BomList  p where p.modelType=:name ",
	        			new String[]{"name"},new Object[]{modelType});
	        	BomList p=null;
	        	if(bls.size()>0) {
	        		p=bls.get(0);
	        	}else {
	        		p=EntityFactory.getEntity(BomList.class);
	        	}
	        		p.setModelType(modelType);
	        		p.setProcedure1(procedure1);
	        		p.setProcedure2(procedure2);
	        		p.setProcedure3(procedure3);
	        		p.setProcedure4(procedure4);
	        		p.setProcedure5(procedure5);
	        		p.setProcedure6(procedure6);
			    	p.setDescription("");
			    	commonDao.store(p);
			    		
        			System.out.println(i);
	        	
		    }
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public void importBigItem(File file) {
		try {
			Workbook workbook = Workbook.getWorkbook(file);
			Sheet sheet = workbook.getSheet(0);
			 for (int i = 1; i <sheet.getRows(); i++) {
				 System.out.println(i);
				 //代码 名称 机种 国别 出库类型
				 String code=sheet.getCell(0,i).getContents();
				 String name=sheet.getCell(1,i).getContents();
				 String modelType=sheet.getCell(2,i).getContents();
				 String countries=sheet.getCell(3,i).getContents();
				 String str1=sheet.getCell(4,i).getContents();
				 if(code==null||code.equals("")){
					 break;
				 }
				 List<BigItem> its=this.commonDao.findByQuery("from BigItem  t where t.code='"+code+"'");
				 BigItem it=null;
				 if(its.size()>0){
					 it=its.get(0);
//					continue;
				}else{
					it=EntityFactory.getEntity(BigItem.class);
//					area.setWarehouse(WarehouseHolder.getWarehouse());
					it.setCode(code);
				}
				 it.setName(name);
				 it.setModelType(modelType);
				 it.setCountries(countries);
				 it.setStr1(str1);
				 it.setWarehouse(WarehouseHolder.getWarehouse());
				 commonDao.store(it);
			 }
		} catch (BiffException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	public void storeBomAccount(BomAccount bl,String zzkw,String hckw) {
		String operType="修改";
		if(bl.isNew()) {
			bl.setWarehouse(WarehouseHolder.getWarehouse());
			operType="添加";
		}
		bl.setCode(bl.getBigItem().getCode());
		bl.setName(bl.getBigItem().getName());
		List<Location> ls=this.commonDao.findByQuery("from Location l where l.code='"+zzkw+"' ");
		Location l=null;
		if(ls.size()<=0){
			l=EntityFactory.getEntity(Location.class);
			l.setCode(zzkw);
			l.setType(LocationType.PROCESS);
			l.setWarehouse(WarehouseHolder.getWarehouse());
			l.setZone(bl.getZone());
			this.commonDao.store(l);
		}else{
			l=ls.get(0);
			l.setType(LocationType.PROCESS);
			this.commonDao.store(l);
		}
		List<Location> l2s=this.commonDao.findByQuery("from Location l where l.code='"+hckw+"' ");
		Location l2=null;
		if(l2s.size()<=0){
			l2=EntityFactory.getEntity(Location.class);
			l2.setCode(hckw);
			l2.setType(LocationType.HCKW);
			l2.setWarehouse(WarehouseHolder.getWarehouse());
			l2.setZone(bl.getZone());
			this.commonDao.store(l2);
		}else{
			l2=l2s.get(0);
			l2.setType(LocationType.HCKW);
			this.commonDao.store(l2);
		}
		
		bl.setStrExtend5(DateUtil.formatDateYMDToStr(new Date()));
		bl.setZzkw(l);
		bl.setHckw(l2);
		if(l!=null){
			l.setHckw(l2);
			l.setHckwCode(hckw);
			this.commonDao.store(l);
		}
		bl.setCreateDate(new Date());
		bl.setCreatePeople(UserHolder.getUser().getName());
		commonDao.store(bl);
		BomAccountLog bal=bl.addBomAccountLog(bl, operType, UserHolder.getUser().getName());
		this.commonDao.store(bal);
		//更改对应库存
//		List<Inventory> invs =this.commonDao.findByQuery("from Inventory inv where inv.zone.id="+bl.getZone().getId()+" "
//				+ " and inv.itemKey.item.id="+bl.getItem().getId()+" and inv.itemKey.pinfan.bonded='"+bl.getBonded()+"' and inv.zzkw.id!="+l.getId());
//		for(Inventory inv:invs){
//			inv.setZzkw(l);
//			this.commonDao.store(inv);
//		}
	}
	
	public void  importBomAccount(File file){
		try {
			Workbook workbook = Workbook.getWorkbook(file);
		    Sheet sheet = workbook.getSheet(0);//得到excel第一页的内容
		    for (int i = 1; i <sheet.getRows(); i++) {
//		    	System.out.println(i);
		    	//完成品品番	完成品型式名	工位	部品品番	品名	A/C	加工内容	税别	单用	制造库位	暂存库位	入库库区	出库库区	出库类型	部品种类	描述
		    	int j=0;
		    	String code=sheet.getCell(j++,i).getContents().trim();//完成品品番
		    	String name=sheet.getCell(j++,i).getContents().trim();//完成品型式名
		    	String gw=sheet.getCell(j++,i).getContents().trim();//工位
	        	String itemCode=sheet.getCell(j++,i).getContents().trim();//部品品番
	        	String itemName=sheet.getCell(j++,i).getContents().trim();//品名
	        	String specs=sheet.getCell(j++,i).getContents().trim();//A/C
	        	String content=sheet.getCell(j++,i).getContents().trim();//加工内容
	        	String bonded=sheet.getCell(j++,i).getContents().trim();//税别
	        	String single=sheet.getCell(j++,i).getContents().trim();//单用
	        	String zzkwCode=sheet.getCell(j++,i).getContents().trim();//制造库位
	        	String zckwCode=sheet.getCell(j++,i).getContents().trim();//暂存库位
	        	String zone=sheet.getCell(j++,i).getContents().trim();//接收方仓库
	        	String w=sheet.getCell(j++,i).getContents().trim();//出货方仓库
	        	String outType=sheet.getCell(j++,i).getContents().trim();//出库类型
	        	String strExtend3=sheet.getCell(j++,i).getContents().trim();//部品种类
	        	String des=sheet.getCell(j++,i).getContents().trim();//描述
	        	if(name==null||name.equals("")) {
	        		break;
	        	}
	        	if(code==null||code.equals("")) {
	        		throw new BusinessException("完成品品番没有不能为空");
	        	}
	        	BomAccount ba=null;
	        	String hql="from BomAccount  p where p.bigItem.code='"+code.trim()+"' and p.item.code='"+itemCode.trim()+"' and p.strExtend1='"+gw+"'"
	        			+ " and  p.bonded='"+bonded+"' and p.outType='"+outType+"' and p.specs='"+specs+"'"
	        					+ " and p.zzkw.code='"+zzkwCode+"'" ;
//	        	if(content==null||content.equals("")){
//	        		hql+=" and (p.content is null or p.content='')";
//	        	}
	        	List<BomAccount> bomAccounts=this.commonDao.findByQuery(hql);
	        	System.out.println(i);
	        	String operType="导入修改";
	        	if(bomAccounts.size()>0) {
	        		ba=bomAccounts.get(0);
//	        		continue;
	        		System.out.println(ba.getId()+"  UPDATE");
	        	}else {
	        		System.out.println("ADD"+i);
	        		operType="导入增加";
	        		ba=EntityFactory.getEntity(BomAccount.class);
	        	}
	        	WarehouseArea zone1=null;
	        	List<WarehouseArea> was=this.commonDao.findByQuery("from WarehouseArea  p where (p.code=:name or p.name=:name) ",
	        			new String[]{"name"},new Object[]{zone});
	        	if(was.size()>0) {
	        		zone1=was.get(0);
	        	}else {
	        		throw new BusinessException(zone+":没有仓库信息");
	        	}
	        	Location hckwLoc=null;
	        	if(zckwCode==null||zckwCode.equals("")) {
	        		throw new BusinessException("暂存区不能为空");
	        	}else{
	        		 List<Location> ls=this.commonDao.findByQuery("from Location l where l.code='"+zckwCode+"' and l.type!='SHIP' ");
	 				if(ls.size()<=0){
	 					hckwLoc=EntityFactory.getEntity(Location.class);
	 					hckwLoc.setCode(zckwCode);
	 					hckwLoc.setType(LocationType.HCKW);
	 					hckwLoc.setWarehouse(WarehouseHolder.getWarehouse());
	 					hckwLoc.setZone(zone1);
	 					this.commonDao.store(hckwLoc);
	 				}else{
	 					hckwLoc=ls.get(0);
	 					hckwLoc.setZone(zone1);
	 					hckwLoc.setType(LocationType.HCKW);
	 					this.commonDao.store(hckwLoc);
	 				}
	        	}
	        	Location zzkw=null;
	        	if(zzkwCode==null||zzkwCode.equals("")) {
	        		throw new BusinessException("制造库位不能为空");
	        	}else{
	        		 List<Location> ls=this.commonDao.findByQuery("from Location l where l.code='"+zzkwCode+"' and l.type!='SHIP' ");
	 				if(ls.size()<=0){
	 					zzkw=EntityFactory.getEntity(Location.class);
	 					zzkw.setCode(zzkwCode);
	 					zzkw.setType(LocationType.PROCESS);
	 					zzkw.setWarehouse(WarehouseHolder.getWarehouse());
	 					zzkw.setZone(zone1);
	 					this.commonDao.store(zzkw);
	 				}else{
	 					zzkw=ls.get(0);
	 					zzkw.setZone(zone1);
	 					zzkw.setType(LocationType.PROCESS);
	 					zzkw.setHckwCode(zckwCode);
	 					zzkw.setHckw(hckwLoc);
	 					this.commonDao.store(zzkw);
	 				}
	        	}
	        	ba.setCode(code);
	        	ba.setName(name);
	        	ba.setItemName(itemName);
	        	ba.setContent(content);
	        	BigItem bigItem=null;
	        	List<BigItem> bigItems=this.commonDao.findByQuery("from BigItem  p where p.code=:code ",
	        			new String[]{"code"},new Object[]{code.trim()});
	        	if(bigItems.size()>0) {
	        		bigItem=bigItems.get(0);
	        	}else {
//	        		System.out.println(code+":没有完成部品基础资料");
	        		throw new BusinessException(code+":没有完成品基础资料");
	        	}
	        	List<Item> items=this.commonDao.findByQuery("from Item  p where p.code=:code ",
	        			new String[]{"code"},new Object[]{itemCode.trim()});
	        	Item item=null;
	        	if(items.size()>0) {
	        		item=items.get(0);
	        	}else {
//	        		System.out.println(itemCode+":没有部品基础资料");
	        		throw new BusinessException(itemCode+":没有部品基础资料");
	        	}
	        	ba.setBigItem(bigItem);
	        	ba.setItem(item);
	        	ba.setSpecs(specs);
	        	ba.setBonded(bonded);
	        	ba.setOutType(outType);
	        	ba.setSingle(single);
	        	ba.setStrExtend2(zzkwCode);
	        	ba.setZzkw(zzkw);
	        	ba.setHckw(hckwLoc);
	        	ba.setStrExtend1(gw);
	        	ba.setDescription(des);
	        	WarehouseArea zone2=null;
	        	List<WarehouseArea> was2=this.commonDao.findByQuery("from WarehouseArea  p where (p.code=:name or p.name=:name) ",
	        			new String[]{"name"},new Object[]{w});
	        	if(was2.size()>0) {
	        		zone2=was2.get(0);
	        	}else {
	        		throw new BusinessException(w+":没有出库仓库信息");
	        	}
	        	ba.setZone(zone1);
	        	ba.setZone1(zone2);
	        	ba.setWarehouse(WarehouseHolder.getWarehouse());
			    ba.setStrExtend5(DateUtil.formatDateYMDToStr(new Date()));
			    ba.setStrExtend3(strExtend3);
			    ba.setCreateDate(new Date());
				ba.setCreatePeople(UserHolder.getUser().getName());
			    commonDao.store(ba);
			    BomAccountLog bal=ba.addBomAccountLog(ba, operType, UserHolder.getUser().getName());
				this.commonDao.store(bal);
		    }
		} catch (BiffException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void  importBomAccountLoc(File file){
		try {
			Workbook workbook = Workbook.getWorkbook(file);
		    Sheet sheet = workbook.getSheet(0);//得到excel第一页的内容
		    for (int i = 1; i <sheet.getRows(); i++) {
//		    	System.out.println(i);
		    	//序号，制造库位
		    	//税别	单用	工位	送货提前期	接收方仓库	出货方仓库	出库类型
		    	String id=sheet.getCell(0,i).getContents().trim();//序号
	        	String tlq=sheet.getCell(11,i).getContents().trim();//投料区,制造库位
	        	BomAccount ba=null;
	        	if(id==null||id.equals("")) {
	        		break;
	        	}else{
	        		ba=this.commonDao.get(BomAccount.class, new Long(id));
	        	}
	        	if(ba==null) {
	        		System.out.println(id);
	        		continue;
	        		//throw new BusinessException("完成品品番没有不能为空");
	        	}
	        	Location zzkw=null;
	        	if(tlq==null||tlq.equals("")) {
	        		throw new BusinessException("投料区不能为空");
	        	}else{
	        		 List<Location> ls=this.commonDao.findByQuery("from Location l where l.code='"+tlq+"' and l.type!='SHIP' ");
	 				if(ls.size()<=0){
	 					zzkw=EntityFactory.getEntity(Location.class);
	 					zzkw.setCode(tlq);
	 					zzkw.setType(LocationType.PROCESS);
	 					zzkw.setWarehouse(WarehouseHolder.getWarehouse());
	 					zzkw.setZone(ba.getZone());
	 					this.commonDao.store(zzkw);
	 				}else{
	 					zzkw=ls.get(0);
	 					zzkw.setZone(ba.getZone());
	 					this.commonDao.store(zzkw);
	 				}
	        	}
	        	ba.setStrExtend2(tlq);
	        	ba.setZzkw(zzkw);
//	        	//更改对应库存
// 				List<Inventory> invs =this.commonDao.findByQuery("from Inventory inv where inv.zone.id="+ba.getZone().getId()+" "
// 						+ " and inv.itemKey.item.id="+ba.getItem().getId()+" and inv.itemKey.pinfan.bonded='"+ba.getBonded()+"'");
// 				for(Inventory inv:invs){
// 					inv.setZzkw(zzkw);
// 					this.commonDao.store(inv);
// 				}
	        	ba.setCreateDate(new Date());
				ba.setCreatePeople(UserHolder.getUser().getName());
			    commonDao.store(ba);
			    BomAccountLog bal=ba.addBomAccountLog(ba, "更新制造库位", UserHolder.getUser().getName());
				this.commonDao.store(bal);
		    }
		} catch (BiffException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void storeProductionPlan(ProductionPlan p,Long id) {
		if(p.isNew()) {
			p.setPlanAssembly(commonDao.load(PlanAssembly.class, id));
		}
		p.setOfflineDate(new Date());
		commonDao.store(p);
	}
	
	public void storeModelPlan(ModelPlan m,Long id) {
		if(m.isNew()) {
			m.setPlanAssembly(commonDao.load(PlanAssembly.class, id));
		}
		commonDao.store(m);
	}
	public void storeProduceMonthPlan(ProduceMonthPlan pm) {
		commonDao.store(pm);
	}

	@Override
	public void deleteItemRelation(List<Long> ids) {
		for(Long id:ids){
			ItemRelation t=this.commonDao.get(ItemRelation.class, id);
			this.commonDao.delete(t);
		}
		
	}

	@Override
	public void deleteBomAccount(List<Long> ids) {
		for(Long id:ids){
			BomAccount t=this.commonDao.get(BomAccount.class, id);
			BomAccountLog bal=t.addBomAccountLog(t, "删除BOM清单", UserHolder.getUser().getName());
		    this.commonDao.store(bal);
			this.commonDao.delete(t);
		}
	}
	@Override
	public void storeBigItem(BigItem bi) {
		bi.setWarehouse(WarehouseHolder.getWarehouse());
		this.commonDao.store(bi);
	}
	@Override
	public void deleteBigItem(List<Long> ids) {
		for(Long id:ids){
			BigItem t=this.commonDao.get(BigItem.class, id);
			this.commonDao.delete(t);
		}
	}

	@Override
	public void deleteBomList(List<Long> ids) {
		for(Long id:ids){
			BomList t=this.commonDao.get(BomList.class, id);
			this.commonDao.delete(t);
		}
	}

	@Override
	public void deletePinfan(List<Long> ids) {
		for(Long id:ids){
			Pinfan t=this.commonDao.get(Pinfan.class, id);
			this.commonDao.delete(t);
		}
		
	}
	public void importProduceMonthPlan(File file,String type) {
		try {
			Workbook workbook = Workbook.getWorkbook(file);
		    Sheet sheet = workbook.getSheet(0);//得到excel第一页的内容
		    PlanAssembly pa=EntityFactory.getEntity(PlanAssembly.class);
		    for (int i = 4; i <sheet.getRows(); i++) {
//		    	System.out.println(i);
		    	//机种	型式名	品番	面向国	年度合计	月度合计	前月欠产
		    	String mdaye=sheet.getCell(1,1).getContents().trim().replace(" ", "").substring(0,7);//月份
//		    	String code=sheet.getCell(0,i).getContents().trim();//机种
		    	String name=sheet.getCell(1,i).getContents().trim();//型式名
	        	String itemCode=sheet.getCell(2,i).getContents().trim();//品番
	        	String content=sheet.getCell(3,i).getContents().trim();//面向国
	        	String yearQuantity=sheet.getCell(4,i).getContents().trim();//年度合计
	        	String monthQuantity=sheet.getCell(5,i).getContents().trim();//月度合计
	        	String quantity=sheet.getCell(6,i).getContents().trim();//前月欠产
	        	String quantity1=sheet.getCell(7,i).getContents().trim();//1号
	        	String quantity2=sheet.getCell(8,i).getContents().trim();//2号
	        	String quantity3=sheet.getCell(9,i).getContents().trim();//3号
	        	String quantity4=sheet.getCell(10,i).getContents().trim();//4号
	        	String quantity5=sheet.getCell(11,i).getContents().trim();//5号
	        	String quantity6=sheet.getCell(12,i).getContents().trim();//6号
	        	String quantity7=sheet.getCell(13,i).getContents().trim();//7号
	        	String quantity8=sheet.getCell(14,i).getContents().trim();//8号
	        	String quantity9=sheet.getCell(15,i).getContents().trim();//9号
	        	String quantity10=sheet.getCell(16,i).getContents().trim();//10号
	        	String quantity11=sheet.getCell(17,i).getContents().trim();//11号
	        	String quantity12=sheet.getCell(18,i).getContents().trim();//12号
	        	String quantity13=sheet.getCell(19,i).getContents().trim();//13号
	        	String quantity14=sheet.getCell(20,i).getContents().trim();//14号
	        	String quantity15=sheet.getCell(21,i).getContents().trim();//15号
	        	String quantity16=sheet.getCell(22,i).getContents().trim();//16号
	        	String quantity17=sheet.getCell(23,i).getContents().trim();//17号
	        	String quantity18=sheet.getCell(24,i).getContents().trim();//18号
	        	String quantity19=sheet.getCell(25,i).getContents().trim();//19号
	        	String quantity20=sheet.getCell(26,i).getContents().trim();//20号
	        	String quantity21=sheet.getCell(27,i).getContents().trim();//21号
	        	String quantity22=sheet.getCell(28,i).getContents().trim();//22号
	        	String quantity23=sheet.getCell(29,i).getContents().trim();//23号
	        	String quantity24=sheet.getCell(30,i).getContents().trim();//24号
	        	String quantity25=sheet.getCell(31,i).getContents().trim();//25号
	        	String quantity26=sheet.getCell(32,i).getContents().trim();//26号
	        	String quantity27=sheet.getCell(33,i).getContents().trim();//27号
	        	String quantity28=sheet.getCell(34,i).getContents().trim();//28号
	        	String quantity29=sheet.getCell(35,i).getContents().trim();//29号
	        	String quantity30=sheet.getCell(36,i).getContents().trim();//30号
	        	String quantity31=sheet.getCell(37,i).getContents().trim();//31号
//	        	String outType=sheet.getCell(38,i).getContents().trim();
//	        	String description=sheet.getCell(7,i).getContents().trim();
	        	ProduceMonthPlan pm=EntityFactory.getEntity(ProduceMonthPlan.class);
	        	StringBuffer sb=new StringBuffer();
//	        	if(code==null&&code.equals("")) {
//	        		throw new BusinessException("完成品型式名没有不能为空");
//	        	}
	        	if(name==null && name.equals("")) {
	        		break;
	        	}
	        	pm.setCode(itemCode);
	        
	        	pm.setName(name);
	        	pm.setCountry(content);
//	        	pm.setOutType(outType);
	        	List<BigItem> items=this.commonDao.findByQuery("from BigItem  p where p.code=:name ",
	        			new String[]{"name"},new Object[]{itemCode.trim()});
	        	BigItem bi=null;
	        	if(items.size()>0) {
	        		bi=items.get(0);
	        	}else {
	        		sb.append(itemCode+",");
	        		continue;
	        		
//	        		throw new BusinessException(itemCode+":没有完成部品基础资料");
	        	}
	        	
	        	pm.setBigItem(bi);
	        	pm.setOutType(bi.getStr1());
//	        	List<BomList> bls=this.commonDao.findByQuery("from BomList  p where p.modelType=:name ",
//	        			new String[]{"name"},new Object[]{code});
//	        	BomList p=null;
//	        	if(bls.size()>0) {
//	        		p=bls.get(0);
//	        	}else {
//	        		continue;
////	        		throw new BusinessException(code+":没有信息");
//	        	}
//	        	pm.setProcedure(code);
//	        	pm.setBomList(p);
	        	pm.setProcedure(bi.getModelType());
	        	pm.setYearQuantity(StrToDouble(yearQuantity));
	        	pm.setMonthQuantity(StrToDouble(monthQuantity));
	        	pm.setQuantity(StrToDouble(quantity));
//	        	pm.setModifyDate(modifyDate1);
	        	pm.setQuantity1(StrToDouble(quantity1));
//	        	pm.setModifyDate1(modifyDate1);
	        	pm.setQuantity2(StrToDouble(quantity2));
	        	pm.setQuantity3(StrToDouble(quantity3));
	        	pm.setQuantity4(StrToDouble(quantity4));
	        	pm.setQuantity5(StrToDouble(quantity5));
	        	pm.setQuantity6(StrToDouble(quantity6));
	        	pm.setQuantity7(StrToDouble(quantity7));
	        	pm.setQuantity8(StrToDouble(quantity8));
	        	pm.setQuantity9(StrToDouble(quantity9));
	        	pm.setQuantity10(StrToDouble(quantity10));
	        	pm.setQuantity11(StrToDouble(quantity11));
	        	pm.setQuantity12(StrToDouble(quantity12));
	        	pm.setQuantity13(StrToDouble(quantity13));
	        	pm.setQuantity14(StrToDouble(quantity14));
	        	pm.setQuantity15(StrToDouble(quantity15));
	        	pm.setQuantity16(StrToDouble(quantity16));
	        	pm.setQuantity17(StrToDouble(quantity17));
	        	pm.setQuantity18(StrToDouble(quantity18));
	        	pm.setQuantity19(StrToDouble(quantity19));
	        	pm.setQuantity20(StrToDouble(quantity20));
	        	pm.setQuantity21(StrToDouble(quantity21));
	        	pm.setQuantity22(StrToDouble(quantity22));
	        	pm.setQuantity23(StrToDouble(quantity23));
	        	pm.setQuantity24(StrToDouble(quantity24));
	        	pm.setQuantity25(StrToDouble(quantity25));
	        	pm.setQuantity26(StrToDouble(quantity26));
	        	pm.setQuantity27(StrToDouble(quantity27));
	        	pm.setQuantity28(StrToDouble(quantity28));
	        	pm.setQuantity29(StrToDouble(quantity29));
	        	pm.setQuantity30(StrToDouble(quantity30));
	        	pm.setQuantity31(StrToDouble(quantity31));
	        	int j=1;
	        	pm.setModifyDate1(date(mdaye,j++));
	        	pm.setModifyDate2(date(mdaye,j++));
	        	pm.setModifyDate3(date(mdaye,j++));
	        	pm.setModifyDate4(date(mdaye,j++));
	        	pm.setModifyDate5(date(mdaye,j++));
	        	pm.setModifyDate6(date(mdaye,j++));
	        	pm.setModifyDate7(date(mdaye,j++));
	        	pm.setModifyDate8(date(mdaye,j++));
	        	pm.setModifyDate9(date(mdaye,j++));
	        	pm.setModifyDate10(date(mdaye,j++));
	        	pm.setModifyDate11(date(mdaye,j++));
	        	pm.setModifyDate12(date(mdaye,j++));
	        	pm.setModifyDate13(date(mdaye,j++));
	        	pm.setModifyDate14(date(mdaye,j++));
	        	pm.setModifyDate15(date(mdaye,j++));
	        	pm.setModifyDate16(date(mdaye,j++));
	        	pm.setModifyDate17(date(mdaye,j++));
	        	pm.setModifyDate18(date(mdaye,j++));
	        	pm.setModifyDate19(date(mdaye,j++));
	        	pm.setModifyDate20(date(mdaye,j++));
	        	pm.setModifyDate21(date(mdaye,j++));
	        	pm.setModifyDate22(date(mdaye,j++));
	        	pm.setModifyDate23(date(mdaye,j++));
	        	pm.setModifyDate24(date(mdaye,j++));
	        	pm.setModifyDate25(date(mdaye,j++));
	        	pm.setModifyDate26(date(mdaye,j++));
	        	pm.setModifyDate27(date(mdaye,j++));
	        	pm.setModifyDate28(date(mdaye,j++));
	        	pm.setModifyDate29(date(mdaye,j++));
	        	pm.setModifyDate30(date(mdaye,j++));
	        	pm.setModifyDate31(date(mdaye,j++));
	        	if(sb!=null){
	        		pm.setDescription(sb.toString()+"无完成品信息");
	        	}
	        	if(i<=4) {
	        		pa.setMonthDate(mdaye);
	    			pa.setStrExtend1("月生产计划");
	    			pa.setStrExtend3(DateUtil.formatDateYMDToStr(new Date()) );
	    			commonDao.store(pa);
		    	}
	        	pm.setPlanAssembly(pa);
			    commonDao.store(pm);
        		System.out.println(i);
		    }
		}catch (Exception e) {
			
			e.printStackTrace();
		}
	}
	public static Date date(String date_str,int i) {
		if (i<10) {
			date_str=date_str+"-0"+i;
		}else {
			date_str=date_str+"-"+i;
		}
        try {
            Calendar zcal = Calendar.getInstance();
            Timestamp timestampnow = new Timestamp(zcal.getTimeInMillis());
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            ParsePosition pos = new ParsePosition(0);
            java.util.Date current = formatter.parse(date_str, pos);
            timestampnow = new Timestamp(current.getTime());
            return timestampnow;
        }
        catch (NullPointerException e) {
            return null;
        }
    }
	public double StrToDouble(String str) {
		Double d=0D;
		try {
			d=Double.parseDouble(str);
			
		}catch (Exception e) {
			// TODO: handle exception
		}
		
		return d;
	}
	
	public void storePlanAssembly(PlanAssembly p) {
		commonDao.store(p);
	}
	
	public void storeAutoProduction(AutoProduction p) {
//		if(p.isNew()){
////			p.setCode(codeManager.getCodeYm("JH", 3));
//			
//			p.setCreateBy(UserHolder.getUser().getName());
//			p.setCreateDate(new Date());
////			p.setStatus("未审核");
//		}
		p.setPlanDate(new Date());
		p.setCreateBy(UserHolder.getUser().getName());
		p.setCreateDate(new Date());
//		else if(p.getStatus().equals("已审核")){
//			throw new BusinessException("状态不对");
//		}
		p.setProcedure(p.getZone1().getGw());
		commonDao.store(p);
	}
	public void deleteAutoProduction(List<Long> ids) {
		for(Long id:ids) {
			AutoProduction p=commonDao.load(AutoProduction.class, id);
			if(p.getCheckBy()!=null) {
				throw new BusinessException("已生成自动计划不能删除");
			}else {
				commonDao.delete(p);
			}
		}
	}
	public void importProductionPlan(File file,String type) {
		try {
			Workbook workbook = Workbook.getWorkbook(file);
		    Sheet sheet = workbook.getSheet(0);//得到excel第一页的内容
		    Long xh=0L;//序号
		    boolean t=true;//是否删除后新增
		    String str="";//调整标识
		   Map<String, Long> map=new HashMap<String, Long>();
		   
//		    PlanAssembly pa=EntityFactory.getEntity(PlanAssembly.class);
		    for (int i = 1; i <sheet.getRows(); i++) {
		    	//No	工位	下线日期	IDNO	月度序号	机型	机型名称	国别	机号
		    	String numberNo=sheet.getCell(0,i).getContents().trim();//No
		    	String procedure=sheet.getCell(1,i).getContents().trim();//工位
		    	
		    	String OfflineDate=sheet.getCell(2,i).getContents().trim();//下线日期
	        	String code=sheet.getCell(3,i).getContents().trim();//IDNO
	        	String name=sheet.getCell(4,i).getContents().trim();//月度序号
	        	String modelType=sheet.getCell(5,i).getContents().trim();//机型
	        	String modelName=sheet.getCell(6,i).getContents().trim();//机型名称
	        	String country=sheet.getCell(7,i).getContents().trim();//国别
	        	String modelNo=sheet.getCell(8,i).getContents().trim();//机号
//	        	String description=sheet.getCell(7,i).getContents().trim();
	        	if(procedure==null||procedure.equals("")){
	        		break;
	        	}
	        	 String mes="";
	        	 if(map.containsKey(procedure)) {
	        		 map.put(procedure,map.get(procedure) +1);
	        	 }else {
	        		 map.put(procedure,1L);
	        	 }
	        	 
	        	if(i<=1) {
	        		List<ProductionPlan> lis11=commonDao.findByQuery(" from ProductionPlan p  where p.strExtend4='"+procedure+"' and p.code='"+code+"'");
		        	if(lis11.size()>0) {
		        		ProductionPlan pds=	lis11.get(0);
		        		xh=pds.getLongExtend1();
		        		map.put(procedure,xh);
		        		System.out.println("第几个="+xh);
//		        		continue;
		        	}else {
		        		List<ProductionPlan> lis114=commonDao.findByQuery(" from ProductionPlan p  where p.strExtend4='"+procedure+"'  order by p.longExtend1 desc ");
		        		if(lis114.size()>0) {
		        			ProductionPlan pds=	lis114.get(0);
			        		xh=pds.getLongExtend1();
			        		map.put(procedure,xh+1);
			        		System.out.println("第几个="+xh);
		        		}
		        	}
	        	}
	        	if(xh>0) {
//	        		xh=xh+1;
	        		List<ProductionPlan> lis11=commonDao.findByQuery(" from ProductionPlan p  where  p.longExtend1="+map.get(procedure)+" and p.strExtend4='"+procedure+"'");
		        	if(lis11.size()>0) {
		        		ProductionPlan pds=	lis11.get(0);
		        		pds.setOfflineDate(new Date());
		        		commonDao.store(pds);
		        		xh=pds.getLongExtend1();
		        		if(pds.getCode().equals(code)) {
		        			System.out.println("第几个="+xh);
		        			continue;
		        		}else {
		        			if(pds.getStrExtend1()!=null&&pds.getStrExtend1().equals("已耗用")) {
		        				pds.setDescription("已耗用不能修改");
		        				commonDao.store(pds);
		        				mes=mes+pds.getModelNo()+"已耗用的不能修改";
		        				
		        				if(mes!=null&&!mes.equals("")) {
		        		        	InterfaceLog log=new InterfaceLog();
		        			    	log.setDealTime(new Date());
		        			    	log.setFileName(sheet.getName());
		        			    	log.setFileType("导入");
		        			    	log.setType("生产顺序计划");
		        			    	log.setToSYS(UserHolder.getUser().getName());
		        			    	log.setStatus("失败");
		        			    	log.setErrorLog(mes);
		        			    	log.setRequestContent("");
		        			    	log.setStr1(procedure);
		        			    	log.setStr2(modelType);
		        			    	log.setStr3(modelName);
		        			    	log.setStr4(modelNo);
		        			    	commonDao.store(log);
		        		        	 }
		        				throw new BusinessException("已耗用的不能修改");
//		        				continue;
		        			}
		        			
				        		List<ProductionPlan>	lis13=commonDao.findByQuery(" from ProductionPlan p  where   p.longExtend1>="+map.get(procedure)+" and p.strExtend4='"+procedure+"' "+" order by p.longExtend1");
				        		List<ProductionPlan>	lis15=commonDao.findByQuery(" from ProductionPlan p  where  p.longExtend1>="+map.get(procedure)+" and p.strExtend4='"+procedure+"' "+" and p.strExtend1='已耗用' order by p.longExtend1");
				        		System.out.println("第几个="+lis13.size()+" 耗用="+lis15.size());
				        		if(lis15.size()>0) {
				        			for(ProductionPlan p:lis15) {
				        				mes=p.getProcedure()+"工位，"+p.getModelNo()+"的数据，存在已耗用的不能修改";
				        				if(mes!=null&&!mes.equals("")) {
				        		        	InterfaceLog log=new InterfaceLog();
				        			    	log.setDealTime(new Date());
				        			    	log.setFileName(sheet.getName());
				        			    	log.setFileType("导入");
				        			    	log.setType("生产顺序计划");
				        			    	log.setToSYS(UserHolder.getUser().getName());
				        			    	log.setStatus("失败");
				        			    	log.setErrorLog(mes);
				        			    	log.setRequestContent("");
				        			    	log.setStr1(procedure);
				        			    	log.setStr2(modelType);
				        			    	log.setStr3(modelName);
				        			    	log.setStr4(modelNo);
				        			    	commonDao.store(log);
				        		        	 }
				        			}
			        				throw new BusinessException("已耗用的不能修改");
				        		}
				        		for(ProductionPlan sd:lis13) {
				        			commonDao.delete(sd);
				        			t=false;
				        		}
				        		
		        		}
		        		
		        	}else {
		        		if(t) {
		        		List<ProductionPlan>	lis13=commonDao.findByQuery(" from ProductionPlan p  where  p.longExtend1>="+map.get(procedure)+" and p.strExtend4='"+procedure+"' "+" order by p.longExtend1");
			        		for(ProductionPlan sd:lis13) {
			        			str="重新导入数据";
			        			commonDao.delete(sd);
			        			t=false;
			        		}
		        		
		        		}
		        	}
	        	}
	        	String hql=" from ItemList p where p.bigItem.code='"+modelType.trim()+"' and  p.outType='CKD单点' and p.modelType!='LDB' ";
	        	if(type!=null&&type.equals("LDB")){
	        		hql=" from ItemList p where  p.bigItem.code='"+modelType.trim()+"' and  p.outType='CKD单点' and p.modelType='LDB' ";
	        	}
	        	List<ItemList> list23=commonDao.findByQuery(hql);
	        	if(list23.size()>0) {
//	        		List<ProductionPlan> lis12=commonDao.findByQuery(" from ProductionPlan p where "+"  p.strExtend4='"+procedure+"' "+" order by p.longExtend1 desc LIMIT 1 ");
//    	        	if(lis12.size()>0) {
//    	        		ProductionPlan p1=lis12.get(0);
//    	        		xh=p1.getLongExtend1();
//    	        	}
//    	        	xh=xh+1;
	        		for(ItemList iteml:list23) {
	    	        	
	    	        	ProductionPlan pm=EntityFactory.getEntity(ProductionPlan.class);
	    	        	pm.setLongExtend1(map.get(procedure));
	    	        	pm.setNumberNo(numberNo);
	    	        	pm.setCode(code);
	    	        	pm.setName(name);
	    	        	pm.setCountry(country);
	    	        	pm.setProcedure(iteml.getModelType());
	    	        	pm.setStrExtend4(procedure);
	    	        	pm.setZone1(iteml.getInZone());
	    	        	pm.setZone2(iteml.getOutZone());
	    	        	pm.setOutType(iteml.getOutType());
	    	        	pm.setStrExtend1("未消耗");
	    	        	pm.setOfflineDate(new Date());
	    	        	pm.setStrExtend3(OfflineDate);
	    	        	List<BigItem> items=this.commonDao.findByQuery("from BigItem  p where p.code=:name ",
	    	        			new String[]{"name"},new Object[]{modelType.trim()});
	    	        	BigItem item=null;
	    	        	if(items.size()>0) {
	    	        		item=items.get(0);
	    	        	}else {
	    	        		System.out.println(modelType);
//	    	        		mes=mes+modelType+"没有完成部品基础资料";
	    	        		throw new BusinessException(modelType+":没有完成部品基础资料");
	    	        	}
	    	        	
	    	        	pm.setBigItem(item);
	    	        	pm.setModelNo(modelNo);
	    	        	pm.setModelName(modelName);
	    	        	pm.setModelType(modelType);
//	    	        	pm.setStrExtend3("拖拉机计划");

	    	        	if(!t) {
	    	        	pm.setDescription(str);
	    	        	}
//	    	        	pm.setPlanAssembly(pa);
	    			    commonDao.store(pm);
	    			    System.out.println("新增"+i);
	        		}
	        		
	        	}else {
//	        		mes=mes+modelType+"工位提前期清单无对应数据"+(i+1)+"行"+modelType.trim();
	        		throw new BusinessException(modelType+"工位提前期清单无对应数据");
	        	}
	        	if(mes!=null&&!mes.equals("")) {
		        	InterfaceLog log=new InterfaceLog();
			    	log.setDealTime(new Date());
			    	log.setFileName(sheet.getName());
			    	log.setFileType("导入");
			    	log.setType("生产顺序计划");
			    	log.setToSYS(UserHolder.getUser().getName());
			    	log.setStatus("失败");
			    	log.setErrorLog(mes);
			    	log.setRequestContent("");
			    	log.setStr1(procedure);
			    	log.setStr2(modelType);
			    	log.setStr3(modelName);
			    	log.setStr4(modelNo);
			    	commonDao.store(log);
	        	 }
	        	
	        	
		    }
		    
		    	
		    
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void importModelPlan(File file,String type) {
		try {
			Workbook workbook = Workbook.getWorkbook(file);
		    Sheet sheet = workbook.getSheet(0);//得到excel第一页的内容
		    PlanAssembly pa=EntityFactory.getEntity(PlanAssembly.class);
		    for (int i = 9; i <sheet.getRows(); i++) {
		    	//NO.	ID_NO	月度连番	计划完成日	型式品番	型式品名	国别	机号	调整计划	备注
		    	String numberNo=sheet.getCell(0,i).getContents().trim();//No
		    	String code=sheet.getCell(1,i).getContents().trim();//ID_NO
		    	String name=sheet.getCell(2,i).getContents().trim();//月度连番
	        	String planDate=sheet.getCell(3,i).getContents().trim();//计划完成日
	        	String modelType=sheet.getCell(4,i).getContents().trim();//型式品番
	        	String modelName=sheet.getCell(5,i).getContents().trim();//型式品名
	        	String country=sheet.getCell(6,i).getContents().trim();//国别	
	        	String modelNo=sheet.getCell(7,i).getContents().trim();//机号
	        	String modifyDate=sheet.getCell(8,i).getContents().trim();//调整计划
	        	String description=sheet.getCell(7,i).getContents().trim();//备注
	        	if(i<=9) {
	    			pa.setMonthDate(modifyDate);
	    			pa.setStrExtend1("履带机计划");
	    			commonDao.store(pa);
		    	}
	        	
	        	ModelPlan pm=EntityFactory.getEntity(ModelPlan.class);
	        	
	        	if(numberNo==null&&numberNo.equals("")) {
	        		throw new BusinessException("No没有不能为空");
	        	}
	        	List<ModelPlan> pms=this.commonDao.findByQuery("from ModelPlan  p where p.numberNo=:name and p.planAssembly.id=:pid",
	        			new String[]{"name","pid"},new Object[]{numberNo.trim(),pa.getId()});
	        	if(pms.size()>0) {
	        		pm=pms.get(0);
	        	}
	        	pm.setNumberNo(numberNo);
	        	pm.setCode(code);
	        	pm.setName(name);
	        	pm.setCountry(country);
	        	pm.setPlanDate(DateUtil.formatStrToDateYMD(planDate));
	        	pm.setModifyDate(DateUtil.formatStrToDateYMD(planDate));
	        	List<BigItem> items=this.commonDao.findByQuery("from BigItem  p where p.code=:name ",
	        			new String[]{"name"},new Object[]{modelType.trim()});
	        	BigItem item=null;
	        	if(items.size()>0) {
	        		item=items.get(0);
	        	}else {
	        		throw new BusinessException(modelType+":没有完成部品基础资料");
	        	}
	        	
	        	pm.setBigItem(item);
	        	pm.setModelNo(modelNo);
	        	pm.setModelName(modelName);
	        	pm.setModelType(modelType);
	        	
	        	pm.setDescription(description);
	        	
	        	pm.setPlanAssembly(pa);
			    commonDao.store(pm);
			    		
        			System.out.println(i);
	        	
		    }
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	public void storeItemList(ItemList itemList) {
		itemList.setCode(itemList.getBigItem().getCode());
		itemList.setName(itemList.getBigItem().getName());
		itemList.setWarehouse(WarehouseHolder.getWarehouse());
		commonDao.store(itemList);
	}
	
	public void deleteItemList(List<Long> ids) {
		for(Long id:ids) {
			ItemList l=commonDao.load(ItemList.class, id);
			commonDao.delete(l);
		}
	}
	public void importItemListn(File file,String type) {
		try {
			Workbook workbook = Workbook.getWorkbook(file);
		    Sheet sheet = workbook.getSheet(0);//得到excel第一页的内容
		    PlanAssembly pa=EntityFactory.getEntity(PlanAssembly.class);
		    for (int i = 1; i <sheet.getRows(); i++) {
		    	//完成品品番	完成品型式名	工位	出库类型	出货提前期	接收方仓库	出货方仓库	计数项:部品品番
		    	String code=sheet.getCell(0,i).getContents().trim();//完成品品番
		    	String name=sheet.getCell(1,i).getContents().trim();//完成品型式名
		    	String modelType=sheet.getCell(2,i).getContents().trim();//工位
	        	String outType=sheet.getCell(3,i).getContents().trim();//出库类型
//	        	String prophase=sheet.getCell(4,i).getContents().trim();//出货提前期
	        	String ck1=sheet.getCell(4,i).getContents().trim();//接收方仓库名
	        	String ck2=sheet.getCell(5,i).getContents().trim();//出货方仓库	
//	        	String modelNo=sheet.getCell(7,i).getContents().trim();//计数项:部品品番
	        	
	        	ItemList pm=EntityFactory.getEntity(ItemList.class);
	        	
	        	if(code==null||code.equals("")) {
	        		throw new BusinessException("完成品品番，没有不能为空");
	        	}
	        	
	        	pm.setCode(code);
	        	pm.setName(name);
	        	List<BigItem> items=this.commonDao.findByQuery("from BigItem  p where p.code=:name ",
	        			new String[]{"name"},new Object[]{code.trim()});
	        	BigItem item=null;
	        	if(items.size()>0) {
	        		item=items.get(0);
	        	}else {
	        		//System.out.println(code+":没有完成部品基础资料"+i);
	        		//continue;
	        		throw new BusinessException(code+":没有完成部品基础资料");
	        	}
	        	List<WarehouseArea> inZones=this.commonDao.findByQuery("from WarehouseArea  p where (p.code=:name or p.name=:name) ",
	        			new String[]{"name"},new Object[]{ck1.trim()});
	        	WarehouseArea inZone=null;
	        	if(inZones.size()>0) {
	        		inZone=inZones.get(0);
	        	}else {
	        		throw new BusinessException(ck1+":没有基础资料");
	        	}
	        	
	        	List<WarehouseArea> outZones=this.commonDao.findByQuery("from WarehouseArea  p where (p.code=:name or p.name=:name) ",
	        			new String[]{"name"},new Object[]{ck2.trim()});
	        	WarehouseArea outZone=null;
	        	if(outZones.size()>0) {
	        		outZone=outZones.get(0);
	        	}else {
	        		//throw new BusinessException(ck2+":没有基础资料");
	        	}
	        	pm.setInZone(inZone);
	        	pm.setOutZone(outZone);
	        	pm.setWarehouse(WarehouseHolder.getWarehouse());
	        	pm.setBigItem(item);
	        	pm.setOutType(outType);
	        	pm.setModelType(modelType);
//	        	pm.setSingle(modelNo);
//	        	pm.setProphase(prophase);
			    commonDao.store(pm);
        		System.out.println(i);
		    }
		} catch (BiffException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch blocko
			e.printStackTrace();
		}
	}

	@Override
	public void importModelChagePage(File file, String type) {
		// TODO 自动生成的方法存根
		try {
			Workbook workbook = Workbook.getWorkbook(file);
		    Sheet sheet = workbook.getSheet(0);//得到excel第一页的内容
		    int k;
		    for (int i = 3; i <sheet.getRows(); i++) {
		    	k=0;
		    	String a1=sheet.getCell(k++,i).getContents().trim();
		    	String a2=sheet.getCell(k++,i).getContents().trim();
		    	String a3=sheet.getCell(k++,i).getContents().trim();
	        	String a4=sheet.getCell(k++,i).getContents().trim();
	        	String a5=sheet.getCell(k++,i).getContents().trim();
	        	String a6=sheet.getCell(k++,i).getContents().trim();
	        	String a7=sheet.getCell(k++,i).getContents().trim();
	        	String a8=sheet.getCell(k++,i).getContents().trim();
	        	String a9=sheet.getCell(k++,i).getContents().trim();
	        	String a10=sheet.getCell(k++,i).getContents().trim();
	        	String a11=sheet.getCell(k++,i).getContents().trim();
	        	String a12=sheet.getCell(k++,i).getContents().trim();
	        	String a13=sheet.getCell(k++,i).getContents().trim();
	        	String a14=sheet.getCell(k++,i).getContents().trim();
	        	String a15=sheet.getCell(k++,i).getContents().trim();
	        	String a16=sheet.getCell(k++,i).getContents().trim();
	        	String a17=sheet.getCell(k++,i).getContents().trim();
	        	String a18=sheet.getCell(k++,i).getContents().trim();
	        	String a19=sheet.getCell(k++,i).getContents().trim();
	        	String a20=sheet.getCell(k++,i).getContents().trim();
	        	List<ModelChange> modelChanges=this.commonDao.findByQuery(" from ModelChange mc where mc.no=:no ",
	        			new String[]{"no"},new Object[]{Integer.parseInt(a1)});
	        	ModelChange modelChange=EntityFactory.getEntity(ModelChange.class);
	        	if (modelChanges.size()>0) {
					modelChange=modelChanges.get(0);
				}
	        	modelChange.setNo(Integer.parseInt(a1));
	        	modelChange.setCode(a2);
	        	modelChange.setName(a3);
	        	modelChange.setBigItem(a4);
	        	modelChange.setBigItemNameO(a5);
	        	modelChange.setBom(a6);
	        	modelChange.setBigItemNameN(a7);
	        	modelChange.setSupplierCode(a8);
	        	modelChange.setSupplierName(a9);
	        	modelChange.setAc(a10);
	        	modelChange.setProductionName(a11);
	        	modelChange.setPinming(a12);
	        	modelChange.setDanyong(Integer.parseInt(a13));
	        	modelChange.setDinghuoBool(Integer.parseInt(a14));
	        	modelChange.setNasuo(a15);
	        	modelChange.setCanliang(Integer.parseInt(a16));
	        	modelChange.setTCode(a17);
	        	modelChange.setTName(a18);
	        	modelChange.setOldchuli(a19);
	        	modelChange.setBegintime(a20);
	        	commonDao.store(modelChange);
		    }
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public String getDzData(Date date) {
//		String URL ="htgetDzDatatp://47.102.204.117:8081/xxwms/"+"appService/asnReceiveServlet";
		String query_date=DateUtil.formatDateYYYYMMDDToStr(date);
		String URL="http://222.92.2.219:8008/api/SendPaintRecordListToWMS?strDate="+query_date;
		System.out.println("请求地址"+URL);
		JSONObject obj=new JSONObject();
		obj.put("QUERY_DATE", query_date);
		obj.put("QUERY_TYPE", "1");
		obj.put("methodType", "scanPlanAsn");
		obj.put("wId", "1060");
		obj.put("workerId", "1162");
		//storeInterfaceLog("吊装数据获取", "WMS", "JBT", QUERY_DATE, obj.toString(), null);
//	    System.out.println("吊装据获取:"+obj.toString());
		String buffer=sendJbtData(URL, obj.toString());
		System.out.println("久保田吊码转译响应报文:"+buffer);
        if (buffer.toString().length()>0) {
        	    buffer=StringEscapeUtils.unescapeJavaScript(buffer);
        	    System.out.println("久保田吊码响应报文:"+buffer);
        		JSONObject json = JSONObject.fromObject(buffer.toString());
        		JSONArray jsonArray = JSONArray.fromObject(json.getString("return data"));
        		//List<HoistingData> ss=this.commonDao.findByQuery("from HoistingData");
		    		//this.commonDao.deleteAll(ss);
 		    for(int i = 0;i<jsonArray.size();i++) {
 		    		JSONObject jsonObject = JSONObject.fromObject(jsonArray.get(i).toString());
 		    		String ID_NO=(String) jsonObject.get("ID_NO");//id_no
 		    		String PARTS_ID=(String) jsonObject.get("PARTS_ID");//组件号
 		    		String STATION_NO=(String) jsonObject.get("STATION_NO");//工位号
 		    		String SERIAL_NO=(String) jsonObject.get("SERIAL_NO");//机号
 		    		String MODEL_CODE=(String) jsonObject.get("MODEL_CODE");//机型编号
 		    		String CREATE_BY=(String) jsonObject.get("CREATE_BY");//创建者
 		    		String CREATE_DATE=(String) jsonObject.get("CREATE_DATE");//创建时间
 		    		if(ID_NO!=null&&!ID_NO.equals("")){
 		    			List<HoistingData> hs=this.commonDao.findByQuery("from HoistingData d where d.str1='"+ID_NO+"' "
 		    					+ " and d.str2='"+PARTS_ID+"'");
 		    			if(hs.size()<=0){
		 		    		HoistingData h=EntityFactory.getEntity(HoistingData.class);
		 		    		h.setStr1(ID_NO);
		 		    		h.setStr2(PARTS_ID);
		 		    		h.setCode(STATION_NO);
		 		    		h.setName(CREATE_BY);
		 		    		h.setAllocateTime(DateUtil.getDateFormat2(CREATE_DATE));
		 		    		h.setStr3(SERIAL_NO);
		 		    		h.setModelType(MODEL_CODE);
		 		    		h.setOrderQuantity(1);
		 		    		h.setUserDate(new Date());
		 		    		h.setStatus("未消耗");
		 		    		this.commonDao.store(h);
 		    			}
 		    		}
 		    }
	       //接口回传日志z
		  //storeInterfaceLog("吊装数据获取返回", "WMS", "JBT", QUERY_DATE, json.toString(), null);
		}
		return null;
	}
	@Override
	public String getXxData(Date date) {
//		String URL ="http://47.102.204.117:8081/xxwms/"+"appService/asnReceiveServlet";
		String query_date=DateUtil.formatDateYYYYMMDDToStr(date);
		String URL="http://222.92.2.219:8008/api/SendProdInfoListToWMS?strDate="+query_date;
		System.out.println("请求地址"+URL);
		JSONObject obj=new JSONObject();
		obj.put("QUERY_DATE", query_date);
		obj.put("QUERY_TYPE", "2");
		obj.put("methodType", "scanPlanAsn");
		obj.put("wId", "1060");
		obj.put("workerId", "1162");
		//storeInterfaceLog("下线数据获取", "WMS", "JBT", "QUERY_DATE", obj.toString(), null);
	    System.out.println("下线数据获取:"+obj.toString());
		String buffer=sendJbtData(URL, obj.toString());
		System.out.println("久保田下线响应报文:"+buffer);
//		InterfaceLog log=EntityFactory.getEntity(InterfaceLog.class);
//		app.storeInterfaceLog(null,"Android", "WMS", "发动机入库上架确认", json.toString(), null);
        if (buffer.toString().length()>0) {
        		JSONObject json = JSONObject.fromObject(buffer.toString());
        		JSONArray jsonArray = JSONArray.fromObject(json.getString("return data"));
 		    for(int i = 0;i<jsonArray.size();i++) {
 		    		JSONObject jsonObject = JSONObject.fromObject(jsonArray.get(i).toString());
 		    		String ID_NO=(String) jsonObject.get("ID_NO");//id_no
 		    		String PLAN_PROD_FINISH_YM=(String) jsonObject.get("PLAN_PROD_FINISH_YM");//生産計画月度
 		    		String MODEL_CODE=(String) jsonObject.get("MODEL_CODE");//机型编号
 		    		String MODEL_NAME=(String) jsonObject.get("MODEL_NAME");//机型名称
 		    		String SERIAL_NO=(String) jsonObject.get("SERIAL_NO");//机号
 		    		String FINAL_LINE_CODE=(String) jsonObject.get("FINAL_LINE_CODE");//最終生産ライン
 		    		String UPDATE_BY_19=(String) jsonObject.get("UPDATE_BY_19");//下线信息登录by
 		    		String UPDATE_DATE_19=(String) jsonObject.get("UPDATE_DATE_19");//下线信息登录date
 		    		if(ID_NO!=null&&!ID_NO.equals("")){
 		    			List<OfflineData> fs=this.commonDao.findByQuery("from OfflineData d where d.str1='"+ID_NO+"' "
 		    					+ " and d.str2='"+PLAN_PROD_FINISH_YM+"'");
 		    			if(fs.size()<=0){
		 		    		OfflineData f=EntityFactory.getEntity(OfflineData.class);
		 		    		f.setStr1(ID_NO);
		 		    		f.setStr2(PLAN_PROD_FINISH_YM);
		 		    		f.setModelType(MODEL_CODE);
		 		    		f.setName(MODEL_NAME);
		 		    		f.setStr3(SERIAL_NO);
		 		    		f.setCode(UPDATE_BY_19);
		 		    		f.setAllocateTime(DateUtil.getDateFormat2(UPDATE_DATE_19));
		 		    		f.setUserName(FINAL_LINE_CODE);
		 		    		f.setUserDate(new Date());
		 		    		f.setOrderQuantity(1);
		 		    		f.setStatus("未消耗");
		 		    		commonDao.store(f);
 		    			}
	 		    		
 		    		}
 		    }
	       //接口回传日志z
		  //storeInterfaceLog("吊码数据获取返回", "WMS", "JBT", QUERY_DATE, json.toString(), null);
		}
		return null;
	}
	
	public void shuaXinStatus(String type,String ids){
		if(type.equals("下线数据")){
			List<OfflineData> OfflineDatas =  commonDao.findByQuery(" from OfflineData od where od.id in ("+ids+")  ");
			for(OfflineData od:OfflineDatas){
				od.setStatus("已耗用");
				commonDao.store(od);
			}
		}else{
			List<HoistingData> HoistingDatas =  commonDao.findByQuery(" from HoistingData hd where hd.id in ("+ids+")  ");
			for(HoistingData hd:HoistingDatas){
				hd.setStatus("已耗用");
				commonDao.store(hd);
			}
		}
	}
	
	public void shuaXinStatus(String type,String xxrq,String model_Type){
//		if(type.equals("下线数据")){
//    		String sql=" select o.allocate_Time,o.model_Type,count(*) "//,GROUP_CONCAT(o.id) as ids "
//			+ " from Offline_Data o "
//			+ " where 1=1 "
//			+ " and o.status='未消耗' "
//			+ " and o.allocate_Time='"+query_date+"' "
//			+ " group by o.allocate_Time,o.model_Type ";
//    		System.out.println(sql);
//			Query   query   =   session.createSQLQuery(sql); 
//			queryOffline=query.list();
//    	}else{
//    		String sql=" select h.allocate_Time,h.model_Type,count(*) "//,GROUP_CONCAT(h.id) as ids "
//			+ " from Hoisting_Data h "
//			+ " where 1=1 "
//			+ " and h.status='未消耗' "
//			+ " and h.allocate_Time='"+query_date+"' "
//			+ " group by h.allocate_Time,h.model_Type ";
//    		System.out.println(sql);
//			Query   query   =   session.createSQLQuery(sql); 
//			queryOffline=query.list();
//    	}
		if(type.equals("下线数据")){
			List<OfflineData> OfflineDatas =  commonDao.findByQuery(" from OfflineData od where od.allocateTime='"+xxrq+"' and  od.modelType='"+model_Type+"'");
			for(OfflineData od:OfflineDatas){
				od.setStatus("已耗用");
				commonDao.store(od);
			}
		}else{
			List<HoistingData> HoistingDatas =  commonDao.findByQuery(" from HoistingData hd where hd.allocateTime='"+xxrq+"' and  hd.modelType='"+model_Type+"'");
			for(HoistingData hd:HoistingDatas){
				hd.setStatus("已耗用");
				commonDao.store(hd);
			}
		}
	}
	
	public String sendJbtData(String URL, String xmlInfo) {
	    InputStream instr = null;
	    xmlInfo="";
	    	try {
	            HttpClient httpClient = new HttpClient();
	            PostMethod postMethod = new PostMethod(URL);
	            // 设置请求头  Content-Type
	            postMethod.setRequestHeader("Content-Type", "application/json");
	            RequestEntity requestEntity = new StringRequestEntity(xmlInfo,"application/json","UTF-8");
	            postMethod.setRequestEntity(requestEntity);
	            httpClient.executeMethod(postMethod);// 执行请求
	            instr =  postMethod.getResponseBodyAsStream();// 获取返回的流
	            BufferedReader br = null;
	            StringBuffer buffer = new StringBuffer();
	            // 将返回的输入流转换成字符串
	            br = new BufferedReader(new InputStreamReader(instr, Charset.forName("UTF-8")));
	            String temp;
	            while ((temp = br.readLine()) != null) {
	                buffer.append(temp);
	            }
	            instr.close();
	            return buffer.toString();
		    } catch (Exception e) {
		     	System.out.println(e.toString());
		     	return  e.getMessage();
		    }
	 }
	
	public InterfaceLog storeInterfaceLog(String request,String fromSys,String toSys,String type,String content,Long id) {
		InterfaceLog log=EntityFactory.getEntity(InterfaceLog.class);
		log.setRequest(request);
		log.setFromSYS(fromSys);
		log.setToSYS(toSys);
		log.setType(type);
		log.setRequestContent(content);
		log.setRequestTime(new Date());
		log.setLogID(id);
		log.setStatus("OPEN");
		commonDao.store(log);
		return log;
	}
	
	 public String getPropertiesParm(String obj){
	   String parm = "";
	   Properties prop = new Properties();   
	   InputStream in = this.getClass().getResourceAsStream("/hibernate.properties");   
	   try {
		    prop.load(in);
		    parm = prop.getProperty(obj).trim();
	   } catch (IOException e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	   }   
	   return parm;
	  }

	@Override
	public List<Object[]> queryData(String type ,String query_date) {
		Session session = ((HibernateDaoSupport)this.commonDao).getSessionFactory().openSession();
		List<Object[]> queryOffline=null;
	    try {
	    	if(type.equals("下线数据")){
	    		String sql=" select o.code,o.model_Type,count(*) "//,GROUP_CONCAT(o.id) as ids "
				+ " from Offline_Data o "
				+ " where 1=1 "
				+ " and o.status='未消耗' "
				+ " and o.allocate_Time='"+query_date+"' and o.code='620611' "
				+ " group by o.code,o.model_Type ";
	    		System.out.println(sql);
				Query   query   =   session.createSQLQuery(sql); 
				queryOffline=query.list();
	    	}else{
	    		String sql=" select h.code,h.model_Type,count(*) "//,GROUP_CONCAT(h.id) as ids "
				+ " from Hoisting_Data h "
				+ " where 1=1 "
				+ " and h.status='未消耗' "
				+ " and h.allocate_Time='"+query_date+"' and h.code='620001' "
				+ " group by h.code,h.model_Type ";
	    		System.out.println(sql);
				Query   query   =   session.createSQLQuery(sql); 
				queryOffline=query.list();
	    	}
        } catch (Exception e) {
        	e.printStackTrace();
    		System.out.print("连接失败");
        }finally{
        	session.close();
        } 
	    return queryOffline;
	}

	@Override
	public void createData(String type, Date date) {
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		String xxrq=sdf.format(date);//下线日期
		if(type.equals("下线数据")){
			//下线数据加上日历号 code=620611,TLH
			List<Object[]> objs = queryData(type,xxrq);
			if(objs.size()>0){
				for(Object[] object:objs){
					String code=object[0].toString().trim();//日历号
					String modelType=object[1].toString();//形式名
					String quantity= object[2].toString();//数量
					createAutoHy(type, code,"TLH", modelType, quantity, xxrq, date);
				}
			}
		}else if(type.equals("吊装数据")){
			//下线数据加上吊装点 code=620001,TLQ,TLB
			List<Object[]> objs = queryData(type,xxrq);
			  if(objs.size()>0){
				for(Object[] object:objs){
					String code=object[0].toString().trim();//形式名
					String modelType=object[1].toString();//形式名
					String quantity= object[2].toString();//数量
					createAutoHy(type, code, "TLQ",modelType, quantity, xxrq, date);
				}
			}
		}
	}
	//生成耗用数据
	public void createAutoHy(String type,String code,String gwxx,String modelType,String qty,String xxrq,Date xxDate) {
		List<BigItem> BigItems =  commonDao.findByQuery(" from BigItem bt where bt.code='"+modelType+"'");
		List<OfflineData> ods = commonDao.findByQuery(" from OfflineData t where t.status='未消耗' and t.allocateTime='"+xxrq+"' "
				+ " and  t.modelType='"+modelType+"' and t.code='620611'");
		List<HoistingData> hds =  commonDao.findByQuery(" from HoistingData t where t.status='未消耗' and t.allocateTime='"+xxrq+"'"
				+ " and  t.modelType='"+modelType+"' and t.code='620001'");
		if(BigItems.size()>0){
			BigItem bigItem=BigItems.get(0);
			if(code.equals("620001")){
				gwxx="TLQ";
			}else if(code.equals("620611")){
				gwxx="TLH";
			}
			SpareParts sp1=EntityFactory.getEntity(SpareParts.class);
			sp1.setCode(gwxx);
			sp1.setAllocateTime(xxDate);
			sp1.setBigItem(bigItem);
			sp1.setOrderQuantity(Double.parseDouble(qty));
			sp1.setStatus("未消耗");
			sp1.setUserDate(new Date());
			sp1.setUserName(UserHolder.getUser().getName());
			sp1.setDescription(type);//备注
			commonDao.store(sp1);
			SpareParts sp2=null;
			if(type.equals("吊装数据")){//吊装数据需要多生成拖拉机变速箱工位的耗用
				sp2=EntityFactory.getEntity(SpareParts.class);
				sp2.setCode("TLB");
				sp2.setAllocateTime(xxDate);
				sp2.setBigItem(bigItem);
				sp2.setOrderQuantity(Double.parseDouble(qty));
				sp2.setStatus("未消耗");
				sp2.setUserDate(new Date());
				sp2.setUserName(UserHolder.getUser().getName());
				sp2.setDescription(type);//备注
				commonDao.store(sp2);
			}
			//刷新状态
			if(type.equals("下线数据")){
				for(OfflineData hd:ods){
					hd.setStatus("已耗用");
					hd.setHyBy(UserHolder.getUser().getName());
					hd.setHyDate(new Date());
					hd.setHyId1(sp1.getId());
					commonDao.store(hd);
					//生产顺序耗用
					List<ProductionPlan> ps=this.commonDao.findByQuery("from ProductionPlan p where p.code='"+hd.getStr1()+"' and p.strExtend1='未消耗'"
							+ " and procedure='TLH' ");
					if(ps.size()>0){
						for(ProductionPlan p:ps){
							p.setStrExtend1("已耗用");
							p.setHyTime(new Date());
							if(p.getProcedure().equals("TLB")){
								p.setSpId(sp2.getId());
							}else{
								p.setSpId(sp1.getId());
							}
							this.commonDao.store(p);
						}
					}else{
						System.out.println(hd.getStr1()+"找不到耗用或已经耗用");
					}
				}
			}else if(type.equals("吊装数据")){
				for(HoistingData hd:hds){
					hd.setStatus("已耗用");
					hd.setHyBy(UserHolder.getUser().getName());
					hd.setHyDate(new Date());
					hd.setHyId1(sp1.getId());
					if(sp2!=null){
						hd.setHyId2(sp2.getId());
					}
					commonDao.store(hd);
					//生产顺序耗用
					List<ProductionPlan> ps=this.commonDao.findByQuery("from ProductionPlan p where p.code='"+hd.getStr1()+"' and p.strExtend1='未消耗'"
							+ " and procedure in ('TLQ','TLB') ");
					if(ps.size()>0){
						for(ProductionPlan p:ps){
							p.setStrExtend1("已耗用");
							p.setHyTime(new Date());
							if(p.getProcedure().equals("TLB")){
								p.setSpId(sp2.getId());
							}else{
								p.setSpId(sp1.getId());
							}
							this.commonDao.store(p);
						}
					}else{
						System.out.println(hd.getStr1()+"找不到耗用或已经耗用");
					}
				}
			}
		}else{
			//continue;
			if(code.equals("620611")){
				for(OfflineData od:ods){
					od.setHyDes("无对应完成品品番");
					commonDao.store(od);
				}
			}else if(code.equals("620001")){
				for(HoistingData hd:hds){
					hd.setHyDes("无对应完成品品番");
					commonDao.store(hd);
				}
			}
		}
		
	}
	
	public void createDataOld(String type, Date date) {
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		String allocateTime=sdf.format(date);//下线日期
		if(type.equals("下线数据")){
			//下线数据加上日历号 code=620611,TLH
			List<Object[]> objs = queryData(type,allocateTime);
			if(objs.size()>0){
				for(Object[] object:objs){
					Date code=(Date) object[0];//下线日期
					String modelType=object[1].toString();//形式名
					String quantity= object[2].toString();//数量
//					String ids=object[3].toString();//下线数据ids
					List<BigItem> BigItems =  commonDao.findByQuery(" from BigItem bt where bt.code='"+modelType+"'  ");
					if(BigItems.size()>0){
						BigItem bigItem=BigItems.get(0);
						SpareParts spareParts=EntityFactory.getEntity(SpareParts.class);
						spareParts.setCode("LDK3H");
						spareParts.setAllocateTime(date);
						spareParts.setBigItem(bigItem);
						spareParts.setOrderQuantity(Double.parseDouble(quantity));
						spareParts.setStatus("未消耗");
						spareParts.setUserDate(new Date());
						spareParts.setUserName(UserHolder.getUser().getName());
						spareParts.setDescription(type);
//						spareParts.setStr5(ids);//下线数据ids
						commonDao.store(spareParts);
						//刷新状态
//						shuaXinStatus(type, ids);
						shuaXinStatus(type, sdf.format(date),modelType);
					}else{
						continue;
					}
				}
			}
		}else if(type.equals("吊装数据")){
			//下线数据加上吊装点 code=620001,TLQ,TLB
			List<Object[]> objs = queryData(type,sdf.format(date));
			  if(objs.size()>0){
				for(Object[] object:objs){
					String modelType=object[1].toString();//形式名
					String quantity= object[2].toString();//数量
//					String ids=object[3].toString();//下线数据ids
					List<BigItem> BigItems =  commonDao.findByQuery(" from BigItem bt where bt.code='"+modelType+"'  ");
					if(BigItems.size()>0){
						BigItem bigItem=BigItems.get(0);
						SpareParts spareParts=EntityFactory.getEntity(SpareParts.class);
						spareParts.setCode("LDK3Q");
						spareParts.setAllocateTime(date);
						spareParts.setBigItem(bigItem);
						spareParts.setOrderQuantity(Double.parseDouble(quantity));
						spareParts.setStatus("未消耗");
						spareParts.setUserDate(new Date());
						spareParts.setUserName(UserHolder.getUser().getName());
						spareParts.setDescription(type);//备注
//						spareParts.setStr5(ids);//下线数据ids
						commonDao.store(spareParts);
						//刷新状态
						shuaXinStatus(type, sdf.format(date),modelType);
					}else{
						continue;
					}
				}
			}
		}
	}
	
	public void inActionPinfan(List<Long> pfIds) {
		for (Long id : pfIds) {
			Pinfan pf = this.commonDao.load(Pinfan.class,id);
			pf.setDisabled(Boolean.TRUE);
			this.commonDao.store(pf);
		}
	}
	public void activePinfan(List<Long> pfIds) {
		for (Long id : pfIds) {
			Pinfan pf = this.commonDao.load(Pinfan.class,id);
			pf.setDisabled(Boolean.FALSE);
			this.commonDao.store(pf);
		}
	}
		
}
