package com.rf.psychological.utils;

import com.rf.psychological.file.ApkDownloadController;
import com.ruiyun.jvppeteer.core.Puppeteer;
import com.ruiyun.jvppeteer.core.browser.Browser;
import com.ruiyun.jvppeteer.core.browser.BrowserFetcher;
import com.ruiyun.jvppeteer.core.page.Page;
import com.ruiyun.jvppeteer.options.LaunchOptions;
import com.ruiyun.jvppeteer.options.LaunchOptionsBuilder;
import com.ruiyun.jvppeteer.options.PDFOptions;
import com.ruiyun.jvppeteer.options.PageNavigateOptions;
import com.ruiyun.jvppeteer.protocol.DOM.Margin;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutionException;

/**
 * @Author:zzf
 * @Date:2022/6/18:11:40
 * @Description: 文件工具类
 */
@Slf4j
public class FileUtil {


    /**
     * html转pdf
     * @param htmlFilePathList html文件路径
     * @throws IOException
     * @throws ExecutionException
     * @throws InterruptedException
     */
    public static void html2pdf(List<String> htmlFilePathList) throws IOException, ExecutionException, InterruptedException {

        //自动下载，第一次下载后不会再下载
        BrowserFetcher.downloadIfNotExist(null);
        ArrayList<String> arrayList = new ArrayList<>();
        //生成pdf必须在无厘头模式下才能生效
        LaunchOptions options = new LaunchOptionsBuilder().withArgs(arrayList).withHeadless(true).build();
        if(OSUtil.isLinux()){
            options.setExecutablePath(".local-browser/linux-722234/chrome-linux/chrome");
        }else{
            options.setExecutablePath(".local-browser/win64-722234/chrome-win/chrome.exe");
        }

        PageNavigateOptions pageNavigateOptions = new PageNavigateOptions();
        pageNavigateOptions.setWaitUntil(Collections.singletonList("networkidle2"));
        PDFOptions pdfOptions = new PDFOptions();
        arrayList.add("--no-sandbox");
        arrayList.add("--disable-setuid-sandbox");
        Browser browser = Puppeteer.launch(options);
        Page page = browser.newPage();
        htmlFilePathList.forEach(item -> {
            File h = new File(item);
            if(!h.exists()){
                return;
            }else{
                try{
                    System.out.println("item------------"+item);
                    System.out.println("h.getName()--"+h.getName());
                    page.goTo("file:///"+h.getAbsolutePath(),pageNavigateOptions);
                    pdfOptions.setPath("./h2p/export_pdf/PDFReport/"+h.getName().replace("html","pdf"));
                    pdfOptions.setFormat("A4");
                    pdfOptions.setPrintBackground(true);
                    Margin margin = new Margin();
                    margin.setTop("70");
                    margin.setBottom("70");
                    margin.setLeft("0");
                    margin.setRight("0");
                    pdfOptions.setMargin(margin);
                    page.pdf(pdfOptions);
                }catch (Exception e){
                    log.error("转换出错："+e.getMessage());
                    e.printStackTrace();
                }finally {
                    //删除html文件
                    FileUtil.deleteFile(h);
                }
            }
        });
        page.close();
        browser.close();
    }

    /**
     * 删除文件
     * @param file
     */
    private static void deleteFile(File file)   {
        if(file.exists())  file.delete();
    }

    /**
     * 文件下载
     * @param file 下载文件信息
     * @param responseFileName 下载文件名称
     * @param deleteFile 是否删除源文件
     */
    public static void downloadFile(HttpServletResponse response,File file,String responseFileName,boolean deleteFile) throws UnsupportedEncodingException {
        response.reset();
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setContentLength((int) file.length());
        String fileName = URLEncoder.encode((responseFileName == null || responseFileName.equals(""))?file.getName():responseFileName,"utf-8");
        response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
        byte[] buffer = new byte[1024];
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        try {
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            OutputStream os = response.getOutputStream();
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {

            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(deleteFile) deleteFile(file);

        }
    }


}
