package cn.iocoder.yudao.framework.excel.core.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.poi.excel.ExcelWriter;
import org.apache.poi.ss.usermodel.*;

import java.util.List;

public class ExcelExtraHelper {

    /**
     * 根据内容自动设置列宽，并设置样式
     * @param writer ExcelWriter
     * @param rows 所有行（含表头）
     * @param timeColumnIndexList 哪些列是时间列（索引从0开始）
     * @param numberColumnIndexList 哪些列是数字列（右对齐）
     */
    public static void enhanceExcel(ExcelWriter writer, List<List<String>> rows,
                                    List<Integer> timeColumnIndexList, List<Integer> numberColumnIndexList) {
        if (CollUtil.isEmpty(rows)) return;

        // ============ 1. 表头样式 ============
        CellStyle headStyle = writer.getHeadCellStyle();
        Font headFont = writer.getWorkbook().createFont();
        headFont.setBold(true);
        headFont.setFontHeightInPoints((short) 12);
        headStyle.setFont(headFont);
        // 设置背景色
        headStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        headStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);

        // ============ 2. 内容样式 ============
        CellStyle contentStyle = writer.getCellStyle();
        contentStyle.setAlignment(HorizontalAlignment.LEFT);
        contentStyle.setVerticalAlignment(VerticalAlignment.CENTER);

        // ============ 3. 时间列样式 ============
        CellStyle timeStyle = writer.getWorkbook().createCellStyle();
        timeStyle.cloneStyleFrom(contentStyle);
        timeStyle.setDataFormat(writer.getWorkbook().createDataFormat().getFormat("yyyy-MM-dd HH:mm"));

        // ============ 4. 数字列样式 ============
        CellStyle numberStyle = writer.getWorkbook().createCellStyle();
        numberStyle.cloneStyleFrom(contentStyle);
        numberStyle.setAlignment(HorizontalAlignment.RIGHT);

        // ============ 5. 根据内容自动调节列宽 ============
        int colSize = rows.get(0).size();
        int[] maxLength = new int[colSize];

        for (List<String> row : rows) {
            for (int colIndex = 0; colIndex < colSize; colIndex++) {
                if (row.size() > colIndex && row.get(colIndex) != null) {
                    String cell = row.get(colIndex);
                    int length = getStringDisplayLength(cell);
                    if (length > maxLength[colIndex]) {
                        maxLength[colIndex] = length;
                    }
                }
            }
        }
        for (int i = 0; i < colSize; i++) {
            writer.setColumnWidth(i, maxLength[i] + 2);
        }

        // ============ 6. 设置时间列 & 数字列格式 ============
        Sheet sheet = writer.getSheet();
        int rowCount = rows.size();

        for (int rowIdx = 1; rowIdx < rowCount; rowIdx++) { // 第0行是表头
            Row row = sheet.getRow(rowIdx);
            if (row == null) continue;
            if (timeColumnIndexList != null)
            for (Integer colIdx : timeColumnIndexList) {
                Cell cell = row.getCell(colIdx);
                if (cell != null) {
                    cell.setCellStyle(timeStyle);
                }
            }
            if (numberColumnIndexList != null)
            for (Integer colIdx : numberColumnIndexList) {
                Cell cell = row.getCell(colIdx);
                if (cell != null) {
                    cell.setCellStyle(numberStyle);
                }
            }
        }
    }

    /**
     * 中文算2长度，英文算1
     */
    private static int getStringDisplayLength(String str) {
        int length = 0;
        for (char c : str.toCharArray()) {
            if (c >= 0x4E00 && c <= 0x9FA5) {
                length += 2;
            } else {
                length += 1;
            }
        }
        return length;
    }
}
