package com.pcloud.book.group.tools;

import com.pcloud.book.group.vo.ExcelDataVO;

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.web.multipart.MultipartFile;

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

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class BookExcelReader {

    public static List<ExcelDataVO> readExcel( MultipartFile file ) throws IOException {
        //获取文件名称
        try (InputStream in = file.getInputStream()) {
            // 读取excel中的数据
            Workbook workbook = judegExcelEdition(file.getOriginalFilename()) ? new XSSFWorkbook(in) : new HSSFWorkbook(in);
            return parseExcel(workbook);
        }
    }

    private static boolean judegExcelEdition( String fileName ) {
        return !fileName.matches("^.+\\.(?i)(xls)$");
    }

    private static List<ExcelDataVO> parseExcel( Workbook workbook ) {
        List<ExcelDataVO> resultDataList = new ArrayList<>();
        // 解析sheet
        for (int sheetNum = 0; sheetNum < workbook.getNumberOfSheets(); sheetNum++) {
            Sheet sheet = workbook.getSheetAt(sheetNum);

            // 校验sheet是否合法
            if (sheet == null) {
                continue;
            }

            // 获取第一行数据
            int firstRowNum = sheet.getFirstRowNum();
            Row firstRow = sheet.getRow(firstRowNum);
            if (null == firstRow) {
                log.warn("解析Excel失败，在第一行没有读取到任何数据！");
            }

            // 解析每一行的数据，构造数据对象
            int rowStart = firstRowNum + 1;
            int rowEnd = sheet.getPhysicalNumberOfRows();
            for (int rowNum = rowStart; rowNum < rowEnd; rowNum++) {
                Row row = sheet.getRow(rowNum);
                if (null == row) {
                    continue;
                }
                ExcelDataVO resultData = convertRowToData(row);
                resultDataList.add(resultData);
            }
        }

        return resultDataList;
    }

    private static String convertCellValueToString( Cell cell ) {
        if (cell == null) {
            return null;
        }
        String returnValue = null;
        switch (cell.getCellType()) {
            case Cell.CELL_TYPE_NUMERIC:   //数字
                Double doubleValue = cell.getNumericCellValue();

                // 格式化科学计数法，取一位整数
                DecimalFormat df = new DecimalFormat("0");
                returnValue = df.format(doubleValue);
                break;
            case Cell.CELL_TYPE_STRING:    //字符串
                returnValue = cell.getStringCellValue();
                break;
            case Cell.CELL_TYPE_BOOLEAN:   //布尔
                boolean booleanValue = cell.getBooleanCellValue();
                returnValue = Boolean.toString(booleanValue);
                break;
            case Cell.CELL_TYPE_BLANK:     // 空值
                break;
            case Cell.CELL_TYPE_FORMULA:   // 公式
                returnValue = cell.getCellFormula();
                break;
            case Cell.CELL_TYPE_ERROR:     // 故障
                break;
            default:
                break;
        }
        return returnValue;
    }

    private static ExcelDataVO convertRowToData( Row row ) {
        ExcelDataVO resultData = new ExcelDataVO();

        Cell cell;
        int cellNum = 0;
        // 序号
        cell = row.getCell(cellNum++);
        String num = convertCellValueToString(cell);
        resultData.setNum(Integer.parseInt(num));
        // 出版社名称
        cell = row.getCell(cellNum++);
        String agentName = convertCellValueToString(cell);
        resultData.setAgentName(agentName);
        // 书名
        cell = row.getCell(cellNum++);
        String bookName = convertCellValueToString(cell);
        resultData.setBookName(bookName);
        // isbn
        cell = row.getCell(cellNum++);
        String isbn = convertCellValueToString(cell);
        resultData.setIsbn(isbn);
        // 分类
        cell = row.getCell(cellNum++);
        String type = convertCellValueToString(cell);
        resultData.setType(type);
        // 二维码数量
        cell = row.getCell(cellNum++);
        String qrcodeNum = convertCellValueToString(cell);
        resultData.setQrcodeNum(Objects.isNull(qrcodeNum) ? 0 : Integer.parseInt(qrcodeNum));

        return resultData;
    }
}