package com.ruoyi.web.controller.tool;


import com.ruoyi.common.config.Global;
import com.ruoyi.common.utils.file.FileUploadUtils;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
import org.springframework.util.ResourceUtils;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;

public class FtlToWordUtils {
    private Configuration configuration = null;

    public FtlToWordUtils() {
        configuration = new Configuration();
        configuration.setDefaultEncoding("UTF-8");
    }

    public String createDoc(String templateFileName, String id,
                            Map<String, Object> sDate) throws IOException {
        String fileName = FileUploadUtils.extractFilenameById(id);
        File saveFile = FileUploadUtils.getAbsoluteFileById(fileName);
        Template t = null;
        try {
            // 取模板的路径
            configuration.setDirectoryForTemplateLoading(ResourceUtils.getFile("classpath:templates"));
            // 设置异常处理
            configuration
                    .setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
            // 设置木板的路径文件
            t = configuration.getTemplate(templateFileName);

        } catch (IOException e) {
            e.printStackTrace();
        }
        // 输出文档路径及名称
        Writer out = null;
        try {
            //设置编码格式
            out = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream(saveFile), "utf-8"));
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        try {
            //套用模板，替换变量
            t.process(sDate, out);
            // 清空缓存
            out.flush();
            // 关闭流
            out.close();
        } catch (TemplateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return FileUploadUtils.getPathFileName(Global.getUploadPath(), fileName);
    }
}
