package com.xtd.common.utils.excel;

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.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.util.StringUtils;

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

/**
 * Created by jenking on 2017/9/8.
 */
public class ImportExcelUtil {

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

    /**
     * 描述：获取IO流中的数据，组装成List<List<Object>>对象
     *
     * @param in,fileName
     * @return
     * @throws IOException
     */
    public static List<List<Object>> getBankListByExcel(InputStream in, String fileName) {
        List<List<Object>> list = null;
        try {
            //创建Excel工作薄
            Workbook work = getWorkbook(in, fileName);
            if (null == work) {
                throw new Exception("创建Excel工作薄为空！");
            }
            Sheet sheet = null;
            Row row = null;
            Cell cell = null;

            list = new ArrayList<List<Object>>();
            //遍历Excel中所有的sheet
            for (int i = 0; i < work.getNumberOfSheets(); i++) {
                sheet = work.getSheetAt(i);
                if (sheet == null) {
                    continue;
                }
                int lastRowNum = sheet.getLastRowNum();
                if (0 == lastRowNum) {
                    continue;
                }
                //遍历当前sheet中的所有行
                int rowNum = lastRowNum + 1;
                System.out.println(sheet.getSheetName() + "一共有" + rowNum + "行");
                int firstRowNum = sheet.getFirstRowNum();
                int max = sheet.getLastRowNum();
                for (int j = firstRowNum; j <= max; j++) {
                    row = sheet.getRow(j);
                    if (null == row) {
                        continue;
                    }
                    //遍历所有的列
                    int firstCellNum = row.getFirstCellNum();
                    int lastCellNum = row.getLastCellNum();
                    List<Object> li = new ArrayList<>();
                    int count = j + 1;
                    System.out.println("第" + count + "行有" + lastCellNum + "列");
                    for (int y = firstCellNum; y < lastCellNum; y++) {
                        cell = row.getCell(y);

                        if (isMergedRegion(sheet, j, y)) {
                            li.add(getMergedRegionValue(sheet, j, y));
                        } else {
                            Object cellValue = getCellValue(cell);
                            if (!StringUtils.isEmpty(cellValue)) {
                                li.add(cellValue);
                            }
                        }


                    }
                    if (li.size() > 0) {
                        list.add(li);
                    }
                }
            }
            work.close();
        } catch (Exception e) {
            throw new RuntimeException("文件解析失败！");
        }
        return list;
    }

    /**
     * 描述：根据文件后缀，自适应上传文件的版本
     *
     * @param inStr,fileName
     * @return
     * @throws Exception
     */
    public static Workbook getWorkbook(InputStream inStr, String fileName) throws Exception {
        Workbook wb = null;
        boolean contains = fileName.contains(".");
        if (contains) {
            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 Exception("不是excel文件！");
            }
            return wb;
        } else {
            throw new Exception("文件错误!");
        }
    }

    /**
     * 描述：对表格中数值进行格式化
     *
     * @param cell
     * @return
     */
    public static Object getCellValue(Cell cell) {
        Object value = null;
        DecimalFormat df = new DecimalFormat("0"); //格式化number String字符
        SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd"); //日期格式化
        DecimalFormat df2 = new DecimalFormat("0"); //格式化数字

        switch (cell.getCellType()) {
            case Cell.CELL_TYPE_STRING:
                value = cell.getRichStringCellValue().getString();
                break;
            case Cell.CELL_TYPE_NUMERIC:
                if ("General".equals(cell.getCellStyle().getDataFormatString())) {
                    value = df.format(cell.getNumericCellValue());
                } else if ("m/d/yy".equals(cell.getCellStyle().getDataFormatString())) {
                    value = sdf.format(cell.getDateCellValue());
                } else {
                    value = df2.format(cell.getNumericCellValue());
                }
                break;
            case Cell.CELL_TYPE_BOOLEAN:
                value = cell.getBooleanCellValue();
                break;
            case Cell.CELL_TYPE_BLANK:
                value = "";
                break;
            default:
                break;
        }
        return value;
    }


    /**
     * 获取合并单元格的内容
     *
     * @param sheet
     * @param row
     * @param column
     * @return
     */
    public static Object getMergedRegionValue(Sheet sheet, int row, int column) {
        int sheetMergeCount = sheet.getNumMergedRegions();
        for (int i = 0; i < sheetMergeCount; i++) {
            CellRangeAddress ca = sheet.getMergedRegion(i);
            int firstColumn = ca.getFirstColumn();
            int lastColumn = ca.getLastColumn();
            int firstRow = ca.getFirstRow();
            int lastRow = ca.getLastRow();
            if (row >= firstRow && row <= lastRow) {
                if (column >= firstColumn && column <= lastColumn) {
                    Row fRow = sheet.getRow(firstRow);
                    Cell fCell = fRow.getCell(firstColumn);
                    return getCellValue(fCell);
                }
            }
        }
        return null;
    }

    /**
     * 判断是否是合并单元格
     *
     * @param sheet
     * @param row
     * @param column
     * @return
     */
    public static boolean isMergedRegion(Sheet sheet, int row, int column) {
        int sheetMergeCount = sheet.getNumMergedRegions();
        for (int i = 0; i < sheetMergeCount; i++) {
            CellRangeAddress range = sheet.getMergedRegion(i);
            int firstColumn = range.getFirstColumn();
            int lastColumn = range.getLastColumn();
            int firstRow = range.getFirstRow();
            int lastRow = range.getLastRow();
            if (row >= firstRow && row <= lastRow) {
                if (column >= firstColumn && column <= lastColumn) {
                    return true;
                }
            }
        }
        return false;
    }

//    public static void main(String[] args) {
//        try {
//            // 对读取Excel表格标题测试
//            String pathname = "e:\\data\\demo1.xls";
//            File filename = new File(pathname);
//            FileInputStream in = new FileInputStream(filename);
//            List<List<Object>> listob = new ImportExcelUtil().getBankListByExcel(in, filename.getName());
//            in.close();
//            //该处可调用service相应方法进行数据保存到数据库中，现只对数据输出
//            if (!StringUtils.isEmpty(listob)) {
//                for (int i = 0; i < listob.size(); i++) {
//                    List<Object> lo = listob.get(i);
//                    System.out.println(lo.get(0) + " ," + lo.get(1) + "," + lo.get(2));
//                }
//            }
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
}
