import JSZip from "jszip";
import axios from "axios";
import { saveAs } from "file-saver";
import Vue from 'vue';
import {
    requestPackageAndAnonymizImage,
} from "@/api/trials/visit.js";
let flag = {};
export const downloadImage = async (id, id2) => {
    if (flag[id2]) return
    flag[id2] = true
    try {
        let params = {
            TrialId: id,
            SubjectVisitId: id2
        }
        let res = await requestPackageAndAnonymizImage(params);
        flag[id2] = false;
        if (res.IsSuccess) {
            if (!res.Result) {
                Vue.prototype.$message.warning(Vue.prototype.$t("trials:upload:message:not"))
                return 1;
            }
            let a = document.createElement("a");
            let href = Vue.prototype.OSSclientConfig.basePath + res.Result;
            let fileName =
                res.Result.split("/")[res.Result.split("/").length - 1];
            a.download = fileName;
            a.href = href;
            a.click();
            URL.revokeObjectURL(href);
            let timer = setTimeout(() => {
                a = null;
                href = null;
                timer = null;
            }, 500)
            return 2;
        } else {
            return false;
        }
    } catch (err) {
        flag[id2] = false;
        console.log(err);
    }
};
const setfolder = async (item) => {
    const zip = new JSZip(); // 创建实例对象
    let patientIds = item.PatientList.map(i => i.PatientIdStr);
    let zipName = `${item.SubjectCode}_${patientIds.join(',')}`;
    let zipObj = {};
    const promises = [];
    for (let visit of item.VisitList) {
        if (!zipObj[`${visit.VisitName}`]) {
            zipObj[`${visit.VisitName}`] = zip.folder(visit.VisitName);
        }
        for (let study of visit.StudyList) {
            let date = study.StudyTime.split(" ")[0];
            for (let series of study.SeriesList) {
                if (
                    !zipObj[
                    `${visit.VisitName}${series.Modality}`
                    ]
                ) {
                    zipObj[
                        `${visit.VisitName}${series.Modality}`
                    ] = zipObj[`${visit.VisitName}`].folder(
                        `${date}_${series.Modality}`
                    );
                }
                for (let instance of series.InstancePathList) {
                    let obj = {
                        subjectCode: item.SubjectCode,
                        visitName: visit.VisitName,
                        date: study.StudyTime.split(" ")[0],
                        modality: series.Modality,
                        instancePath: instance.Path,
                        dicomName: instance.Path.split("/Dicom/")[1],
                    };
                    const promise = handleBatchDown(
                        obj,
                        zipObj[
                        `${visit.VisitName}${series.Modality}`
                        ],
                    );
                    promises.push(promise);
                }
            }
        }
    }
    // 生成 zip 文件
    Promise.all(promises)
        .then(() => {
            // 生成zip 文件
            zip
                .generateAsync({
                    type: "blob",
                    compression: "DEFLATE", // STORE: 默认不压缩， DEFLATE：需要压缩
                    compressionOptions: {
                        level: 9, // 压缩等级 1~9   1 压缩速度最快， 9 最优压缩方式
                    },
                })
                .then((res) => {
                    saveAs(res, zipName + ".zip"); // 使用FileSaver.saveAs保存文件，文件名可自定义
                    flag[id2] = false;
                    zipObj = null;
                });
        })
        .catch((reason) => { flag[id2] = false; });
};
const handleBatchDown = async (item, zip) => {
    return new Promise((resolve) => {
        getFileData(
            Vue.prototype.OSSclientConfig.basePath + item.instancePath
        ).then((res) => {
            const fileName = item.dicomName + ".dcm";
            zip.file(fileName, res.data, { binary: true });
            resolve();
        });
    });
};
const getFileData = (fileUrl) => {
    return new Promise((resolve, reject) => {
        axios(fileUrl, {
            method: "GET",
            responseType: "blob", // 返回的数据会被强制转为blob类型 ，转换成arraybuffer 也行
        })
            .then((res) => {
                resolve(res);
            })
            .catch((error) => {
                reject(error);
            });
    });
};
export const fileDownload = (content, filename) => {
    const eleLink = document.createElement("a");
    eleLink.download = filename;
    eleLink.style.display = "none";
    const blob = new Blob([content]);
    eleLink.href = URL.createObjectURL(blob);
    document.body.appendChild(eleLink);
    eleLink.click();
    document.body.removeChild(eleLink);
};