package com.njcn.event.utils;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;

/**
 * @author hongawen
 * @version 1.0.0
 * @date 2022年08月23日 19:32
 */
@Component
public class FreemarkerUtil {
    @Autowired
    FreeMarkerConfigurer freeMarkerConfigurer;
    private static String path = FreemarkerUtil.class.getClassLoader().getResource("").getPath();

    public  String generateString(String templateFileName, String templateDirectory, Map<String, Object> datas)
            throws IOException, TemplateException {
        // 生成模板对象
        Template template =  freeMarkerConfigurer.getConfiguration().getTemplate(templateFileName);

        // 将datas写入模板并返回
        try (StringWriter stringWriter = new StringWriter()) {
            template.process(datas, stringWriter);
            stringWriter.flush();
            return stringWriter.getBuffer().toString();
        }
    }
}
