package com.fuyuanshen.equipment.handler;

import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import org.apache.poi.ss.usermodel.*;

import java.util.Map;

/**
 * @author: 默苍璃
 * @date: 2025-06-07 18:05
 */
public class ImageWriteHandler implements SheetWriteHandler {

    private Map<Integer, byte[]> imageMap;
    private int imageColIndex;

    public ImageWriteHandler(Map<Integer, byte[]> imageMap) {
        this(imageMap, 2);
    }

    public ImageWriteHandler(Map<Integer, byte[]> imageMap, int imageColIndex) {
        this.imageMap = imageMap;
        this.imageColIndex = imageColIndex;
    }

    @Override
    public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
        if (imageMap == null || imageMap.isEmpty()) {
            return;
        }

        Workbook workbook = writeWorkbookHolder.getWorkbook();
        Sheet sheet = writeSheetHolder.getSheet();

        // 设置图片列的宽度
        sheet.setColumnWidth(imageColIndex, 20 * 256); // 20个字符宽度

        for (Map.Entry<Integer, byte[]> entry : imageMap.entrySet()) {
            int dataRowIndex = entry.getKey();
            int rowIndex = dataRowIndex + 1; // 跳过标题行
            byte[] imageData = entry.getValue();

            if (imageData != null && imageData.length > 0) {
                insertImage(workbook, sheet, rowIndex, imageData);
            }
        }
    }

    private void insertImage(Workbook workbook, Sheet sheet, int rowIndex, byte[] imageData) {
        try {
            // 获取或创建行（确保行存在）
            Row row = sheet.getRow(rowIndex);
            if (row == null) {
                row = sheet.createRow(rowIndex);
            }

            // 设置合适的行高（不要设置过大）
            row.setHeightInPoints(60); // 60磅，足够显示小图

            // 添加图片到工作簿
            int pictureIdx = workbook.addPicture(imageData, Workbook.PICTURE_TYPE_JPEG);

            // 创建绘图对象
            Drawing<?> drawing = sheet.createDrawingPatriarch();

            // 关键修改：使用MOVE_DONT_RESIZE锚点类型，避免影响行高
            ClientAnchor anchor = workbook.getCreationHelper().createClientAnchor();
            anchor.setAnchorType(ClientAnchor.AnchorType.MOVE_DONT_RESIZE);
            anchor.setCol1(imageColIndex);
            anchor.setRow1(rowIndex);
            anchor.setCol2(imageColIndex + 1);
            anchor.setRow2(rowIndex + 1);

            // 设置较小的偏移量，确保图片在单元格内
            anchor.setDx1(0);
            anchor.setDy1(0);
            anchor.setDx2(512 * 5); // 约5个字符宽度
            anchor.setDy2(256 * 4); // 约4行高度

            // 插入图片
            Picture picture = drawing.createPicture(anchor, pictureIdx);

            // 不要调用resize()，避免自动调整影响行高
            // picture.resize();

        } catch (Exception e) {
            System.err.println("插入图片失败，行: " + rowIndex);
            e.printStackTrace();
        }
    }

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