package com.wmyun.module.system.service.pdf;

import cn.hutool.core.io.IoUtil;
import com.wmyun.module.infra.api.file.FileApi;
import com.wmyun.module.system.controller.admin.pdf.vo.PdfResultVO;
import jakarta.annotation.Resource;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;


/**
 * @author zhouc
 * @date 2025/3/1 15:42
 * @className PdfSplitServiceImpl
 * @description
 */

@Service
public class PdfSplitServiceImpl implements PdfSplitService {
    @Resource
    private FileApi fileService;

    public List<PdfResultVO> splitPdf(File sourceFile, String outputDir) throws IOException {
        List<PdfResultVO> results = new ArrayList<>();
        try (PDDocument document = PDDocument.load(sourceFile)) {
            int totalPages = document.getNumberOfPages();
            for (int i = 0; i < totalPages; i++) {
                // 创建单页文档
                PDDocument singlePageDoc = new PDDocument();
                singlePageDoc.addPage(document.getPage(i));
                // 生成文件名和路径
                String fileName = "page_" + (i + 1) + ".pdf";
                File outputFile = new File(outputDir, fileName);
                singlePageDoc.save(outputFile);
                MultipartFile multipartFile = convertToMultipartFile(outputFile.getAbsolutePath());
                String filePath = fileService.createFile(fileName, null, IoUtil.readBytes(multipartFile.getInputStream()));
                // 构建返回VO
                results.add(new PdfResultVO(
                        fileName,
                        filePath,
                        outputFile.length()
                ));
                singlePageDoc.close();
            }
        }
        return results;
    }

    public MultipartFile convertToMultipartFile(String filePath) throws IOException {
        File file = new File(filePath);
        FileInputStream input = new FileInputStream(file);
        return new MockMultipartFile(
                "file",          // 表单字段名
                file.getName(),   // 原始文件名
                Files.probeContentType(file.toPath()),    // MIME类型（需根据实际文件类型修改）
                input            // 文件流
        );
    }

    public void splitPdfByPages(File sourceFile, String outputDir, int startPage, int endPage) throws IOException {
        try (PDDocument document = PDDocument.load(sourceFile)) {
            int totalPages = document.getNumberOfPages();
            // 校验页码范围
            if (startPage < 1 || endPage > totalPages) {
                throw new IllegalArgumentException("页码超出范围");
            }

            PDDocument newDoc = new PDDocument();
            for (int i = startPage - 1; i < endPage; i++) {
                newDoc.addPage(document.getPage(i));
            }

            String fileName = sourceFile.getName().replace(".pdf",
                    "_split_" + startPage + "-" + endPage + ".pdf");
            newDoc.save(new File(outputDir, fileName));
            newDoc.close();
        }
    }

    public void splitAllPages(File sourceFile, String outputDir) throws IOException {
        try (PDDocument document = PDDocument.load(sourceFile)) {
            int totalPages = document.getNumberOfPages();
            for (int i = 0; i < totalPages; i++) {
                PDDocument singlePageDoc = new PDDocument();
                singlePageDoc.addPage(document.getPage(i));
                singlePageDoc.save(new File(outputDir, "page_" + (i + 1) + ".pdf"));
                singlePageDoc.close();
            }
        }
    }
    // PDF转多张图片（每页一张）
    public List<PdfResultVO> PdfToImageConverter(File pdfFile, String outputDir) throws IOException {
        List<PdfResultVO> results = new ArrayList<>();
        try (PDDocument document = PDDocument.load(pdfFile))  {
            PDFRenderer renderer = new PDFRenderer(document);
            for (int i = 0; i < document.getNumberOfPages();  i++) {
                BufferedImage image = renderer.renderImageWithDPI(i,  300); // 300 DPI
                String imageName = "page_" + (i + 1) + ".png";
                File outputImage = new File(outputDir, imageName);
                ImageIO.write(image,  "PNG", outputImage);
//                imagePaths.add(outputImage.getAbsolutePath());
                MultipartFile multipartFile = convertToMultipartFile(outputImage.getAbsolutePath());
                String filePath = fileService.createFile(imageName, null, IoUtil.readBytes(multipartFile.getInputStream()));
                // 构建返回VO
                results.add(new PdfResultVO(
                        imageName,
                        filePath,
                        outputImage.length()
                ));
            }
        }
        return results;
    }
}
