package com.rf.psychological.utils;

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.*;
import com.ruiyun.jvppeteer.protocol.DOM.Margin;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutionException;

@Slf4j
public class Html2PNG {

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

        BrowserFetcher.downloadIfNotExist(null);
        ArrayList<String> arrayList = new ArrayList<>();
        PageNavigateOptions pageNavigateOptions = new PageNavigateOptions();
        pageNavigateOptions.setWaitUntil(Collections.singletonList("networkidle2"));
        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");
        }
        arrayList.add("--no-sandbox");
        arrayList.add("--disable-setuid-sandbox");
        Browser browser = Puppeteer.launch(options);
        Page page = browser.newPage();
        //page.goTo("https://www.baidu.com/?tn=98012088_10_dg&ch=3");
        htmlFilePathList.forEach(item -> {
            File file = new File(item);
            try {
                page.goTo("file:///"+file.getAbsolutePath(),pageNavigateOptions);
                ScreenshotOptions screenshotOptions = new ScreenshotOptions();
                // 设置截图范围
                screenshotOptions.setFullPage(true);
                // 设置存放的路径
                screenshotOptions.setPath("./h2p/export_pdf/PDFReport/"+file.getName().replace("html","png"));
                page.screenshot(screenshotOptions);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }finally {
                //删除html文件
                Html2PNG.deleteFile(file);
            }
        });
        page.close();
        browser.close();
    }

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

}
