package com.yiboshi.science.utils;

import freemarker.cache.ClassTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.InputStreamSource;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Locale;

public class WordUtils {
    public void export( Object dataModel,HttpServletResponse response,String templateName) {
        Configuration configuration = new Configuration();
        configuration.setDefaultEncoding("utf-8");
        configuration.setEncoding(Locale.getDefault(), "utf-8");
        try {
            response.setContentType("application/msword; charset=UTF-8");// application/x-download
            response.setHeader("content-disposition", "attachment;filename=document.doc");
            response.setHeader("Accept-Ranges", "bytes");
//          response.setHeader("Content-Disposition", "attachment; " + encodeFileName(request, fileName + ".doc"));
            OutputStream outputStream = response.getOutputStream();
            Writer out = new OutputStreamWriter(outputStream);

            configuration.setClassicCompatible(true);//处理dataModel中如果为null的情况
            //既能保证本地运行找得到模板文件，又能保证jar包运行能找到得到模板文件
            configuration.setClassForTemplateLoading(this.getClass(), "/template");
            configuration.setTemplateLoader(new ClassTemplateLoader(this.getClass(), "/template"));
            Template template = configuration.getTemplate(templateName, "utf-8");
            template.process(dataModel, out);

            outputStream.close();
            out.close();
        } catch (IOException | TemplateException e) {
            e.printStackTrace();
        }
    }

    public void exportStream(HttpServletResponse response, Object dataModel) {
        Configuration configuration = new Configuration();
        configuration.setDefaultEncoding("utf-8");
        configuration.setEncoding(Locale.getDefault(), "utf-8");
        try {
            configuration.setClassicCompatible(true);//处理dataModel中如果为null的情况
            //既能保证本地运行找得到模板文件，又能保证jar包运行能找到得到模板文件
            configuration.setClassForTemplateLoading(this.getClass(), "/template");
            configuration.setTemplateLoader(new ClassTemplateLoader(this.getClass(), "/template"));
            Template template = configuration.getTemplate("word.ftl", "utf-8");

            InputStreamSource file = createDoc(dataModel, template);
            InputStream fin = file.getInputStream();
            ServletOutputStream out;

            response.setContentType("application/x-msdownload");
            response.setHeader("content-disposition", "attachment;filename=document.doc");
            response.setHeader("Accept-Ranges", "bytes");

            out = response.getOutputStream();
            // 缓冲区
            byte[] buffer = new byte[1024];
            int bytesToRead;
            while ((bytesToRead = fin.read(buffer)) != -1) {
                out.write(buffer, 0, bytesToRead);
            }
            out.flush();
            fin.close();
        } catch (IOException | TemplateException e) {
            e.printStackTrace();
        }
    }

    public static InputStreamSource createDoc(Object dataModel, Template template) throws TemplateException, IOException, TemplateException {
        StringWriter out1 = new StringWriter();
        Writer out = new BufferedWriter(out1, 10240);
        //将数据输出到模板
        template.process(dataModel, out);
        out.close();
        out1.close();
        return new ByteArrayResource(out1.toString().getBytes(StandardCharsets.UTF_8));
    }

    public String encodeFileName(HttpServletRequest request, String fileName) throws UnsupportedEncodingException {
        String new_filename = URLEncoder.encode(fileName, "UTF8").replaceAll("\\+", "%20");
        String agent = request.getHeader("USER-AGENT").toLowerCase();
        if (null != agent && -1 != agent.indexOf("msie")) {
            /**
             * IE浏览器，只能采用URLEncoder编码
             */
            return "filename=\"" + new_filename + "\"";
        } else if (null != agent && -1 != agent.indexOf("applewebkit")) {
            /**
             * Chrome浏览器，只能采用ISO编码的中文输出
             */
            return "filename=\"" + new String(fileName.getBytes("UTF-8"), "ISO8859-1") + "\"";
        } else if (null != agent && -1 != agent.indexOf("opera")) {
            /**
             * Opera浏览器只可以使用filename*的中文输出
             * RFC2231规定的标准
             */
            return "filename*=" + new_filename;
        } else if (null != agent && -1 != agent.indexOf("safari")) {
            /**
             * Safani浏览器，只能采用iso编码的中文输出
             */
            return "filename=\"" + new String(fileName.getBytes("UTF-8"), "ISO8859-1") + "\"";
        } else if (null != agent && -1 != agent.indexOf("firefox")) {
            /**
             * Firfox浏览器，可以使用filename*的中文输出
             * RFC2231规定的标准
             */
            return "filename*=" + new_filename;
        } else {
            return "filename=\"" + new_filename + "\"";
        }
    }
}
