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

import cn.wise.sc.acquisition.business.enumation.FileExt;
import cn.wise.sc.acquisition.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.*;
import java.nio.charset.StandardCharsets;
import java.util.List;
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");
			if (template ==null){
				System.out.println("==========================\n 报错-================\n");
			}
			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);
			/*HSSFWorkbook xssfWorkbook = new HSSFWorkbook(in);
			ByteArrayOutputStream os = new ByteArrayOutputStream();
			xssfWorkbook.write(os);
			byte[] bytes = os.toByteArray();*/

			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();
			}
		}
	}


	/**
	 * 根据模板导出office文件  带上下标的
	 *
	 * @param templeName       导出的文件名
	 * @param templateFileName 模板名字
	 * @param beanParams       替换模板中的参数  <${模板占位符},对应值>
	 * @param response         响应体
	 */
	public static void writeWordReportSXB(
			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");
			if (template ==null){
				System.out.println("==========================\n 报错-================\n");
			}
			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);
			/*HSSFWorkbook xssfWorkbook = new HSSFWorkbook(in);
			ByteArrayOutputStream os = new ByteArrayOutputStream();
			xssfWorkbook.write(os);
			byte[] bytes = os.toByteArray();*/

			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();
			}
		}
	}

}
