package cn.wise.sc.cement.business.util;

import cn.wise.sc.cement.business.enumation.FileExt;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * @description:
 * @author: qh
 * @create: 2020-10-10 15:22
 **/
@Slf4j
public class WordUtil {

	/**
	 * 模板路径
	 */
	private static final String FTL_FP = "/templates/";
	private static Configuration configuration;

	static {
		configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
		configuration.setDefaultEncoding("utf-8");
	}

	/**
	 * 根据模板导出office文件
	 *
	 * @param templeName       导出的文件名
	 * @param templateFileName 模板名字
	 * @param beanParams       替换模板中的参数  <${模板占位符},对应值>
	 * @param response         响应体
	 */
	public static void writeWordReport(
			String templeName,
			String templateFileName,
			Map<String, Object> beanParams,
			HttpServletResponse response,
			FileExt fileExt) {
		Writer out = null;
		File file = null;
		try {
			configuration.setClassForTemplateLoading(WordUtil.class, FTL_FP);
			Template template = configuration.getTemplate(templateFileName, "UTF-8");

			String filePath;
			filePath = "";
			file = new File(filePath + templeName);
			//输出文件
			FileOutputStream fos = new FileOutputStream(file);
			out = new OutputStreamWriter(fos, StandardCharsets.UTF_8);
			//变量替换
			template.process(beanParams, out);
			FileInputStream in = new FileInputStream(file);

			byte[] buffer = new byte[in.available()];
			int i = in.read(buffer);
			if (i == -1) {
				return;
			}
			in.close();

			response.reset();
			ServletOutputStream outputStream = response.getOutputStream();
			response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
			response.setContentType("application/octet-stream");
			templeName = new String((templeName).getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
			response.setHeader("Content-Disposition", "attachment;filename=" + templeName + fileExt.getName());
			outputStream.write(buffer);
			outputStream.flush();
			outputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (out != null) {
					out.close();
					boolean delete = file.delete();
					if (!delete) {
						log.debug(file.getName() + "文件删除失败!");
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
