package com.trade.common.utils.file;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

import com.aspose.cells.PdfSaveOptions;
import com.aspose.cells.Workbook;
import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;

/**
 * Aspose OP工具类
 * </p>
 * <新增了excel转pdf的功能 20241109>
 * </p>
 */
public class ASopUtil {

    private static final String licenseStr = "<License>\n" + "  <Data>\n" + "    <Products>\n"
            + "      <Product>Aspose.Total for Java</Product>\n" + "      <Product>Aspose.Words for Java</Product>\n"
            + "    </Products>\n" + "    <EditionType>Enterprise</EditionType>\n"
            + "    <SubscriptionExpiry>20991231</SubscriptionExpiry>\n"
            + "    <LicenseExpiry>20991231</LicenseExpiry>\n"
            + "    <SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>\n" + "  </Data>\n"
            + "  <Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>\n"
            + "</License>";

    public static File docTransfer(InputStream inputStream, String outPath, int saveFormat) {
        if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
            // return;
            throw new RuntimeException("验证License失败");
        }
        File file = null;
        try {
            file = new File(outPath); // 新建一个空白pdf文档
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            FileOutputStream os = new FileOutputStream(file);
            Document doc = new Document(inputStream);
            doc.save(os, saveFormat);// 生成文件
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }

    public static File doc2pdf(String inPath, String outPath) {
        if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
            // return;
            throw new RuntimeException("验证License失败");
        }
        File file = null;
        try {
            file = new File(outPath); // 新建一个空白pdf文档
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            FileOutputStream os = new FileOutputStream(file);
            Document doc = new Document(inPath); // Address是将要被转化的word文档
            doc.save(os, SaveFormat.PDF);// 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,
                                         // EPUB, XPS, SWF 相互转换
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }

    /**
     * excel 转 pdf
     *
     * @param excelFilePath excel文件路径
     */
    public static void excel2pdf(String excelFilePath) {
        excel2pdf(excelFilePath, null, null);
    }

    /**
     * excel 转 pdf
     *
     * @param excelFilePath excel文件路径
     * @param convertSheets 需要转换的sheet
     */
    public static void excel2pdf(String excelFilePath, int[] convertSheets) {
        excel2pdf(excelFilePath, null, convertSheets);
    }

    /**
     * excel 转 pdf
     *
     * @param excelFilePath excel文件路径
     * @param pdfFilePath pdf文件路径
     */
    public static void excel2pdf(String excelFilePath, String pdfFilePath) {
        excel2pdf(excelFilePath, pdfFilePath, null);
    }

    /**
     * excel 转 pdf
     *
     * @param excelFilePath excel文件路径
     * @param pdfFilePath pdf文件路径
     * @param convertSheets 需要转换的sheet
     */
    public static void excel2pdf(String excelFilePath, String pdfFilePath, int[] convertSheets) {
        try {
            getCellsLicense();
            pdfFilePath = pdfFilePath == null ? getPdfFilePath(excelFilePath) : pdfFilePath;
            Workbook wb = new Workbook(excelFilePath);
            FileOutputStream fileOS = new FileOutputStream(pdfFilePath);
            PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
            pdfSaveOptions.setOnePagePerSheet(true);
            if (null != convertSheets) {
                printSheetPage(wb, convertSheets);
            }
            wb.save(fileOS, pdfSaveOptions);
            fileOS.flush();
            fileOS.close();
            System.out.println("convert success");
        } catch (Exception e) {
            System.out.println("convert failed");
            e.printStackTrace();
            throw new RuntimeException("文件转换失败");
        }
    }

    /**
     * 获取 生成的 pdf 文件路径，默认与源文件同一目录
     *
     * @param excelFilePath excel文件
     * @return 生成的 pdf 文件
     */
    private static String getPdfFilePath(String excelFilePath) {
        return excelFilePath.split("\\.")[0] + ".pdf";
    }

    /**
     * 隐藏workbook中不需要的sheet页。
     *
     * @param sheets 显示页的sheet数组
     */
    private static void printSheetPage(Workbook wb, int[] sheets) {
        for (int i = 1; i < wb.getWorksheets().getCount(); i++) {
            wb.getWorksheets().get(i).setVisible(false);
        }
        if (null == sheets || sheets.length == 0) {
            wb.getWorksheets().get(0).setVisible(true);
        } else {
            for (int i = 0; i < sheets.length; i++) {
                wb.getWorksheets().get(i).setVisible(true);
            }
        }
    }

    private static boolean getLicense() {
        boolean result = false;
        try {
            // 凭证
            InputStream license = new ByteArrayInputStream(licenseStr.getBytes(StandardCharsets.UTF_8));
            License asposeLic = new License();
            asposeLic.setLicense(license);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    private static void getCellsLicense() {
        InputStream license = new ByteArrayInputStream(licenseStr.getBytes(StandardCharsets.UTF_8));
        com.aspose.cells.License asposeLic = new com.aspose.cells.License();
        asposeLic.setLicense(license);
    }

    public static void main(String[] args) {
        String inPath = "C:\\Users\\dawn7\\Desktop\\123456789012345678.xlsx";
        String outPath = "C:\\Users\\dawn7\\Desktop\\123456789012345678.pdf";
        excel2pdf(inPath, outPath);
    }
}
