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

import com.dev.energy.server.exception.BusinessException;
import com.dev.energy.server.model.EntityFactory;
import com.dev.energy.server.service.pojo.DefaultBaseManager;
import com.dev.energy.server.util.LocalizedMessage;
import com.dev.energy.server.web.security.UserHolder;
import com.dev.swms.server.model.abstractEntity.BigItem;
import com.dev.swms.server.model.abstractEntity.DesignList;
import com.dev.swms.server.model.abstractEntity.Pinfan;
import com.dev.swms.server.model.abstractEntity.PlanPickDetail;
import com.dev.swms.server.model.abstractEntity.PlanPickTicket;
import com.dev.swms.server.model.base.Address;
import com.dev.swms.server.model.base.BillType;
import com.dev.swms.server.model.base.CompanyCode;
import com.dev.swms.server.model.base.Contact;
import com.dev.swms.server.model.base.Item;
import com.dev.swms.server.model.base.ItemRelation;
import com.dev.swms.server.model.base.Line;
import com.dev.swms.server.model.base.Location;
import com.dev.swms.server.model.base.LocationTaskMode;
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.PackageUnit;
import com.dev.swms.server.model.base.Province;
import com.dev.swms.server.model.base.RackType;
import com.dev.swms.server.model.base.Store;
import com.dev.swms.server.model.base.Stowage;
import com.dev.swms.server.model.base.Structure;
import com.dev.swms.server.model.base.Warehouse;
import com.dev.swms.server.model.base.WarehouseArea;
import com.dev.swms.server.model.count.CommonCode;
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.shipping.PickTicket;
import com.dev.swms.server.model.shipping.PickTicketDetail;
import com.dev.swms.server.model.shipping.PickTicketStatus;
import com.dev.swms.server.model.shipping.PlanShipDetail;
import com.dev.swms.server.service.base.ImportFileManager;
import com.dev.swms.server.service.base.ItemManager;
import com.dev.swms.server.service.base.WarehouseManager;
import com.dev.swms.server.service.interfaceLog.InterfaceLogManager;
import com.dev.swms.server.service.inventory.InventoryManager;
import com.dev.swms.server.service.receiving.ASNManager;
import com.dev.swms.server.service.receiving.MoveDocManager;
import com.dev.swms.server.service.receiving.PutawayAllocator;
import com.dev.swms.server.service.sequence.BussinessCodeManager;
import com.dev.swms.server.service.shipping.PickTicketManager;
import com.dev.swms.server.utils.DateUtil;
import com.dev.swms.server.utils.DateUtils;
import com.dev.swms.server.web.filter.WarehouseHolder;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfReaderContentParser;
import com.itextpdf.text.pdf.parser.SimpleTextExtractionStrategy;
import com.itextpdf.text.pdf.parser.TextExtractionStrategy;

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

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;  
import java.io.FileNotFoundException;  
import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;
import java.math.BigDecimal;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.text.PDFTextStripper;

import java.net.MalformedURLException;
import java.io.OutputStreamWriter;
import java.io.FileOutputStream;
import java.io.FileReader; 

//import org.pdfbox.pdfparser.PDFParser;  
//import org.pdfbox.pdmodel.PDDocument;  
//import org.pdfbox.util.PDFTextStripper;  

@SuppressWarnings("unchecked")
public class DefaultImportFileManager extends DefaultBaseManager implements ImportFileManager{
	protected final BussinessCodeManager bussinessCodeManager;
	protected final ASNManager asnManager;
	protected final PickTicketManager pickTicketManager;
	
	public DefaultImportFileManager(ASNManager manager1, BussinessCodeManager manager2,PickTicketManager manager3) {
		super();
		this.asnManager = manager1;
		this.bussinessCodeManager = manager2;
		this.pickTicketManager=manager3;
	}
	
	@Override
	public void importASN() {
		try {
			String fileName="/Users/houjianlan/Documents/项目/阿凡达/NY.pdf";
			String fileName_txt="/Users/houjianlan/Documents/项目/阿凡达/NY.txt";
			ParsePdf(fileName);
			String oldData = parseTxt(new File(fileName_txt));
			System.out.println(oldData);
			//System.out.println(getPdfFileText(fileName));
			//readFdf() ;
			//aaa();
			//FileInputStream  infile=new FileInputStream("/Users/houjianlan/Documents/项目/阿凡达/20181021.pdf");
			//InputStream input = new FileInputStream(new File(fileName));
			//this.getTextFromPdf(input, Boolean.TRUE);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
//		// TODO Auto-generated method stub
//		String result = null;  
//        FileInputStream is = null;  
//        PDDocument document = null;
//        try {  
//            is = new FileInputStream("/Users/houjianlan/Documents/项目/阿凡达/20181021.pdf");  
//            PDFParser parser = new PDFParser(is);  
//            parser.parse();  
//            document = parser.getPDDocument();  
//            PDFTextStripper stripper = new PDFTextStripper();  
//            result = stripper.getText(document);  
//        } catch (FileNotFoundException e) {  
//            // TODO Auto-generated catch block  
//            e.printStackTrace();  
//        } catch (IOException e) {  
//            // TODO Auto-generated catch block  
//            e.printStackTrace();  
//        } finally {  if (is != null) {  
//            try {  
//                is.close();  
//            } catch (IOException e) {  
//                // TODO Auto-generated catch block  
//                e.printStackTrace();  
//            }  
//        }  
//        if (document != null) {  
//            try {  
//                document.close();  
//            } catch (IOException e) {  
//                // TODO Auto-generated catch block  
//                e.printStackTrace();  
//            }  
//        }  
//    }  
//        System.out.println(result);
//        
//        try {
//			this.readFileOfPDF();
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
    //return result;  
	}
	
//	public String readFileOfPDF() throws IOException {
//        String context = null;
//        FileInputStream  infile=null;
//        try {
//        	   infile = new FileInputStream("/Users/houjianlan/Documents/项目/阿凡达/20181021.pdf");// 创建一个文件输入流
//            // 新建一个PDF解析器对象
//            PDFParser parser = new PDFParser(infile);
//            // 对PDF文件进行解析
//            parser.parse();
//            // 获取解析后得到的PDF文档对象
//            PDDocument pdfdocument = parser.getPDDocument();
//            output = new OutputStreamWriter(new FileOutputStream(textFile),  
//     		       encoding); 
//            // 新建一个PDF文本剥离器
//            PDFTextStripper stripper = new PDFTextStripper();
//            // 从PDF文档对象中剥离文本
//            context = stripper.getText(pdfdocument);
//            System.out.println("PDF文件的文本内容如下：");
//             System.out.println(context);
// 
//        } catch (Exception e) {
//            System.out.println("读取PDF文件失败！" + e.getMessage());
//        } finally {
// 
//            if (infile != null) {
//                try {
//                    infile.close();
//                } catch (IOException e1) {
//                }
//            }
//        }
//        return context;
//    }
	
	 public void readFdf() throws Exception {  
		    // 是否排序  
		    boolean sort = false;  
		    // pdf文件名  
		    String pdfFile = "/Users/houjianlan/Documents/项目/阿凡达/20181021.pdf";  
		    // 输入文本文件名称  
		    String textFile = null;  
		    // 编码方式  
		    String encoding = "UTF-8";  
		    // 开始提取页数  
		    int startPage = 1;  
		    // 结束提取页数  
		    int endPage = Integer.MAX_VALUE;  
		    // 文件输入流，生成文本文件  
		    Writer output = null;  
		    // 内存中存储的PDF Document  
		    PDDocument document = null;  
		    try {  
		     try {  
		      // 首先当作一个URL来装载文件，如果得到异常再从本地文件系统//去装载文件  
		      URL url = new URL(pdfFile);  
		     //注意参数已不是以前版本中的URL.而是File。  
		      document = PDDocument.load(new File(pdfFile));  
		     // 获取PDF的文件名  
		      String fileName = url.getFile();  
		      // 以原来PDF的名称来命名新产生的txt文件  
		      if (fileName.length() > 4) {  
		       File outputFile = new File(fileName.substring(0, fileName  
		         .length() - 4)  
		         + ".txt");  
		       textFile = outputFile.getName();  
		      }  
		     } catch (MalformedURLException e) {  
		      // 如果作为URL装载得到异常则从文件系统装载  
		     //注意参数已不是以前版本中的URL.而是File。  
		      document = PDDocument.load(new File(pdfFile));  
		      if (pdfFile.length() > 4) {  
		       textFile = pdfFile.substring(0, pdfFile.length() - 4)  
		         + ".txt";  
		      }  
		     }  
		     // 文件输入流，写入文件倒textFile  
		     output = new OutputStreamWriter(new FileOutputStream(textFile),  
		       encoding);  
		     // PDFTextStripper来提取文本  
		     PDFTextStripper stripper = null;  
		     stripper = new PDFTextStripper();  
		     // 设置是否排序  
		     stripper.setSortByPosition(sort);  
		     // 设置起始页  
		     stripper.setStartPage(startPage);  
		     // 设置结束页  
		     stripper.setEndPage(endPage);  
		     // 调用PDFTextStripper的writeText提取并输出文本  
		     stripper.writeText(document, output);  
		    } finally {  
		     if (output != null) {  
		      // 关闭输出流  
		      output.close();  
		     }  
		     if (document != null) {  
		      // 关闭PDF Document  
		      document.close();  
		     }  
		    }  
		   }  
	 
	 
		public  void aaa() throws IOException{
			PDDocument document = new PDDocument();
			PDPage page = new PDPage();
			document.addPage(page);
			
//			PDFont font = PDTrueTypeFont.loadTTF(document, new File("SIMSUN.TTC"));
			PDFont font = PDType1Font.HELVETICA_BOLD;
			
			PDPageContentStream contentStream = new PDPageContentStream(document, page);
			contentStream.beginText();
			contentStream.setFont(font, 14);
			contentStream.moveTextPositionByAmount(100, 700);
			contentStream.drawString("Hello World+=====");
//			contentStream.drawString("中文");
			contentStream.endText();
			
			contentStream.close();
			
			try {
				document.save("/Users/houjianlan/Documents/项目/阿凡达/test.pdf");
			} catch (Exception e) {
				e.printStackTrace();
			}
			document.close();
		}
		
		public  String getTextFromPdf(InputStream fileStream, boolean sort) {
			int startPage = 1;
			String content = null;
			PDDocument document = null;
			try {
				document = PDDocument.load(fileStream);
				int endPage = null == document ? Integer.MAX_VALUE : document.getNumberOfPages();
				PDFTextStripper stripper = new PDFTextStripper();
				stripper.setSortByPosition(sort);
				stripper.setStartPage(startPage);
				stripper.setEndPage(endPage);
				content = stripper.getText(document);
				System.out.println("pdf 文件解析，内容为：" + content);
			}catch (Exception e) {
				System.out.println("文件解析异常，信息为： " + e.getMessage());
			}
			return null;
		}
		
		public  String getPdfFileText(String fileName) throws IOException {  
			   PdfReader reader = new PdfReader(fileName);  
			   PdfReaderContentParser parser = new PdfReaderContentParser(reader);  
			   StringBuffer buff = new StringBuffer();  
			   TextExtractionStrategy strategy;  
			   for (int i = 1; i <= reader.getNumberOfPages(); i++) {  
			    strategy = parser.processContent(i,  
			      new SimpleTextExtractionStrategy());  
			    buff.append(strategy.getResultantText());  
			   }  
			   return buff.toString();  
			  }  
		
		public void ParsePdf(String path) throws Exception {
			File file = new File(path);
			PDDocument doc = PDDocument.load(file);
			int pagenumber = doc.getNumberOfPages();
			// System.out.print("pages" + pagenumber);
			String s = path.substring(0, path.length() - 4);// 这边截取的时候 写死了 所以文件只能放在类似 D：//下面
			FileOutputStream fos = new FileOutputStream(s + ".txt");
			Writer writer = new OutputStreamWriter(fos, "UTF-8");
			PDFTextStripper stripper = new PDFTextStripper();
			stripper.setSortByPosition(true);// 排序
			stripper.writeText(doc, writer);
			writer.close();
			doc.close();
		}
		
		public String parseTxt(File file) {
			StringBuilder result = new StringBuilder();
			try {
				BufferedReader br = new BufferedReader(new FileReader(file));// 构造一个BufferedReader类来读取文件
				String s = null;
				int lineIndex = 0;
				while ((s = br.readLine()) != null) {// 使用readLine方法，一次读一行
					lineIndex++;
					String regex = "^[0-9].*[0-9]$";//从头到尾之后数字，来作为判断表格的依据
					if (s.matches(regex)) {
						System.out.println(lineIndex + ":" + s);
						//result.append(System.lineSeparator() + s);
					}
				}
				br.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			return result.toString();
		}
		public void importASN(Long asnId,File file){
			ASN asn=this.commonDao.get(ASN.class, asnId);
			if(asn==null){
				throw new BusinessException("请先保存入库单");
			}
			if(asn.getWarehouse().getCode().equals("VMI国内部品仓库")){
				importASNVMI(asnId,file);
			}else{
				importASNKAMS(asnId,file);
			}
			
//			importASNVMI2(file);
		}
		public void importASNKAMS(Long asnId,File file){
			Workbook workbook;
			try {
				//品番	品名	AC	加工内容	税别	数量	备注
				workbook = Workbook.getWorkbook(file);
				Sheet sheet = workbook.getSheet(0);//得到excel第一页的内容
				if(sheet.getColumns()<6){
					throw new BusinessException("该模版列数不正确，不能小于6");
				}
				ASN asn=this.commonDao.get(ASN.class, asnId);
				if(asn==null){
					throw new BusinessException("请先保存入库单");
				}
				 for (int i = 1; i <sheet.getRows(); i++) {
					 System.out.println("======"+i);
					 int j=0;
					String item_code=sheet.getCell(j++,i).getContents().trim();
					if(item_code==null||item_code.equals("")){
				 		return;
				 	}
					j++;
					String ac=sheet.getCell(j++,i).getContents().trim();
					String jgzx=sheet.getCell(j++,i).getContents().trim();
					String sb=sheet.getCell(j++,i).getContents().trim();
					String zzkw=sheet.getCell(j++,i).getContents().trim();
					String quantity=sheet.getCell(j++,i).getContents().trim();
					String bz=sheet.getCell(j++,i).getContents().trim();
					Location zz_loc=null;
					if(zzkw!=null&&!zzkw.equals("")){
						List<Location> los=this.commonDao.findByQuery("from Location l where l.code='"+zzkw+"'");
						if(los.size()<=0){
							throw new BusinessException("第"+(i+1)+"制造库位不存在");
						}
						zz_loc=los.get(0);
					}
					item_code=item_code.trim();
					List<Item> items=this.commonDao.findByQuery("from Item i where i.code='"+item_code+"' and i.warehouse.id="+WarehouseHolder.getWarehouse().getId());
						//	+ " and i.company.id="+asn.getCompany().getId());
					if(items.size()>0){
						Item item=items.get(0);
						ASNDetail ad=EntityFactory.getEntity(ASNDetail.class);
						ad.setItem(item);
						ad.setExpectedQuantity(Double.parseDouble(quantity));
						ad.setExpectedQtyOfMasterUnit(ad.getExpectedQuantity());
						ad.setAsn(asn);
						ad.setLineNo(asn.getAsnDetails().size() + i);
						ad.setPO(ac);
						ad.setSourceId(jgzx);
						ad.setZzkw(zz_loc);
						LotInfo l=new LotInfo();
						l.setPropC1(sb);
						ad.setLotInfo(l);
						ad.setTemperature(sb);
						this.commonDao.store(ad);
						asn.setExpectedQuantity(asn.getExpectedQuantity()+Double.parseDouble(quantity));
						asn.setTemperature(sb);
						asn.setSourceId(sb);
						this.commonDao.store(asn);
//						asnManager.addASNDetail(asn.getId(),ad);
					}else{
						throw new BusinessException("第"+(i+1)+"行货品代码"+item_code+"不存在");
					}
				 }
			} catch (BiffException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
		public void importASNVMI(Long asnId,File file){
			Workbook workbook;
			try {
				workbook = Workbook.getWorkbook(file);
				Sheet sheet = workbook.getSheet(0);//得到excel第一页的内容
				if(sheet.getColumns()<1){
					throw new BusinessException("该模版列数不正确，不能小于2");
				}
				ASN asn=this.commonDao.get(ASN.class, asnId);
				if(asn==null){
					throw new BusinessException("请先保存入库单");
				}
				 for (int i = 1; i <sheet.getRows(); i++) {
					 System.out.println("======"+i);
					 //货品自编码 数量
					String item_code=sheet.getCell(0,i).getContents().trim();
					if(item_code==null||item_code.equals("")){
				 		return;
				 	}
					String quantity=sheet.getCell(1,i).getContents().trim();
					item_code=item_code.trim();
					List<Item> items=this.commonDao.findByQuery("from Item i where i.code='"+item_code+"' and i.warehouse.id="+WarehouseHolder.getWarehouse().getId()
							+ " and i.company.id="+asn.getCompany().getId());
					if(items.size()>0){
						Item item=items.get(0);
						ASNDetail ad=EntityFactory.getEntity(ASNDetail.class);
						ad.setItem(item);
						ad.setExpectedQuantity(Double.parseDouble(quantity));
						ad.setExpectedQtyOfMasterUnit(ad.getExpectedQuantity());
						ad.setAsn(asn);
						ad.setLineNo(asn.getAsnDetails().size() + i);
						this.commonDao.store(ad);
						asn.setExpectedQuantity(asn.getExpectedQuantity()+Double.parseDouble(quantity));
						this.commonDao.store(asn);
//						asnManager.addASNDetail(asn.getId(),ad);
					}else{
						throw new BusinessException("第"+(i+1)+"行货品代码"+item_code+"不存在");
					}
				 }
			} catch (BiffException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
//		public void importASNKAMS(Long asnId,File file){
//			Workbook workbook;
//			try {
//				workbook = Workbook.getWorkbook(file);
//				Sheet sheet = workbook.getSheet(0);//得到excel第一页的内容
//				if(sheet.getColumns()<1){
//					throw new BusinessException("该模版列数不正确，不能小于2");
//				}
//				ASN asn=this.commonDao.get(ASN.class, asnId);
//				if(asn==null){
//					throw new BusinessException("请先保存入库单");
//				}
//				 for (int i = 1; i <sheet.getRows(); i++) {
//					 System.out.println("======"+i);
//					 //货品自编码 数量
//					String item_code=sheet.getCell(0,i).getContents().trim();
//					if(item_code==null||item_code.equals("")){
//				 		return;
//				 	}
//					String AC=sheet.getCell(2,i).getContents().trim();
//					String sp=sheet.getCell(3,i).getContents().trim();
//					String bannd=sheet.getCell(4,i).getContents().trim();
//					String quantity=sheet.getCell(5,i).getContents().trim();
//					String des=sheet.getCell(6,i).getContents().trim();
//					item_code=item_code.trim();
//					List<Item> items=this.commonDao.findByQuery("from Item i where i.code='"+item_code+"' and i.warehouse.id="+WarehouseHolder.getWarehouse().getId()
//							+ " and i.company.id="+asn.getCompany().getId());
//					if(items.size()>0){
//						Item item=items.get(0);
//						ASNDetail ad=EntityFactory.getEntity(ASNDetail.class);
//						ad.setItem(item);
//						LotInfo lotInfo=new LotInfo();
//						lotInfo.setPropC1(bannd);
//						ad.setLotInfo(lotInfo);
//						ad.setExpectedQuantity(Double.parseDouble(quantity));
//						ad.setExpectedQtyOfMasterUnit(ad.getExpectedQuantity());
//						ad.setAsn(asn);
//						ad.setLineNo(asn.getAsnDetails().size() + i);
//						ad.setRemark(des);
//						ad.setPO(AC);
//						ad.setSourceId(sp);
//						this.commonDao.store(ad);
//						asn.setExpectedQuantity(asn.getExpectedQuantity()+Double.parseDouble(quantity));
//						this.commonDao.store(asn);
////						asnManager.addASNDetail(asn.getId(),ad);
//					}else{
//						throw new BusinessException("第"+(i+1)+"行货品代码"+item_code+"不存在");
//					}
//				 }
//			} catch (BiffException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			} catch (IOException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//			
//		}
		public void importASNold(File file){
			Workbook workbook;
			try {
				workbook = Workbook.getWorkbook(file);
				Sheet sheet = workbook.getSheet(0);//得到excel第一页的内容
				if(sheet.getColumns()<11){
					throw new BusinessException("该模版列数不正确，不能小于11");
				}
				HashMap<String,String> map=new HashMap<String, String>();
				 List<Location> ls =  commonDao.findByQuery(" from Location o where o.warehouse.id=:id  and o.type ='RECEIVE' and o.disabled=false",
							new String[] { "id"},new Object[] {WarehouseHolder.getWarehouse().getId()});
				 Location l =ls.get(0);
				 for (int i = 1; i <sheet.getRows(); i++) {
					 System.out.println("======"+i);
					 //订单号（ASN）	货品自编码	货品名称	规格	单位	数量	重量	批号	生产日期,逻辑库位	备注
				 	String relatedBill1=sheet.getCell(0,i).getContents().trim();
				 	if(relatedBill1==null||relatedBill1.equals("")){
				 		return;
				 	}
					String item_code=sheet.getCell(1,i).getContents().trim();
					String quantity=sheet.getCell(5,i).getContents().trim();
					String weight=sheet.getCell(6,i).getContents().trim();
					if(weight==null||weight.equals("")){
						weight="0";
					}
					String propC1=sheet.getCell(7,i).getContents().trim();
					String d1=sheet.getCell(8,i).getContents().trim();
					String dockLoc=sheet.getCell(9,i).getContents().trim();
					String remark=sheet.getCell(10,i).getContents().trim();
					List<Item> items=this.commonDao.findByQuery("from Item i where i.code='"+item_code+"'");
					if(items.size()>0){
						List<ASN> asns=this.commonDao.findByQuery("from ASN a where a.relatedBill1=:relatedBill1 ",
								new String[]{"relatedBill1"},new Object[]{relatedBill1});
						ASN asn=null;
						Item item=items.get(0);
						if(asns.size()>0){
							asn=asns.get(0);
							if(!map.containsKey(relatedBill1)){
								throw new BusinessException("第"+(i+1)+"行订单号已导入");
							}
						}else{
							map.put(relatedBill1, relatedBill1);
							asn=EntityFactory.getEntity(ASN.class);
							asn.setOrderDate(new Date());
							asn.setCompany(item.getCompany());
							asn.setCode(this.bussinessCodeManager.getCodeForYm("RP",3));
							asn.setWarehouse(WarehouseHolder.getWarehouse());
							asn.setStatus(ASNStatus.OPEN);
							asn.setRelatedBill1(relatedBill1);
							List<BillType> bts =  commonDao.findByQuery(" from BillType o where o.company.id=:id  and o.type ='RECEIVE' and o.disabled=false",
									new String[] { "id"},new Object[] {item.getCompany().getId()});
							asn.setBillType(bts.get(0));
							asn.setDock(l); 
							asn.setUserTracking();
							asn.setDescription(remark);
							commonDao.store(asn);
						}
						LotInfo lotInfo=new LotInfo();
						lotInfo.setPropC1(propC1);
						lotInfo.setPropD1(DateUtil.formatStrToDateYMD(d1));
						if(lotInfo.getPropD1()==null){
							lotInfo.setPropD1(DateUtil.formatStrToDateYMD01(d1));
						}
						PackageUnit unit =item.getMinPackageUnit();
						ASNDetail ad=EntityFactory.getEntity(ASNDetail.class);
						if(dockLoc!=null&&!dockLoc.equals("")){
							List<BillType> bts =  commonDao.findByQuery(" from BillType o where o.company.id=:id  and o.type ='RECEIVE' and o.disabled=false",
									new String[] { "id"},new Object[] {item.getCompany().getId()});
							List<Location> dockLocs =  commonDao.findByQuery(" from Location o where o.warehouse.id=:wId  and o.code=:code and o.disabled=false",
									new String[] { "wId","code"},new Object[] {WarehouseHolder.getWarehouse().getId(),dockLoc});
							if(dockLocs.size()>=0){
								 ad.setDock(dockLocs.get(0));
								 List<BillType> thbts =  commonDao.findByQuery(" from BillType o where o.company.id="+item.getCompany().getId()+""
								 		+ "  and o.type ='RECEIVE' and o.disabled=false and o.name like '%退货%'");
								 if(thbts.size()>0){
									 asn.setBillType(thbts.get(0));
								 }else{
									 throw new BusinessException("货主"+item.getCompany().getName()+"无退货入库单据类型");
								 }
							}else{
								throw new BusinessException("第"+(i+1)+"行库位"+dockLoc+"不存在");
							}
						
						}
						ad.setPackageUnit(unit);
						ad.setItem(item);
						ad.setLotInfo(lotInfo);
						ad.setExpectedQuantity(Double.parseDouble(quantity));
						ad.setWeight(Double.parseDouble(weight));
						asnManager.addASNDetail(asn.getId(),ad);
					}else{
						throw new BusinessException("第"+(i+1)+"行货品代码不存在");
					}
				 }
			} catch (BiffException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
		public void importXBKPickTicket(File file){
			try {
				Workbook workbook = Workbook.getWorkbook(file);
			    Sheet sheet = workbook.getSheet(workbook.getSheets().length-1);//得到excel第一页的内容
			    if(sheet.getColumns()<16){
					throw new BusinessException("该模版列数不正确，不能小于16");
				}
			    SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");//小写的mm表示的是分钟  
			    String hpdm1="";
			    Structure s=null;
			    String cusCode=CompanyCode.XBK;
				List<Structure> ss=this.commonDao.findByQuery("from Structure s where s.code=:code",new String[]{"code"},new Object[]{cusCode});
				if(ss.size()>0){
	        			s=ss.get(0);
				}else{
	        			throw new BusinessException("代码为"+cusCode+"的货主不存在");
	        		}
			    String hpdm=null;
			    List<BillType> billTypes = commonDao.findByQuery("from BillType b where  b.company.id =:company_id and b.type='SHIP'  ",
						new String[] { "company_id"}, new Object[] { s.getId() });
				BillType b=null;
				if(billTypes.size()>0){
					b=billTypes.get(0);
				}else{
					throw new BusinessException(s.getName()+"货主出库单类型没有，需要维护！");
				}
				List<Location> objs =  commonDao.findByQuery(" from Location o where o.warehouse.id=:id  and o.type ='SHIP'",
						new String[] { "id"},new Object[] {1l});
			    for (int i = 1; i <sheet.getRows(); i++) {
				    	System.out.println(i);
				    	//序号	类别	门店单号	客户单号	货品号	货品名称	备注	门店号	门店名称	
				    	//批号	生产日期	到期日	总数	单位	等同数量	批号数	货位号
				    	String xuhao=sheet.getCell(0,i).getContents().trim();
			        	String leibie=sheet.getCell(1,i).getContents().trim();
			        	String mddh=sheet.getCell(2,i).getContents().trim();
			        	String khdh=sheet.getCell(3,i).getContents().trim();
		//	        	Double bzq=Double.parseDouble(sheet.getCell(3,i).getContents().trim()==null?"0":sheet.getCell(3,i).getContents().trim());
			        	String itemCode=sheet.getCell(4,i).getContents().trim();
			        	String itemName=sheet.getCell(5,i).getContents().trim();
			        	String des=sheet.getCell(6,i).getContents().trim();
			        	String mdh=sheet.getCell(7,i).getContents().trim();
			        	String mdmc=sheet.getCell(8,i).getContents().trim();
			        	String ph=sheet.getCell(9,i).getContents().trim();
			        	String scrq=sheet.getCell(10,i).getContents().trim();
			        	String dqr=sheet.getCell(11,i).getContents().trim();
			        	String zs=sheet.getCell(12,i).getContents().trim();
			        	String unit=sheet.getCell(13,i).getContents().trim();
			        	String ttsl=sheet.getCell(14,i).getContents().trim();
			        	String phsl=sheet.getCell(15,i).getContents().trim();
			        	String kwh=sheet.getCell(16,i).getContents().trim();
			        	if(xuhao==null||xuhao.equals("")){
			        		break;
			        	}
			        if(null!=itemCode && !itemCode.equals("")){
				    		hpdm=itemCode;
				    	}else{
				    		itemCode=hpdm;
				    	}
		//	        	Double weight=Double.parseDouble(sheet.getCell(14,i).getContents().trim()==null?"0":sheet.getCell(14,i).getContents().trim());
		//	        	Double grossWeight=Double.parseDouble(sheet.getCell(15,i).getContents().trim()==null?"0":sheet.getCell(15,i).getContents().trim());
		//	        	Double length=Double.parseDouble(sheet.getCell(16,i).getContents().trim()==null?"0":sheet.getCell(16,i).getContents().trim());
		//	        	Double width=Double.parseDouble(sheet.getCell(17,i).getContents().trim()==null?"0":sheet.getCell(17,i).getContents().trim());
		//	        	Double height=Double.parseDouble(sheet.getCell(18,i).getContents().trim()==null?"0":sheet.getCell(18,i).getContents().trim());
		//	        	sint mpbz=Integer.parseInt(sheet.getCell(19,i).getContents().trim()==""?"0":sheet.getCell(19,i).getContents().trim());
		//	        	Double quantity=Double.parseDouble(orderQuantity==null?"0":orderQuantity);
		        	    Double cAcoefficient=null;
			        	int bzcj=0;
			        	Double bsdgl=null;
		        		PickTicket p=EntityFactory.getEntity(PickTicket.class);
		    			List<PickTicket> pickTickets = commonDao.findByQuery("from PickTicket p where  p.relatedBill1 =:relatedBill1 and p.company.id =:company",
		    					new String[] { "relatedBill1","company"}, new Object[] { khdh,s.getId() });
		    			if(pickTickets.size()>0){
		    				p=pickTickets.get(0);
		    			}
		    			p.setCompany(s);
		    			p.setBillType(b);
		    			if(objs.size()>0){
		    				 Location l =objs.get(0);
		    				 p.setDock(l);
		    			 }
		    			p.setCode(this.bussinessCodeManager.getCodeForYm("CP",5));
		    			p.setWarehouse(commonDao.load(Warehouse.class, 1l));
		    			p.setStatus(PickTicketStatus.OPEN);
		    			p.setUserName("imp-"+UserHolder.getUser().getLoginName());
		    			p.setUpdateTime(new Date());
		    			p.setOrderDate(new Date());
		    			p.setReceivedDate(new Date());
		    			List<Store> stores = commonDao.findByQuery(" from Store s where  s.code=:code ",new String[] { "code"}, new Object[] { mdh });
		    			if(stores.size()>0){
		    				Store st=stores.get(0);
		    				p.setStore(st);
		    				p.setShipToName(st.getName());
		    				p.setShipToContact(st.getContact());
		    				p.setShipToAddress(st.getAddress());
		    				if(st.getLine()!=null){
		    					Line l=commonDao.load(Line.class, st.getLine().getId());
		    					p.setLineName(l.getLineName());
		    				}
		    			}
		    			p.setDescription(des);
		    			p.setRelatedBill1(khdh);
		    			p.setRelatedBill2(mddh);
		    			p.setRelatedBill3(leibie);
		    			p.setEquatedQuantity(ttsl);
		    			commonDao.store(p);
		    			PickTicketDetail ptd=EntityFactory.getEntity(PickTicketDetail.class);
		        		Item item=EntityFactory.getEntity(Item.class);
		        		List<Item> items=commonDao.findByQuery("from Item t where t.code=:code and t.disabled=0 and t.company.id=:id",
		    					new String[]{"code","id"},new Object[]{itemCode,s.getId()});
				    	if(items.size()>0){
				    		item=items.get(0);
				    		ptd.setPackageUnit(item.getMinPackageUnit());
				    		ptd.setCaCoefficient(item.getCAcoefficient()==null?0:item.getCAcoefficient());
				    	}else{
				    		throw new BusinessException(i+1+"行货品,"+itemCode+"不存在!");
					 }
				    	NewLotInfo newLotInfo=new NewLotInfo();
				    	newLotInfo.setPropC1(ph);
				    	newLotInfo.setPropD1(scrq);
				    	newLotInfo.setPropD2(dqr);
				    	ptd.setNewLotInfo(newLotInfo);
				    	ptd.setOrderQuantity(Double.parseDouble(zs));
				    	ptd.setLineNumber(xuhao);
				    	ptd.setItem(item);
//				    	ptd.setEquatedQuantity(ttsl);
//				    	ptd.setLocCode(kwh);
//				    	ptd.setCaCoefficient(caCoefficient);
				    	pickTicketManager.addPlanPickTicketDetail(p.getId(),ptd);
		        	}
			} catch (BiffException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	public void importHLXPickTicket(File file){
		try {
			Workbook workbook = Workbook.getWorkbook(file);
		    Sheet sheet = workbook.getSheet(workbook.getSheets().length-1);//得到excel第一页的内容
		    SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");//小写的mm表示的是分钟  
		    String cus=CompanyCode.HLX;
		    Structure s=null;
			List<Structure> ss=this.commonDao.findByQuery("from Structure s where s.code=:code",new String[]{"code"},new Object[]{cus});
			if(ss.size()>0){
        			s=ss.get(0);
			}else{
        			throw new BusinessException("代码为"+cus+"的货主不存在");
        		}
			List<BillType> billTypes = commonDao.findByQuery("from BillType b where  b.company.id =:company_id and b.type='SHIP'  ",
					new String[] { "company_id"}, new Object[] { s.getId() });
			BillType b=null;
			if(billTypes.size()>0){
				b=billTypes.get(0);
			}else{
				throw new BusinessException(s.getName()+"货主出库单类型没有，需要维护！");
			}
			List<Location> ls =  commonDao.findByQuery(" from Location o where o.warehouse.id=:id  and o.type ='SHIP'",
					new String[] { "id"},new Object[] {WarehouseHolder.getWarehouse().getId()});
			HashMap<String,String> map=new HashMap<String, String>();
			if(sheet.getColumns()<10){
				throw new BusinessException("该模版列数不正确，不能小于10");
			}
		    for (int i = 1; i <sheet.getRows(); i++) {
		    		int j=0;
		    		//凭证日期	物料	物料描述	Ship-to pa	Ship-to pa	销售凭证	请求交货日	   订单数量	       净价值	交货	PO 号码	单位	Order quan	工厂	库位	开票凭证	销售凭证	Credit Sta	     累计确认量	   交货量	    开票数量	Net Price	街道 (Ship to)	街道 (Sold to)	Loc.Sal. W	售达方	名称 (Sold t	DS	Res.Done	创建者	定价日期	Gross Weig	WUn	Rj	        Volume	Volume Uni
			    	String pzrq=sheet.getCell(j++,i).getContents().trim();
			    	String itemCode=sheet.getCell(j++,i).getContents().trim();
		     	String itemName=sheet.getCell(j++,i).getContents().trim();
		     	String mdh=sheet.getCell(j++,i).getContents().trim();
		     	String mdmc=sheet.getCell(j++,i).getContents().trim();
		     	String r1=sheet.getCell(j++,i).getContents().trim();
		     	String jhrq=sheet.getCell(j++,i).getContents().trim();
		     	String quantity=sheet.getCell(j++,i).getContents().trim();
		     	String jjz=sheet.getCell(j++,i).getContents().trim();
		     	String r2=sheet.getCell(j++,i).getContents().trim();
		     	String r3=sheet.getCell(j++,i).getContents().trim();
		     	if(pzrq!=null&&!pzrq.equals("")){
		     		pzrq=pzrq.replace(".", "-");
		     	}
		     	if(jhrq!=null&&!jhrq.equals("")){
		     		jhrq=jhrq.replace(".", "-");
		     	}
			    	if(itemCode==null||itemCode.equals("")){
		        		break;
		        	}
			    	List<Item> Items=this.commonDao.findByQuery("from Item s where s.code=:code",new String[]{"code"},new Object[]{itemCode});
			    	if(quantity==null||quantity.equals("")){
			    		quantity="0";
				}
				List<Item> items=this.commonDao.findByQuery("from Item i where i.code='"+itemCode+"'");
				if(items.size()>0){
					List<PickTicket> pts=this.commonDao.findByQuery("from PickTicket pt where pt.relatedBill1=:relatedBill1 ",
							new String[]{"relatedBill1"},new Object[]{r1});
					PickTicket pt=null;
					Item item=items.get(0);
					if(pts.size()>0){
						pt=pts.get(0);
						if(!map.containsKey(r1)){
							throw new BusinessException("第"+(i+1)+"行订单号"+r1+"已导入");
						}
					}else{
						map.put(r1, r1);
						pt=EntityFactory.getEntity(PickTicket.class);
						List<Store> stores = commonDao.findByQuery(" from Store s where  s.code=:code ",
								new String[] { "code"}, new Object[] { mdh});
						if(stores.size()>0){
							String address=sheet.getCell(23,i).getContents().trim();
							String person=sheet.getCell(24,i).getContents().trim();
							Store st=stores.get(0);
							if(st.getContact()==null&&person!=null&&!person.equals("")){
								Contact c=new Contact();
								c.setPerson(person);
								st.setContact(c);
							}
							if(st.getAddress()==null&&address!=null&&!address.equals("")){
								Address addr=new Address();
								addr.setAddress(address);
								st.setAddress(addr);
							}
							this.commonDao.store(st);
							pt.setStore(st);
							pt.setShipToName(st.getName());
							pt.setShipToContact(st.getContact());
							pt.setShipToAddress(st.getAddress());
						}
						pt.setOrderDate(convertDate(pzrq));
						if(pt.getOrderDate()==null){
							pt.setOrderDate(new Date());
						}
						pt.setRequireArriveDate(convertDate(jhrq));
						pt.setCompany(item.getCompany());
						pt.setCode(this.bussinessCodeManager.getCodeForYm("CP",5));
						pt.setWarehouse(WarehouseHolder.getWarehouse());
						pt.setStatus(PickTicketStatus.PRE_OPEN);
						pt.setRelatedBill1(r1);
						pt.setRelatedBill2(r2);
						pt.setRelatedBill3(r3);
						pt.setBillType(b);
						pt.setDock(ls.get(0)); 
						pt.setUserTracking();
						commonDao.store(pt);
					}
//						LotInfo lotInfo=new LotInfo();
//						lotInfo.setPropC1(propC1);
//						lotInfo.setPropD1(DateUtil.formatStrToDateYMD(d1));
//						if(lotInfo.getPropD1()==null){
//							lotInfo.setPropD1(DateUtil.formatStrToDateYMD01(d1));
//						}
					PackageUnit unit =item.getMinPackageUnit();
					PickTicketDetail d=EntityFactory.getEntity(PickTicketDetail.class);
					d.setPackageUnit(unit);
					d.setItem(item);
//					d.setNewLotInfo(lotInfo);
					d.setOrderQuantity(convertDouble(quantity));
//					d.setWeight(convertDouble(weight));
//					d.setRemark(remark);
//					d.setLocCode(ljkw);
					pickTicketManager.addPlanPickTicketDetail(pt.getId(),d);
					}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 importHLX2PickTicket(File file){
		try {
			Workbook workbook = Workbook.getWorkbook(file);
		    Sheet sheet = workbook.getSheet(workbook.getSheets().length-1);//得到excel第一页的内容
		    if(sheet.getColumns()<10){
				throw new BusinessException("该模版列数不正确，不能小于10");
			}
		    SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");//小写的mm表示的是分钟  
			String oldDriverName="";
			String oldLictrailer="";
			int j=0;
			Date shipDate=DateUtil.increaseDate(new Date(),"DAY",1);
			String d1=sheet.getCell(1,0).getContents().trim();
			if(d1!=null&&!d1.equals("")){
				d1=d1.substring(0, d1.indexOf("号"));
				Date d=DateUtil.formatStrToDateYMD(DateUtil.getYear()+"-"+d1);
				if(d!=null){
					shipDate=d;
				}
			}
		    for (int i = 2; i <sheet.getRows(); i++) {
		     	String r1=sheet.getCell(3,i).getContents().trim();
		     	String qty=sheet.getCell(7,i).getContents().trim();
		     	String driverName=sheet.getCell(8,i).getContents().trim();
		     	String lictrailer=sheet.getCell(9,i).getContents().trim();
		     	String remark=sheet.getCell(10,i).getContents().trim();
		     	if(r1==null||r1.equals("")){
		     		j++;
		     		continue;
		     	}else{
		     		j=0;
		     	}
		     	if(j>=10){
		     		break;
		     	}
		     	if(driverName==null||driverName.equals("")){
		     		driverName=oldDriverName;
		     	}else{
		    			Pattern p = Pattern.compile("\\s*|\t|\r|\n");
		    			Matcher m = p.matcher(driverName);
		    			driverName = m.replaceAll("");
		     		oldDriverName=driverName;
		     	}
		     	if(lictrailer==null||lictrailer.equals("")){
		     		lictrailer=oldLictrailer;
		     	}else{
		     		oldLictrailer=lictrailer;
		     	}
			    	if(qty==null||qty.equals("")){
			    		qty="0";
				}
				List<PickTicket> pts=this.commonDao.findByQuery("from PickTicket pt where pt.relatedBill1=:relatedBill1 ",
						new String[]{"relatedBill1"},new Object[]{r1});
				if(pts.size()>0){
					PickTicket pt=pts.get(0);
					if(pt.getStatus().equals(PickTicketStatus.PRE_OPEN)){
						pt.setStatus(PickTicketStatus.OPEN);
					}
					pt.setDescription(remark);
					pt.setLictrailer(lictrailer);
					pt.setLineName(driverName);
					pt.setDriverName(driverName);
					pt.setBOLQuantity(Double.parseDouble(qty));
					pt.setShipDate(shipDate);
					this.commonDao.store(pt);
				}else{
					throw new BusinessException("第"+(i+1)+"行订单号"+r1+"不存在");
				}
	        	}
		} catch (BiffException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void importPickTicket(File file,String type){
		Workbook workbook;
		try {
			workbook = Workbook.getWorkbook(file);
			Sheet sheet = workbook.getSheet(workbook.getSheets().length-1);
			if(sheet.getColumns()<11){
				throw new BusinessException("该模版列数不正确，不能小于11");
			}
			HashMap<String,String> map=new HashMap<String, String>();
			List<Location> ls =  commonDao.findByQuery(" from Location o where o.warehouse.id=:id  and o.type ='SHIP' and o.disabled=false",
						new String[] { "id"},new Object[] {WarehouseHolder.getWarehouse().getId()});
			 Location l =ls.get(0);
			 for (int i = 2; i <sheet.getRows(); i++) {
				 int j=0;
				 //货主名称（必填）	发货订单号	订单日期（必填）	货品代码（必填）	货品名称	数量（必填）	
				 //出库类型	批号	生产日期	地址	收货人	联系电话
			    String cus_name=sheet.getCell(j++,i).getContents().trim();
			 	String relatedBill1=sheet.getCell(j++,i).getContents().trim();
			 	if(relatedBill1==null||relatedBill1.equals("")){
			 		return;
			 	}
			 	String fhrq=sheet.getCell(j++,i).getContents().trim();
				String item_code=sheet.getCell(j++,i).getContents().trim();
				String item_name=sheet.getCell(j++,i).getContents().trim();
				String quantity=sheet.getCell(j++,i).getContents().trim();
				String cklx=sheet.getCell(j++,i).getContents().trim();
				String propC1=sheet.getCell(j++,i).getContents().trim();
				String d1=sheet.getCell(j++,i).getContents().trim();
				String address=sheet.getCell(j++,i).getContents().trim();
				String toName=sheet.getCell(j++,i).getContents().trim();
				String tel=sheet.getCell(j++,i).getContents().trim();
//				String remark=sheet.getCell(j++,i).getContents().trim();
				List<Structure> ss=this.commonDao.findByQuery("from Structure s where s.name='"+cus_name+"'");
				if(ss.size()<=0){
					throw new BusinessException("第"+(i+1)+"行货主"+cus_name+"不存在");
				}
				Structure s=ss.get(0);
				List<Item> items=this.commonDao.findByQuery("from Item i where i.code='"+item_code+"' and i.company.id="+s.getId());
				if(items.size()>0){
					Item item=items.get(0);
					List<PickTicket> pts=this.commonDao.findByQuery("from PickTicket pt where pt.relatedBill1=:relatedBill1 ",
							new String[]{"relatedBill1"},new Object[]{relatedBill1});
					PickTicket pt=null;
					if(pts.size()>0){
						pt=pts.get(0);
						if(!map.containsKey(relatedBill1)){
							throw new BusinessException("第"+(i+1)+"行订单号"+relatedBill1+"已导入");
						}
					}else{
						map.put(relatedBill1, relatedBill1);
						pt=EntityFactory.getEntity(PickTicket.class);
						pt.setOrderDate(convertDate(fhrq));
						pt.setCompany(item.getCompany());
						pt.setCode(this.bussinessCodeManager.getCodeForYm("CP",5));
						pt.setWarehouse(WarehouseHolder.getWarehouse());
						pt.setStatus(PickTicketStatus.OPEN);
						pt.setRelatedBill1(relatedBill1);
						List<BillType> bts =  commonDao.findByQuery(" from BillType o where o.type ='SHIP' ");
						pt.setBillType(bts.get(0));
						pt.setDock(l); 
						pt.setUserTracking();
						Address ad=new Address();
						ad.setAddress(address);
						Contact c=new Contact();
						c.setPerson(toName);
						c.setTelephone(tel);
						pt.setShipToAddress(ad);
						pt.setShipToContact(c);
						pt.setShipmentType(cklx);
//						pt.setDescription(remark);
						commonDao.store(pt);
					}
					NewLotInfo lotInfo=new NewLotInfo();
					lotInfo.setPropC1(propC1);
					lotInfo.setPropD1(DateUtil.formatDateYMDToStr(convertDate(d1)));
					PackageUnit unit =item.getMinPackageUnit();
					PickTicketDetail d=EntityFactory.getEntity(PickTicketDetail.class);
					d.setPackageUnit(unit);
					d.setItem(item);
					d.setNewLotInfo(lotInfo);
					d.setOrderQuantity(convertDouble(quantity));
//					d.setRemark(remark);
//					d.setLocCode(ljkw);
					pickTicketManager.addPlanPickTicketDetail(pt.getId(),d);
				}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 importPickTicket(File file){
		Workbook workbook;
		try {
			workbook = Workbook.getWorkbook(file);
			Sheet sheet = workbook.getSheet(workbook.getSheets().length-1);
			if(sheet.getColumns()<11){
				throw new BusinessException("该模版列数不正确，不能小于11");
			}
			HashMap<String,String> map=new HashMap<String, String>();
			List<Location> ls =  commonDao.findByQuery(" from Location o where o.warehouse.id=:id  and o.type ='SHIP' and o.disabled=false",
						new String[] { "id"},new Object[] {WarehouseHolder.getWarehouse().getId()});
			 Location l =ls.get(0);
			 for (int i = 2; i <sheet.getRows(); i++) {
				 int j=0;
				 //货主名称（必填）	发货订单号	订单日期（必填）	货品代码（必填）	货品名称	数量（必填）	
				 //出库类型	批号	生产日期	地址	收货人	联系电话
			    String cus_name=sheet.getCell(j++,i).getContents().trim();
			 	String relatedBill1=sheet.getCell(j++,i).getContents().trim();
			 	if(relatedBill1==null||relatedBill1.equals("")){
			 		return;
			 	}
			 	String fhrq=sheet.getCell(j++,i).getContents().trim();
				String item_code=sheet.getCell(j++,i).getContents().trim();
				String item_name=sheet.getCell(j++,i).getContents().trim();
				String quantity=sheet.getCell(j++,i).getContents().trim();
				String cklx=sheet.getCell(j++,i).getContents().trim();
				String propC1=sheet.getCell(j++,i).getContents().trim();
				String d1=sheet.getCell(j++,i).getContents().trim();
				String address=sheet.getCell(j++,i).getContents().trim();
				String toName=sheet.getCell(j++,i).getContents().trim();
				String tel=sheet.getCell(j++,i).getContents().trim();
//				String remark=sheet.getCell(j++,i).getContents().trim();
				List<Structure> ss=this.commonDao.findByQuery("from Structure s where s.name='"+cus_name+"'");
				if(ss.size()<=0){
					throw new BusinessException("第"+(i+1)+"行货主"+cus_name+"不存在");
				}
				Structure s=ss.get(0);
				List<Item> items=this.commonDao.findByQuery("from Item i where i.code='"+item_code+"' and i.company.id="+s.getId());
				if(items.size()>0){
					Item item=items.get(0);
					List<PickTicket> pts=this.commonDao.findByQuery("from PickTicket pt where pt.relatedBill1=:relatedBill1 ",
							new String[]{"relatedBill1"},new Object[]{relatedBill1});
					PickTicket pt=null;
					if(pts.size()>0){
						pt=pts.get(0);
						if(!map.containsKey(relatedBill1)){
							throw new BusinessException("第"+(i+1)+"行订单号"+relatedBill1+"已导入");
						}
					}else{
						map.put(relatedBill1, relatedBill1);
						pt=EntityFactory.getEntity(PickTicket.class);
						pt.setOrderDate(convertDate(fhrq));
						pt.setCompany(item.getCompany());
						pt.setCode(this.bussinessCodeManager.getCodeForYm("CP",5));
						pt.setWarehouse(WarehouseHolder.getWarehouse());
						pt.setStatus(PickTicketStatus.OPEN);
						pt.setRelatedBill1(relatedBill1);
						List<BillType> bts =  commonDao.findByQuery(" from BillType o where o.type ='SHIP' ");
						pt.setBillType(bts.get(0));
						pt.setDock(l); 
						pt.setUserTracking();
						Address ad=new Address();
						ad.setAddress(address);
						Contact c=new Contact();
						c.setPerson(toName);
						c.setTelephone(tel);
						pt.setShipToAddress(ad);
						pt.setShipToContact(c);
						pt.setShipmentType(cklx);
//						pt.setDescription(remark);
						commonDao.store(pt);
					}
					NewLotInfo lotInfo=new NewLotInfo();
					lotInfo.setPropC1(propC1);
					lotInfo.setPropD1(DateUtil.formatDateYMDToStr(convertDate(d1)));
					PackageUnit unit =item.getMinPackageUnit();
					PickTicketDetail d=EntityFactory.getEntity(PickTicketDetail.class);
					d.setPackageUnit(unit);
					d.setItem(item);
					d.setNewLotInfo(lotInfo);
					d.setOrderQuantity(convertDouble(quantity));
//					d.setRemark(remark);
//					d.setLocCode(ljkw);
					pickTicketManager.addPlanPickTicketDetail(pt.getId(),d);
				}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 importItem(File file){
		importItemVIM(file);
	}
	public void importStoreLine(File file){
		try {
			Workbook workbook = Workbook.getWorkbook(file);
			Sheet sheet = workbook.getSheet(0);
		    if(sheet.getColumns()<5){
				throw new BusinessException("该模版列数不正确，不能小于5");
			}
		    Map<String,String> map=new HashMap<String,String>();
		    boolean temp1=Boolean.FALSE;
		    boolean temp2=Boolean.FALSE;
		    if(sheet.getColumns()>=9){
		    		temp1=Boolean.TRUE;
		    }
		    if(sheet.getColumns()>=13){
	    			temp2=Boolean.TRUE;
		    }
		    for (int i = 1; i <sheet.getRows(); i++) {
		    	 	boolean delete=Boolean.FALSE;
			    	//货主代码	门店	名称	线路	顺序号	门店	名称	周四线路	顺序号	门店	名称	周日线路	顺序号	
			    int j=0;
			    	String cusCode=sheet.getCell(j++,i).getContents().trim();
			    	String storeCode=sheet.getCell(j++,i).getContents().trim();
			    	String storeName=sheet.getCell(j++,i).getContents().trim();
			    	String line=sheet.getCell(j++,i).getContents().trim();
			    	String seq=sheet.getCell(j++,i).getContents().trim();
			    	if(map==null||map.get(line+"0")==null||map.get(line+"0").equals("")){
		    			map.put(line+"0", line+"0");
		    			delete=Boolean.TRUE;
		        }else{
		        		delete=Boolean.FALSE;
		        }
			    	if(null==cusCode||cusCode.equals("")){
			    		return;
			    	}
		        	List<Structure> ss=this.commonDao.findByQuery("from Structure s where s.code=:code",
		        			new String[]{"code"},new Object[]{cusCode});
		        	if(ss.size()<=0){
		        		throw new BusinessException(i+1+"行货主"+cusCode+"不存在!");
		        	}
		        	Structure company=ss.get(0);
	        		String mes=this.saveStore(delete,storeCode, storeName, company, line, seq, "0");
	        		if(mes!=null&&!mes.equals("")){
		        		throw new BusinessException(i+1+"行线路"+line+"不存在!");
		        }
		        	if(temp1){
			        String storeCode1=sheet.getCell(j++,i).getContents().trim();
			        	String storeName1=sheet.getCell(j++,i).getContents().trim();
			        	String line1=sheet.getCell(j++,i).getContents().trim();
			        String seq1=sheet.getCell(j++,i).getContents().trim();
			        if(map==null||map.get(line1+"1")==null||map.get(line1+"1").equals("")){
			    			map.put(line1+"1", line1+"1");
			    			delete=Boolean.TRUE;
			        }else{
			        		delete=Boolean.FALSE;
			        }
			        String mess=this.saveStore(delete,storeCode1, storeName1, company, line1, seq1, "1");
			        if(mess!=null&&!mess.equals("")){
			        		throw new BusinessException(i+1+"行线路"+line1+"不存在!");
			        }
			    	}
			    	if(temp2){
			        String storeCode2=sheet.getCell(j++,i).getContents().trim();
			        String storeName2=sheet.getCell(j++,i).getContents().trim();
		        		String line2=sheet.getCell(j++,i).getContents().trim();
		        		String seq2=sheet.getCell(j++,i).getContents().trim(); 
		        		if(map==null||map.get(line2+"2")==null||map.get(line2+"2").equals("")){
				    		map.put(line2+"2", line2+"2");
				    		delete=Boolean.TRUE;
			        }
		        		String mess=this.saveStore(delete,storeCode2, storeName2, company, line2, seq2, "2");
		        		if(mess!=null&&!mess.equals("")){
			        		throw new BusinessException(i+1+"行线路"+line2+"不存在!");
			        }
			    	}
		    }
		} catch (BiffException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	int convertInt(String str){
		try {
			return Integer.parseInt(str);
		} catch (Exception e) {
			return 0;
		}
	}
	
	double convertDouble(String str){
		try {
			return Double.parseDouble(str);
		} catch (Exception e) {
			return 0;
		}
	}
	
	Date convertDate(String str){
		if(str!=null&&!str.equals("")&&str.length()>=2){
			if(!str.substring(0, 2).equals("20")){
				str="20"+str;
			}
		}
		Date date=DateUtil.formatStrToDateYMD(str);
		if(date==null){
			date=DateUtil.formatStrToDateYMD01(str);
		}
		return date;
	}
	
	private Item getItem(String itemCode,Long companyId){
		List<Item> its=commonDao.findByQuery("from Item t where t.code=:code and t.disabled=0 and t.company.id=:companyId",
				new String[]{"code","companyId"},new Object[]{itemCode,companyId});
		if(its.size()>0){
			return its.get(0);
		}else{
			return null;
		}
	}
	
	private String saveStore(Boolean delete,String code,String name,Structure company,String lineName,String seq,String type){
	 	if(code!=null&&!code.equals("")){
	 		List<Line> lines=commonDao.findByQuery("from Line l where l.lineName=:lineName",
					new String[]{"lineName"},new Object[]{lineName});
	    	 	if(lines.size()<=0){
	    	 		return lineName+"线路不存在!";
	    	 	}
	 		if(delete){
	 			if(type.equals("0")){
		 			List<Store> ss=this.commonDao.findByQuery("from Store s where s.line.id=:lineId",
		 					new String[]{"lineId"},new Object[]{lines.get(0).getId()});
		 			for(Store s:ss){
		 				s.setLine(null);
		 				s.setSequenceNo(0);
		 				this.commonDao.store(s);
		 			}
	 			}else if(type.equals("1")){
		 			List<Store> ss=this.commonDao.findByQuery("from Store s where s.lineThursday.id=:lineId",
		 					new String[]{"lineId"},new Object[]{lines.get(0).getId()});
		 			for(Store s:ss){
		 				s.setLineThursday(null);
		 				s.setSequenceNo1(0);
		 				this.commonDao.store(s);
		 			}
	 			}else if(type.equals("2")){
		 			List<Store> ss=this.commonDao.findByQuery("from Store s where s.lineSunday.id=:lineId",
		 					new String[]{"lineId"},new Object[]{lines.get(0).getId()});
		 			for(Store s:ss){
		 				s.setLineSunday(null);
		 				s.setSequenceNo2(0);
		 				this.commonDao.store(s);
		 			}
	 			}
	 		}
	    	 	List<Store> stores=commonDao.findByQuery("from Store s where s.code=:code and s.company.id=:id",
						new String[]{"code","id"},new Object[]{code,company.getId()});
	    	 	
	    	 	Store s=null;
	    	 	if(stores.size()>0){
	    	 		s=stores.get(0);
	    	 	}else{
	    	 		s=EntityFactory.getEntity(Store.class);
	    	 		s.setCode(code);
	    	 		s.setName(lineName);
	    	 		s.setCompany(company);
	    	 	}
	    	 	if(type.equals("0")){
	    	 		s.setLine(lines.get(0));
	    	 		s.setSequenceNo(convertInt(seq));
	    	 	}else if(type.equals("1")){
	    	 		s.setLineThursday(lines.get(0));
	    	 		s.setSequenceNo1(convertInt(seq));
	    	 	}else if(type.equals("2")){
	    	 		s.setLineSunday(lines.get(0));
	    	 		s.setSequenceNo2(convertInt(seq));
	    	 	}
	    	 	this.commonDao.store(s);
	 	}
	 	return null;
	}

	public void importItemVIM(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 gys=sheet.getCell(0,i).getContents();//供应商
				 //名称
				 String code=sheet.getCell(2,i).getContents();//代码
				 String name=sheet.getCell(3,i).getContents();//名称
				 String loc=sheet.getCell(4,i).getContents();//库位
				 List<Structure> ss=this.commonDao.findByQuery("from Structure  s where s.code='"+gys+"'");
				 if(ss.size()>0){
					 Structure st=ss.get(0);//it.company.id="+st.getId()+" and
					 List<Item> its=this.commonDao.findByQuery("from Item  it where  it.code='"+code+"' and it.warehouse="+WarehouseHolder.getWarehouse().getId());
					 Item it=null;
					 if(its.size()>0){
						it=its.get(0);
					}else{
						 it=EntityFactory.getEntity(Item.class);
						 it.setWarehouse(WarehouseHolder.getWarehouse());
						 it.setCompany(st);
						 it.setCode(code);
						 it.setUnit("件");
					}
					 it.setCompany(st);
					 it.setName(name);
					 List<Location> locs=this.commonDao.findByQuery("from Location  t where t.code='"+loc+"'");
					 if(locs.size()>0){
						 it.setLocation(locs.get(0));
					 }else{
						 throw new BusinessException(loc+"货位不存在!");
					 }
					 commonDao.store(it);
				 }else{
					 throw new BusinessException(gys+"供应商不存在!");
				 }
				 
				 
			 }
		} catch (BiffException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	public void importItemFdj(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();//代码
				 if(code==null||code.equals("")){
					 break;
				 }
				 List<Item> its=this.commonDao.findByQuery("from Item  it where  it.code='"+code+"' and it.warehouse="+WarehouseHolder.getWarehouse().getId());
				 Item it=null;
				 if(its.size()>0){
					it=its.get(0);
					it.setBeWeight(Boolean.TRUE);
					this.commonDao.store(it);
				 }else{
					 throw new BusinessException(code+"物料不存在!");
				 }
			 }
		} catch (BiffException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	public void importItemYbh(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();//代码
				 if(code==null||code.equals("")){
					 break;
				 }
				 List<Item> its=this.commonDao.findByQuery("from Item  it where  it.code='"+code+"' and it.warehouse="+WarehouseHolder.getWarehouse().getId());
				 Item it=null;
				 if(its.size()>0){
					it=its.get(0);
					it.setBeMachin(Boolean.TRUE);
					this.commonDao.store(it);
				 }else{
					 throw new BusinessException(code+"物料不存在!");
				 }
			 }
		} catch (BiffException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	public void importItemRelation(File file) {
		try {
			Workbook workbook = Workbook.getWorkbook(file);
			Sheet sheet = workbook.getSheet(0);
			Structure st=this.commonDao.get(Structure.class, new Long("1003"));
			 for (int i = 1; i <sheet.getRows(); i++) {
				 System.out.println(i);
				 //key	品番	纳入场所	门	箱种	收容数	备注
				 String key=sheet.getCell(0,i).getContents();
				 String item_code=sheet.getCell(1,i).getContents();
				 String site=sheet.getCell(2,i).getContents();
				 String door=sheet.getCell(3,i).getContents();
				 String caseType=sheet.getCell(4,i).getContents();
				 String qty=sheet.getCell(5,i).getContents();
				 String remark=sheet.getCell(6,i).getContents();
				 List<Item> its=this.commonDao.findByQuery("from Item  it where it.warehouse.id=1020 and it.code='"+item_code+"'");
				 ItemRelation ir=null;
				 if(its.size()>0){
					 Item it=its.get(0);
					 List<ItemRelation> irs=this.commonDao.findByQuery("from ItemRelation  it where it.item.id="+it.getId()+" and it.key='"+key+"'");
					 if(irs.size()>0){
						 ir=irs.get(0);
					 }else{
						 ir=EntityFactory.getEntity(ItemRelation.class);
					 }
					 ir.setKey(key);
					 ir.setItem(its.get(0));
					 ir.setSite(site);
					 ir.setDoor(door);
					 ir.setCaseType(caseType);
					 try {
						 ir.setQty(Integer.parseInt(qty));
					 } catch (Exception e) {
						 ir.setQty(1);
					 }
					 ir.setRemark(remark);
					 ir.setCreateBy(UserHolder.getUser().getName());
					 ir.setCreateDate(new Date());
					 this.commonDao.store(ir);
				}
				
			 }
		} catch (BiffException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	@Override
	public void importSupplier(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();//名称
				 List<Structure> sts=this.commonDao.findByQuery("from Structure  st where st.code='"+code+"'");
				 Structure st=null;
				 if(sts.size()>0){
					st=sts.get(0);
					continue;
				}else{
					st=EntityFactory.getEntity(Structure.class);
					st.setWarehouse(WarehouseHolder.getWarehouse());
					st.setCode(code);
					st.setName(name);
					st.setBeSupplier(Boolean.TRUE);
				}
				 commonDao.store(st);
			 }
		} catch (BiffException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	@Override
	public void importZone(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 s_code=sheet.getCell(3,i).getContents();//名称
				 if(code==null||code.equals("")){
					 break;
				 }
				 List<WarehouseArea> areas=this.commonDao.findByQuery("from WarehouseArea  t where t.code='"+code+"'");
				 WarehouseArea area=null;
				 if(areas.size()>0){
					 area=areas.get(0);
//					continue;
				}else{
					area=EntityFactory.getEntity(WarehouseArea.class);
					area.setWarehouse(WarehouseHolder.getWarehouse());
					area.setCode(code);
				}
				 if(s_code!=null&&!s_code.equals("")){
					 List<Structure> sts=this.commonDao.findByQuery("from Structure  st where st.code='"+s_code+"'");
					 if(sts.size()>0){
						 area.setSupplier(sts.get(0));
					 }else{
						 throw new BusinessException(s_code+"供应商不存在!");
					 }
				 }
				 area.setName(name);
				 commonDao.store(area);
			 }
		} catch (BiffException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	@Override
	public void importPlanShipDetail(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);
				 int j=0;
				 String xh=sheet.getCell(j++,i).getContents();
				 String gys=sheet.getCell(j++,i).getContents();
				 String mh=sheet.getCell(j++,i).getContents();
				 String pf=sheet.getCell(j++,i).getContents();
				 String cpmc=sheet.getCell(j++,i).getContents();
				 String hz=sheet.getCell(j++,i).getContents();
				 String srs=sheet.getCell(j++,i).getContents();
				 String xs=sheet.getCell(j++,i).getContents();
				 String shsl=sheet.getCell(j++,i).getContents();
				 String djrq=sheet.getCell(j++,i).getContents();
				 String ddbh=sheet.getCell(j++,i).getContents();
				 String bz=sheet.getCell(j++,i).getContents();
				 String nrzsr=sheet.getCell(j++,i).getContents();
				 String bhsl=sheet.getCell(j++,i).getContents();
				 String bhrq=sheet.getCell(j++,i).getContents();
				 String cksl=sheet.getCell(j++,i).getContents();
				 String ckrq=sheet.getCell(j++,i).getContents();
				 String key=sheet.getCell(j++,i).getContents();
				 List<PlanShipDetail> sds=commonDao.findByQuery("from PlanShipDetail p where p.key='"+key+"'");
				 if(sds.size()>0){
					 throw new BusinessException((i+1)+"行key已存在!");
				 }
				 List<Item> its=commonDao.findByQuery("from Item p where p.code='"+pf+"' and p.warehouse.id=1020");
				 if(its.size()<=0){
					 throw new BusinessException((i+1)+"行品番"+pf+"不存在!");
				 }
				 //序号	供应商	门号	品番	产品名称	何姿	收容数	箱数	送货数量	登记日期	定单编号	备注	纳入指示日	备货数量	备货日期	出库数量	出库日期	二维码
				 PlanShipDetail psd=EntityFactory.getEntity(PlanShipDetail.class);
				 psd.setXh(Integer.parseInt(xh));
				 psd.setGys(gys);
				 psd.setMh(mh);
				 psd.setItem(its.get(0));
				 psd.setHz(hz);
				 psd.setSrs(Integer.parseInt(srs.replace(",", "")));
				 psd.setXs(Integer.parseInt(xs));
				 psd.setShsl(Integer.parseInt(shsl));
				 psd.setDjrq(convertDate(djrq));
				 psd.setDdbh(ddbh);
				 psd.setNrzsr(convertDate(nrzsr));
				 psd.setCreateBy(UserHolder.getUser().getName());
				 psd.setCreateDate(new Date());
				 psd.setKey(key);
				 psd.setWarehouse(commonDao.get(Warehouse.class, 1020L));
				 commonDao.store(psd);
			 }
		} catch (BiffException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	public void importASNVMI2(File file){
		Workbook workbook;
		try {
			workbook = Workbook.getWorkbook(file);
			Sheet sheet = workbook.getSheet(0);//得到excel第一页的内容
			if(sheet.getColumns()<3){
				throw new BusinessException("该模版列数不正确，不能小于3");
			}
			 HashMap<String,String> map=new HashMap<String, String>();
			 List<Location> ls =  commonDao.findByQuery(" from Location o where o.warehouse.id=:id  and o.type ='RECEIVE' and o.disabled=false",
						new String[] { "id"},new Object[] {WarehouseHolder.getWarehouse().getId()});
			 List<BillType> bts =  commonDao.findByQuery(" from BillType o where o.code='ZCRK'  and o.type ='RECEIVE'");
			 Location l =ls.get(0);
			 BillType bt=bts.get(0);
			 for (int i = 1; i <sheet.getRows(); i++) {
				 System.out.println("======"+i);
				 //订单号（ASN）货品自编码 数量
			 	String relatedBill1=sheet.getCell(0,i).getContents().trim();
			 	if(relatedBill1==null||relatedBill1.equals("")){
			 		return;
			 	}
				String item_code=sheet.getCell(1,i).getContents().trim();
				String quantity=sheet.getCell(2,i).getContents().trim();
				String zone_code="外协厂-"+sheet.getCell(0,i).getContents().trim();
				List<Item> items=this.commonDao.findByQuery("from Item i where i.code='"+item_code+"' and i.warehouse.id="+WarehouseHolder.getWarehouse().getId());
				if(items.size()>0){
					List<ASN> asns=this.commonDao.findByQuery("from ASN a where a.relatedBill1=:relatedBill1 ",
							new String[]{"relatedBill1"},new Object[]{relatedBill1});
					ASN asn=null;
					Item item=items.get(0);
					if(asns.size()>0){
						asn=asns.get(0);
						if(!map.containsKey(relatedBill1)){
							throw new BusinessException("第"+(i+1)+"行订单号已导入");
						}
					}else{
						map.put(relatedBill1, relatedBill1);
						List<WarehouseArea> zones =  commonDao.findByQuery(" from WarehouseArea o where o.warehouse.id=:id  and o.name ='"+zone_code+"' and o.disabled=false",
								new String[] { "id"},new Object[] {WarehouseHolder.getWarehouse().getId()});
						if(zones.size()<=0){
						    throw new BusinessException("第"+(i+1)+"行"+zone_code);
						}
						asn=EntityFactory.getEntity(ASN.class);
						asn.setZone(zones.get(0));
						asn.setOrderDate(new Date());
						asn.setCompany(item.getCompany());
						asn.setCode(this.bussinessCodeManager.getCodeForYm("RP",3));
						asn.setWarehouse(WarehouseHolder.getWarehouse());
						asn.setStatus(ASNStatus.ACTIVE);
						asn.setRelatedBill1(relatedBill1);
						asn.setBillType(bt);
						asn.setDock(l); 
						asn.setUserTracking();
						commonDao.store(asn);
					}
					ASNDetail ad=EntityFactory.getEntity(ASNDetail.class);
					ad.setItem(item);
					ad.setExpectedQuantity(Double.parseDouble(quantity));
					ad.setExpectedQtyOfMasterUnit(ad.getExpectedQuantity());
					ad.setAsn(asn);
					this.commonDao.store(ad);
					asn.setExpectedQuantity(asn.getExpectedQuantity()+Double.parseDouble(quantity));
					this.commonDao.store(asn);
//					asnManager.addASNDetail(asn.getId(),ad);
				}else{
					throw new BusinessException("第"+(i+1)+"行货品代码不存在");
				}
			 }
		} catch (BiffException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	@Override
	public void importDesignList(File file) {
		try {
			//序号	変通No.11桁	设变号	一括番号	旧品番	旧品名	关联设变	新品番	新品名	供应商代码	供应商名称	A/C	加工内容	品名(中文)	单用	订货要否	纳所	产量	T型式代码	T型式名	旧品处理	系统实施日	创建人	创建时间
			//No	変通no.11桁	设变号	一括番号	关联设变	KIND实施日	旧品番	新品番	品名	AC	加工内容	单用	订货要否	门号	纳所	计划使用量	供应商名称	供应商代码	机种	T形式代码	T形式名	构成	顺序	设变通知摘要	旧品处理	备注

			Workbook workbook = Workbook.getWorkbook(file);
			Sheet sheet = workbook.getSheet(0);//得到excel第一页的内容
			for (int i = 2; i <sheet.getRows(); i++) {
				int j=0;
				 String no=sheet.getCell(j++,i).getContents().trim();//序号
				 String designNo=sheet.getCell(j++,i).getContents().trim();//変通No.11桁
				 String code=sheet.getCell(j++,i).getContents().trim();//设变号
				 String designOneNo=sheet.getCell(j++,i).getContents().trim();//一括番号
				 String releDesign=sheet.getCell(j++,i).getContents().trim();//关联设变
				 String putDate=sheet.getCell(j++,i).getContents().trim();//系统实施日
				 String oldItemCode=sheet.getCell(j++,i).getContents().trim();//旧品番
				 String newItemCode=sheet.getCell(j++,i).getContents().trim();//新品番
				 String newItemName=sheet.getCell(j++,i).getContents().trim();//新品名
				 String quantity=sheet.getCell(j++,i).getContents().trim().equals("")?"0":sheet.getCell(j-1,i).getContents().trim();//A/C
				 String content=sheet.getCell(j++,i).getContents().trim();//加工内容				 
//				 String pm=sheet.getCell(j++,i).getContents().trim();//品名(中文)
				 String sepQty=sheet.getCell(j++,i).getContents().trim().equals("")?"0":sheet.getCell(j-1,i).getContents().trim();//单用
				 String isbeimportant=sheet.getCell(j++,i).getContents().trim().equals("")?"0":sheet.getCell(j-1,i).getContents().trim();//订货要否
				 String mh=sheet.getCell(j++,i).getContents().trim();//门号
				 String institute=sheet.getCell(j++,i).getContents().trim();//纳所			
				 String outputQty=sheet.getCell(j++,i).getContents().trim().equals("")?"0":sheet.getCell(j-1,i).getContents().trim();//产量
				 String supplierName=sheet.getCell(j++,i).getContents().trim();//供应商名称
				 String supplierCode=sheet.getCell(j++,i).getContents().trim();//供应商代码
				 String jz=sheet.getCell(j++,i).getContents().trim();//机种
				 String bigItemCode=sheet.getCell(j++,i).getContents().trim();//T型式代码
				 j++;//T型式名
				 j++;//构成
				 j++;//顺序
				 String sbtzzy=sheet.getCell(j++,i).getContents().trim();//设变通知摘要
				 String handle=sheet.getCell(j++,i).getContents().trim();//旧品处理
				 String remark=sheet.getCell(j++,i).getContents().trim();//备注
				 if(no==null || no.length()<=0){
					 break;
				 }
				 
				 Item oldItem=null;
				 if(oldItemCode!=null&&oldItemCode.length()>0){
					 List<Item> oldItems=this.commonDao.findByQuery(" from Item item where item.code='"+oldItemCode+"'  and item.disabled=0 and item.warehouse.id="+WarehouseHolder.getWarehouse().getId()+" ");
					 if(oldItems.size()>0){
						 oldItem=oldItems.get(0);
					 }
				 }
				 
				 Item newItem=null;
				 if(newItemCode!=null&&newItemCode.length()>0){
					 List<Item> newItems=this.commonDao.findByQuery(" from Item item where item.code='"+newItemCode+"'  and item.disabled=0 and item.warehouse.id="+WarehouseHolder.getWarehouse().getId()+" ");
					 if(newItems.size()>0){
						 newItem=newItems.get(0);
					 }
				 }
				 
				 BigItem bigItem=null;
				 if(newItemCode!=null&&newItemCode.length()>0){
					 List<BigItem> BigItems=this.commonDao.findByQuery(" from BigItem bt where bt.code='"+bigItemCode+"' ");
					 if(BigItems.size()>0){
						 bigItem=BigItems.get(0);
					 }
				 }
				 boolean beimportant=false;
				 if(isbeimportant.equals("1")){
					 beimportant=true;
				 }
				 DesignList designList=EntityFactory.getEntity(DesignList.class);
				 designList.setDesignNo(designNo);
				 designList.setCode(code);
				 designList.setDesignOneNo(designOneNo);
				 designList.setOldItem(oldItem);
				 designList.setOldItemCode(oldItemCode);
				 designList.setReleDesign(releDesign);
				 designList.setNewItem(newItem);
				 designList.setNewItemCode(newItemCode);
				 designList.setSupplierCode(supplierCode);
				 designList.setSupplierName(supplierName);
				 designList.setQuantity(Double.parseDouble(quantity));
				 designList.setContent(content);
				 designList.setSepQty(Double.parseDouble(sepQty));
				 designList.setBeimportant(beimportant);
				 designList.setInstitute(institute);
				 designList.setOutputQty(Double.parseDouble(outputQty));
				 designList.setBigItem(bigItem);
				 designList.setHandle(handle);
				 designList.setPutDate(putDate);
				 designList.setCreatePeople(UserHolder.getUser().getName());
				 designList.setCreateDate(new Date());
				 designList.setSbtzzy(sbtzzy);
				 designList.setJz(jz);
				 designList.setRemark(remark);
				 commonDao.store(designList);
				 System.out.println((i+1));
			}
			
		} catch (BiffException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}catch (Exception e){
			e.printStackTrace();
		}
	}

	@Override
	public void importPrint(File file) {
		try {
			Workbook workbook = Workbook.getWorkbook(file);
			Sheet sheet = workbook.getSheet(0);//得到excel第一页的内容
			String name=(new Date()).getTime()+"";
			List<CommonCode> cs=this.commonDao.findByQuery("from CommonCode c where c.codeType='库位导入打印'");
			this.commonDao.deleteAll(cs);
			for (int i = 1; i <sheet.getRows(); i++) {
				 String code=sheet.getCell(0,i).getContents().trim();
				 if(code==null || code.length()<=0){
					 break;
				 }
				 CommonCode c=EntityFactory.getEntity(CommonCode.class);
				 c.setCode(name+i);
				 c.setName(code);
				 c.setCodeType("库位导入打印");
				 c.setOperator(UserHolder.getUser().getName());
				 c.setOperateDate(new Date());
				 commonDao.store(c);
				 System.out.println((i+1));
			}
			
		} catch (BiffException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}catch (Exception e){
			e.printStackTrace();
		}
		
	}
	
	@Override
	public void importPfPrint(File file) {
		try {
			Workbook workbook = Workbook.getWorkbook(file);
			Sheet sheet = workbook.getSheet(0);//得到excel第一页的内容
			List<Province> ps=this.commonDao.findByQuery("from Province p");
			this.commonDao.deleteAll(ps);
			for (int i = 1; i <sheet.getRows(); i++) {
				int j=0;
				 String code=sheet.getCell(j++,i).getContents().trim();
				 String name=sheet.getCell(j++,i).getContents().trim();
				 String bonded=sheet.getCell(j++,i).getContents().trim();
				 String locCode=sheet.getCell(j++,i).getContents().trim();
				 String hz=sheet.getCell(j++,i).getContents().trim();
				 String srs=sheet.getCell(j++,i).getContents().trim();
				 if(code==null || code.length()<=0){
					 break;
				 }
				 Province p=EntityFactory.getEntity(Province.class);
				 p.setCode(code);
				 p.setName(name);
				 p.setBonded(bonded);
				 p.setLocCode(locCode);
				 p.setHz(hz);
				 p.setSrs(srs);
				 p.setCreatDate(new Date());
				 p.setCreatPeople(UserHolder.getUser().getName());
				 this.commonDao.store(p);
				 System.out.println((i+1));
			}
			
		} catch (BiffException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}catch (Exception e){
			e.printStackTrace();
		}
		
	}
	
	@Override
	public void importSgzs(File file) {
		try {
			
			Workbook workbook = Workbook.getWorkbook(file);
			Sheet sheet = workbook.getSheet(0);
			HashMap<String,String> map=new HashMap<String, String>();
			BillType bill=commonDao.load(BillType.class, new Long("10"));
			 for (int i = 1; i <sheet.getRows(); i++) {
				//指示日	指示单号	品番	品番名称	AC	加工内容	税别	指示数	指示备注	出库库区	入库库区 制造库位
				 int j=0;
				 String zsr=sheet.getCell(j++,i).getContents();
				 String zsdh=sheet.getCell(j++,i).getContents();
				 String pf=sheet.getCell(j++,i).getContents();
				 String pfmc=sheet.getCell(j++,i).getContents();
				 String ac=sheet.getCell(j++,i).getContents();
				 String jgnr=sheet.getCell(j++,i).getContents();
				 String sb=sheet.getCell(j++,i).getContents();
				 String zss=sheet.getCell(j++,i).getContents();
				 String zsbz=sheet.getCell(j++,i).getContents();
				 String ckkq=sheet.getCell(j++,i).getContents();
				 String rkkq=sheet.getCell(j++,i).getContents();
				 String zzkw=sheet.getCell(j++,i).getContents();
				 if(pf==null||pf.equals("")){
				 	continue;
				 }
				 storeSgzs(map, bill, i, zsr, zsdh, pf, ac, sb, jgnr, zss, zsbz, ckkq, rkkq, zzkw);
			 }
		} catch (BiffException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	@Override
	public void importSgzsKams(File file) {
		try {
			Workbook workbook = Workbook.getWorkbook(file);
			Sheet sheet = workbook.getSheet(0);
			HashMap<String,String> map=new HashMap<String, String>();
			BillType bill=commonDao.load(BillType.class, new Long("10"));
			 String zsdh=bussinessCodeManager.getCodeForYm("ZS",3);
			 for (int i = 1; i <sheet.getRows(); i++) {
//				 //指示日	品番	AC	加工内容	制造库位	税别	指示数	指示备注	出库库区	入库库区
				 int j=0;
				 String zsr=sheet.getCell(j++,i).getContents();
				 String pf=sheet.getCell(j++,i).getContents();
				 String ac=sheet.getCell(j++,i).getContents();
				 String jgnr=sheet.getCell(j++,i).getContents();
				 String zzkw=sheet.getCell(j++,i).getContents();
				 String sb=sheet.getCell(j++,i).getContents();
				 String zss=sheet.getCell(j++,i).getContents();
				 String zsbz=sheet.getCell(j++,i).getContents();
				 String ckkq=sheet.getCell(j++,i).getContents();
				 String rkkq=sheet.getCell(j++,i).getContents();
				 if(pf==null||pf.equals("")){
					 continue;
				 }
				 //指示日	品番	AC	加工内容	制造库位	税别	指示数	指示备注	出库库区	入库库区
				 storeSgzs(map, bill, i, zsr, zsdh, pf, ac, sb, jgnr, zss, zsbz, ckkq, rkkq, zzkw);
			 }
		} catch (BiffException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	public void storeSgzs(HashMap<String,String> map,BillType bill,int i,String zsr,String zsdh,String pf,String ac,String sb,String jgnr,String zss,String zsbz,String ckkq,String rkkq,String zzkw){
		 if(zzkw==null||zzkw.equals("")){
			 zzkw="0";
		 }
		 List<Item> its=commonDao.findByQuery("from Item it where it.code='"+pf+"'");
		 if(its.size()<=0){
			 throw new BusinessException((i+1)+"行"+pf+"品番不存在!");
		 }
		 List<WarehouseArea> zone2s=this.commonDao.findByQuery("from WarehouseArea z where z.code=:code",new String[]{"code"},new Object[]{ckkq});
		 if(zone2s.size()<=0){
			 throw new BusinessException((i+1)+"行"+ckkq+"出库库区不存在!");
		 }
		 List<WarehouseArea> zone1s=this.commonDao.findByQuery("from WarehouseArea z where z.code=:code",new String[]{"code"},new Object[]{rkkq});
		 if(zone1s.size()<=0){
			 throw new BusinessException((i+1)+"行"+rkkq+"入库库区不存在!");
		 }
	 	
	 	 List<Location> los=this.commonDao.findByQuery("from Location z where z.code=:code",new String[]{"code"},new Object[]{zzkw});
		 if(los.size()<=0){
			 throw new BusinessException((i+1)+"行"+zzkw+"制造库位不存在!");
		 }
	 	List<PlanPickTicket> pts=this.commonDao.findByQuery("from PlanPickTicket pt where pt.code=:zsdh ",
				new String[]{"zsdh"},new Object[]{zsdh});
	 	PlanPickTicket pt=null;
		if(pts.size()<=0){
			map.put(zsdh, zsdh);
			pt=EntityFactory.getEntity(PlanPickTicket.class);
			pt.setWarehouse(WarehouseHolder.getWarehouse());
			pt.setStatus(PickTicketStatus.OPEN);
			pt.setBillType(bill);
			pt.setCode(zsdh);
			pt.setRelatedBill1("指示单");
            pt.setZone1(zone1s.get(0));
            pt.setZone2(zone2s.get(0));
            pt.setOrderDate(new Date());
            pt.setDescription(zsbz);
            pt.setUpdateTime(new Date());
            pt.setUserName(UserHolder.getUser().getName());
			if(pt.getCompany()==null) {
				pt.setCompany(commonDao.load(Structure.class, 1002L));
			}
		}else{
			if(!map.containsKey(zsdh)){
				throw new BusinessException("第"+(i+1)+"行订单号"+zsdh+"已导入");
			}
			pt=pts.get(0);
		}
		this.commonDao.store(pt);
		 //明细
		Item it=its.get(0);
		PlanPickDetail ptd=EntityFactory.getEntity(PlanPickDetail.class);
		ptd.setItem(it);
//		try {
			ptd.setOrderQuantity(Double.parseDouble(zss));
//		} catch (BusinessException e) {
//			throw new BusinessException("第"+(i+1)+"行指示数不正确");
//		}
		
		ptd.setZone1(pt.getZone1());
		ptd.setZone2(pt.getZone2());
		ptd.setDescription(zsbz);
		List<Pinfan> pf1=commonDao.findByQuery(" from Pinfan p where p.item.id="+it.getId()+" and p.zone.id="+pt.getZone2().getId());
//		if(pf1.size()>0) {
//			Pinfan pf2=pf1.get(0);
			ptd.setBonded(sb);
			ptd.setSpecs(ac);
			ptd.setContent(jgnr);
//			ptd.setHezi(hz);
//		}
		ptd.setPlanPickTicket(pt);
		ptd.setZzkw(los.get(0));
		commonDao.store(ptd);
	}


}
