import { ref } from 'vue';
import { ElMessage } from "element-plus"
import JSZip from 'jszip';
import { saveAs } from 'file-saver';
import { getApi } from "@/api/tobAcco_api.js"

const fileList = ref([]); // 文件列表

export async function downloadFiles(a) {
    const zip = new JSZip();

    for (const url of a) {
        const cleanUrl = url.trim().replace(/^`|`$/g, ''); // 去除多余的空格和反引号
        try {
            const response = await fetch(cleanUrl);
            if (!response.ok) {
                throw new Error(`Failed to fetch ${cleanUrl}`);
            }
            const blob = await response.blob();
            const fileName = cleanUrl.split('/').pop();
            zip.file(fileName, blob);
            ElMessage.success('下载成功');
        } catch (error) {
            console.error('下载文件时出错:', error);
        }
    }

    const content = await zip.generateAsync({ type: 'blob' });
    saveAs(content, '反馈附件.zip');
}

export const getUrl = (ids) => {
    fileList.value = [];
    ids.forEach((item) => {
        if (item == "" || item == null) return;
        getApi({}, `/mosty-base/minio/file/download/${item}`).then((res) => {
          fileList.value.push({
            name: res.originalName,
            id: res.id,
            url: res.url,
            suffix: res.suffix
          });
          //去重
          let map = new Map();
          for (let item of fileList.value) {
            map.set(item.id, item);
          }
          fileList.value = [...map.values()];
          if(fileList.value.length == ids.length){
            // 下载文件
            downloadFiles(fileList.value.map(item => item.url));
          }
          console.log('=====================',fileList.value)
        
        });
      });
}

// 使用示例
// const a = [
//     " `http://47.108.232.77:9000/image/2025-06-10/0bf07d8419754d379e77b6d46a501028.txt` ",
//     " `http://47.108.232.77:9000/image/2025-06-10/cf1e7693a2304d3bbf2c1dfb2f9129ba.png` "
// ];
// downloadFiles(a);