package com.qmth.distributed.print.business.util;

import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.*;
import com.qmth.distributed.print.business.bean.dto.PdfDto;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.enums.PageSizeEnum;
import com.qmth.teachcloud.common.enums.UploadFileEnum;
import com.qmth.teachcloud.common.util.JacksonUtil;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Objects;
import java.util.StringJoiner;

/**
 * @Description: 合并pdf util
 * @Param:
 * @return:
 * @Author: wangliang
 * @Date: 2021/4/7
 */
public class PdfUtil {
    private final static Logger log = LoggerFactory.getLogger(PdfUtil.class);

    /**
     * 将多个PDF合并成一个PDF
     *
     * @param files
     * @param outputPath
     */
    public static String mergePdf(String[] files, String outputPath) {
        if (Objects.nonNull(files)) {
            log.info("files:{},outputPath:{}", JacksonUtil.parseJson(files), outputPath);
        } else {
            log.info("files is null");
        }
        Document document = null;
        PdfCopy copy = null;
        StringJoiner dirName = null;
        try {
            if (Objects.nonNull(files) && files.length > 0) {
                document = new Document(new PdfReader(files[0]).getPageSize(1));
                if (Objects.isNull(outputPath)) {
                    LocalDateTime nowTime = LocalDateTime.now();
                    StringJoiner stringJoiner = new StringJoiner("").add(SystemConstant.PDF_TEMP_FILES_DIR).add(File.separator);
                    dirName = new StringJoiner("")
                            .add(UploadFileEnum.PDF.getTitle()).add(File.separator)
                            .add(String.valueOf(nowTime.getYear())).add(File.separator)
                            .add(String.format("%02d", nowTime.getMonthValue())).add(File.separator)
                            .add(String.format("%02d", nowTime.getDayOfMonth()))
                            .add(File.separator).add(SystemConstant.getUuid()).add(SystemConstant.PDF_PREFIX);
                    outputPath = stringJoiner.toString() + dirName.toString();
                }
                copy = new PdfSmartCopy(document, new FileOutputStream(outputPath));
                document.open();
                for (int i = 0; i < files.length; i++) {
                    PdfReader reader = new PdfReader(files[i]);
                    int numberOfPages = reader.getNumberOfPages();
                    for (int j = 1; j <= numberOfPages; j++) {
                        document.newPage();
                        PdfImportedPage page = copy.getImportedPage(reader, j);
                        copy.addPage(page);
                    }
                    reader.close();
                }
            }
        } catch (Exception e) {
            log.error("请求出错", e);
        } finally {
            if (Objects.nonNull(document)) {
                document.close();
            }
            if (Objects.nonNull(copy)) {
                copy.flush();
                copy.close();
            }
        }
        return Objects.nonNull(dirName) ? dirName.toString() : null;
    }

    /**
     * 新增pdf page
     *
     * @param pdfFile
     * @return
     * @throws IOException
     */
    public static PdfDto addPdfPage(File pdfFile) throws IOException {
        PdfReader reader = null;
        FileOutputStream fileOutputStream = null;
        int pageCount = 0;
        try {
            if (Objects.nonNull(pdfFile)) {
                reader = new PdfReader(pdfFile.getPath());
                pageCount = reader.getNumberOfPages();
                if (Math.abs(pageCount % 2) == 1) {//取偶
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    PdfStamper stamper = new PdfStamper(reader, baos);
                    stamper.insertPage(pageCount + 1, reader.getPageSizeWithRotation(1));
                    stamper.close();
                    fileOutputStream = new FileOutputStream(pdfFile);
                    IOUtils.write(baos.toByteArray(), fileOutputStream);
                }
            }
        } catch (Exception e) {
            log.error("请求出错", e);
        } finally {
            if (Objects.nonNull(reader)) {
                reader.close();
            }
            if (Objects.nonNull(fileOutputStream)) {
                fileOutputStream.flush();
                fileOutputStream.close();
            }
        }
        return new PdfDto(PageSizeEnum.A3, Objects.nonNull(reader) ? reader.getNumberOfPages() : 0, pageCount);
    }

    /**
     * 获取pdfPages
     *
     * @param pdfFile
     * @return
     * @throws IOException
     */
    public static int getPdfPages(File pdfFile) throws IOException {
        PdfReader reader = null;
        try {
            if (Objects.nonNull(pdfFile)) {
                reader = new PdfReader(pdfFile.getPath());
                return reader.getNumberOfPages();
            }
        } catch (Exception e) {
            log.error("请求出错", e);
        } finally {
            if (Objects.nonNull(reader)) {
                reader.close();
            }
        }
        return 0;
    }

//    public static void main(String[] args) {
//        String[] files = {
//                "/Users/king/Downloads/测试附件/101_148382537591291904_signAndSticker.pdf",
//                "/Users/king/Downloads/pdf/3120ee49668e4bf48fd8c161a2abb73b的副本A3.pdf",
//                "/Users/king/Downloads/测试附件/101_158277997340655616_paperPackage.pdf"
////                "/Users/king/Downloads/测试附件/101_148382537591291904_signAndSticker.pdf"
//        };
//        String outputPath = "/Users/king/Downloads/pdf/merge1.pdf";
//        PdfUtil.mergePdf(files, outputPath);
//    }
}
