package com.xkrs.utils;

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.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author ZHY
 * @date 2020/6/17 15:56
 */
public class ExcelImportUtil {
    private Workbook wb;
    private Sheet sheet;
    private Row row;

    String xls = ".xls";
    String xlsx = ".xlsx";

    /**
     * 读取Excel
     *
     * @author ZHY
     */
    public ExcelImportUtil(MultipartFile file) throws Exception {
        String filename = file.getOriginalFilename();
        String ext = filename.substring(filename.lastIndexOf("."));
        InputStream is = file.getInputStream();
        if (xls.equals(ext)) {
            wb = new HSSFWorkbook(is);
        } else if (xlsx.equals(ext)) {
            wb = new XSSFWorkbook(is);
        } else {
            wb = null;
        }
    }

    /**
     * 读取Excel表格表头的内容输出
     *
     */
    public List<Map<String, Object>> readExcelTitleOut() {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        if (wb != null) {
            sheet = wb.getSheetAt(0);
            row = sheet.getRow(0);
            // 标题总列数
            int colNum = row.getPhysicalNumberOfCells();

            System.out.println("colNum:" + colNum);

            Map<String, Object> map = new LinkedHashMap<String, Object>();

            for (int i = 0; i < colNum; i++) {
                String stringCellValue = row.getCell(i).getStringCellValue();
                map.put(stringCellValue, null);
            }
            list.add(map);
            return list;
        }
        return list;
    }

    /**
     * 读取Excel表格表头
     *
     */
    public String[] readExcelTitle() {
        String[] title = {};
        if (wb != null) {
            sheet = wb.getSheetAt(0);
            row = sheet.getRow(0);
            // 标题总列数
            int colNum = row.getPhysicalNumberOfCells();

            System.out.println("colNum:" + colNum);

            title = new String[colNum];

            for (int i = 0; i < colNum; i++) {
                Cell cell = row.getCell(i);
                title[i] = cell.getStringCellValue().replaceAll("\\s+", "");
            }
        }
        return title;
    }

    /**
     * 读取Excel表格的某一个数值
     * @return
     */
    public  Map<String, Object> readExcelSomeTitle(){
        Map<String, Object> map = new LinkedHashMap<>();
        if (wb != null) {
            sheet = wb.getSheetAt(0);
            String title = parseExcel(sheet.getRow(2).getCell(1));
            String remark = parseExcel(sheet.getRow(3).getCell(1));
            map.put("date",title);
            map.put("remark",remark);
        }
        return map;
    }

    /**
     * 读取Excel数据内容
     *
     */
    public List<Map<String, String>> readExcelContent() {
        List<Map<String, String>> list = new ArrayList<>();
        if (wb != null) {
            //获取sheet表
            sheet = wb.getSheetAt(0);
            // 得到总行数
            int rowNum = sheet.getLastRowNum();
            //获取表头的标题
            String[] readExcelTitle = readExcelTitle();
            // 正文内容应该从第二行开始,第一行为表头的标题
            for (int i = 1; i <= rowNum; i++) {
                row = sheet.getRow(i);
                if (row == null) {
                    continue;
                }
                Map<String, String> map = new LinkedHashMap<>();
                for (int j = 0; j < readExcelTitle.length; j++) {
                    //获取每一列的数据值
                    String str = parseExcel(row.getCell(j));
                    //判断对应行的列值是否为空
                    if (str != null || "".equals(str)) {
                        //表头的标题为键值，列值为值
                        map.put(readExcelTitle[j], str);
                    }
                }
                //判段添加的对象是否为空
                if (!map.isEmpty()){
                    list.add(map);
                }
            }
        }
        return list;
    }

    /**
     *
     * 根据Cell类型设置数据
     *
     */
    int ss = 20;
    int xx = 58;
    private String parseExcel(Cell cell) {
        String result = "";
        if (cell != null) {
            SimpleDateFormat sdf = null;
            switch (cell.getCellType()) {
                // 数字类型
                case NUMERIC:
                    // 处理日期格式、时间格式
                    if (DateUtil.isCellDateFormatted(cell)) {
                        if (cell.getCellStyle().getDataFormat() == ss) {
                            sdf = new SimpleDateFormat("HH:mm");
                        } else {// 日期
                            sdf = new SimpleDateFormat("yyyy-MM-dd");
                        }
                        String dateFormat = sdf.format(cell.getDateCellValue());
                        result = dateFormat;
                    } else if (cell.getCellStyle().getDataFormat() == xx) {
                        // 处理自定义日期格式：m月d日(通过判断单元格的格式id解决，id的值是58)
                        sdf = new SimpleDateFormat("yyyy-MM-dd");
                        double value = cell.getNumericCellValue();
                        Date date = DateUtil.getJavaDate(value);
                        result = sdf.format(date);
                    } else {
                        double value = cell.getNumericCellValue();
                        DecimalFormat format = new DecimalFormat("#.###########");
                        String strVal = format.format(value);
                        result = strVal;
                    }
                    break;
                // String类型
                case STRING:
                    result = cell.getRichStringCellValue().toString();
                    break;
                default:
                    break;
            }
        }
        return result;
    }
}
