package com.ruoyi;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.core.util.ZipUtil;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.domain.TestRecords;
import com.ruoyi.service.TestRecordsService;
import org.apache.commons.io.IOUtils;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@SpringBootTest
public class TestDownload {

    @Autowired
    private TestRecordsService testRecordsService;

    @Test
    public void Test() throws FileNotFoundException {
        Set<String> addedFiles = new HashSet<>(); // 用于存储已经添加的文件名

        // 压缩包的名称和路径
        String zipFilePath = "D:\\downloaded_files.zip";
        // 创建ZIP输出流
//        FileOutputStream fos = new FileOutputStream(zipFilePath);
//        ZipOutputStream zos = new ZipOutputStream(fos);
        try (FileOutputStream fos = new FileOutputStream(zipFilePath);
             ZipOutputStream zos = new ZipOutputStream(fos)) {
            Long taskId = 1808391769025445890L;
            List<TestRecords> list = testRecordsService.selectListByTaskId(taskId);
            list.forEach(testRecord -> {
                System.out.println("testRecord = " + testRecord);
            });


            // 转换列表中每个 TestRecords 对象的 attachmentId 字段为字符串数组
            List<String[]> convertedList = list.stream()
                    .filter(testRecord -> {
                        String attachmentId = testRecord.getAttachmentId();
                        return attachmentId != null;
                    })
                    .map(testRecord -> testRecord.getAttachmentId().split("、"))
                    .collect(Collectors.toList());

            convertedList.forEach(testRecord -> {
                System.out.println("convertedList = " + testRecord);
            });
            // 遍历convertedList中的每个数组
            for (String[] attachments : convertedList) {
                // 遍历数组中的每个元素
                for (String attachmentId : attachments) {
                    HttpResponse response = HttpUtil.createPost("https://10.12.48.78:8090/api/project/download/" + attachmentId)
                            .execute();

                    if (response.isOk()) {
                        System.out.println("response = " + response);

                        // 从响应头中获取文件名,这里Content-Disposition头包含文件名
                        String contentDisposition = response.header("Content-Disposition");
                        String fileName = parseAndDecodeFilename(contentDisposition);

                        if (StrUtil.isNotBlank(fileName) && !addedFiles.contains(fileName)) {
                            addedFiles.add(fileName); // 添加文件名到集合中

                            // 创建ZIP条目并写入到ZIP输出流
                            ZipEntry zipEntry = new ZipEntry(fileName);
                            zos.putNextEntry(zipEntry);

                            // 直接从HTTP响应中读取字节并写入到ZIP输出流
                            IOUtils.copy(response.bodyStream(), zos);

                            // 完成条目写入
                            zos.closeEntry();

                            // 关闭输出流
//                            IoUtil.close(zos);
//                            IoUtil.close(fos);

                            System.out.println("文件已添加到压缩包:" + zipFilePath);

                        } else {
                            System.err.println("无法从响应头中提取文件名");
                        }
                    } else {
                        System.err.println("下载失败,状态码:" + response.getStatus());
                    }
                }
            }

        }  catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 解码文件名称
     * @param contentDisposition
     * @return
     * @throws UnsupportedEncodingException
     */
    private static String parseAndDecodeFilename(String contentDisposition) throws UnsupportedEncodingException {
        String[] parts = contentDisposition.split("; ");
        for (String part : parts) {
            if (part.startsWith("filename*")) {
                // 分割出编码后的文件名,忽略前缀如 utf8''
                int start = part.indexOf("''") + 2;
                String encodedFileName = part.substring(start).trim();
                // 解码文件名
                return URLDecoder.decode(encodedFileName, String.valueOf(StandardCharsets.UTF_8));
            }
        }
        return null; // 如果没有找到filename*则返回null
    }
}