package com.bonus.hn.bearing.capacity.backstage.tools;

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.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;
/**
 * @author bonus
 */
public class ComplexExcelExporter {
    public static void exportComplexExcel(List<Map<String, Object>> leftData, String filePath) {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Sheet1");

        int rowNum = 0;

        // 导出左侧数据
        rowNum = exportData(sheet, leftData, 0, 0, true);

        // 导出中间数据
//        rowNum = exportData(sheet, middleData, 0, 4,false); // 根据实际情况调整起始列索引
//
//        // 导出右侧数据
//        exportData(sheet, rightData, 0, 2,true); // 根据实际情况调整起始行索引和起始列索引

        try (FileOutputStream outputStream = new FileOutputStream(filePath)) {
            workbook.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static int exportData(Sheet sheet, List<Map<String, Object>> data, int startRow, int startCol, boolean tf) {
        int rowNum = startRow;

        for (int i = 0; i < data.size(); i++) {
            Map<String, Object> rowData1 = data.get(i);
            rowNum = createMergedRow(sheet, rowNum, startCol, rowData1, tf);
        }

        return rowNum;
    }

    private static int createMergedRow(Sheet sheet, int rowNum, int startCol, Map<String, Object> rowData, boolean isMerge) {
        Row row = sheet.createRow(rowNum);
        int colIdx = startCol;
        for (String key : rowData.keySet()) {
            Cell cell = row.createCell(colIdx);
            cell.setCellValue(rowData.get(key).toString());
            if (rowNum + 1 > 2 && (rowNum + 1) % 3 == 0) {
                if (colIdx < 4) {
                    // 合并单元格
                    sheet.addMergedRegion(new CellRangeAddress(rowNum - 2, rowNum, colIdx, colIdx));
                }
            }
            colIdx++;
        }

        return rowNum + 1;
    }


    public static void main(String[] args) {

    }
}
