import { saveAs } from 'file-saver';
import JSZip from 'jszip';
import request from '@/utils/ImageRequest';
import { show_message } from './tdesign_tool';
import { v4 } from 'uuid';

const getFile = (url: string) => {
  return new Promise((resolve, reject) => {
    request
      .get(url, {
        responseType: 'blob',
        // headers:{
        // }
      })
      .then((res) => {
        resolve(res);
      })
      .catch((error) => {
        reject(error);
      });
  });
};
export const batchQrCodeZip = async (list: any[]) => {
  const zip = new JSZip();
  const promises: any[] = [];
  for (const item of list) {
    const promise = getFile(item).then((data: any) => {
      const cur_id = v4();
      // 下载文件, 并存成ArrayBuffer对象
      zip.file(cur_id + '.png', data, { binary: true }); // 逐个添加文件，需要加后缀".png"
    });
    promises.push(promise);
  }
  const zipname = 'expamle.zip';
  Promise.all(promises)
    .then((res) => {
      zip.generateAsync({ type: 'blob' }).then((content) => {
        // 生成二进制流
        saveAs(content, zipname); // 利用file-saver保存文件  自定义文件名
        show_message('导出成功', 'success');
      });
    })
    .catch((res) => {
      show_message('导出失败', 'error');
    });
};
