package com.engine.organization.util.excel;

import org.apache.commons.lang3.Validate;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import static org.apache.poi.ss.usermodel.CellType.STRING;


public class ExcelSupport {

    private static final String pattern = "yyyy-MM-dd HH:mm:ss";

    //excel类型
    public static final String EXCEL_TYPE_XLSX = "xlsx";
    public static final String EXCEL_TYPE_XLS = "xls";


    /**
     * 解析文件，获取单个sheet
     *
     * @param file       文件
     * @param sheetIndex sheet下标，从0开始
     * @return sheet
     */
    public static Sheet parseFile(MultipartFile file, int sheetIndex) {
        Workbook workBook = null;
        try (InputStream ins = file.getInputStream();) {
            String fileName = file.getOriginalFilename();
            if (fileName.endsWith(EXCEL_TYPE_XLSX)) {
                workBook = new XSSFWorkbook(ins);
            } else if (fileName.endsWith(EXCEL_TYPE_XLS)) {
                workBook = new HSSFWorkbook(ins);
            } else {
                throw new IllegalArgumentException("File format error! Only xlsx and xls types are supported");
            }
            return workBook.getSheetAt(sheetIndex);
        } catch (Exception e) {
            throw new IllegalArgumentException(e);
        }
    }

    /**
     * 解析文件，获取单个sheet
     *
     * @param sheetIndex sheet下标，从0开始
     * @return sheet
     */
    public static Sheet parseFile(InputStream ins, int sheetIndex,String fileName) {
        Workbook workBook = null;
        try {
            if (fileName.endsWith(EXCEL_TYPE_XLSX)) {
                workBook = new XSSFWorkbook(new BufferedInputStream(ins));
            } else if (fileName.endsWith(EXCEL_TYPE_XLS)) {
                workBook = new HSSFWorkbook(new BufferedInputStream(ins));
            } else {
                throw new IllegalArgumentException("File format error! Only xlsx and xls types are supported");
            }
            return workBook.getSheetAt(sheetIndex);
        } catch (Exception e) {
            throw new IllegalArgumentException(e);
        }
    }

    /**
     * 获取sheet的头列
     *
     * @param sheet
     * @param headerIndex 头下标
     * @return
     */
    public static List<String> getSheetHeader(Sheet sheet, int headerIndex) {
        List<String> headers = new ArrayList<>();
        Row headerRow = sheet.getRow(headerIndex);
        Iterator cellIterator = headerRow.cellIterator();
        while (cellIterator.hasNext()) {
            Cell cell = (Cell) cellIterator.next();
            String stringCellValue = cell.getStringCellValue();
            headers.add(stringCellValue);
        }
        return headers;
    }


    /**
     * 返回指定单元格的数据
     *
     * @param sheet     指定sheet
     * @param rowIndex  第几行，从0开始
     * @param cellIndex 第几列，从0开始
     * @return 值
     */
    public static String getCellValue(Sheet sheet, int rowIndex, int cellIndex) {
        Validate.notNull(sheet.getRow(rowIndex), "Line %s is empty and cannot be resolved", rowIndex);
        return getCellValue(sheet.getRow(rowIndex).getCell(cellIndex));
    }

    /**
     * 格式化解析的数据
     */
    public static String getCellValue(Cell cell) {
        String cellValue = "";
        if (cell != null) {
            switch (cell.getCellType()) {
                case NUMERIC: // 数值类型
                    if (DateUtil.isCellDateFormatted(cell)) {
                        cellValue = getDateStr(cell.getDateCellValue(), pattern);
                    } else {
                        cell.setCellType(STRING);
                        cellValue = cell.getStringCellValue();
                    }
                    break;
                case STRING: // 字符串类型
                    cellValue = cell.getStringCellValue();
                    break;
                case BOOLEAN: // 布尔类型
                    cellValue = String.valueOf(cell.getBooleanCellValue());
                    break;
                case FORMULA: // 公式类型
                    cellValue = String.valueOf(cell.getCellFormula());
                    break;
                case BLANK: // 空白类型
                    cellValue = "";
                    break;
                case ERROR:
                    cellValue = "";
                    break;
                default:
                    cellValue = cell.toString().trim();
                    break;
            }
        }
        return cellValue.trim();
    }

    public static Date getDate(String dateStr, String pattern) {
        try {
            return new SimpleDateFormat(pattern).parse(dateStr);
        } catch (ParseException e) {
            throw new IllegalArgumentException(e);
        }
    }

    private static String getDateStr(Date date, String pattern) {
        return new SimpleDateFormat(pattern).format(date);
    }
}
