package com.emr.util;

import com.itextpdf.text.pdf.PdfCopyFields;
import com.itextpdf.text.pdf.PdfReader;
import com.lowagie.text.Document;
import com.lowagie.text.PageSize;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfImportedPage;
import com.lowagie.text.pdf.PdfWriter;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

public class PDFHelper
{
    public static int GetTotalPages(String pdfPath) throws Exception
    {
        if (!FileHelper.File_IsExist(pdfPath))
        {
            return 0;
        }
        PdfReader reader = new PdfReader(pdfPath);
        return reader.getNumberOfPages();
    }
    public static void Append(List<String> pdfPathes, String toPath) throws Exception
    {
        if (pdfPathes.size() == 0)
        {
            return;
        }
        for (String srcPath:pdfPathes
             ) {
            Append(srcPath, toPath);

        }
    }
    public static void Append(String pdfPath, String toPath) throws Exception
    {
        if (!FileHelper.File_IsExist(pdfPath))
        {
            return;
        }
        int pdfPageCount = GetTotalPages(pdfPath);
        List<Integer> pdfPageNos = new ArrayList<>();
        for (Integer i = 0; i < pdfPageCount; i++)
        {
            pdfPageNos.add(i);
        }
        GetPDFPagesToFile(pdfPath, pdfPageNos, toPath);
    }
    public static void Append(String pdfPath, List<Integer> pdfPageNos, String toPath)throws Exception
    {
        if (!FileHelper.File_IsExist(pdfPath))
        {
            return;
        }
        int pdfPageCount = GetTotalPages(pdfPath);
        for (Integer pdfPageNo:pdfPageNos
             ) {

            if (pdfPageNo < 0 || pdfPageNo > pdfPageCount - 1) {
                throw new ExSys("Invalid page number! \"{0}\"", pdfPageNo);
            }
        }
        GetPDFPagesToFile(pdfPath, pdfPageNos, toPath);
    }
    public static void Append(String pdfPath, int pdfPageNoFrom, int pdfPageNoTo, String toPath)throws Exception
    {
        List<Integer> pdfPageNos = new ArrayList<>();
        for (Integer i = pdfPageNoFrom; i <= pdfPageNoTo; i++)
        {
            pdfPageNos.add(i);
        }
        GetPDFPagesToFile(pdfPath, pdfPageNos, toPath);
    }

    public static void GetPDFPagesToFile(String pdfPath, List<Integer> pdfPageNos, String toPath) throws Exception
    {
        if (!FileHelper.File_IsExist(pdfPath))
        {
            return;
        }
        if (pdfPageNos.size() == 0)
        {
            return;
        }
        int pdfPageCount = GetTotalPages(pdfPath);
        for  (Integer pdfPageNo : pdfPageNos)
        {
            if (pdfPageNo < 0 || pdfPageNo > pdfPageCount - 1)
            {
                throw new ExSys("Invalid page number! \"{0}\"", pdfPageNo);
            }
        }
        String tmpFile = FileHelper.GetTempFile();
        try
        {
            //toReader一定要在PdfCopyFields之后释放
            PdfReader toReader = null;
            if (FileHelper.File_IsExist(toPath))
            {
                toReader = new PdfReader(toPath);
            }
            try
            {
                //pdfReader一定要在PdfCopyFields之后释放
                PdfReader pdfReader = new PdfReader(pdfPath);
                FileOutputStream tmpFileStream = new FileOutputStream(tmpFile);
                PdfCopyFields tmpCpy = new PdfCopyFields(tmpFileStream);
                tmpCpy.open();
                try
                {
                    if (toReader != null)
                    {
                        tmpCpy.addDocument(toReader);
                    }
                    for (Integer pageNo:pdfPageNos
                         ) {
                        tmpCpy.addDocument(pdfReader, String.format("%d", pageNo + 1));
                    }
                }
                finally
                {
                    tmpCpy.close();
                    if(tmpFileStream!=null)
                    {
                        tmpFileStream.close();
                    }
                    if(pdfReader!=null)
                    {
                        pdfReader.close();
                    }
                }
            }
            finally
            {
                if (toReader != null)
                {
                    toReader.close();
                }
            }
            FileHelper.DeleteFile(toPath);
            FileHelper.CopyFile(tmpFile, toPath);
        }
        finally
        {
            FileHelper.DeleteFile(tmpFile);
        }
    }

    public static void Convert2A4(String pdf, String toPath) throws Exception {
        Document document = new Document(PageSize.A4);
        PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream(toPath));
        document.open();
        PdfContentByte cb = pdfWriter.getDirectContent();
        com.lowagie.text.pdf.PdfReader pdfReader = new com.lowagie.text.pdf.PdfReader(pdf);

        for (int j = 1; j <= pdfReader.getNumberOfPages(); j++) {
            // 新增一页，不然多页的PDF会重合到一页
            document.newPage();
            PdfImportedPage page = pdfWriter.getImportedPage(pdfReader, j);
            // 计算缩小比例 以最大缩小比例为主
            // pdfReader.getPageSize(index) index是从1开始不是0
            float w = PageSize.A4.getWidth() / pdfReader.getPageSize(1).getWidth();
            float h = PageSize.A4.getHeight() / pdfReader.getPageSize(1).getHeight();
            float Scale = w > h ? h : w;
            cb.addTemplate(page, Scale, 0, 0, Scale, 0, 0);
        }

        document.close();
    }
}
