package com.bcxin.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.bcxin.utils.constant.Const;
import com.google.common.io.Files;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.util.Objects;

/**
 * <p>
 * 实现文档的在线浏览-转换pdf的同时转为swf
 * </p>
 *
 * @author 罗鹏
 * @date 2018/3/14 
 */
@Data
@Slf4j
public class DocConverter {


    private String environment;
    static Office2Pdf office2Pdf = new Office2Pdf();
    private String outputPath;//文件保存路径，如果不设置就输出在默认位置
    private String outputFolderPath;//文件保存路径，如果不设置就输出在默认位置
    private String sourceFileName;
    private String sourceFileExtension;
    private File localFile;
    private File pdfFile;
    private File swfFile;
    private File zipFile;

    private String httpLocalFile;
    private String httpPdfFile;
    private String httpZipFile;
    private String httpSwfFile;


    /*
     * 初始化
     * @param fileUrl
     */
    public void init(String fileUrl) {

        /*环境：windows :linux(涉及pdf2swf路径问题)*/
        String os = System.getProperty("os.name");
        if (os.toLowerCase().startsWith("win")) {
            environment = "windows";
        } else {
            environment = "linux";
        }

        sourceFileName = Files.getNameWithoutExtension(fileUrl);
        sourceFileExtension = Files.getFileExtension(fileUrl);

        /* 仅仅需要转换 */
        String classifyDir = "temp";

        /*生成路径*/
        String materialPath = ConfigUtil.getValue("material_path");
        this.outputPath = BcxinFileUtil.appendFolderPath(new String[]{materialPath,classifyDir,DateUtil.today()});
        this.outputFolderPath = BcxinFileUtil.appendFolderPath(new String[]{classifyDir,DateUtil.today()});

        String radom = BcxinFileUtil.radom();
        if (StrUtil.isNotEmpty(outputPath)) {
            swfFile = new File(outputPath + radom + ".swf");
            pdfFile = new File(outputPath + radom + ".pdf");
            zipFile = new File(outputPath + radom + ".zip");
            localFile = new File(outputPath + radom + "." + sourceFileExtension);
        }

        String url = ConfigUtil.getValue("web_url");
        httpLocalFile = url + Const.DOWNLOADURL_PREFIX + outputFolderPath + radom + "." + sourceFileExtension;
        httpPdfFile = url + Const.DOWNLOADURL_PREFIX + outputFolderPath + radom + ".pdf";
        httpZipFile = url + Const.DOWNLOADURL_PREFIX + outputFolderPath + radom + ".zip";
        httpSwfFile = url + Const.DOWNLOADURL_PREFIX + outputFolderPath + radom + ".swf";

        /*下载源文件*/
        BcxinFileUtil.download(url,localFile);;

    }


    /*
    * 其他格式转为PDF
    * @param file
    */
    private void doc2pdf() throws Exception {
        String targetFilePath = pdfFile.getAbsolutePath();
        if (!pdfFile.exists()) {
            if ( Const.DOC_FILE_LIST.contains(sourceFileExtension) ) {
                office2Pdf.word2pdf(localFile.getPath(), targetFilePath);
            } else if ( Const.PPT_FILE_LIST.contains(sourceFileExtension)) {
                office2Pdf.ppt2pdf(localFile.getPath(), targetFilePath);
            } else if ( Const.XLS_FILE_LIST.contains(sourceFileExtension)) {
                office2Pdf.excel2pdf(localFile.getPath(), targetFilePath);
            } else if (Const.IMG_FILE_LIST.contains(sourceFileExtension)) {
                office2Pdf.imgToPdf(localFile.getPath(), targetFilePath);
            } else if (Const.ZIP_FILE_LIST.contains(sourceFileExtension)) {
                office2Pdf.zipToPdf(localFile.getPath(), zipFile.getAbsolutePath());
            }
        }
    }

    
    /*
     * 转换成swf
     */
    private void pdf2swf() throws Exception {
        Runtime r = Runtime.getRuntime();
        if (!swfFile.exists()) {
            if (pdfFile.exists()) {
                if (Objects.equals(environment,"windows"))//windows环境处理
                {
                    try {
                        String swftoolsPath = ConfigUtil.getValue("swftools_path");
                        Process p = r.exec(swftoolsPath + "pdf2swf.exe " + pdfFile.getPath() + " -o " + swfFile.getPath() + " -T 9");
                        System.out.print(BcxinFileUtil.loadStream(p.getInputStream()));
                        System.err.print(BcxinFileUtil.loadStream(p.getErrorStream()));
                        System.out.print(BcxinFileUtil.loadStream(p.getInputStream()));
                        System.err.println("****swf转换成功，文件输出：" + swfFile.getPath() + "****");
                        if (pdfFile.exists()) {
                            pdfFile.delete();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        throw e;
                    }
                } else if (Objects.equals(environment,"linux"))//linux环境处理
                {
                    try {
                        Process p = r.exec("pdf2swf " + pdfFile.getPath() + " -o " + swfFile.getPath() + " -T 9");
                        System.out.print(BcxinFileUtil.loadStream(p.getInputStream()));
                        System.err.print(BcxinFileUtil.loadStream(p.getErrorStream()));
                        System.err.println("****swf转换成功，文件输出：" + swfFile.getPath() + "****");
                        if (pdfFile.exists()) {
                            pdfFile.delete();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        throw e;
                    }
                }
            } else {
                System.out.println("****pdf不存在，无法转换****");
            }
        } else {
            System.out.println("****swf已存在不需要转换****");
        }
    }

    /*
     * 转换主方法
     */
    public boolean convert() {
        if (swfFile.exists()) {
            System.out.println("****swf转换器开始工作，该文件已经转换为swf****");
            return true;
        }

        if (Objects.equals(environment,"windows")) {
            System.out.println("****swf转换器开始工作，当前设置运行环境windows****");
        } else {
            System.out.println("****swf转换器开始工作，当前设置运行环境linux****");
        }

        try {
            doc2pdf();
            ///* 如果是pdf转换，且不需要预览功能，则不需要生成 swf*/
            //if ("pdf".equals(ConfigUtil.getValue("convert"))
            //        && "1".equals(how)) {
            //    return true;
            //}

            return true;

            //pdf2swf();
            //if (swfFile.exists()) {
            //
            //} else {
            //    return false;
            //}

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

}
