package cn.cecep.talroad.util;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.poi.util.IOUtils;
import org.springframework.boot.system.ApplicationHome;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Map;

@Slf4j
public class ExportWordUtil {

    /**
     * 导出到word返回给响应对象
     * @param dataMap
     * @param response
     */
    public static void exportToWord(Map<String,Object> dataMap , HttpServletResponse response ,String templateFileName,String exportFileName,String downFileName) throws IOException, TemplateException {
        Configuration configuration = new Configuration();
        configuration.setClassForTemplateLoading(ExportWordUtil.class,"/");
        configuration.setDefaultEncoding("UTF-8");
        Template template = configuration.getTemplate(templateFileName);
        File file = new File(exportFileName);
        InputStream resourceAsStream = ExportWordUtil.class.getResourceAsStream("/" + exportFileName);
        if(resourceAsStream == null){
            response.sendError(500,"导出失败，文件损坏，请联系管理员");
            return;
        }
        FileUtils.copyInputStreamToFile(resourceAsStream,file);
        //写入文件中
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream);
        template.process(dataMap,outputStreamWriter);
        //读取流返回给前台
        FileInputStream fileInputStream = new FileInputStream(file);
        response.setContentType("application/force-download");// 设置强制下载不打开
        response.addHeader("Content-Disposition", "attachment;fileName="+downFileName);// 设置文件名
        IOUtils.copy(fileInputStream,response.getOutputStream());
        //关闭流
        IOUtils.closeQuietly(fileInputStream);
        IOUtils.closeQuietly(response.getOutputStream());
        outputStreamWriter.close();
        fileOutputStream.close();
        file.delete();
    }
}
