import streamSaver from "streamsaver";
import "./zip-stream.js";
import store from '@/store'
import dcmjs from './dcmUpload/dcmjs'
streamSaver.mitm = `${window.location.origin}/mitm.html?version=2.0.0`
// 下载文件并压缩
function zipFiles(zipName, files) {
    return new Promise((resolve) => {
        try {
            console.log("同步下载打包开始时间：" + new Date());
            store.dispatch('trials/setUnLock', true)
            files = formatFiles(files)
            // 创建压缩文件输出流  
            let zipFileOutputStream = streamSaver.createWriteStream(zipName);
            // 创建下载文件流  
            const fileIterator = files.values();
            let Url = [];
            let readableZipStream = new ZIP({
                async pull(ctrl) {
                    const fileInfo = fileIterator.next();
                    if (fileInfo.done) {//迭代终止  
                        ctrl.close();
                    } else {
                        let { name, url, IsEncapsulated = false } = fileInfo.value;
                        if (IsEncapsulated) {
                            url = await downloadFileToUrl(url)
                            Url.push(url)
                        }
                        // url = decodeUtf8(url); // 待定，可能做过特殊处理
                        return fetch(url).then(res => {
                            ctrl.enqueue({
                                name,
                                stream: () => res.body
                            });
                        })
                    }
                }
            });
            if (window.WritableStream && readableZipStream.pipeTo) {
                // 开始下载  
                readableZipStream
                    .pipeTo(zipFileOutputStream)
                    .then(() => {
                        console.log("同步下载打包结束时间：" + new Date());
                        resolve(true)
                    }).catch(err => {
                        console.log(err);
                        resolve(false)
                    }).finally(() => {
                        store.dispatch('trials/setUnLock', false)
                        readableZipStream = null;
                        zipFileOutputStream = null;
                        if (Url && Url.length > 0) {
                            Url.forEach(url => {
                                URL.revokeObjectURL(url)
                            })
                            Url = null
                        }
                    });
            } else {
                store.dispatch('trials/setUnLock', false)
                readableZipStream = null;
                zipFileOutputStream = null;
                if (Url && Url.length > 0) {
                    Url.forEach(url => {
                        URL.revokeObjectURL(url)
                    })
                    Url = null
                }
                resolve(false)
            }
        } catch (err) {
            console.log(err);
            resolve(false)
        }
    })

}
// 下载文件并修改名称
async function updateFile(file, name) {
    return new Promise(async resolve => {
        try {
            store.dispatch('trials/setUnLock', true)
            let fileOutputStream = streamSaver.createWriteStream(name);
            // file = decodeUtf8(file);
            let res = await fetch(file);
            res.body.pipeTo(fileOutputStream).then(() => {
                resolve(true)
            }).catch(err => {
                console.log(err)
                resolve(false)
            }).finally(() => {
                store.dispatch('trials/setUnLock', false)
                fileOutputStream = null;
            });
        } catch (err) {
            console.log(err)
            resolve(false)
        }
    })
}
//  同名文件修改名称
function formatFiles(files) {
    let fileObj = {};
    files.forEach(file => {
        let arr = Object.keys(fileObj);
        if (!~arr.indexOf(file.name)) {
            fileObj[file.name] = 1;
        } else {
            let name = file.name;
            file.name = name.split(".")[0] + `(${fileObj[name]})` + name
                .substring(name.lastIndexOf('.'))
                .toLocaleLowerCase()
            fileObj[name]++;
        }
    })
    return files;
}
function decodeUtf8(bytes) {
    let str = bytes.split('?');
    let str2 = str[0].split('/');
    let name = str2[str2.length - 1];
    name = encodeURIComponent(name);
    str.shift();
    str2.pop();
    return str2.join("/") + '/' + name;
}
// 下载文件进行修改并输出本地url
function downloadFileToUrl(url) {
    return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        xhr.open('GET', url);
        xhr.responseType = 'arraybuffer';
        xhr.onload = function () {
            try {
                const arraybuffer = xhr.response;
                let dataset = dcmjs.data.DicomMessage.readFile(arraybuffer)
                let newDicomFile = dataset.write({ fragmentMultiframe: false, startOffset: false }) // fragmentMultiframe 原始数据是否进行分割
                const bufferArray = new Uint8Array(newDicomFile)
                const blob = new Blob([bufferArray], { type: 'application/octet-stream' })
                const href = URL.createObjectURL(blob)
                resolve(href)
            } catch (err) {
                reject(err);
            }
        };
        xhr.send();
    })
}
export async function downLoadFile(file, name, type = 'file') {
    if (type === 'zip') return await zipFiles(name, file);
    return await updateFile(file, name)

}