import JSZip from 'jszip'
import FileSaver from 'file-saver'
import { message } from 'antd';

function getBase64Image(img: any) {
    let canvas = document.createElement('canvas');
    canvas.width = img.width;
    canvas.height = img.height;
    let ctx = canvas.getContext('2d') as any;
    ctx.drawImage(img, 0, 0, img.width, img.height);
    let ext = img.src.substring(img.src.lastIndexOf('.') + 1).toLowerCase();
    return canvas.toDataURL('image/' + ext);
}

/**
 * 将Base64字符串转换为data URL
 * @param {string} base64String - Base64字符串
 * @param {string} fileType - 文件类型
 * @return {string} data URL
 */
const base64ToURL = (base64String: any, fileType: any) => {
    // fileType 是你要处理的文件类型，比如 'application/pdf'、'image/png' 等
    // 直接将 Base64 字符串嵌入到 URL 中
    const url = `data:${fileType};base64,${base64String}`;
    return url;
}

//传入图片路径，返回base64
const getBase64 = (img: any) => {
    let image = new Image();
    image.setAttribute('crossOrigin', 'anonymous'); // 必须设置在src之前，跨域使用
    image.src = img;
    return new Promise((resolve) => {
        if (img) {
            image.onload = () => {
                resolve(getBase64Image(image));
            }
        }
    })
}

//将完整的base64转换为blob
const dataURLtoBlob = (dataurl: any) => {
    var arr = dataurl.split(","),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n)
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
    }
    return new Blob([u8arr], { type: mime })
}

// 将base64转换为文件
const base64ImgtoFile = (dataurl: any, filename = 'file') => {
    try {
        const arr = dataurl.split(',')
        const mime = arr[0].match(/:(.*?);/)[1]
        const suffix = mime.split('/')[1]
        const bstr = atob(arr[1])
        let n = bstr.length
        const u8arr = new Uint8Array(n)
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n)
        }
        return new File([u8arr], `${filename}.${suffix}`, {
            type: mime
        })
    } catch (err) {
        return Promise.reject(err);
    }
}


export default function toZip(imgSrcList: any, fileName: any) {
    let imgBase64 = [] as any;
    let zip = new JSZip();  //实例化一个压缩文件对象
    let imgFolder = zip.folder(fileName) as any;; //新建一个图片文件夹用来存放图片，参数为文件名
    for (let i = 0; i < imgSrcList.length; i++) {
        let src = imgSrcList[i];
        imgBase64.push(src.substring(22))
        // let suffix = src.substring(src.lastIndexOf('.'));
        // getBase64(src)
        //     .then((base64: any) => imgBase64.push(base64.substring(22)))
        //     .catch(error => console.log('error', error))

    }

    function polling() {
        setTimeout(() => {
            if (imgSrcList.length === imgBase64.length) {
                for (let i = 0; i < imgSrcList.length; i++) {
                    imgFolder.file(i + '.png', imgBase64[i], { base64: true });
                }
                zip.generateAsync({ type: 'blob' }).then(function (content) {
                    FileSaver.saveAs(content, `${fileName}.zip`);
                });
                message.destroy()
                message.success('打包完成')
            } else {
                console.log('已完成：' + imgBase64.length + '/' + imgSrcList.length)
                polling();
            }
        }, 300);
    }

    polling();
}
