package jnpf.handler;

import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;

import java.util.HashMap;
import java.util.Map;

public class CustomCellWriteHandler implements CellWriteHandler {
    // 记录每列的最大宽度（列索引 -> 最大宽度）
    private final Map<Integer, Integer> maxColumnWidthMap = new HashMap<>();

    @Override
    public void afterCellDispose(CellWriteHandlerContext context) {
        // 设置列宽的逻辑
        Sheet sheet = context.getWriteWorkbookHolder().getWorkbook().getSheetAt(0);
        int columnIndex = context.getCell().getColumnIndex();
        // 示例1：固定列宽
        sheet.setColumnWidth(columnIndex, 20 * 256);
        // 示例2：根据内容动态调整列宽（简单逻辑）
        String content = getCellValueAsString(context.getCell());
        // 计算单元格内容宽度（考虑中文）
        int width = calculateColumnWidth(content);
        // 更新最大列宽
        if (width > maxColumnWidthMap.getOrDefault(columnIndex, 0)) {
            maxColumnWidthMap.put(columnIndex, width);
            sheet.setColumnWidth(columnIndex, width * 256);
        }
    }

    // 动态计算列宽（中文字符按 2 倍宽度计算）
    private int calculateColumnWidth(String text) {
        int chineseCharCount = countChineseCharacters(text);
        int otherCharCount = text.length() - chineseCharCount;
        return (int) (chineseCharCount * 2 * 1.2 + otherCharCount * 1.0); // 额外增加 20% 缓冲
    }

    // 统计中文字符数量
    private int countChineseCharacters(String text) {
        return (int) text.chars().filter(c -> c >= 0x4E00 && c <= 0x9FA5).count();
    }

    private String getCellValueAsString(Cell cell) {
        String result = null;
        switch (cell.getCellType()) {
            case STRING:
                result = cell.getStringCellValue();
                break;
            case NUMERIC:
                result = String.valueOf(cell.getNumericCellValue());
                break;
            case BOOLEAN:
                result = String.valueOf(cell.getBooleanCellValue());
                break;
        }
        return result;
    }
}
