package com.nmgs.util;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

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


public class ReadExcel {
    private final static String excel2003L = ".xls";    //2003- 版本的excel
    private final static String excel2007U = ".xlsx";   //2007+ 版本的excel

    /**
     * Excel导入
     */
    public static List<Map<String,Object>> getBankListByExcel(InputStream in, String fileName, int index) throws Exception {
        List<Map<String,Object>> list = null;
        //创建Excel工作薄
        Workbook work = getWorkbook(in, fileName);
        FormulaEvaluator evaluator=work.getCreationHelper().createFormulaEvaluator();
        if (null == work) {
            throw new Exception("创建Excel工作薄为空！");
        }
        Sheet sheet = null;
        Row row = null;
        Cell cell = null;
        list = new ArrayList<>();
        //遍历Excel中所有的sheet
        for (int i = 0; i < work.getNumberOfSheets(); i++) {
            sheet = work.getSheetAt(i);
            if (sheet == null) {
                continue;
            }
            //遍历当前sheet中的所有行
            //包涵头部，所以要小于等于最后一列数,这里也可以在初始值加上头部行数，以便跳过头部
            for (int j = sheet.getFirstRowNum() + 1; j <= sheet.getLastRowNum(); j++) {
                Map<String,Object> map=new HashMap<>();
                //读取一行
                row = sheet.getRow(j);
                //去掉空行和表头
                if (row == null || row.getFirstCellNum() == j) {
                    continue;
                }
                //遍历所有的列
                List<Object> li = new ArrayList<>();
                Boolean b = true;
                if(j+1==1577){
                    System.out.println("aaa");
                }
                for (int y = row.getFirstCellNum(); y < index; y++) {
                    cell = row.getCell(y);
                    if ("".equals(getCellValue(cell,evaluator)) && y == row.getFirstCellNum()) {
                        b = false;
                        break;
                    }
                    li.add(getCellValue(cell,evaluator));
                }
                if (b) {
                    map.put("rowIndex",j+1);
                    map.put("list",li);
                    list.add(map);
                }

            }
        }
        return list;
    }

    /**
     * 描述：根据文件后缀，自适应上传文件的版本
     */
    public static Workbook getWorkbook(InputStream inStr, String fileName) throws Exception {
        Workbook wb = null;
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        if (excel2003L.equals(fileType)) {
            wb = new HSSFWorkbook(inStr);  //2003-
        } else if (excel2007U.equals(fileType)) {
            wb = new XSSFWorkbook(inStr);  //2007+
        } else {
            throw new RuntimeException("Excel版本错误");
        }
        return wb;
    }

    /**
     * 描述：对表格中数值进行格式化
     */
    public static Object getCellValue(Cell cell,FormulaEvaluator evaluator) {
        Object value = null;
        DecimalFormat df = new DecimalFormat("0");  //格式化字符类型的数字
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");  //日期格式化
        SimpleDateFormat sdf2 = new SimpleDateFormat(DateUtils.YYYY_MM_DD_HH_MM_SS);  //日期格式化
        DecimalFormat df2 = new DecimalFormat("0.00");  //格式化数字
        if (cell == null) {
            value = "";
            return value;
        }
        switch (cell.getCellType()) {
            case STRING:
                value = cell.getRichStringCellValue().getString().replace(" ","").replace("\n","").trim();
                break;
            case NUMERIC:
                System.out.println(cell.getCellStyle().getDataFormatString());
                if ("General".equals(cell.getCellStyle().getDataFormatString())) {
                    value = cell.getNumericCellValue();
                } else if ("m\\/d\\/yyyy".equals(cell.getCellStyle().getDataFormatString())) {
                    value = cell.getDateCellValue();
                } else if ("m/d/yy".equals(cell.getCellStyle().getDataFormatString())) {
                    value = cell.getDateCellValue();
                } else if ("yyyy/m/d;@".equals(cell.getCellStyle().getDataFormatString())) {
                    value = cell.getDateCellValue();
                } else if ("yyyy-m-d hh:mm:ss".equals(cell.getCellStyle().getDataFormatString())) {
                    value = cell.getDateCellValue();
                } else if ("yyyy\\-m\\-d\\ hh:mm:ss".equals(cell.getCellStyle().getDataFormatString())) {
                    value = cell.getDateCellValue();
                } else {
                    value = cell.getNumericCellValue();
                }
                break;
            case BOOLEAN:
                value = cell.getBooleanCellValue();
                break;
            case BLANK:
                value = "";
                break;
            case FORMULA:
                value = evaluator.evaluate(cell).getStringValue().replace(" ","").replace("\n","").trim();
                break;
            default:
                break;
        }
        return value;
    }
}

