package com.hotwj.platform.reportStatistics.template;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
import org.springframework.stereotype.Component;

import java.io.StringWriter;

@Component
public class VelocityTemplateRenderer {
    private final VelocityEngine engine;

    public VelocityTemplateRenderer() {
        engine = new VelocityEngine();
        engine.setProperty(RuntimeConstants.RESOURCE_LOADER, "class");
        engine.setProperty("class.resource.loader.class", ClasspathResourceLoader.class.getName());
        engine.setProperty(RuntimeConstants.INPUT_ENCODING, "UTF-8");
        engine.init();
    }

    public String render(String templatePath, VelocityContext ctx) {
        Template tpl = engine.getTemplate(templatePath, "UTF-8");
        StringWriter sw = new StringWriter();
        tpl.merge(ctx, sw);
        return sw.toString();
    }
}
