<template>
    <div class="upload-file-box">
        <Upload type="drag" action="" :show-upload-list="false" multiple :before-upload="customUpload" class="upload-wrap">
            <Icon class="upload-icon" custom="iconfont icon-upload" v-show="!uploadedList.length" />
            <p class="upload-text" :style="{marginTop: uploadedList.length ? '25px':'0px'}">
                <Icon size="24" style="font-size: 22px;vertical-align: baseline;margin-right: 5px;" custom="iconfont icon-upload" v-show="uploadedList.length" />
                {{$t('teachContent.uploadText')}}
            </p>
            <p class="upload-text" style="font-size:12px;">* 上传相同名字的文件会自动覆盖</p>
            <p class="upload-text" :style="{fontSize:'12px',marginBottom: uploadedList.length ? '25px':'50px'}">
                * 勾选
                <Icon custom="iconfont icon-convert" size="12"  class="is-parse-htex"/>
                支持PPTX文档转换成HTEX教材
            </p>
        </Upload>
        <div class="upload-file-box">
            <div class="upload-file-item" v-for="(item,index) in uploadedList" :key="index">
                <div class="upload-item-left">
                    <p class="upload-file-name">
                        <span v-if="item.type == 'res'" class="file-type-tag" style="color: #1FFCC5;border-color: #1FFCC5">教材</span>
                        <span v-else-if="item.type == 'image'" class="file-type-tag" style="color: #45C84A;border-color: #45C84A">图片</span>
                        <span v-else-if="item.type == 'video'" class="file-type-tag" style="color: #8E2BDD;border-color: #8E2BDD">视频</span>
                        <span v-else-if="item.type == 'audio'" class="file-type-tag" style="color: #E1027B;border-color: #E1027B">音频</span>
                        <span v-else-if="item.type == 'doc'" class="file-type-tag" style="color: #03C0C2;border-color: #03C0C2">{{item.isParse ? '转换':'文档'}}</span>
                        <span v-else class="file-type-tag" style="color: #E87B22; border-color: #E87B22">其他</span>
                        <span>{{item.name}}</span>
                    </p>
                    <span class="upload-info-wrap" style="color:white;">
                        {{parseInt(item.loadedBytes * 100 / item.size)+'%'}}
                    </span>
                    <span class="upload-info-wrap">
                        {{getSizeByBytes(item.loadedBytes)+'/'+getSizeByBytes(item.size)}}
                    </span>
                    <span v-if="item.extension == 'PPTX'" class="upload-info-wrap parse-label" @click="item.isParse = !item.isParse" :style="{color:item.isParse ? '#1cc0f3':'#808080'}">
                        <Icon class="is-parse-htex" size="12" custom="iconfont icon-convert" />
                        转成HTEX教材
                    </span>
                    <Progress style="top:-10px;" v-if="item.status == 0" :percent="item.loadedBytes * 100 / item.size" status="active" stroke-color="#1CC0F3" :stroke-width="2" hide-info />
                </div>
                <div class="upload-item-right">
                    <Icon type="ios-close" class="delete-btn" color="red" size="30" style="float:right;" @click="deleteFile(index)" />
                </div>
            </div>
        </div>
    </div>
</template>
<script>
import '@/icons/svg/loading3.svg';
import BlobTool from '@/utils/blobTool.js';
export default {
    data() {
        return {
            uploadedList: [],
            containerClient: null,
            routerScope: ''
        }
    },
    props: {
        //默认文件列表
        defaultFileList: {
            default: () => {
                return []
            },
            type: Array
        },
        //文件路径
        path: {
            default: '',
            type: String,
            required: true
        },
        //授权信息
        sasString: {
            default: '',
            type: String,
            required: true
        },
        //blob链接
        urlString: {
            default: '',
            type: String,
            required: true
        },
        //容器名称
        containerName: {
            default: '',
            type: String,
            required: true
        },
        //文件大小限制
        maxSize: {
            default: 2 * 1024 * 1024 * 1024,
            type: Number
        },
        //文件格式限制
        format: {
            default: () => {
                return []
            },
            type: Array
        }
    },
    methods: {
        //删除文件
        deleteFile(index) {
            this.containerClient.deleteBlob(this.uploadedList[index].blob).then(
                res => {
                    //删除缩略图和封面
                    if (this.uploadedList[index].type == 'image') {
                        let thum = this.uploadedList[index].blob.replace('/image/', '/thum/')
                        this.containerClient.deleteBlob(thum)
                    } else if (this.uploadedList[index].type == 'video') {
                        let thum = this.uploadedList[index].blob.replace('/video/', '/thum/')
                        thum = thum.slice(0, thum.lastIndexOf('.')) + '.png'
                        this.containerClient.deleteBlob(thum)
                    }
                    this.$emit('deleteFile', this._.cloneDeep(this.uploadedList[index]))
                    this.uploadedList.splice(index, 1)
                    this.$Message.success('删除成功！')
                },
                err => {
                    this.$Message.error('删除失败！')
                }
            )
        },
        getFileType(fileName) {
            let extension = fileName.substring(fileName.lastIndexOf('.') + 1, fileName.length)
            extension = extension.toUpperCase()
            for (let key in this.$GLOBAL.CONTENT_TYPES) {
                if (this.$GLOBAL.CONTENT_TYPES[key].indexOf(extension) != -1) {
                    return key
                }
            }
            return 'other'
        },
        getSizeByBytes(bytes) {
            return bytes / 1024 < 1024 ? (bytes / 1024).toFixed(1) + 'KB' : bytes / 1024 / 1024 < 1024 ? (bytes / 1024 / 1024).toFixed(1) + 'M' : (bytes / 1024 / 1024 / 1024).toFixed(1) + 'G'
        },
        async customUpload(file) {
            if (file.size > this.maxSize) {
                this.$Message.error({
                    content: "文件大小超出限制",
                    duration: 3
                })
                return false
            }

            let extension = file.name.substring(file.name.lastIndexOf('.') + 1, file.name.length)
            if (this.format.length > 0 && this.format.indexOf(extension) == -1) {
                this.$Message.error({
                    content: "文件类型不支持",
                    duration: 3
                })
                return false
            }

            let fileType = this.getFileType(file.name)
            //上传文件
            let fileInfo = {
                url: this.urlString + '/' + this.containerName + '/' + fileType + '/' + file.name,
                name: file.name,
                size: file.size,
                loadedBytes: 0,
                progress: 0,
                status: 0,
                type: fileType,
                file: file,
                extension: extension.toUpperCase(),
                isParse: false
            }
            this.uploadedList.push(fileInfo)
            let _this = this
            let index = this.uploadedList.length - 1
            // this.containerClient.upload(file, fileType, {
            //     onProgress: function (e) {
            //         _this.uploadedList[index].loadedBytes = e.loadedBytes
            //         _this.uploadedList[index].progress = parseInt(e.loadedBytes * 100 / file.size)
            //     }
            // }).then(
            //     res => {
            //         this.uploadedList[index].status = 1
            //         this.uploadedList[index].blob = res.blob
            //         extension = extension.toUpperCase()
            //         if (res.type == 'image') {
            //             this.uploadThum(file)
            //             this.$emit('successData', res)
            //         } else if (res.type == 'video') {
            //             this.uploadPoater(res)
            //             this.$emit('successData', res)
            //         } else if (extension == 'PPTX') {
            //             this.$Modal.confirm({
            //                 title: '文件解析',
            //                 okText: '是',
            //                 cancelText: '否',
            //                 content: `<p>是否将<strong style='color:red;'>${file.name}</strong>转成HTEX文件？</p>`,
            //                 onOk: () => {
            //                     this.$emit('parsing')
            //                     this.$emit('successData', res)
            //                     let delBlob = res.blob
            //                     this.$api.teachContent.ParseDoc({
            //                         file: res.url,
            //                         scope: this.routerScope
            //                     }).then(
            //                         parseRes => {
            //                             this.containerClient.deleteBlob(delBlob)
            //                             res.blob = `/res/${res.name}/index.json`
            //                             res.extension = 'HTEX'
            //                             res.name = res.name.replace('pptx', 'HTEX').replace('PPTX', 'HTEX')
            //                             res.type = 'res'

            //                             this.$emit('parseComplete')
            //                             this.$Message.success('解析成功')
            //                         },
            //                         parseErr => {
            //                             this.$Message.error('解析失败')
            //                         }
            //                     )
            //                 },
            //                 onCancel: () => {
            //                     this.$emit('successData', res)
            //                 }
            //             })
            //         } else if (extension == 'HTEX') {
            //             let delBlob = res.blob
            //             this.$emit('parsing')
            //             res.blob = `/res/${res.name}/index.json`
            //             this.$emit('successData', res)
            //             this.$api.teachContent.ParseDoc({
            //                 file: res.url,
            //                 scope: this.routerScope
            //             }).then(
            //                 parseRes => {
            //                     this.containerClient.deleteBlob(delBlob)
            //                 },
            //                 parseErr => {
            //                     this.$Message.error('上传失败')
            //                     this.containerClient.deleteBlob(delBlob)
            //                 }
            //             ).finally(() => {
            //                 this.$emit('parseComplete')
            //             })
            //         }
            //     },
            //     err => {
            //         this.uploadedList[index].status = 2
            //         if (err.spaceError) {
            //             this.$Message.error(err.spaceError)
            //         } else {
            //             this.$Message.error("上传失败")
            //         }
            //     }
            // )
            return false
        },
        //处理图片缩略图
        async uploadThum(file) {
            let dataUrl = await this.$jsFn.fileToURL(file)
            dataUrl = await this.$jsFn.compressImgByUrl(dataUrl, file.name, 0.1)
            let f = this.$jsFn.dataURLtoFile(dataUrl, file.name)
            this.containerClient.upload(f, 'thum').then(
                res => {
                    console.log('压缩图上传成功')
                },
                err => {
                    console.log('压缩图上传失败')
                }
            )
        },
        //处理视频封面
        async uploadPoater(file) {
            let n = file.name.substring(0, file.name.lastIndexOf('.'))
            console.log(n)
            console.log('视频蜂蜜昂')
            let dataUrl = await this.$jsFn.createVideoPoster(file.url + this.sasString, file.name, 0.1)
            let f = this.$jsFn.dataURLtoFile(dataUrl, n + '.png')
            console.log(f)
            this.containerClient.upload(f, 'thum').then(
                res => {
                    console.log('视频封面上传成功')
                },
                err => {
                    console.log('视频封面上传失败')
                }
            )
        }
    },
    created() {
        let route = this.$route
        if (route.name == 'personalcontent') {
            this.routerScope = 'private'
        } else {
            this.routerScope = 'school'
        }
    },
    watch: {
        urlString: {
            handler(v, o) {
                if (this.urlString && this.containerName && this.sasString) {
                    let scope = ''
                    if (this.containerName == this.$store.state.userInfo.TEAMModelId) {
                        scope = 'private'
                    } else if (this.containerName == this.$store.state.userInfo.schoolCode) {
                        scope = 'school'
                    }
                    //初始化Blob
                    this.containerClient = new BlobTool(this.urlString, this.containerName, this.sasString, scope)
                }
            }
        },
        containerName: {
            handler(v, o) {
                if (this.urlString && this.containerName && this.sasString) {
                    let scope = ''
                    if (this.containerName == this.$store.state.userInfo.TEAMModelId) {
                        scope = 'private'
                    } else if (this.containerName == this.$store.state.userInfo.schoolCode) {
                        scope = 'school'
                    }
                    //初始化Blob
                    this.containerClient = new BlobTool(this.urlString, this.containerName, this.sasString, scope)
                }
            }
        },
        sasString: {
            handler(v, o) {
                if (this.urlString && this.containerName && this.sasString) {
                    let scope = ''
                    if (this.containerName == this.$store.state.userInfo.TEAMModelId) {
                        scope = 'private'
                    } else if (this.containerName == this.$store.state.userInfo.schoolCode) {
                        scope = 'school'
                    }
                    //初始化Blob
                    this.containerClient = new BlobTool(this.urlString, this.containerName, this.sasString, scope)
                }
            }
        }
    }
}

</script>
<style scoped>
.upload-text {
    margin: 10px 0px;
    font-size: 24px;
}
.upload-icon {
    font-size: 50px;
    margin-top: 60px;
}
.upload-file-item {
    color: #909090;
    margin-top: 5px;
    padding: 5px 2px 0px 5px;
    display: flex;
}
.upload-item-left {
    width: calc(100% - 25px);
}
.upload-item-right {
    width: 25px;
}
.upload-info-wrap {
    float: right;
    margin-left: 10px;
    vertical-align: middle;
    /* color: white; */
    line-height: 30px;
}

.upload-file-item:hover {
    /* color: white; */
    /* background: #585858; */
    border-radius: 5px;
}

.upload-file-item:hover .delete-btn {
    display: inline-block;
}
.upload-loading-icon {
    vertical-align: middle;
}
.upload-file-name {
    display: inline-block;
    color: #eeeeee;
    line-height: 30px;
}

.delete-btn {
    display: none;
}
.file-type-tag {
    border: 1px solid;
    /*border-color:white;*/
    border-radius: 2px;
    padding: 0px 4px;
    margin-right: 5px;
    font-size: 12px;
}
.parse-label {
    cursor: pointer;
    font-size: 12px;
    user-select: none;
}
.is-parse-htex {
    vertical-align: baseline;
}
</style>
