<template>
    <div class="divborder newSearchDiv" style="min-height:500px;">
        <!-- <div>
            <div class="filechose">
                <div class="iconfile">
                    <Icon type="md-folder" size="20"></Icon>
                </div>
                <input class="inputfile" type="file" @change="handleFileChange">
            </div>
            <div class="filename">{{fileinfo}}<span style="color:#57a3f3;">{{filesize}}</span></div>
            <div class="uploadbtn">
                <Button type="primary" icon="md-folder" @click="handleUpload">上传文件</Button>
            </div>
        </div> -->
        <!-- <div class="progressitem">
            <h4>进度条</h4>
            <div class="onitem">
                <div v-for="(item,index) in data" :key="index" class="outitem">
                    <div class="progressdiv">{{item.partName}}</div>
                    <div class="progressdiv">
                        <Progress :percent="item.percentage" :stroke-color="['#108ee9', '#87d068']" />
                    </div>
                </div>
            </div>
        </div> -->

        <!-- 下载组件 -->
        
        <Modal class="newModalClass" :title="title1" v-model="addmodal" :styles="{width:'880px'}">
            <div class="modal_body">
                <div>
                    <div class="filter">
                        <label>问题：</label>
                        <Input class="searchInput MaxWidth" type="text" />
                    </div>
                </div>
                <div>
                    <label>上传文件：</label>
                    <div style="display: inline-block;vertical-align: text-top;width:200px;">
                        <largeFileUpload @getFileInfo="getFileInfo"></largeFileUpload>
                    </div>
                </div>
                <div>
                    <div class="filter">
                        <label>问题：</label>
                        <Input class="searchInput MaxWidth" type="text" />
                    </div>
                </div>
                <Button type="text" size="large" @click="downfile">下载文件</Button>
            </div>
            <div slot="footer">
                <Button type="text" size="large" @click="addmodal = false">{{$t('1033')}}</Button>
            </div>
        </Modal>
    </div>
</template>
<script>

export default {
    data () {
        return {
            file: null,
            data: [],
            fileinfo: '',
            filesize: '',
            addmodal:true,
            title1:'添加',
            fileInfo:''
        }
    },
    created () {

    },
    methods: {
        getFileInfo(e){
            this.fileInfo = e;
            console.log(11111)
            console.log(this.fileInfo)
            console.log(e)
        },
        downfile(){
            //下载文件,借口要写上loading
            this.axios
            .request({
                url: '/config/FileSystem/Download?fileId=d9e1545c-dd5a-4e6b-bcd3-549705a9ecad',
                method: 'get'
            })
            .then(res => {
                console.log(1111)
                console.log(res)
                // 创建隐藏的可下载链接
                var eleLink = document.createElement('a');
                eleLink.download = '文件名称.zip';
                eleLink.style.display = 'none';
                // 字符内容转变成blob地址
                var blob = new Blob([res.data]);
                eleLink.href = URL.createObjectURL(blob);
                // 触发点击
                document.body.appendChild(eleLink);
                eleLink.click();
                // 然后移除
                document.body.removeChild(eleLink);
            })
        },
        request ({
            url,
            method = 'post',
            data,
            headers = {},
            onProgress = e => e,
            requestList
        }) {
            return new Promise(resolve => {
                const xhr = new XMLHttpRequest();
                xhr.upload.onprogress = onProgress;
                xhr.open(method, url);
                Object.keys(headers).forEach(key =>
                    xhr.setRequestHeader(key, headers[key])
                );
                xhr.send(data);
                xhr.onload = e => {
                    resolve({
                        data: e.target.response
                    });
                };
            });
        },
        // 上传文件
        handleFileChange (e) {
            const [file] = e.target.files;
            if (!file) { return; }
            Object.assign(this.$data, this.$options.data());
            this.file = file;
            this.fileinfo = this.file.name + ' ';
            this.filesize = this.getFileSize(this.file.size);
        },
        getFileSize (count) {
            let str = '';
            if (count >= 1024 * 1024 * 1024) {
                str = Math.round(count / 1024 / 1024 / 1024 * 100) / 100 + 'G';
            } else if (count >= 1024 * 1024) {
                str = Math.round(count / 1024 / 1024 * 100) / 100 + 'MB';
            } else if (count >= 1024) {
                str = Math.round(count / 1024 * 100) / 100 + 'kb';
            } else {
                str = count + 'b';
            }
            return str;
        },
        // 文件切片
        createFileChunk (file) {
            const fileChunkList = [];
            const chunkSize = 8 * 1024 * 1024;
            let cur = 0;
            while (cur < file.size) {
                fileChunkList.push({
                    file: file.slice(cur, cur + chunkSize),
                    start: cur,
                    end: cur + chunkSize < this.file.size ? cur + chunkSize : this.file.size
                })
                cur += chunkSize;
            }
            return fileChunkList;
        },
        // 上传切片
        uploadChunks () {
            const requestList = this.data
                .map((item, index) => {
                    const formData = new FormData();
                    formData.append('file', item.file, item.partName);
                    return { formData };
                })
                .map(({ formData }, index) =>
                    this.request({
                        url: 'http://172.8.10.74:10086/api/File/upload?' + this.data[index].params,
                        data: formData,
                        onProgress: this.createProgressHandler(this.data[index])
                    })
                )
            // 并发切片
            Promise.all(requestList)
            // 发送合并请求
            // this.mergeRequest();
        },
        handleUpload () {
            if (!this.file) { return; }
            const fileChunkList = this.createFileChunk(this.file);
            this.data = fileChunkList.map((item, index) => ({
                file: item.file,
                start: item.start,
                end: item.end,
                partName: this.file.name + '.part-' + (parseInt(index) + 1),
                params: 'total=' + fileChunkList.length + '&curIdx=' + (parseInt(index) + 1) + '&startSize=' + item.start + '&endSize=' + item.end,
                percentage: 0
            }))
            this.uploadChunks();
        },
        // mergeRequest(){
        //     this.request({
        //         url: "http://localhost:3000/merge",
        //         headers: {
        //             "content-type": "application/json"
        //         },
        //         data: JSON.stringify({
        //             filename: this.file.name
        //         })
        //     });
        // },
        createProgressHandler (item) {
            return e => {
                item.percentage = parseInt(String((e.loaded / e.total) * 100));
            };
        }
    }
}
</script>
<style lang="less" scoped>
.progressitem{
    padding: 10px;
    margin: 50px 10px;
    border: 1px solid #ddd;
    border-radius:5px;
    .onitem{
        max-height: 400px;
        height:400px;
        overflow: auto;
        .outitem{
            border:1px solid #ddd;
            padding:10px;
            margin:5px 0px;
            width:100%;
            .progressdiv{
                width:50%;
                display:inline-block;

            }
        }
    }

}

.filechose{
    position:relative;
    left:10px;
    display:inline-block;
    .iconfile{
        width: 100px;
        height: 100px;
        line-height: 100px;
        text-align: center;
        border: 2px dashed #ddd;
        border-radius:6px;
    }
    .inputfile{
        position: absolute;
        top:0;
        left:0;
        width:100px;
        height:100px;
        opacity: 0;
    }
}
.filename{
    display: inline-block;
    margin-left:20px;
    font-size: 12px;
    font-weight: bold;
}
.uploadbtn{
    display: inline-block;
    position: relative;
    left: 100px;
}

</style>
