<template>
    <Modal v-model="uploadStatus" :ok-text="textLoading ? $t('updModal.uploading') : isComplete ? $t('updModal.complete'):$t('updModal.comfirmUpd')" :cancel-text="$t('updModal.cancelUpd')" :title="$t('teachContent.btnUpload')" class="upload-modal dark-iview-modal" width="800" :mask-closable="false" :closable="false" @on-ok="modalOk" @on-cancel="modalCancel" :loading="modalLoading">
        <div class="upload-file-box">
            <!-- <p>上传到：{{pdInfo.filterPeriodName}}</p> -->
            <ResBelong v-show="routerScope == 'school'" showLabel class="upd-to-pd" :pdId="pdId"></ResBelong>
            <Upload type="drag" action="" :show-upload-list="false" multiple :before-upload="customUpload" class="upload-wrap" :disabled="textLoading">
                <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;">{{$t('updModal.tips1')}}</p>
                <p class="upload-text" :style="{fontSize:'12px',marginBottom: uploadedList.length ? '25px':'50px'}">
                    {{$t('updModal.tips3')}}
                </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">
                                {{$t('updModal.fileType1')}}
                            </span>
                            <span v-else-if="item.type == 'image'" class="file-type-tag" style="color: #45C84A;border-color: #45C84A">
                                {{$t('updModal.fileType2')}}
                            </span>
                            <span v-else-if="item.type == 'video'" class="file-type-tag" style="color: #8E2BDD;border-color: #8E2BDD">
                                {{$t('updModal.fileType3')}}
                            </span>
                            <span v-else-if="item.type == 'audio'" class="file-type-tag" style="color: #E1027B;border-color: #E1027B">
                                {{$t('updModal.fileType4')}}
                            </span>
                            <span v-else-if="item.type == 'doc'" class="file-type-tag" style="color: #03C0C2;border-color: #03C0C2">
                                {{item.isParse ? $t('updModal.fileType5'):$t('updModal.fileType6')}}
                            </span>
                            <span v-else class="file-type-tag" style="color: #E87B22; border-color: #E87B22">
                                {{$t('updModal.fileType7')}}
                            </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" />
                            {{$t('updModal.resolve')}}
                        </span> -->
                        <!-- pptx是否转换 -->
                        <Checkbox class="upload-info-wrap parse-label" v-if="item.extension == 'PPTX'" v-model="item.isParse">
                            {{$t('updModal.resolve')}}
                        </Checkbox>
                        <Progress style="top:-10px;" v-if="item.status == 0" :percent="item.progress" 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>
    </Modal>

</template>
<script>
import BlobTool from '@/utils/blobTool.js'
import ResBelong from '@/view/teachcontent/ResBelong.vue'
export default {
    components: {
        ResBelong
    },
    data() {
        return {
            uploadedList: [],
            containerClient: null,
            routerScope: '',
            uploadStatus: false,
            textLoading: false,
            modalLoading: false,
            isComplete: false, //是否完成上传
            loadingCount: 0
        }
    },
    props: {
        //文件路径
        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
        },
        //资源所属学段
        pdId: {
            default: '',
            type: String
        },
        //上传到容器位置 school/private
        scope: {
            default: '',
            type: String
        }
    },
    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.uploadedList.splice(index, 1)
                    this.$Message.success(this.$t('updModal.delOk'))
                },
                err => {
                    this.$Message.error(this.$t('updModal.delErr'))
                }
            )
        },
        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: this.$t('updModal.sizeErr'),
                    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: this.$t('updModal.typeErr'),
                    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)
            this.modalLoading = true
            this.isComplete = false
            return false
        },
        // modal取消事件
        modalCancel() {
            if (this.uploadedList.length) {
                let blobsFile = this.uploadedList.filter(item => {
                    let flag = true
                    if (item.extension == 'HTEX') {
                        flag = false
                    }
                    if (item.extension == 'PPTX' && item.isParse) {
                        flag = false
                    }
                    return flag
                })
                if (blobsFile.length) {
                    let blobs = blobsFile.map(item => {
                        return item.blob
                    })
                    this.containerClient.deleteBlobBatch(blobs).then().finally(() => {
                        blobsFile.forEach((item) => {
                            if (item.type == 'image') {
                                let thum = item.blob.replace('/image/', '/thum/')
                                this.containerClient.deleteBlob(thum)
                            } else if (item.type == 'video') {
                                let thum = item.blob.replace('/video/', '/thum/')
                                thum = thum.slice(0, thum.lastIndexOf('.')) + '.png'
                                this.containerClient.deleteBlob(thum)
                            }
                        })
                        this.uploadedList = []
                    })
                }

                let prefixFiles = this.uploadedList.filter(item => {
                    let flag = false
                    if (item.extension == 'HTEX') {
                        flag = true
                    }
                    if (item.extension == 'PPTX' && item.isParse) {
                        flag = true
                    }
                    return flag
                })

                if (prefixFiles.length) {
                    prefixFiles.forEach(item => {
                        this.$api.blob.deletePrefix({
                            cntr: this.routerScope == 'school' ? this.$store.state.userInfo.schoolCode : this.$store.state.userInfo.TEAMModelId,
                            prefix: `res/${item.name.replace('.HTEX', '')}`
                        }).then(
                            res => {
                            },
                            err => {
                                this.$Message.error(this.$t('updModal.cancelErr'))
                            }
                        )
                    })
                    this.uploadedList = []
                }
            }
            this.textLoading = false
        },
        // modal确认事件
        modalOk() {
            //已完成上传操作，关闭对话框、emit
            if (this.isComplete) {
                this.$emit("successData", this.uploadedList)
                this.uploadedList = []
            } else { //还未上传文件，则上传文件
                this.textLoading = true
                this.uploadedList.forEach((item, index) => {
                    if (item.loadedBytes < item.size) {
                        this.loadingCount++
                        //默认使用props接受的路径，没有则根据文件类型上传
                        this.confirmUpload(item.file, this.path || item.type, index)
                    }
                })

            }
        },
        // 确认上传文件
        confirmUpload(file, fileType, index) {
            let extension = this.uploadedList[index].extension
            let _this = this
            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
                    if (res.type == 'image') {
                        this.uploadThum(file)
                    } else if (res.type == 'video') {
                        this.uploadPoater(res)
                    } else if (extension == 'PPTX') {
                        if (_this.uploadedList[index].isParse) {
                            let delBlob = res.blob
                            this.$api.teachContent.ParseDoc({
                                file: res.url,
                                scope: this.routerScope
                            }).then(
                                parseRes => {
                                    this.containerClient.deleteBlob(delBlob, res.size)
                                    this.uploadedList[index].blob = `/res/${res.name}/index.json`
                                    this.uploadedList[index].extension = 'HTEX'
                                    this.uploadedList[index].name = res.name.replace('pptx', 'HTEX').replace('PPTX', 'HTEX')
                                    this.uploadedList[index].type = 'res'
                                },
                                parseErr => {
                                    this.$Message.error(this.$t('updModal.resolveErr'))
                                }
                            ).finally(() => {
                                this.counterReduce()
                            })
                        } else {
                            this.counterReduce()
                        }
                    } else if (extension == 'HTEX') {
                        let delBlob = res.blob
                        this.uploadedList[index].blob = `/res/${res.name}/index.json`
                        this.$api.teachContent.ParseDoc({
                            file: res.url,
                            scope: this.routerScope
                        }).then(
                            parseRes => {
                                this.containerClient.deleteBlob(delBlob)
                            },
                            parseErr => {
                                this.$Message.error(this.$t('updModal.updErr'))
                                this.containerClient.deleteBlob(delBlob)
                            }
                        ).finally(() => {
                            this.counterReduce()
                        })
                    }
                    this.uploadedList[index].createTime = res.createTime
                },
                err => {
                    this.uploadedList[index].status = 2
                    if (err.spaceError) {
                        this.$Message.error(err.spaceError)
                    } else {
                        this.$Message.error(this.$t('updModal.updErr'))
                    }
                }
            ).finally(() => {
                if (fileType != 'video' && fileType != 'image' && extension !== 'PPTX' && extension !== 'HTEX') {
                    this.counterReduce()
                }
            })
        },
        // 上传/解析完成计数器减1
        counterReduce() {
            if (--this.loadingCount == 0) {
                this.textLoading = false
                this.isComplete = true
                this.modalLoading = 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(this.$t('updModal.compressImgOk'))
                },
                err => {
                    console.log(this.$t('updModal.compressImgErr'))
                }
            ).finally(() => {
                this.counterReduce()
            })
        },
        //处理视频封面
        async uploadPoater(file) {
            let n = file.name.substring(0, file.name.lastIndexOf('.'))
            let dataUrl = await this.$jsFn.createVideoPoster(file.url + this.sasString, file.name, 0.1)
            let f = this.$jsFn.dataURLtoFile(dataUrl, n + '.png')
            this.containerClient.upload(f, 'thum').then(
                res => {
                    console.log(this.$t('updModal.posterOk'))
                },
                err => {
                    console.log(this.$t('updModal.posterErr'))
                }
            ).finally(() => {
                this.counterReduce()
            })
        }
    },
    created() {
        let route = this.$route
        //没有接收 scope,则通过内容模块逻辑，路由判断
        if (!this.scope) {
            if (route.name == 'personalcontent') {
                this.routerScope = 'private'
            } else {
                this.routerScope = 'school'
            }
        }
        // 使用组件接收的值
        else{
            this.routerScope = this.scope
        }

    },
    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>
.upd-to-pd {
    margin-bottom: 10px;
}
.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;
    cursor: pointer;
}
.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;
    color: white;
}

.is-parse-htex {
    vertical-align: baseline;
}
</style>
<style>
.parse-label .ivu-checkbox-inner {
    background: transparent;
    width: 14px;
    height: 14px;
    border-color: #909090;
}
.parse-label .ivu-checkbox-checked .ivu-checkbox-inner:after {
    content: "";
    display: block;
    width: 8px;
    height: 13px;
    border-right: 2px solid #fff;
    border-bottom: 2px solid #fff;
    transform: rotate(35deg);
    position: absolute;
    top: -4px;
    left: 3px;
    border-radius: 0;
    background-color: initial;
    border-color: #0094ff;
}
</style>
