package com.platform.utils.excel;

import com.platform.constant.ConstantExcel;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class ExcelUtil {

    private static final String EXCEL_XLS = "xls";
    private static final String EXCEL_XLSX = "xlsx";


    public static Workbook writeExcel(List<Map<String , String>> dataList, int columnCount, String xlsxPath, int type) {
        OutputStream out = null;
        try {
            // 获取总列数
            int columnNumCount = columnCount;
            // 读取Excel文档
            File xlsxFile = new File(xlsxPath);
            HSSFWorkbook workBook = new HSSFWorkbook();
            // sheet 对应一个工作页
            HSSFSheet sheet = workBook.createSheet();
            HSSFCellStyle cellstyle = workBook.createCellStyle();
            HSSFRow hssfRow = sheet.createRow((short) 0);
            sheet.createFreezePane(0, 1);
            if (type == 1) {
                for (int i = 0; i < ConstantExcel.ORDEREXCELCOLENNAME.length; ++i) {
                    HSSFCell cell = hssfRow.createCell((short)i);
                    cell.setCellValue(ConstantExcel.ORDEREXCELCOLENNAME[i]);
                    cell.setCellStyle(cellstyle);
                }
            }
            // 创建文件输出流，输出电子表格：这个必须有，否则你在sheet上做的任何操作都不会有效
            out = new FileOutputStream(xlsxPath);
            workBook.write(out);
            /**
             * 往Excel中写新数据
             */
            if (type == 1) {
                for (int j = 0; j < dataList.size(); j++) {
                    // 创建一行：从第二行开始，跳过属性列
                    Row row = sheet.createRow(j + 1);
                    // 得到要插入的每一条记录
                    Map<String, String> dataMap = dataList.get(j);

                    for (int i = 0; i < ConstantExcel.ORDEREXCELCOLENNAME.length; ++i) {
                        String value = dataMap.get(ConstantExcel.ORDEREXCELCOLENNAME[i]);
                        Cell cell = row.createCell(i);
                        cell.setCellValue(value);
                    }
                }
            }
            else {
                log.error("writeExcel出错：" + type);
            }
            // 创建文件输出流，准备输出电子表格：这个必须有，否则你在sheet上做的任何操作都不会有效
            out = new FileOutputStream(xlsxPath);
            workBook.write(out);
            log.info("数据导出成功");
            return workBook;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (out != null) {
                    out.flush();
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 判断Excel的版本,获取Workbook
     *
     * @return
     * @throws IOException
     */
    public static Workbook getWorkbok(File file) throws IOException {
        try {
            Workbook wb = null;
            InputStream in = new FileInputStream(file);

            if (!in.markSupported()) {
                in = new PushbackInputStream(in, 8);
            }

            if (file.getName().endsWith(EXCEL_XLS)) {
                wb = new HSSFWorkbook(in);
            } else if (file.getName().endsWith(EXCEL_XLSX)) {
                wb = new XSSFWorkbook(in);
            } else {
                log.error("你的excel版本目前poi解析不了");
            }
            return wb;
        } catch (Exception e) {
            log.error("WriteExcelServiceImpl-getWorkbok");
            StringWriter trace = new StringWriter();
            e.printStackTrace(new PrintWriter(trace));
            log.error(trace.toString());
            return null;
        }
    }

}
