package org.sky.scientific.utils;

import freemarker.template.Template;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class TemplateService {

	@Autowired
	private FreeMarkerConfigurer freeMarkerConfigurer;

	private final Map<String, Template> cache = new ConcurrentHashMap<>();

	@PostConstruct
	public void init(){
		preloadTemplates();
	}

	private void preloadTemplates(){
		//遍历classpath: templates/下的.ftl文件
		List<String> templates = Arrays.asList("年度高新技术企业发展情况报表.ftl","项目变更表.ftl","项目实施表.ftl","项目立项表.ftl","项目结题表.ftl");
		for (String name : templates) {
			try {
				Template template = freeMarkerConfigurer.getConfiguration().getTemplate(name);
				cache.put(name, template);
			} catch (Exception e) {
				throw new RuntimeException("Failed to preload template: " + name, e);
			}
		}
	}

	public void processTemplate(String templateName, Object data, OutputStreamWriter out){
		Template template = cache.get(templateName);
		try {
			template.process(data, out);
		} catch (Exception e) {
			throw new RuntimeException("Failed to process template: " + templateName, e);
		} finally {
			try {
				out.close();
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		}
	}

}
