package org.dromara.zhishu.handler;

import com.alibaba.excel.write.handler.RowWriteHandler;
import com.alibaba.excel.write.handler.context.RowWriteHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;

@Slf4j
public class TipRowWriteHandler implements RowWriteHandler {

    private final java.util.Map<Integer, String> tipMap = new java.util.HashMap<>();
    private CellStyle cachedTipStyle;
    private boolean columnWidthSet = false;
    private boolean hasData = false;  // 标记是否有数据

    public TipRowWriteHandler() {
        tipMap.put(5, "表头文字不要有任何改动。");      // 第6行
        tipMap.put(7, "发布商品任务ISBN、价格、库存列必须有且必填。");  // 第8行
        tipMap.put(8, "修改价格、库存、上下架状态任务 ISBN、商品ID、商品编码必填其中一个");  // 第9行
        tipMap.put(10, "用鼠标指向每列的标题都有详细的说明。");  // 第11行
    }

    @Override
    public void beforeRowCreate(RowWriteHandlerContext context) {
        // 设置L列宽度（只一次）
        if (!columnWidthSet && context.getRowIndex() == 0) {
            Sheet sheet = context.getWriteSheetHolder().getSheet();
            sheet.setColumnWidth(11, 80 * 256);
            columnWidthSet = true;
            log.info("已设置L列宽度为80个字符");
        }
    }

    @Override
    public void afterRowDispose(RowWriteHandlerContext context) {
        int rowIndex = context.getRowIndex();

        // 检查是否有数据（除了表头之外的行）
        if (rowIndex > 0) {
            hasData = true;
        }

        // 检查当前行是否是需要写入提示的行
        if (tipMap.containsKey(rowIndex)) {
            Sheet sheet = context.getWriteSheetHolder().getSheet();
            Workbook workbook = sheet.getWorkbook();

            Row row = sheet.getRow(rowIndex);
            if (row == null) {
                row = sheet.createRow(rowIndex);
            }

            Cell cell = row.getCell(11);
            if (cell == null) {
                cell = row.createCell(11);
            }

            cell.setCellValue(tipMap.get(rowIndex));
            cell.setCellStyle(getOrCreateTipStyle(workbook));

            log.debug("已在L{}单元格添加提示文字", rowIndex + 1);
        }

        // 判断是否是最后一行（空LIST时，只有rowIndex=0，不会进入这里）
        // 如果有数据，走上面的逻辑；如果空LIST，不会进入afterRowDispose
    }

    /**
     * 供外部调用的方法：空LIST时手动触发提示写入
     */
    public void addTipsForEmptyList(Sheet sheet) {
        if (sheet == null) {
            return;
        }
        Workbook workbook = sheet.getWorkbook();
        CellStyle tipStyle = getOrCreateTipStyle(workbook);

        for (java.util.Map.Entry<Integer, String> entry : tipMap.entrySet()) {
            int rowIndex = entry.getKey();
            Row row = sheet.getRow(rowIndex);
            if (row == null) {
                row = sheet.createRow(rowIndex);
            }
            Cell cell = row.getCell(11);
            if (cell == null) {
                cell = row.createCell(11);
            }
            cell.setCellValue(entry.getValue());
            cell.setCellStyle(tipStyle);
        }

        log.info("空LIST场景：已在L6、L8、L9、L11添加提示文字");
    }

    private CellStyle getOrCreateTipStyle(Workbook workbook) {
        if (cachedTipStyle == null) {
            Font font = workbook.createFont();
            font.setBold(true);
            font.setFontHeightInPoints((short) 12);
            font.setColor(IndexedColors.RED.getIndex());

            cachedTipStyle = workbook.createCellStyle();
            cachedTipStyle.setFont(font);
            cachedTipStyle.setWrapText(true);
            cachedTipStyle.setAlignment(HorizontalAlignment.LEFT);
            cachedTipStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        }
        return cachedTipStyle;
    }
}