package com.yizhi.application.caseLibrary.util;

import com.alibaba.fastjson.JSON;
import com.yizhi.application.caseLibrary.constant.CaseLibraryConstants;
import org.icepdf.core.exceptions.PDFException;
import org.icepdf.core.exceptions.PDFSecurityException;
import org.icepdf.core.pobjects.Document;
import org.icepdf.core.pobjects.Page;
import org.icepdf.core.util.GraphicsRenderingHints;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * *
 *
 * @param
 * @author dingxiaowei
 * @date 2019/7/18
 * @return
 */
@Component
public class StuCommonUtils {


    private static final Logger LOGGER = LoggerFactory.getLogger(StuCommonUtils.class);

    @Autowired
    private StuUpConvert stuUpConvert;


    @Value("${ACTIVE}")
    public String active;

    /**
     * 将上传的pdf转换成图片拼接富文本
     *
     * @param pdfFileName
     * @param pdfOssUrl
     */
    public String translatePdfToPhoto(String pdfOssUrl, String pdfFileName) {
        if (StringUtils.isEmpty(pdfOssUrl) || StringUtils.isEmpty(pdfFileName)) {
            return null;
        }

        String imageDir = null;
        try {
            imageDir = stuUpConvert.convert(pdfOssUrl, pdfFileName, CaseLibraryConstants.DOC_PATH, 200, 0, CaseLibraryConstants.OPENOFFICE_PATH);
        } catch (IOException e) {
            LOGGER.error("将上传的pdf转换成图片拼接富文本，错误：", e);
        }

        File dir = new File(imageDir);
        File[] files = dir.listFiles();

        String uploadFile;
        String key;
        List<String> imageOssPathList = new ArrayList<>(files.length);

        if (files.length > 0) {
            for (File file : files) {
                uploadFile = file.getAbsolutePath();
                key = pdfFileName.substring(0, pdfFileName.lastIndexOf(".")) + "/" + file.getName() + System.currentTimeMillis();
                String result = OssUpload.upload(uploadFile, key, active);
                imageOssPathList.add(result);
            }
            //上传完成以后,将本地文件夹删除
            deleteDir(dir);
        }

        if (!CollectionUtils.isEmpty(imageOssPathList)) {
            String htmlBR = "<p><br></p>";
            String content = htmlBR;
            StringBuilder sb = new StringBuilder(content);

            for (int i = 1; i <= imageOssPathList.size(); i++) {
                for (String image : imageOssPathList) {
                    String index = image.substring(image.lastIndexOf("/") + 1, image.lastIndexOf("."));
                    if (index.equals(String.valueOf(i))) {
                        sb.append("<p><img src=\" " + image + " \" /></p>");
                        sb.append("<p><br></p>");
                    }
                }
            }

            return sb.toString();
        }
        return null;
    }


    public String downLoadFromUrl(String urlStr, String fileName, String outputFilePath) {

        File file = null;
//        FileInfo fileInfo = new FileInfo();
        try {
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //防止屏蔽程序抓取而返回403错误
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            conn.setRequestProperty("Charsert", "UTF-8");
            conn.setRequestProperty("Accept-Charset", "UTF-8");
            //得到输入流
            InputStream inputStream = conn.getInputStream();
            //获取自己数组
            byte[] buffer = new byte[1024];
            int len = 0;
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            while ((len = inputStream.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }
            bos.close();

            byte[] getData = bos.toByteArray();
            //文件保存位置
            File saveDir = new File(outputFilePath);
            if (!saveDir.exists()) {
                saveDir.mkdirs();
            }
            file = new File(saveDir + File.separator + fileName);
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(getData);
            if (fos != null) {
                fos.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
        } catch (Exception e) {
            LOGGER.info("fileName={},outputFilePath={}", fileName, outputFilePath);
            LOGGER.info("urlStr={},异常={}", urlStr, JSON.toJSONString(e));
        }
        return file.getAbsolutePath();
    }


//    /**
//     * pdf转pdf(scale 默认1.0)
//     * @param pdfPath pdf路径
//     * @param outputFilePath 输出图片路径
//     * @param endPage 截取到n页结束
//     * @param filename 文件名
//     * @throws InterruptedException
//     * @throws PDFException
//     * @throws PDFSecurityException
//     * @throws IOException
//     */
//    public boolean convert(String pdfPath, String outputFilePath,int endPage,String filename)
//            throws InterruptedException, PDFException, PDFSecurityException, IOException {
//        return convert(pdfPath, outputFilePath,1.0f,endPage,filename);
//    }


    public String pdfToPng(String pdfPath, String outputFilePath, int dpi, int flag) {
        try {
            boolean retStatus = pdfToPng1(pdfPath, outputFilePath, 1.5f, flag, "");
        } catch (Exception e) {
            LOGGER.info("Pdf转Png发生错误{}", JSON.toJSONString(e));
        }
        return outputFilePath;
    }

    /**
     * pdf转pdf
     *
     * @param pdfPath        pdf路径
     * @param outputFilePath 输出图片路径
     * @param scale          放大比例 （放大比例越大越清晰）
     * @param endPage        截取到n页结束
     * @param filename       文件名
     * @throws InterruptedException
     * @throws PDFException
     * @throws PDFSecurityException
     * @throws IOException
     */
    public boolean pdfToPng1(String pdfPath, String outputFilePath, float scale, int endPage, String filename)
            throws InterruptedException, PDFException, PDFSecurityException, IOException {

        if (createDirectory(outputFilePath)) {

            Document document = new Document();
            document.setFile(pdfPath);

            int pages = document.getNumberOfPages();
            if (endPage > 0) {//大于0则打印具体页数
                if (endPage < pages) {
                    pages = endPage;
                }
            }

            //float scale = 2.0f;
            float rotation = 0f;

            for (int i = 0; i < pages; i++) {
                BufferedImage image = (BufferedImage)
                        document.getPageImage(i,
                                GraphicsRenderingHints.PRINT,
                                Page.BOUNDARY_TRIMBOX, rotation, scale);
                RenderedImage rendImage = image;

                String imgFilePathPrefix = outputFilePath + File.separator + filename + (i + 1) + ".png";

                File file = new File(imgFilePathPrefix);
                ImageIO.write(rendImage, "png", file);

                image.flush();
                document.dispose();
            }

        }
        return true;
    }


    private static boolean createDirectory(String folder) {
        File dir = new File(folder);
        if (dir.exists()) {
            return true;
        } else {
            return dir.mkdirs();
        }
    }

    //删除法目录方法
    private static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            //递归删除目录中的子目录下
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        // 目录此时为空，可以删除
        return dir.delete();
    }


}
