package com.ruoyi.common.utils;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.ZipUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class WordUtil {

    private static final Configuration configuration;

    public static final String GEN_DIRECTORY = "wordTemp";

    private static final String TEMPLATE_FOLDER = "/wordTemplate";

    private WordUtil() {
    }

    static {
        configuration = new Configuration(Configuration.VERSION_2_3_29);
        configuration.setClassForTemplateLoading(WordUtil.class, TEMPLATE_FOLDER);
        configuration.setDefaultEncoding(CharsetUtil.UTF_8);
    }

    /**
     * 导出excel
     *
     * @param response     响应对象
     * @param dataMap      word文档中参数
     * @param templateName 为模板的名字  例如xxx.ftl
     * @throws IOException
     */
    public static void exportMillCertificateWord(HttpServletResponse response, Map dataMap, String templateName)
        throws IOException {
        Template freemarkerTemplate = configuration.getTemplate(templateName);
        File file = createDoc(dataMap, freemarkerTemplate);
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/x-download");
        String fileName = new String(getFileName().getBytes(), "ISO-8859-1");
        response.setHeader("Content-Disposition", "attachment;filename=".concat(fileName));
        try (InputStream fin = Files.newInputStream(file.toPath());
            ServletOutputStream out = response.getOutputStream();) {
            byte[] buffer = new byte[512];// 缓冲区
            int bytesToRead = -1;
            // 通过循环将读入的Word文件的内容输出到浏览器中
            while ((bytesToRead = fin.read(buffer)) != -1) {
                out.write(buffer, 0, bytesToRead);
            }
        } finally {
            file.deleteOnExit();
        }
    }

    public static File genFile(Map dataMap, String templateName)
        throws IOException {
        Template freemarkerTemplate = configuration.getTemplate(templateName);
        return createDoc(dataMap, freemarkerTemplate);
    }

    private static File createDoc(Map<?, ?> dataMap, Template template) {
        createWordDirectory();
        String filePath =
            getGenDirectory() + File.separator + "报价_" + dataMap.get("quotationNo") + "_" + DateUtils.parseDateToStr(
                "yyyyMMddHHmmssSSS", new Date())
                + ".docx";
        File f = new File(filePath);
        log.info("[报价导出]临时文件路径: [{}]", f.getAbsolutePath());
        Template t = template;
        try (Writer w = new OutputStreamWriter(new FileOutputStream(f), "utf-8")) {
            // 这个地方不能使用FileWriter因为需要指定编码类型否则生成的Word文档会因为有无法识别的编码而无法打开
            t.process(dataMap, w);
        } catch (Exception ex) {
            log.error("根据word模板生成docx异常", ex);
        }
        return f;
    }

    private static void createWordDirectory() {
        File file = new File(getGenDirectory());
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    private static String getGenDirectory() {
        return GEN_DIRECTORY + File.separator + DateUtils.dateTime();
    }


    public static String getFileName() {
        return "temp_" + DateUtils.dateTimeNow() + ".docx";
    }

    public static void exportZip(HttpServletResponse response, List<File> fileList)
        throws IOException {
        String path = getGenDirectory() + File.separator + "zip_" + DateUtils.dateTimeNow() + ".zip";
        File zipFile = new File(path);
        ZipUtil.zip(zipFile, false, fileList.toArray(new File[0]));
        response.setCharacterEncoding(CharsetUtil.UTF_8);
        response.setContentType("application/x-download");
        String fileName = new String(getFileName().getBytes(), StandardCharsets.ISO_8859_1);
        response.setHeader("Content-Disposition", "attachment;filename=".concat(fileName));
        try (InputStream fin = Files.newInputStream(zipFile.toPath());
            ServletOutputStream out = response.getOutputStream();) {
            byte[] buffer = new byte[512];// 缓冲区
            int bytesToRead = -1;
            // 通过循环将读入的Word文件的内容输出到浏览器中
            while ((bytesToRead = fin.read(buffer)) != -1) {
                out.write(buffer, 0, bytesToRead);
            }
        }
    }

}
