package org.jeecg.modules.common.util;

import freemarker.cache.ClassTemplateLoader;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.io.*;

@Slf4j
public class FreemarkerUtil {
    private static Configuration cfg;

    static {
        cfg = new Configuration(Configuration.getVersion());
        try {
            cfg.setTemplateLoader(new ClassTemplateLoader(FreemarkerUtil.class.getClassLoader(),"/"));
            cfg.setDefaultEncoding("UTF-8");
        } catch (Exception e) {
//            e.printStackTrace();
            log.error(e.getMessage(), e);
        }
    }

    /**
     * 根据模板文件生成
     *
     * @param templeteFilePath
     * @param rootData
     * @param newFilePath
     */
    public static void generteFile(String templeteFilePath, Object rootData,
                            String newFilePath) {
        Writer out = null;
        try {

            Template t = cfg.getTemplate(templeteFilePath, "UTF-8");
            out = new OutputStreamWriter(new FileOutputStream(newFilePath),
                    "UTF-8");
            t.process(rootData, out);
        } catch (Exception e) {
//            e.printStackTrace();
            log.error(e.getMessage(), e);
        } finally {
            try {
                if (out != null)
                    out.close();
            } catch (IOException e) {
//                e.printStackTrace();
                log.error(e.getMessage(), e);
            }
        }
    }

    /**
     * 根据模板文件生成
     *
     * @param url
     * @param fileName
     * @param rootData
     * @param request
     */
    public static InputStream generteFile(String url, String fileName, Object rootData, HttpServletRequest request) {
        ByteArrayOutputStream output = null;
        Writer writer = null;
        try {
            Configuration configuration = new Configuration();
            configuration.setServletContextForTemplateLoading(request.getSession().getServletContext(), url);
            configuration.setDefaultEncoding("utf-8");
            Template t = configuration.getTemplate(fileName);
            output = new ByteArrayOutputStream();
            writer = new BufferedWriter(new OutputStreamWriter(output, "utf-8"), 10240);
            t.process(rootData, writer);
            writer.flush();
            byte[] byteFile = output.toByteArray();
            InputStream inputStream = new ByteArrayInputStream(byteFile, 0, byteFile.length);
            return inputStream;
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
//                    e.printStackTrace();
                    log.error(e.getMessage(), e);
                }
            }
            if (output != null) {
                try {
                    output.close();
                } catch (IOException e) {
//                    e.printStackTrace();
                    log.error(e.getMessage(), e);
                }
            }
        }
    }

    /**
     * 根据模板字符串生成
     *
     * @param templeteString
     * @param rootMap
     * @return
     */
    public static String generteString(String templeteString, Object rootMap) {
        try {
            Configuration cfg = new Configuration();
            StringTemplateLoader stringLoader = new StringTemplateLoader();
            stringLoader.putTemplate("myTemplate", templeteString);
            cfg.setTemplateLoader(stringLoader);
            Template template = cfg.getTemplate("myTemplate", "utf-8");

            StringWriter writer = new StringWriter();
            template.process(rootMap, writer);
            return writer.toString();
        } catch (IOException e) {
//            e.printStackTrace();
            log.error(e.getMessage(), e);
        } catch (TemplateException e) {
//            e.printStackTrace();
            log.error(e.getMessage(), e);
        }
        return "";
    }

    public static String generteStringByFile(String templeteFilePath, Object rootMap) {
        try {
            StringWriter writer = new StringWriter();
            Template t = cfg.getTemplate(templeteFilePath, "UTF-8");
            t.process(rootMap, writer);
            return writer.toString();
        } catch (Exception e) {
//            e.printStackTrace();
            log.error(e.getMessage(), e);
        }
        return "";
    }

}
