package com.ruoyi.business.utils;

import net.lingala.zip4j.io.inputstream.ZipInputStream;
import net.lingala.zip4j.io.outputstream.ZipOutputStream;
import net.lingala.zip4j.model.LocalFileHeader;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.model.enums.CompressionLevel;
import net.lingala.zip4j.model.enums.CompressionMethod;
import net.lingala.zip4j.model.enums.EncryptionMethod;
import okhttp3.Response;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class FileZipUtils {

    public static void decryptZip(Response response) throws Exception {
        Path storageDir = Paths.get(
                System.getProperty("user.dir"), // 获取项目根目录
                "ruoyi-modules/ruoyi-system-dataexchange/src/main/resources/filesIn" // 指定存储目录
        ).toAbsolutePath();
        // 确保目录存在
        Files.createDirectories(storageDir);
        // 修改为项目根目录下的存储路径
        System.out.println("Final storage path: " + storageDir.toAbsolutePath());
        // System.out.println("响应体body: " + response.body().string());

        // 确保目录存在
        Files.createDirectories(storageDir);
        try (InputStream responseInputStream = response.body().byteStream()) {
            // 2. 设置ZIP密码
            String password = "QLdQIASYMlT9SUUg";
            List<String> extractedContents = new ArrayList<>();
            try (ZipInputStream zipInputStream = new ZipInputStream(responseInputStream, password.toCharArray())) {
                LocalFileHeader fileHeader;
                byte[] buffer = new byte[8192]; // 8KB 缓冲区
                // 遍历 ZIP 中的每个文件
                while ((fileHeader = zipInputStream.getNextEntry()) != null) {
                    String fileName = fileHeader.getFileName().split("_")[1];
                    Path outputPath = storageDir.resolve(fileName);
                    // 确保父目录存在
                    Files.createDirectories(outputPath.getParent());
                    try (OutputStream outputStream = Files.newOutputStream(outputPath)) {
                        int bytesRead;
                        while ((bytesRead = zipInputStream.read(buffer)) != -1) {
                            outputStream.write(buffer, 0, bytesRead);
                        }
                    }
                }
            }
        }
    }


    public static void getEncryptZip(HttpServletResponse response, Map<String, String> fileInfo) throws IOException {
        // 1. 定义要下载的图片URL列表
        List<String> imageUrls = new ArrayList<>();
        Path storageDir = Paths.get(
                System.getProperty("user.dir"), // 获取项目根目录
                "ruoyi-modules\\ruoyi-system-dataexchange\\src\\main\\resources\\filesOut" // 改用Windows路径分隔符
        ).toAbsolutePath();
        imageUrls.add(storageDir.resolve(fileInfo.get("Name")).toString());
        // imageUrls.add(storageDir.resolve("1512b987-6954-4533-8154-e8b8bcce5a6e.png").toString());
        // 2. 设置ZIP密码
        String password = "8iot1blDJgNK36Do";
        setResHeader(response, "MaterialFile-"+fileInfo.get("Id")+".zip");
        // 3. 创建ZIP输出流（直接写入HTTP响应流）
        try (ServletOutputStream outputStream = response.getOutputStream()) {
            try (ZipOutputStream zipOut = new ZipOutputStream(outputStream, password.toCharArray())) {
                for (String imageUrl : imageUrls) {
                    try (FileInputStream fileInputStream = new FileInputStream(new File(imageUrl))) {
                        addFileToZip(zipOut, fileInputStream, fileInfo.get("Id")+"_"+imageUrl.substring(imageUrl.lastIndexOf("\\") + 1));
                    }
                }
            }
        }
    }

    /**
     * @Description: 设置响应头
     * @data:[response,zipFileName 文件名没有后缀]
     * @Author: J
     * @Date: 2025-03-26 13:57:13
     */
    public static void setResHeader(HttpServletResponse response, String zipFileName) {
        try {
            response.setContentType("application/zip");
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(zipFileName + ".zip", "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @Description: 将图片下载并打包成ZIP文件，写入输出流
     * @data:[zipOut zip输出流, imageInputStream 单个文件流, fileName 单个文件名称带后缀]
     * @Author: J
     * @Date: 2025-03-26 13:55:10
     */
    public static void addFileToZip(ZipOutputStream zipOut, InputStream imageInputStream, String fileName) throws IOException {
        ZipParameters zipParams = new ZipParameters();
        zipParams.setCompressionMethod(CompressionMethod.DEFLATE); // 使用 DEFLATE 算法
        zipParams.setCompressionLevel(CompressionLevel.HIGHER);    // 设置压缩级别
        zipParams.setFileNameInZip(fileName);
        zipParams.setEncryptFiles(true);
        zipParams.setEncryptionMethod(EncryptionMethod.AES);
        // 3. 开始写入ZIP条目
        zipOut.putNextEntry(zipParams);
        // 4. 下载图片并流式写入ZIP
        try (InputStream imageStream = imageInputStream) {
            int bytesRead;
            byte[] buffer = new byte[8192]; // 8KB缓冲区
            while ((bytesRead = imageStream.read(buffer)) != -1) {
                zipOut.write(buffer, 0, bytesRead);
            }
        }
        // 5. 关闭当前条目
        zipOut.closeEntry();
    }


}
