package org.springblade.common.utils;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Slf4j
public class ExportWordUtil {

	public static String percentEncode(String s) throws UnsupportedEncodingException {
		String encode = URLEncoder.encode(s, StandardCharsets.UTF_8.toString());
		return encode.replaceAll("\\+", "%20");
	}
	public static void down(HttpServletResponse response, String filePath, String realFileName) {
		String percentEncodedFileName = null;
		try {
			percentEncodedFileName = percentEncode(realFileName);
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
		StringBuilder contentDispositionValue = new StringBuilder();
		contentDispositionValue.append("attachment; filename=").append(percentEncodedFileName).append(";").append("filename*=").append("utf-8''").append(percentEncodedFileName);

		response.addHeader("Access-Control-Allow-Origin", "*");
		response.addHeader("Access-Control-Expose-Headers", "Content-Disposition,download-filename");
		response.setHeader("Content-disposition", contentDispositionValue.toString());
		response.setHeader("download-filename", percentEncodedFileName);
		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 void zipAndDownload(HttpServletResponse response, List<String> filePathList, String zipFileName) {
		try {
			response.setContentType("application/zip");
			response.setHeader("Content-Disposition", "attachment; filename=\"" + percentEncode(zipFileName) + "\"");

			try (ServletOutputStream outputStream = response.getOutputStream();
				 ZipOutputStream zipOut = new ZipOutputStream(outputStream)) {

				for (String filePath : filePathList) {
					File fileToZip = new File(filePath);
					String fileName = fileToZip.getName();

					// 创建ZIP条目
					ZipEntry zipEntry = new ZipEntry(fileName);
					zipOut.putNextEntry(zipEntry);

					// 将文件内容写入ZIP输出流
					try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(fileToZip))) {
						byte[] buff = new byte[1024];
						int len;
						while ((len = bis.read(buff)) > 0) {
							zipOut.write(buff, 0, len);
						}
					}

					// 完成当前ZIP条目的写入
					zipOut.closeEntry();
				}

				// ZIP文件完成，刷新输出流
				zipOut.flush();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
