package com.tax.file.utils.invoice;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.tax.file.model.FinCuspay;
import com.tax.file.model.FinCuspayDetail;
import com.tax.file.model.FinInvoice;
import com.tax.file.model.FinInvoiceDetail;
import com.tax.file.model.FinOldcar;
import com.tax.file.model.FinVehicle;
import com.yxcheng.token.utils.ExcelReadUtil;
import com.yxcheng.token.utils.StringUtil;
/** 
 * excel读写工具类 
 * 
 * */ 
public class FileExcelReadUtil extends ExcelReadUtil {
	
    private static final Logger logger = LoggerFactory.getLogger(FileExcelReadUtil.class);


	 /** 
     * 读入excel文件，解析后返回发票信息
     * @param inputStream 
     * @param invType 发票类型
     * @param tkFileId tk_file的记录ID
     * @throws IOException  
     */  
    public static Map<String,List> readInvoiceExcel(InputStream inputStream,String invType,int tkFileId) throws Exception{  
    	logger.info("ReadFileTask readInvoiceExcel tkFile id:"+tkFileId);
        InvoiceCellRead cellRead = InvoiceCellReadFactory.getInstance(invType);
        
        if(cellRead == null){
        	logger.error("ReadFileTask readInvoiceExcel get InvoiceCellRead is null:"+tkFileId);
        	return null;
        }
    	
    	//获得Workbook工作薄对象  
        Workbook workbook = getWorkBook(inputStream); 
        Map<String,List> result = new HashMap<String,List>();
        
        List<FinInvoice> invoiceList = new ArrayList<FinInvoice>();
        List<FinVehicle> vehicleList = new ArrayList<FinVehicle>();
        List<FinOldcar> oldCarList = new ArrayList<FinOldcar>();
        List<FinCuspay> cuspayList = new ArrayList<FinCuspay>();
        List<FinInvoiceDetail> invoiceDetailList = new ArrayList<FinInvoiceDetail>();
        List<FinCuspayDetail> cuspayDetailList = new ArrayList<FinCuspayDetail>();
         
        if(workbook != null){  
            for(int sheetNum = 0;sheetNum < workbook.getNumberOfSheets();sheetNum++){  
                //获得当前sheet工作表  
                Sheet sheet = workbook.getSheetAt(sheetNum);  
                if(sheet == null){  
                    continue;  
                }  
                
                if(sheetNum == 2){//只读取前2个sheet页
                	break;
                }
                //获得当前sheet的开始行  
                int firstRowNum  = sheet.getFirstRowNum();  
                //获得当前sheet的结束行  
                int lastRowNum = sheet.getLastRowNum();  
                //循环除了第一行的所有行  
                for(int rowNum = firstRowNum+2;rowNum <= lastRowNum;rowNum++){  
                    //获得当前行  
                    Row row = sheet.getRow(rowNum);  
                    if(row == null){  
                        break;  
                    }  
                     
                    if(sheetNum == 0){
                    	FinInvoice invoice = null;
                    	FinVehicle vehicle = null;
                    	FinOldcar oldcar = null;
                    	FinCuspay cuspay = null;
                    	if("03".equals(invType)){
                    		vehicle = getVehicle(row,invType,tkFileId);
                    	}else if("15".equals(invType)){
                    		oldcar = getOldcar(row, invType, tkFileId);
                    	}else if("17".equals(invType)){//海关缴款书
                    		cuspay = getCuspay(row, invType, tkFileId);
                    	}else{
                    		invoice = getFinvoice(row,invType,tkFileId,cellRead);
                    	}
                    	
                    	if(invoice != null){
                    		invoiceList.add(invoice);
                    	}
                    	if(vehicle != null){
                    		vehicleList.add(vehicle);
                    	}
                    	if(oldcar != null){
                    		oldCarList.add(oldcar);
                    	}
                    	if(cuspay != null){
                    		cuspayList.add(cuspay);
                    	}
                    }else if(sheetNum == 1){
                    	if("17".equals(invType)){
                    		/*FinCuspayDetail cuspayDetail = getCuspayDetail(row);
                        	if(cuspayDetail != null){
                        		cuspayDetailList.add(cuspayDetail);
                        	}*/
                    	}else{
                    	   /*	FinInvoiceDetail invoiceDetail = getFinvoiceDetail(row,cellRead);
                        	if(invoiceDetail != null){
                        		invoiceDetailList.add(invoiceDetail);
                        	}*/
                    	}
                    }
                    
                }  
            }  
          
        }  
        
        result.put("invoiceList", invoiceList);
        result.put("vehicleList", vehicleList);
        result.put("oldCarList", oldCarList);
        result.put("cuspayList", cuspayList);
        result.put("invoiceDetailList", invoiceDetailList);
        result.put("cuspayDetailList", cuspayDetailList);
        return result;  
    }  
    
    /** 
     * 根据行获取机动车发票主信息
     * @param row 
     * @param invType 
     * @param tkFileId 
     * @param cellRead 单元格读取器
     * @throws IOException  
     */  
    public static FinVehicle getVehicle(Row row,String invType,int tkFileId) throws Exception{
    	
    	  row = checkNullRow(row);
          if(row == null){
         	 return null;
          }
    	
    	//获得当前行的开始列  
        int firstCellNum = row.getFirstCellNum();  
        //获得当前行的列数  
        int lastCellNum = row.getPhysicalNumberOfCells();  
          
        FinVehicle invoice = new FinVehicle();
        invoice.setCreateBy("systemauto");
        invoice.setCreateDate(new Date());
        invoice.setTkFileId(tkFileId);
        
        //循环当前行  
        for(int cellNum = firstCellNum+1; cellNum < lastCellNum;cellNum++){  
            Cell cell = row.getCell(cellNum);  
            String cellValue = getCellValue(cell);
            CarInvoiceCellRead.readCellVehicle(invoice, cellNum, cellValue);
        }  
        
        if(StringUtil.isEmpty(invoice.getInvNum())){
        	invoice = null;
        }
        
        return invoice;
    }
    
    /** 
     * 根据行获取二手车发票主信息
     * @param row 
     * @param invType 
     * @param tkFileId 
     * @param cellRead 单元格读取器
     * @throws IOException  
     */  
    public static FinOldcar getOldcar(Row row,String invType,int tkFileId) throws Exception{
    	
    	  row = checkNullRow(row);
          if(row == null){
         	 return null;
          }
    	
    	//获得当前行的开始列  
        int firstCellNum = row.getFirstCellNum();  
        //获得当前行的列数  
        int lastCellNum = row.getPhysicalNumberOfCells();  
          
        FinOldcar invoice = new FinOldcar();
        invoice.setCreateBy("systemauto");
        invoice.setCreateDate(new Date());
        invoice.setTkFileId(tkFileId);
        
        //循环当前行  
        for(int cellNum = firstCellNum+1; cellNum < lastCellNum;cellNum++){  
            Cell cell = row.getCell(cellNum);  
            String cellValue = getCellValue(cell);
            OldCarInvoiceCellRead.readCellInvoice(invoice, cellNum, cellValue);
        }  
        
        if(StringUtil.isEmpty(invoice.getInvNum())){
        	invoice = null;
        }
        
        return invoice;
    }
    
    /** 
     * 根据行获取海关缴款书发票主信息
     * @param row 
     * @param invType 
     * @param tkFileId 
     * @param cellRead 单元格读取器
     * @throws IOException  
     */  
    public static FinCuspay getCuspay(Row row,String invType,int tkFileId) throws Exception{
    	
    	  row = checkNullRow(row);
          if(row == null){
         	 return null;
          }
    	
    	//获得当前行的开始列  
        int firstCellNum = row.getFirstCellNum();  
        //获得当前行的列数  
        int lastCellNum = row.getPhysicalNumberOfCells();  
          
        FinCuspay cuspay = new FinCuspay();
        cuspay.setCreateBy("systemauto");
        cuspay.setCreateDate(new Date());
        cuspay.setTkFileId(tkFileId);
        cuspay.setDelFlag("0");
        
        //循环当前行  
        for(int cellNum = firstCellNum+1; cellNum < lastCellNum;cellNum++){  
            Cell cell = row.getCell(cellNum);  
            String cellValue = getCellValue(cell);
            FinCuspayCellRead.readCellCuspay(cuspay, cellNum, cellValue);
        }  
        
        if(StringUtil.isEmpty(cuspay.getPayNo())){
        	cuspay = null;
        }
        
        return cuspay;
    }
    
    /** 
     * 根据行获取发票主信息
     * @param row 
     * @param invType 
     * @param tkFileId 
     * @param cellRead 单元格读取器
     * @throws IOException  
     */  
    public static FinInvoice getFinvoice(Row row,String invType,int tkFileId,InvoiceCellRead cellRead) throws Exception{
    	
    	  row = checkNullRow(row);
          if(row == null){
         	 return null;
          }
    	
    	//获得当前行的开始列  
        int firstCellNum = row.getFirstCellNum();  
        //获得当前行的列数  
        int lastCellNum = row.getPhysicalNumberOfCells();  
          
        FinInvoice invoice = new FinInvoice();
        //invoice.setCreateBy("systemauto");
        invoice.setCreateDate(new Date());
        invoice.setInvtype(invType);
        //invoice.setTkFileId(tkFileId);
        //invoice.setDelFlag("0");
        
        //循环当前行  
        for(int cellNum = firstCellNum+1; cellNum < lastCellNum;cellNum++){  
            Cell cell = row.getCell(cellNum);  
            String cellValue = getCellValue(cell);
            cellRead.readCellInvoice(invoice, cellNum, cellValue);
        }  
        
        if(StringUtil.isEmpty(invoice.getInvnum())){
        	invoice = null;
        }
        
        return invoice;
    }
    
    /** 
     * 根据行获取发票明细信息
     * @param row 
     * @throws IOException  
     */  
    public static FinCuspayDetail getCuspayDetail(Row row) throws Exception{
    	
         row = checkNullRow(row);
         if(row == null){
        	 return null;
         }
       
    	//获得当前行的开始列  
        int firstCellNum = row.getFirstCellNum();  
        //获得当前行的列数  
        int lastCellNum = row.getPhysicalNumberOfCells();  
        FinCuspayDetail cuspayDetail = new FinCuspayDetail();
          
        //循环当前行  
        for(int cellNum = firstCellNum; cellNum < lastCellNum;cellNum++){  
            Cell cell = row.getCell(cellNum);  
            String cellValue = getCellValue(cell);
            FinCuspayCellRead.readCellDetail(cuspayDetail, cellNum, cellValue);
        }  
        
        if(StringUtil.isEmpty(cuspayDetail.getPayNo())){
        	cuspayDetail = null;
        }
        
        return cuspayDetail;
    }
    
    
    /** 
     * 根据行获取发票明细信息
     * @param row 
     * @param cellRead 单元格读取器
     * @throws IOException  
     */  
    public static FinInvoiceDetail getFinvoiceDetail(Row row,InvoiceCellRead cellRead) throws Exception{
    	
         row = checkNullRow(row);
         if(row == null){
        	 return null;
         }
         
         boolean flag = false;
         Cell cellInvdate = row.getCell(3);  
         String cellValueInvdate = getCellValue(cellInvdate);
         if(StringUtil.isNotEmpty(cellValueInvdate) && cellValueInvdate.trim().length() == 10){
        	 flag = true;
         }
         
    	//获得当前行的开始列  
        int firstCellNum = row.getFirstCellNum();  
        //获得当前行的列数  
        int lastCellNum = row.getPhysicalNumberOfCells();  
        FinInvoiceDetail invoiceDetail = new FinInvoiceDetail();
          
        //循环当前行  
        for(int cellNum = firstCellNum; cellNum < lastCellNum;cellNum++){  
            Cell cell = row.getCell(cellNum);  
            String cellValue = getCellValue(cell);
            cellRead.readCellDetail(invoiceDetail, cellNum, cellValue,flag);
        }  
        
        if(StringUtil.isEmpty(invoiceDetail.getInvNum())){
        	invoiceDetail = null;
        }else{
        	invoiceDetail.setKindnum(invoiceDetail.getInvKind()+invoiceDetail.getInvNum());
        }
        
        return invoiceDetail;
    }
    /** 
     * 校验行是否为空
     * @param row 
     */ 
    public static Row checkNullRow(Row row){
    	 Cell cellKind = row.getCell(1);
    	 if(cellKind == null){
    		 return null;
    	 }
    	 
         String value = cellKind.getStringCellValue();
         if(StringUtil.isEmpty(value)){  
             return null;  
         }
         
         Cell cellXh = row.getCell(0);
         String cellValueXh = getCellValue(cellXh);
         if(StringUtil.isNotEmpty(cellValueXh) && cellValueXh.indexOf("xh") > 0){
        	 return null;
         }
         
         
         return row;
    }
    
}
