package com.ruoyi.project.common.controller;


import com.deepoove.poi.XWPFTemplate;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;

import io.jsonwebtoken.lang.Assert;

import org.jodconverter.core.DocumentConverter;
import org.jodconverter.core.document.DefaultDocumentFormatRegistry;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;

import java.util.Map;

/**
 * 通用附件Controller
 *
 * @author ruoyi
 * @date 2020-12-11
 */
@RestController
@RequestMapping("/common/word")
public class WordController extends BaseController
{
    @Resource
    private DocumentConverter documentConverter;

    /**
     * @author lsc
     * @param templatePath word模板文件路径
     * @param fileDir      生成的文件存放地址
     * @param fileName     生成的文件名
     * @param paramMap     参数集合
     * @return 返回word生成的路径
     */
    public String createWord(String templatePath, String fileDir, String fileName, Map<String, Object> paramMap) throws IOException {
        Assert.notNull(templatePath, "word模板文件路径不能为空");
        Assert.notNull(fileDir, "生成的文件存放地址不能为空");
        Assert.notNull(fileName, "生成的文件名不能为空");
        File dir = new File(fileDir);
        if (!dir.exists()) {
            logger.info("目录不存在，创建文件夹{}!", fileDir);
            dir.mkdirs();
        }
        String filePath = fileDir +"/"+ fileName;
        logger.info("目录{}!", filePath);
        // 读取模板渲染参数
        InputStream is = getClass().getClassLoader().getResourceAsStream(templatePath);
        XWPFTemplate template = XWPFTemplate.compile(is).render(paramMap);
        try {
            // 将模板参数写入路径
            template.writeToFile(filePath);
            template.close();
        } catch (Exception e) {
            logger.error("生成word异常{}", e.getMessage());
            e.printStackTrace();
        }
        String pathFileName = getPathFileName(RuoYiConfig.getFilePath("/"+ "ticketWord"), fileName);
        return pathFileName;
    }

    public String createPDF(String fileDir, String wordName,String pdfName, Map<String, Object> paramMap) throws IOException {
        System.out.println("使用流的方式转换PDF！");
        //使用流的方式转换PDF
        try {
            InputStream in = Files.newInputStream(Paths.get(fileDir +"/"+ wordName));
            OutputStream outPDF = Files.newOutputStream(Paths.get(fileDir +"/"+ pdfName));
            documentConverter.convert(in)
                    .as(DefaultDocumentFormatRegistry.DOCX)
                    .to(outPDF)
                    .as(DefaultDocumentFormatRegistry.PDF)
                    .execute();
            System.out.println("转换完成！");
            String pathFileName = getPathFileName(RuoYiConfig.getFilePath("/"+ "ticketWord"), pdfName);
            return pathFileName;
        }catch (Exception e){
            System.out.println("转换出错！");
        }
        return null;
    };


        /**
         * 通用附件上传
         */
    @GetMapping("/createWord")
    public AjaxResult word() throws IOException
    {
        System.out.println("使用流的方式转换PDF！");
        //使用流的方式转换PDF
        try {
            InputStream in = Files.newInputStream(Paths.get("D:/ticket/demo/sems.docx"));
            OutputStream outPDF = Files.newOutputStream(Paths.get("D:/ticket/demo/html.pdf"));
            documentConverter.convert(in)
                    .as(DefaultDocumentFormatRegistry.DOCX)
                    .to(outPDF)
                    .as(DefaultDocumentFormatRegistry.PDF)
                    .execute();
            System.out.println("转换完成！");
        }catch (Exception e){
            System.out.println("转换出错！");
        }


//        Map<String, Object> params = new HashMap<>();
//        // 渲染文本
//        params.put("no","10210120102");
////        params.put("apply_man","知识追寻者");
//
//        // 模板路径
//        String templatePath = "static/word/ticket.docx";
//        // 生成word的路径
//        String fileDir = "D:/ticket/demo";
//        // 生成word的文件
//        String fileName = "zszxz.doc";
//        String wordPath = createWord(templatePath, fileDir, fileName, params);
//
//        try {
//            //读取word文档
//            XWPFDocument document = null;
//            try (InputStream in = Files.newInputStream(Paths.get("D:/ticket/demo/sems.docx"))) {
//                document = new XWPFDocument(in);
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
////             将word转成pdf
//            PdfOptions options = PdfOptions.create();
//            try (OutputStream outPDF = Files.newOutputStream(Paths.get("D:/ticket/demo/html.pdf"))) {
//                PdfConverter.getInstance().convert(document, outPDF, options);
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//            String srcPath = "D:/ticket/demo/sems.doc";
//            String desPath = "D:/ticket/demo/openoffice.pdf";
//            Word2Pdf(srcPath, desPath);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//        System.out.println("生成文档路径：" + wordPath);
        return null;
    }

    // 将word格式的文件转换为pdf格式
    public void Word2Pdf(String srcPath, String desPath) throws IOException {
        // 源文件目录
        File inputFile = new File(srcPath);
        if (!inputFile.exists()) {
            System.out.println("源文件不存在！");
            return;
        }
        // 输出文件目录
        File outputFile = new File(desPath);
        if (!outputFile.getParentFile().exists()) {
            outputFile.getParentFile().exists();
        }
        // 调用openoffice服务线程
        String command = "C:/Program Files (x86)/OpenOffice 4/program/soffice.exe -headless -accept=\"socket,host=127.0.0.1,port=8100;urp;\"";
        Process p = Runtime.getRuntime().exec(command);

        // 连接openoffice服务
//        OpenOfficeConnection connection = new SocketOpenOfficeConnection(
//                "127.0.0.1", 8100);
//        connection.connect();
//
//        // 转换word到pdf
//        DocumentConverter converter = new OpenOfficeDocumentConverter(
//                connection);
//        converter.convert(inputFile, outputFile);
//
//        // 关闭连接
//        connection.disconnect();

        // 关闭进程
        p.destroy();
        System.out.println("转换完成！");
    }

    private static final String getPathFileName(String uploadDir, String fileName) throws IOException
    {
        int dirLastIndex = RuoYiConfig.getProfile().length() + 1;
        String currentDir = StringUtils.substring(uploadDir, dirLastIndex);
        String pathFileName = Constants.RESOURCE_PREFIX + "/" + currentDir + "/" + fileName;
        return pathFileName;
    }

}
