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 org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFDrawing;
import org.apache.poi.xssf.usermodel.XSSFSheet;

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

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

    @Override
    public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
        Workbook workbook = writeWorkbookHolder.getWorkbook();
        Sheet sheet = writeSheetHolder.getSheet();

        // 获取设备图片列索引（假设是第4列，索引3）
        int imageColIndex = 3;

        // 遍历所有行
        for (int rowIndex = 1; rowIndex <= sheet.getLastRowNum(); rowIndex++) { // 从第2行开始（跳过标题）
            Row row = sheet.getRow(rowIndex);
            if (row == null) continue;

            Cell imageCell = row.getCell(imageColIndex);
            if (imageCell == null) continue;

            // 获取图片数据
            byte[] imageData = null;
            if (imageCell.getCellType() == CellType.STRING) {
                // 处理Base64编码的图片（如果需要）
            }

            if (imageData != null && imageData.length > 0) {
                try {
                    // 添加图片到工作表
                    int pictureIdx = workbook.addPicture(imageData, Workbook.PICTURE_TYPE_JPEG);

                    // 创建绘图对象
                    if (sheet instanceof XSSFSheet) {
                        XSSFSheet xssfSheet = (XSSFSheet) sheet;
                        XSSFDrawing drawing = xssfSheet.createDrawingPatriarch();

                        // 设置图片位置
                        XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, imageColIndex, rowIndex, imageColIndex + 1, rowIndex + 1);

                        // 创建图片
                        drawing.createPicture(anchor, pictureIdx);
                    }

                    // 清除单元格内容
                    imageCell.setBlank();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}