package com.yeejoin.equipmanage.common.utils;

import freemarker.template.Configuration;
import freemarker.template.Template;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class FreemarkerUtil {
	/**
     * 日志记录器
     */
	final static Logger logger = LoggerFactory.getLogger(FreemarkerUtil.class);


	private static Configuration conf = null;
	private static Map<String, Template> allTemplates = null;
	
	static {
		conf = new Configuration(Configuration.VERSION_2_3_23);
		conf.setDefaultEncoding("UTF-8");
		conf.setClassForTemplateLoading(FreemarkerUtil.class, "/temp");
		allTemplates = new HashMap<>();
		try {
			allTemplates.put("taskTemp", conf.getTemplate("taskTemp.ftl"));
		} catch (IOException e) {
			logger.info(e.getMessage(), e);
			throw new RuntimeException(e);
		}
	}
	
	
	/**
	 * 导出设备测试结果，生成Word文档
	 * 
	 * @param resultMap 测试结果数据
	 * @param tempType 导出文件类型
	 */
	public static File getDocFile(Map<String, Object> resultMap, String tempType) {

		File file = null;
		// 调用createDoc方法生成Word文档
		file = createDoc(resultMap, tempType);
		return file;
	}
	
	private static File createDoc(Map<String, Object> dataMap, String fileType) {
		Date date = new Date();
		String name = "template_" + date.getTime() + ".doc";
		File f = new File(name);
		Template t = allTemplates.get(fileType);
		try {
			// 这个地方不能使用FileWriter因为需要指定编码类型否则生成的Word文档会因为有无法识别的编码而无法打开
			Writer w = new OutputStreamWriter(new FileOutputStream(f), "utf-8");
			t.process(dataMap, w);
			w.close();
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
			throw new RuntimeException(ex);
		}
		return f;
	}
}
