package jnpf.attendance.excel;

import com.alibaba.excel.write.handler.RowWriteHandler;
import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;


public class HeadStyleHandler implements RowWriteHandler, SheetWriteHandler {
    @Override
    public void afterRowDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Integer relativeRowIndex, Boolean isHead) {
        Sheet sheet = writeSheetHolder.getSheet();
        XSSFCellStyle contextCellStyle = getContextCellStyle(sheet);
        int rowNum = row.getRowNum();
        Workbook workbook = sheet.getWorkbook();
        Font font = workbook.createFont();
        font.setFontHeight((short) (20 * 18));
        font.setColor(IndexedColors.WHITE.getIndex());
        for (Cell cell : row) {
            if (isHead) {
                if (textSetRedFont(cell)) {
                    contextCellStyle.setAlignment(HorizontalAlignment.LEFT);
                    cell.setCellStyle(contextCellStyle);
                    continue;
                }
                // 3层表头结构：
                // rowNum == 0: 标题行（蓝色背景，白色字体）
                // rowNum == 1: 说明行（黑色字体，左对齐，无背景）
                // rowNum == 2: 表头行（黑色字体，大小11，无背景）
                if (rowNum == 0) {
                    // 标题行：蓝色背景，白色字体
                    contextCellStyle.setFont(font);
                    contextCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
                    contextCellStyle.setFillForegroundColor(new XSSFColor(new java.awt.Color(48, 84, 150), null));
                } else if (rowNum == 1) {
                    // 说明行：黑色字体，左对齐，无背景
                    Font noteFont = workbook.createFont();
                    noteFont.setFontHeight((short) (20 * 11));
                    noteFont.setColor(IndexedColors.BLACK.getIndex());
                    contextCellStyle.setFont(noteFont);
                    contextCellStyle.setAlignment(HorizontalAlignment.LEFT);
                    contextCellStyle.setFillPattern(FillPatternType.NO_FILL);
                    contextCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
                } else if (rowNum == 2) {
                    // 表头行：黑色字体，大小11，无背景
                    Font headerFont = workbook.createFont();
                    headerFont.setFontHeight((short) (20 * 11));
                    headerFont.setColor(IndexedColors.BLACK.getIndex());
                    contextCellStyle.setFont(headerFont);
                    contextCellStyle.setFillPattern(FillPatternType.NO_FILL);
                    contextCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
                }
            }
            cell.setCellStyle(contextCellStyle);
        }
        
        // 实现自动行高调整，使用手动计算方式避免兼容性问题
        calculateAndSetRowHeight(row);
    }

    /**
     * 手动计算并设置行高
     * @param row 行对象
     */
    private void calculateAndSetRowHeight(Row row) {
        float defaultRowHeight = 30.0f; // 默认行高
        float maxCellHeight = defaultRowHeight;
        
        // 遍历行中的每个单元格，根据内容计算所需高度
        for (Cell cell : row) {
            String cellValue = getCellValueAsString(cell);
            if (cellValue != null) {
                // 计算基于内容的行高
                float cellHeight = calculateCellHeight(cellValue);
                if (cellHeight > maxCellHeight) {
                    maxCellHeight = cellHeight;
                }
            }
        }
        
        // 设置行高，确保不低于默认行高
        row.setHeightInPoints(Math.max(maxCellHeight, defaultRowHeight));
    }
    
    /**
     * 根据单元格内容和列宽计算所需行高
     * @param content 单元格内容
     * @return 计算的行高
     */
    private float calculateCellHeight(String content) {
        if (content == null || content.isEmpty()) {
            return 19.0f;
        }
        // 计算需要的行数
        String[] lines = content.split("\n");
        int lineCount = lines.length;

        
        // 每行大约15点高度
        return lineCount * 19;
    }
    
    public Boolean textSetRedFont(Cell cell) {
        String cellValue = getCellValueAsString(cell);
        if (cellValue != null && cellValue.contains("[RED]")) {
            Workbook workbook = cell.getSheet().getWorkbook();
            // 创建红色字体
            Font redFont = workbook.createFont();
            redFont.setColor(IndexedColors.RED.getIndex());
            redFont.setFontHeight((short) (20 * 14));
            redFont.setBold(true);
            // 创建正常字体
            Font normalFont = workbook.createFont();
            normalFont.setColor(IndexedColors.BLACK.getIndex());
            normalFont.setFontHeight((short) (20 * 12));
            // 移除 [RED] 标记并保留原始内容
            String cleanValue = cellValue.replace("[RED]", "");
            XSSFRichTextString richText = new XSSFRichTextString(cleanValue);
            // 分割文本为行
            String[] lines = cleanValue.split("\n");
            int currentIndex = 0;
            for (String line : lines) {
                // 检查当前行是否包含 [RED] 标记
                if (cellValue.contains("[RED]"+ line)) {
                    richText.applyFont(currentIndex, currentIndex + line.length(), redFont);
                } else {
                    richText.applyFont(currentIndex, currentIndex + line.length(), normalFont);
                }
                currentIndex += line.length() + 1; // +1 for \n
            }

            cell.setCellValue(richText);
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

    /**
     * 安全地获取单元格的字符串值
     *
     * @param cell 单元格对象
     * @return 单元格的字符串表示
     */
    private String getCellValueAsString(Cell cell) {
        if (cell == null) {
            return null;
        }

        try {
            switch (cell.getCellType()) {
                case STRING:
                    return cell.getStringCellValue();
                case NUMERIC:
                    if (DateUtil.isCellDateFormatted(cell)) {
                        return cell.getDateCellValue().toString();
                    } else {
                        // 数值转字符串
                        return String.valueOf(cell.getNumericCellValue());
                    }
                case BOOLEAN:
                    return String.valueOf(cell.getBooleanCellValue());
                case FORMULA:
                    // 尝试获取公式结果
                    try {
                        return cell.getStringCellValue();
                    } catch (Exception e) {
                        try {
                            return String.valueOf(cell.getNumericCellValue());
                        } catch (Exception ex) {
                            return cell.getCellFormula();
                        }
                    }
                case BLANK:
                default:
                    return "";
            }
        } catch (Exception e) {
            // 如果出现异常，返回空字符串而不是抛出异常
            return "";
        }
    }

    private XSSFCellStyle getContextCellStyle(Sheet sheet) {
        Workbook workbook = sheet.getWorkbook();
        Font font = workbook.createFont();
        font.setBold(false);
        font.setFontName("宋体");
        font.setFontHeight((short) (20 * 11));
        XSSFCellStyle headCellStyle = (XSSFCellStyle) workbook.createCellStyle();
        //居中
        headCellStyle.setAlignment(HorizontalAlignment.CENTER);
        headCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
        //设置表头高度
        //上下居中
        headCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        headCellStyle.setFont(font);
        // 设置自动换行;
        headCellStyle.setWrapText(true);
        return headCellStyle;
    }

    @Override
    public void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
        // 不需要实现
    }

    @Override
    public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
        // 在所有数据写入完成后，设置表头列宽自适应
        Sheet sheet = writeSheetHolder.getSheet();
        autoSizeHeaderColumns(sheet, 3);  // 前3行是表头
    }

    /**
     * 设置表头列宽自适应
     */
    private void autoSizeHeaderColumns(Sheet sheet, int headerRowCount) {
        if (sheet.getRow(0) == null) {
            return;
        }
        
        // 遍历所有列
        for (int col = 0; col < sheet.getRow(0).getLastCellNum(); col++) {
            // 遍历表头行，找到最长的内容
            int maxWidth = 0;
            for (int row = 0; row < headerRowCount; row++) {
                Row headerRow = sheet.getRow(row);
                if (headerRow != null) {
                    Cell cell = headerRow.getCell(col);
                    if (cell != null) {
                        String content = cell.getStringCellValue();
                        if (content != null && !content.isEmpty()) {
                            // 中文字符算2个单位，英文算1个单位
                            int width = content.replaceAll("[\u4e00-\u9fa5]", "**").length();
                            maxWidth = Math.max(maxWidth, width);
                        }
                    }
                }
            }
            // 设置列宽，额外增加2个字符的边距
            if (maxWidth > 0) {
                sheet.setColumnWidth(col, (maxWidth + 2) * 256);
            }
        }
    }
}