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

import com.wmyun.module.system.controller.admin.pdf.vo.PdfResultVO;
import org.apache.pdfbox.pdmodel.PDDocument;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zhouc
 * @date 2025/3/1 15:42
 * @className PdfSplitServiceImpl
 * @description
 */
public class PdfSplitServiceImpl {
    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);

                // 构建返回VO
                results.add(new PdfResultVO(
                        fileName,
                        outputFile.getAbsolutePath(),
                        outputFile.length()
                ));
                singlePageDoc.close();
            }
        }
        return results;
    }

    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();
            }
        }
    }
}
