package com.jtyjy.pdf2pptx.converter;

import com.alibaba.fastjson.JSONObject;
import com.jtyjy.pdf2pptx.application.ShutdownContext;
import com.jtyjy.pdf2pptx.controller.WebSocketServer;
import com.jtyjy.pdf2pptx.support.Constant;
import com.jtyjy.pdf2pptx.support.FileUtil;
import com.jtyjy.pdf2pptx.support.PdfTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * pdf转pptx
 * 常量Constant.SOURCE_PATH为待转换文件根目录
 *
 * @author guan
 */
@Component
public class Pdf2Pptx {

    private static final Logger logger = LoggerFactory.getLogger(Pdf2Pptx.class);

    // 执行标识
    private static boolean exeFlag = true;

    private static ExecutorService executorService;

    public static Integer totalPdf = 0;

    public static transient Integer finishPdf = 0;

    @Autowired
    private RestTemplate restTemplate;

    public long converte(String path) {
        return conver(path, this);
//        shutdownContext.initiateShutdown(0);
    }

    private static long conver(String path, Pdf2Pptx pdf2Pptx) {
        long totalTime = 0L;
        System.setProperty("java.awt.headless", "false");
        //读取指定文件夹下所有文件并转换为图片
        long startTime = System.currentTimeMillis();
        List<String> allFilePathName = new ArrayList<>();
        FileUtil.getAllFilePathNameRe(path, allFilePathName);
        //判断图片是否存在
        List<String> allFilePathName2 = new ArrayList<>();
        FileUtil.getAllFilePathNameRe(path, allFilePathName2);
        for (String filePathName : allFilePathName) {
            if (filePathName.endsWith(".pdf")&&!allFilePathName2.contains(filePathName.replace(".pdf", ".pptx"))) {
                totalPdf++;
            }
        }
        logger.info("待转换pdf总数：{}", totalPdf);
        for (String filePathName : allFilePathName) {
            File file = new File(filePathName);
            if (file.getName().endsWith(".pdf")) {
                if (!allFilePathName2.contains(file.getAbsolutePath().replace(".pdf", ".pptx"))) {
                    logger.info("转换pdf：{} 为图片开始", file.getAbsolutePath());
                    long begin = System.currentTimeMillis();
                    executorService = Executors.newFixedThreadPool(6);
                    Pdf2Png.pdf2Image(file.getAbsolutePath(), file.getParent(), 300, executorService);
                    long end = System.currentTimeMillis();
                    logger.info("转换pdf：{} 为图片完成，耗时{}ms", file.getAbsolutePath(), end - begin);
                    while (exeFlag) {
                        if (((ThreadPoolExecutor) executorService).getActiveCount() == 0) {
                            executorService.shutdown();
                            exeFlag = false;
                            System.out.println("转换图片已经完成");
                            Pdf2Pptx.finishPdf++;
                            logger.info("已转换pdf数量：{}", Pdf2Pptx.finishPdf);
                            //发送消息
                            try {
                                Double message = (Double.valueOf(finishPdf) / (Double.valueOf(totalPdf) * Double.valueOf(2)))*Double.valueOf(100);
                                pdf2Pptx.restTemplate.getForObject( "http://localhost:8080/checkcenter/socket/push/1994?message="+message, Object.class);
                            } catch (Exception e) {
                                logger.error("推送消息出错：", e);
                            }
                        }
                    }
                    exeFlag = true;
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        logger.error("错误：", e);
                    }
                } else {
                    logger.info("文件：{} 已经转换", file.getAbsolutePath());
                    System.err.println("文件：[" + file.getAbsolutePath() + "] 已经转换");
                }

            }
        }


        //将图片插入PPT
        List<String> allDirPathName = new ArrayList<>();
        FileUtil.getAllDirPathNameRe(path, allDirPathName);
        List<String> threads = new ArrayList<>();
        threads.add("1");
        threads.add("2");
        threads.add("3");
        threads.add("4");
        Map<String, List<String>> allot = allotOfAverage(threads, allDirPathName);
        ExecutorService executorService = Executors.newFixedThreadPool(4);
        for (int i = 1; i <= 4; i++) {
            if (allot.get(String.valueOf(i)) != null) {
                executorService.execute(new PdfTask(allot.get(String.valueOf(i)), path,pdf2Pptx.restTemplate));
            }
        }
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            logger.error("错误：{}", e);
        }
        while (exeFlag) {
            if (((ThreadPoolExecutor) executorService).getActiveCount() == 0) {
                executorService.shutdown();
                exeFlag = false;
                System.out.println("转换ppt已经完成");
                logger.info("转换所有ppt已经完成");
            }
        }
        long endTime = System.currentTimeMillis();
        totalTime = endTime - startTime;
        logger.info("总耗时：{}ms", totalTime);
        //删除所有生成的图片文件
        for (String dirPathName : allDirPathName) {
            if (dirPathName.endsWith("_图片") && FileUtil.delFolder(dirPathName)) {
                logger.info("删除文件夹：{}及其文件成功", dirPathName);
            }
        }
        pdf2Pptx.restTemplate.getForObject( "http://localhost:8080/checkcenter/socket/push/1994?message="+100, Object.class);
        return totalTime;
    }

    /**
     * 平均分配
     *
     * @param users
     * @param tasks
     * @return
     */
    public static Map<String, List<String>> allotOfAverage(List<String> users, List<String> tasks) {
        //保存分配的信息
        Map<String, List<String>> allot = new ConcurrentHashMap<String, List<String>>();
        if (users != null && users.size() > 0 && tasks != null && tasks.size() > 0) {
            for (int i = 0; i < tasks.size(); i++) {
                int j = i % users.size();
                if (allot.containsKey(users.get(j))) {
                    List<String> list = allot.get(users.get(j));
                    list.add(tasks.get(i));
                    allot.put(users.get(j), list);
                } else {
                    List<String> list = new ArrayList<String>();
                    list.add(tasks.get(i));
                    allot.put(users.get(j), list);
                }
            }
        }
        return allot;
    }

    public static void main(String[] args) {
        double message =  (Double.valueOf(1) / (Double.valueOf(3) * Double.valueOf(2))*Double.valueOf(100));
        System.out.println(message);
    }

}
