package com.bonus.common.core.utils.poi;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.commons.io.IOUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author 16043
 */
public class MultiSheetExcelExporter {

    private final Workbook workbook;
    private int currentRowNum;

    private SimpleDateFormat dateFormat;

    public MultiSheetExcelExporter() {
        this.workbook = new XSSFWorkbook();
        this.currentRowNum = 0;
        this.dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    }

    public Sheet createSheet(String sheetName) {
        Sheet sheet = workbook.createSheet(sheetName);
        currentRowNum = 0;
        return sheet;
    }

    public void addHeaderRow(Sheet sheet, List<String> headers) {
        Row headerRow = sheet.createRow(currentRowNum++);
        for (int i = 0; i < headers.size(); i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers.get(i));
            // 可以在这里设置标题行的样式
        }
    }

    public void addHeaderRowAndTitle(Sheet sheet, List<String> headers,String title) {

        // 创建一个样式对象用于标题行
        CellStyle titleStyle = workbook.createCellStyle();
        titleStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        titleStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        Font titleFont = workbook.createFont();
        titleFont.setBold(true); // 设置字体加粗
        titleStyle.setFont(titleFont);
        // 设置水平居中对齐
        titleStyle.setAlignment(HorizontalAlignment.CENTER);
        // 添加标题行
        Row titleRow = sheet.createRow(currentRowNum++);
        Cell titleCell = titleRow.createCell(0);
        titleCell.setCellValue(title); // 标题内容
        titleCell.setCellStyle(titleStyle);
        // 如果需要合并单元格，可以使用下面的语句
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, headers.size() - 1));
        Row headerRow = sheet.createRow(currentRowNum++);
        for (int i = 0; i < headers.size(); i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers.get(i));
            // 可以在这里设置标题行的样式
            cell.setCellStyle(titleStyle);
        }
    }

    public void addDataRows(Sheet sheet, List<Map<String, Object>> dataList, List<String> headers) {

        // 创建一个样式对象
        CellStyle titleStyle = workbook.createCellStyle();
        // 设置水平居中对齐
        titleStyle.setAlignment(HorizontalAlignment.CENTER);

        for (Map<String, Object> rowData : dataList) {
            Row row = sheet.createRow(currentRowNum++);
            for (int i = 0; i < headers.size(); i++) {
                String header = headers.get(i);
                Cell cell = row.createCell(i);
                Object value = rowData.get(header);
                if (value != null) {
                    if (value instanceof Date) {
                        cell.setCellValue(dateFormat.format((Date) value));
                    } else if (value instanceof String) {
                        cell.setCellValue((String) value);
                    } else if (value instanceof Number) {
                        cell.setCellValue(((Number) value).doubleValue());
                    } else if (value instanceof Boolean) {
                        cell.setCellValue((Boolean) value);
                    } else {
                        cell.setCellValue(value.toString());
                    }
                }
                cell.setCellStyle(titleStyle);
            }
        }
    }

    public void exportToResponse(HttpServletResponse response, String fileName) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName + ".xlsx", "UTF-8"));
        workbook.write(response.getOutputStream());
        IOUtils.closeQuietly(workbook);
    }
}