package io.renren.common.utils;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.commons.lang.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

@SuppressWarnings("deprecation")
public class ExportWordUtils {
    private Template template;

    public ExportWordUtils(String basePackage, String templateName) throws Exception {
        init(basePackage, templateName);
    }

    private void init(String basePackage, String templateName) throws Exception {
        Configuration config = new Configuration();//需要指定版本
        config.setClassLoaderForTemplateLoading(io.renren.common.utils.ExportWordUtils.class.getClassLoader(), basePackage);//去那个文件夹下寻找模板文件
        config.setOutputEncoding("utf-8");
        template = config.getTemplate(templateName);//模板名称获取模板
    }

    public <K, V> void doExport(OutputStream out, Map<K, V> results) throws TemplateException, IOException {
        template.process(results, new OutputStreamWriter(out));//对模板进行数据填充
    }

    public void setHeader(HttpServletRequest request, HttpServletResponse response, String fileName) throws UnsupportedEncodingException {
        String userAgent = request.getHeader("User-Agent");
        if(StringUtils.contains(userAgent, "MSIE")||StringUtils.contains(userAgent, "Trident") ||
                StringUtils.contains(userAgent, "Edge")){ //解决IE中文名称乱码
            fileName = URLEncoder.encode(fileName,"UTF8");
        }else if(StringUtils.contains(userAgent, "Firefox")){//火狐和其他浏览器中文名乱码
            fileName = new String(fileName.getBytes("utf8"), "ISO8859-1");
        }
        response.setContentType("application/octet-stream;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;" + " filename=\""+fileName+"\"");
    }
}


