package cn.iocoder.yudao.module.tickets.tools;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * POI-TL工具类
 * @author PQZ
 * @date 13:49 2024/10/12
**/
public class WordUtil {
    /**模版路径*/
    public static String TEMPLATE_PATH = "/templates/gdmb.docx";

    public static void down(HttpServletResponse response, String filePath, String fileName) {
        String encodeName = null;
        try {
            encodeName = encodeStr(fileName);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition,download-filename");
        response.setHeader("Content-disposition", "attachment; filename=" + encodeName + ";" + "filename*=" + "utf-8''" + encodeName);
        response.setHeader("download-filename", encodeName);
        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(filePath));
             // 输出流
             BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());) {
            byte[] buff = new byte[1024];
            int len = 0;
            while ((len = bis.read(buff)) > 0) {
                bos.write(buff, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 编码工具方法
     */
    public static String encodeStr(String fileName) throws UnsupportedEncodingException {
        return URLEncoder.encode(fileName,"UTF-8");
    }

}
