package org.fool.glorious.excel.service;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
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 java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public abstract class AbstractExcelService implements ExcelService {

    private String path;

    public AbstractExcelService(String path) {
        this.path = path;
    }

    private Workbook open(String path) {
        try {
            return initializePoi(new FileInputStream(new File(path)));
        } catch (FileNotFoundException e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    @Override
    public List<List<String>> traverseWorkbook(int index) {
        Workbook workbook = open(path);

        Sheet sheet = workbook.getSheetAt(index);
        int rows = sheet.getPhysicalNumberOfRows();
        List<List<String>> ret = new ArrayList(rows);
        int cols = sheet.getRow(0).getPhysicalNumberOfCells();
        for (int i = 1; i < rows; ++i) {   // 第一行为表头，跳过
            Row row = sheet.getRow(i);
            List<String> lRow = new ArrayList(cols);
            for (int j = 0; j < cols; ++j) {
                lRow.add(getCellValue(row.getCell(j)));
            }
            ret.add(lRow);
        }

        try {
            workbook.close();
        } catch (IOException e) {
            log.warn(e.getMessage(), e);
        }

        return ret;
    }

    private String getCellValue(Cell cell) {
        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case NUMERIC:
                return String.valueOf(cell.getNumericCellValue());
            default:
                return StringUtils.EMPTY;

        }
    }

    abstract protected Workbook initializePoi(FileInputStream fis);
}
