package digital.laboratory.platform.entrustment.misc;

import digital.laboratory.platform.common.core.constant.OSSDirectoryConstants;
import digital.laboratory.platform.common.oss.service.OssFile;
import digital.laboratory.platform.entrustment.handler.AppStartupRunner;
import lombok.RequiredArgsConstructor;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.StringWriter;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class Template2html {
	private final OssFile ossFile;

	/**
	 * 根据模板生成检材标签的 html, 供 qz 打印使用
	 *
	 * @return html 字符串
	 */
	public String gethtml(String templateName, Map<String, Object> data) throws Exception {
		String templateFileName = AppStartupRunner.getCfg(templateName);

		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		ossFile.fileGet(OSSDirectoryConstants.TEMPLATE_DIRECTORY + "/"+ templateFileName, bos);
		String templateString = bos.toString("UTF-8");
		bos.close();

		try {
			// 设置自定义指令使用的类
			Velocity.setProperty("userdirective",
					"digital.laboratory.platform.entrustment.misc.VelocityQRCodeImage," +
							"digital.laboratory.platform.entrustment.misc.VelocityBarCodeImage");
			//初始化模板
			Velocity.init();

			//获取上下文
			VelocityContext context = new VelocityContext();
			//把数据填入上下文
			for (String key : data.keySet()) {
				context.put(key, data.get(key));
			}

			StringWriter w = new StringWriter();
			Velocity.evaluate(context, w, "Velocity",  templateString);
			w.flush();
			return w.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
