package com.ajb.common.utils.office;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
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.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import com.ajb.common.utils.string.StringUtil;

public class ExcelUtils {
	/**
	 * 是否是2003的excel，返回true是2003
	 * @param fileName
	 * @return
	 */
	public static boolean isExcel2003(String fileName)  {    
		return fileName.matches("^.+\\.(?i)(xls)$");    
	}
     
	/**
	 * 是否是2007的excel，返回true是2007
	 * @param fileName
	 * @return
	 */
	public static boolean isExcel2007(String fileName)  {    
		return fileName.matches("^.+\\.(?i)(xlsx)$");    
	}
      
	/** 
	* 验证EXCEL文件 
	* @param filePath 
	* @return 
	*/  
	public static boolean validateExcel(String fileName){  
		if(fileName == null || !(isExcel2003(fileName) || isExcel2007(fileName))){    
			return false;    
		}    
		return true;  
	}
	
	/**
	 * 通用性检查：1、文件是否为空
	 * 		   2、格式是否为excel
	 * 		   3、长度是否为空
	 * @param file
	 * @return
	 */
	public static String commonUploadCheck(MultipartFile file){
		String checkResult = "";
		if(file == null){
			checkResult = "文件不能为空";
		}else{
			String fileName = file.getOriginalFilename();
			if(!ExcelUtils.validateExcel(fileName)){
				checkResult = "文件必须为excel格式！请检查文件后缀名是否为.xls或.xlsx";
			}else{
				long size = file.getSize();
				if(StringUtils.isEmpty(fileName) || size == 0){
					checkResult = "文件不能为空";
				}
			}
		}
		return checkResult;
	}
	
	/** 
     * 描述：获取IO流中的数据，组装成List<List<Object>>对象 
     * @param in,fileName 
     * @return 
     * @throws IOException  
     */  
    public static List<List<Object>> getBankListByExcel(InputStream is,String fileName) throws Exception{  
    	List<List<Object>> list = null;
        Workbook work = getWorkbook(is,fileName);//创建Excel工作薄  
        if(null == work){
            throw new Exception("创建Excel工作薄为空！");
        }
        Sheet sheet = null;
        Row row = null;
        Cell cell = null;

        list = new ArrayList<List<Object>>();
        for (int i = 0; i < work.getNumberOfSheets(); i++) {//遍历Excel中所有的sheet
            sheet = work.getSheetAt(i); 
            if(sheet==null){continue;} 
            for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) {//遍历当前sheet中的所有行 
                row = sheet.getRow(j);
                if(row == null){continue;}//||row.getFirstCellNum() == j
                List<Object> li = new ArrayList<Object>();//遍历所有的列
                for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++){
                    cell = row.getCell(y);
                    li.add(getCellValue(cell));
                }
                list.add(li);
            }
        }
//        work.close();
        return list;
    }
    
	/** 
     * 描述：根据文件后缀，自适应上传文件的版本  
     * @param inStr,fileName 
     * @return 
     * @throws Exception 
     */  
    public static Workbook getWorkbook(InputStream is,String fileName) throws Exception{  
    	Workbook wb = null;
    	if(ExcelUtils.isExcel2003(fileName)){
    		wb = new HSSFWorkbook(is);
    	}else{
    		wb = new XSSFWorkbook(is);
    	}
        return wb;  
    }
    
	private static boolean isDateCell(String dataFormatString){
		boolean isDateCell = false;
		if(StringUtil.isNullOrBlank(dataFormatString)){
			return false;
		}
		if(dataFormatString.contains("y") && dataFormatString.contains("m") && dataFormatString.contains("d")){
			isDateCell = true;
		}
		return isDateCell;
	}
	
	/** 
	 * 描述：对表格中数值进行格式化 
     * @param cell 
     * @return 
     */  
	public static String getCellValue(Cell cell){  
        String value = null;  
        DecimalFormat df = new DecimalFormat("0");  //格式化number String字符
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");  //日期格式化
//        DecimalFormat df2 = new DecimalFormat("0.00");  //格式化数字
        
        /*String message = "单元格类型：";
        if(cell.getCellType() == 0){
        	message += "NUMBERIC";
        }else if(cell.getCellType() == 1){
        	message += "STRING";
        }else if(cell.getCellType() == 4){
        	message += "BOOLEAN";
        }else if(cell.getCellType() == 2){
        	message += "FORMULA";
        }else{
        	message += "其他类型";
        }*/
        String dataFormStr = cell.getCellStyle().getDataFormatString();
        switch (cell.getCellType()) {
        case Cell.CELL_TYPE_NUMERIC:
//        	message += "	DataFormatString:"+cell.getCellStyle().getDataFormatString()+"	NumericCellValue:"+cell.getNumericCellValue()+"	DateCellValue:"+cell.getDateCellValue();
        	if("General".equals(dataFormStr)){  
                value = df.format(cell.getNumericCellValue());  
            }else if(isDateCell(dataFormStr)){  
                value = sdf.format(cell.getDateCellValue());  
            }else{  
            	value = df.format(cell.getNumericCellValue());
            }  
            break;
        case Cell.CELL_TYPE_STRING:  
            value = cell.getRichStringCellValue().getString();
            break;
        case Cell.CELL_TYPE_BOOLEAN:  
            value = cell.getBooleanCellValue()+"";  
            break;
        case Cell.CELL_TYPE_FORMULA: // 公式
            value = cell.getStringCellValue()+ "";
            break;
        case Cell.CELL_TYPE_BLANK:  
            value = "";  
            break;
        case Cell.CELL_TYPE_ERROR: // 故障
            value = "非法字符";
            break;
        default:
        	value = "未知类型";
            break;  
        }
//        message += "	value:"+value;
//        System.out.println(message);
        if(value != null){
        	value = value.trim();
        }
        return value;  
    }
	/*int totalRows = sheet.getPhysicalNumberOfRows();//得到Excel的行数
	int totalCells = 0;//总列数  
	if(totalRows>=2 && sheet.getRow(1) != null){//得到Excel的列数(前提是有行数)，从第二行算起   
		totalCells=sheet.getRow(1).getPhysicalNumberOfCells();  
	}
	StringBuffer sbf = new StringBuffer();
	for(int r=0;r<totalRows;r++){//循环Excel行数,从第二行开始。标题不入库  
		Row row = sheet.getRow(r);  
		if (row == null){  
			System.out.println("第"+(r+1)+"行数据有问题，请仔细检查！");  
			continue;  
		}
		for(int c = 0; c <totalCells; c++){  
			Cell cell = row.getCell(c);  
			if (null != cell){
				System.out.print(cell.getStringCellValue()+"	");
				sbf.append(cell.getStringCellValue()+"	");
			}
		}
		System.out.println();
		sbf.append("\n");
	}*/
	
	public static boolean checkEnd(List<Object> rowData){
		boolean endFlag = false;
		if(rowData == null || rowData.size() == 0){
			endFlag = true;
		}else{
			endFlag = true;
			for(Object item : rowData){
				String value = (String)item;
				if(value != null && !"".equals(value.trim())){
					endFlag = false;
					break;
				}
			}
		}
		return endFlag;
	}
	
	public static void main(String[] args){
		File file = new File("C:\\Users\\zxh\\Desktop\\test.xlsx");
		List<List<Object>> dataList = null;
		try {
			dataList = getBankListByExcel(new FileInputStream(file),file.getName());
		} catch (Exception e) {
			e.printStackTrace();
		}
		for(List<Object> row : dataList){
			for(Object data : row){
				System.out.print(data.toString()+"	");
			}
			System.out.println();
		}
	}
}
