package org.example.mybatisplus.tools;


import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.Document;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPageMar;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPageSz;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSectPr;

import javax.imageio.ImageIO;
import java.awt.Color;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class ImageUtils {
    public static List<BufferedImage> convertPdfToImages(String pdfPath, int dpi) throws Exception {
        PDDocument document = PDDocument.load(new File(pdfPath));
        PDFRenderer renderer = new PDFRenderer(document);
        List<BufferedImage> images = new ArrayList<>();
        for (int i = 0; i < document.getNumberOfPages(); i++) {
            BufferedImage image = renderer.renderImageWithDPI(i, dpi);
            images.add(image);
        }
        document.close();
        return images;
    }
    public static BufferedImage convertSheetToImage(Sheet sheet) {
        // 计算表格尺寸
        int rows = sheet.getPhysicalNumberOfRows();
        int cols = sheet.getRow(0).getPhysicalNumberOfCells();
        int cellWidth = 100;
        int cellHeight = 20;
        int imageWidth = cols * cellWidth;
        int imageHeight = rows * cellHeight;

        BufferedImage image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = image.createGraphics();
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, imageWidth, imageHeight);
        g.setColor(Color.BLACK);

        // 绘制表格内容
        for (int i = 0; i < rows; i++) {
            Row row = sheet.getRow(i);
            for (int j = 0; j < cols; j++) {
                Cell cell = row.getCell(j);
                String value = cell != null ? cell.toString() : "";
                g.drawString(value, j * cellWidth + 2, i * cellHeight + 15);
            }
        }
        g.dispose();
        return image;
    }
    public static void main(String[] args) throws Exception {
        InputStream in = new FileInputStream("G:\\Code\\new\\fxy-tool\\input.docx");
        // 创建新文档
        XWPFDocument document = new XWPFDocument(in);
        // 插入PDF图片
//        List<BufferedImage> pdfImages = PdfToImage.convertPdfToImages("input.pdf", 150);
//        for (BufferedImage img : pdfImages) {
//            insertImage(doc, img, "PDF_Page");
//        }

        // 插入Excel图片
        Workbook workbook = WorkbookFactory.create(new File("G:\\Code\\new\\fxy-tool\\input.xls"));
        for (Sheet sheet : workbook) {
            BufferedImage excelImage = convertSheetToImage(sheet);
            insertImage1(document, excelImage, "Excel_Sheet");
        }
        workbook.close();

        // 创建段落和运行对象
        /*XWPFParagraph paragraph = document.createParagraph();
        XWPFRun run = paragraph.createRun();
        PDDocument pdf = PDDocument.load(new File("G:\\Code\\new\\fxy-tool\\1.pdf"));
        PDFRenderer renderer = new PDFRenderer(pdf);
        for (int i = 0; i < pdf.getNumberOfPages(); i++) {
            BufferedImage image = renderer.renderImageWithDPI(i, 300);
            // 读取图片文件到字节数组
            InputStream is = bufferedImageToInputStream(image,"jpg");
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = is.read(buffer)) != -1) {
                baos.write(buffer, 0, bytesRead);
            }
            byte[] imageBytes = baos.toByteArray();

            // 获取图片原始尺寸
            int originalWidth = image.getWidth();
            int originalHeight = image.getHeight();

            // 获取页面设置
            CTSectPr sectPr = document.getDocument().getBody().getSectPr();
            if (sectPr == null) {
                sectPr = document.getDocument().getBody().addNewSectPr();
            }

            // 获取页面宽度和边距（单位为Twips）
            CTPageSz pageSize = sectPr.getPgSz();
            CTPageMar pageMar = sectPr.getPgMar();

            long pageWidthTwips = Long.parseLong(pageSize.getW().toString());
            long leftMarginTwips = Long.parseLong(pageMar.getLeft().toString());
            long rightMarginTwips = Long.parseLong(pageMar.getRight().toString());

            // 计算可用宽度（Twips）并转换为EMU
            long availableWidthTwips = pageWidthTwips - leftMarginTwips - rightMarginTwips;
            int targetWidthEMU = (int) (availableWidthTwips * Units.EMU_PER_DXA);

            // 计算目标高度（保持宽高比）
            int targetHeightEMU = (int) (targetWidthEMU * ((double) originalHeight / originalWidth));

            // 插入图片
            run.addPicture(new ByteArrayInputStream(imageBytes),
                    Document.PICTURE_TYPE_JPEG,
                    "pdf"+i+".png",
                    targetWidthEMU,
                    targetHeightEMU);
        }
        pdf.close();*/
        // 保存文档
        FileOutputStream out = new FileOutputStream("output.docx");
        document.write(out);
        out.close();
        document.close();
    }
    public static InputStream bufferedImageToInputStream(BufferedImage bufferedImage, String format) throws IOException {
        // 创建一个ByteArrayOutputStream来存储图像数据
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // 使用ImageIO将BufferedImage写入到ByteArrayOutputStream中
        ImageIO.write(bufferedImage, format, baos);
        // 将ByteArrayOutputStream转换为InputStream，以便在其他地方使用
        return new ByteArrayInputStream(baos.toByteArray());
    }
    private static void insertImage1(XWPFDocument doc, BufferedImage image, String title) throws Exception {
        XWPFParagraph para = doc.createParagraph();
        XWPFRun run = para.createRun();
        // 将BufferedImage转为字节数组
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, "PNG", baos);
        byte[] imageData = baos.toByteArray();

        // 计算图片尺寸
        int widthEMU = Units.toEMU(image.getWidth());
        int heightEMU = Units.toEMU(image.getHeight());

        run.addPicture(new ByteArrayInputStream(imageData),
                XWPFDocument.PICTURE_TYPE_PNG,
                "image.png",
                widthEMU,
                heightEMU);
    }
    static void insertImage(XWPFDocument doc, XWPFParagraph p, String imagePath, XWPFRun placeholderRun) throws IOException {
        try (FileInputStream is = new FileInputStream(imagePath)) {
            XWPFRun run = p.createRun();


            // 图片文件路径
            File imageFile = new File(imagePath);
            // 读取图片文件到字节数组
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = is.read(buffer)) != -1) {
                baos.write(buffer, 0, bytesRead);
            }
            byte[] imageBytes = baos.toByteArray();

            // 获取图片原始尺寸
            BufferedImage image = ImageIO.read(imageFile);
            int originalWidth = image.getWidth();
            int originalHeight = image.getHeight();

            // 获取页面设置
            CTSectPr sectPr = doc.getDocument().getBody().getSectPr();
            if (sectPr == null) {
                sectPr = doc.getDocument().getBody().addNewSectPr();
            }

            // 获取页面宽度和边距（单位为Twips）
            CTPageSz pageSize = sectPr.getPgSz();
            CTPageMar pageMar = sectPr.getPgMar();

            long pageWidthTwips = Long.parseLong(pageSize.getW().toString());
            long leftMarginTwips = Long.parseLong(pageMar.getLeft().toString());
            long rightMarginTwips = Long.parseLong(pageMar.getRight().toString());

            // 计算可用宽度（Twips）并转换为EMU
            long availableWidthTwips = pageWidthTwips - leftMarginTwips - rightMarginTwips;
            int targetWidthEMU = (int) (availableWidthTwips * Units.EMU_PER_DXA);

            // 计算目标高度（保持宽高比）
            int targetHeightEMU = (int) (targetWidthEMU * ((double) originalHeight / originalWidth));

            // 插入图片
            run.addPicture(new ByteArrayInputStream(imageBytes),
                    Document.PICTURE_TYPE_PNG,
                    imageFile.getName(),
                    targetWidthEMU,
                    targetHeightEMU);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}