<template>
    <div>
        <Button type="success" :loading="isLoading" :disabled="urlList.length < 2" @click="getSasStr(urlList)">{{ text }}</Button>
    </div>
</template>

<script>
    import FileSaver from "file-saver";
    import JSZip from "jszip";
    export default {
        name: "BasePackage",
        props: ['urlList', 'text', 'student'],
        data() {
            return {
                isLoading: false,
                sasString: ''
            };
        },
        created() { },
        methods: {

            /**
             * 获取blob授权信息
             * */
            getSasStr(list) {
                this.$api.blob.getContainerSAS().then(
                    (res) => {
                        if (res.error == null) {
                            this.sasString = res.result.data.SAS
                            this.downloadFile(list)
                        } else {
                            this.$Message.error('API error!')
                        }
                    },
                    (err) => {
                        this.$Message.error('API error!')
                    }
                )
            },

            downloadFile(data) {
                this.isLoading = true
                const selectList = [];
                const downloadname = data[0];
                for (let index = 0; index < data.length; index++) {
                    selectList.push(data[index] + this.sasString);
                }
                if (selectList.length == data.length) {
                    this.handleBatchDownload(selectList, downloadname); //存储待打包的URI数组和包的名称
                }
            },
            async handleBatchDownload(selectList, name) {
                const self = this;
                const data = selectList;
                const zip = new JSZip();
                const cache = {};
                const promises = [];

                /* 循环下载所有文件后 加入promise队列 */
                await data.forEach(item => {
                    const promiseItem = self.getFile(item).then(dta => {
                        const arr_name = item.split("/"); //处理名称
                        var file_name = arr_name[arr_name.length - 1].split('?')[0];
                        zip.file(file_name, dta, { binary: true }); // 逐个添加文件
                        cache[file_name] = dta;
                    });
                    promises.push(promiseItem);
                });

                Promise.all(promises).then(() => {
                    zip.generateAsync({ type: "blob" }).then(content => {
                        // 生成二进制流
                        FileSaver.saveAs(content, this.student.name + this.student.id + ".zip"); // 利用file-saver保存文件
                        this.isLoading = false;
                    })
                        .catch(err => {
                            console.log(err);
                            this.isLoading = false;
                        });
                });
            },

            //获取文件的arraybuffer格式并传入进行打包准备
            getFile(url) {
                return new Promise((resolve, reject) => {
                    var xhr = new XMLHttpRequest();
                    var formData = new FormData();
                    xhr.open('get', url);  //url填写后台的接口地址，如果是post，在formData append参数（参考原文地址）
                    xhr.responseType = 'arraybuffer';
                    xhr.onload = function (e) {
                        resolve(e.currentTarget.response)
                    };
                    xhr.send(formData);
                })
            }
        },
        mounted() { }
    };
</script>

