<template>
    <div class="teach-content">
        <Loading bgColor="rgba(103, 103, 103, 0.27)" type="1" v-show="isLoading"></Loading>
        <div class="teach-content-main">
            <!--文件分类列表-->
            <div class="content-type-list">
                <vuescroll>
                    <div @click="selectFileType(index)" :class="item.type === activeType ? 'content-type-item content-type-item-active':'content-type-item'" v-for="(item,index) in contentTypeList" :key="index">
                        <Icon v-if="item.icon.indexOf('iconfont') != -1" :custom="item.icon" color="white" size="20" />
                        <Icon v-else :type="item.icon" color="white" size="20" />
                        <span class="content-type-label">{{item.label}}</span>
                        <Tooltip transfer theme="light" :content="item.tips" :max-width="248" placement="bottom" offset="-20">
                            <Icon type="ios-alert-outline" color="#1cc0f3" size="20" v-if="item.tips" style="position:absolute;top:-16px;margin-left:5px;" />
                        </Tooltip>
                    </div>
                    <!-- Blob空间计算 -->
                    <div :class="($access.can('admin.*|content-school-upd') || routerScope == 'private') ? 'space-box animated fadeIn fast' : 'space-box animated fadeOut fast'">
                        <div class="percent-box">
                            <span class="percent-item-span storage-full" :style="{ width: '100%' }" v-if="sizeInfo.total > storageSpace"></span>
                            <span class="percent-item-span storage-res" :style='{ width: getPercent(sizeInfo.res) }'></span>
                            <span class="percent-item-span storage-image" :style='{ width: getPercent(sizeInfo.image) }'></span>
                            <span class="percent-item-span storage-video" :style='{ width: getPercent(sizeInfo.video) }'></span>
                            <span class="percent-item-span storage-audio" :style='{ width: getPercent(sizeInfo.audio) }'></span>
                            <span class="percent-item-span storage-doc" :style='{ width: getPercent(sizeInfo.doc) }'></span>
                            <span class="percent-item-span storage-other" :style='{ width: getPercent(sizeInfo.other) }'></span>
                            <span class="percent-item-span storage-data" :style='{ width: getPercent(sizeInfo.data) }'></span>
                        </div>
                        <p :style="{color: sizeInfo.total > storageSpace ? 'red' : 'white', fontSize: sizeInfo.total > storageSpace ? '14px' : '12px'}">
                            <span>
                                {{$t('teachContent.space')}}
                            </span>
                            <span v-show="sizeLoading">
                                {{$t('teachContent.calcing')}}
                            </span>
                            <span v-show="!sizeLoading">
                                {{$jsFn.formatBytes(sizeInfo.total)}}/{{ $jsFn.formatBytes(storageSpace)}}
                            </span>
                            <span v-if="sizeInfo.total > storageSpace">{{$t('teachContent.blobFull')}}</span>
                        </p>
                        <div class="percent-detail-box">
                            <p class="percent-detail-text" v-if="sizeInfo.res != 0">
                                <span class="text-dot storage-res"></span>
                                <span>{{$t('teachContent.filterRes')}}</span>
                                <span class="text-size">{{$jsFn.formatBytes(sizeInfo.res)}}</span>
                            </p>
                            <p class="percent-detail-text" v-if="sizeInfo.image != 0">
                                <span class="text-dot storage-image"></span>
                                <span>{{$t('teachContent.filterPicture')}}</span>
                                <span class="text-size">{{$jsFn.formatBytes(sizeInfo.image)}}</span>
                            </p>
                            <p class="percent-detail-text" v-if="sizeInfo.video != 0">
                                <span class="text-dot storage-video"></span>
                                <span>{{$t('teachContent.filterVideo')}}</span>
                                <span class="text-size">{{$jsFn.formatBytes(sizeInfo.video)}}</span>
                            </p>
                            <p class="percent-detail-text" v-if="sizeInfo.audio != 0">
                                <span class="text-dot storage-audio"></span>
                                <span>{{$t('teachContent.filterAudio')}}</span>
                                <span class="text-size">{{$jsFn.formatBytes(sizeInfo.audio)}}</span>
                            </p>
                            <p class="percent-detail-text" v-if="sizeInfo.doc != 0">
                                <span class="text-dot storage-doc"></span>
                                <span>{{$t('teachContent.filterDoc')}}</span>
                                <span class="text-size">{{$jsFn.formatBytes(sizeInfo.doc)}}</span>
                            </p>
                            <p class="percent-detail-text" v-if="sizeInfo.other != 0">
                                <span class="text-dot storage-other"></span>
                                <span>{{$t('teachContent.otherType')}}</span>
                                <span class="text-size">{{$jsFn.formatBytes(sizeInfo.other)}}</span>
                            </p>
                            <p class="percent-detail-text" v-if="sizeInfo.data != 0">
                                <span class="text-dot storage-data"></span>
                                <span>{{$t('teachContent.appData')}}</span>
                                <span class="text-size">{{$jsFn.formatBytes(sizeInfo.data)}}</span>
                            </p>
                        </div>
                    </div>
                </vuescroll>
            </div>
            <!--文件表格列表-->
            <div class="content-file-list-box">
                <!--筛选、操作域-->
                <div class="content-file-filter">
                    <ResBelong class="pd-filter-wrap" v-show="routerScope == 'school'" @pd-change="(data)=>{filterPeriod = data}"></ResBelong>
                    <div class="content-filter-wrap">
                        <Input v-model="keyWord" search size="small" :placeholder="$t('teachContent.searchText')" class="key-word-search" @on-change="searchKeyWord" @on-search="searchKeyWord" />
                        <CheckboxGroup v-model="extFilter"  @on-change="filterFileByExtension">
                            <Checkbox :label="item" v-for="(item ,index) in extensions" :key="index">
                                <span>{{item}}</span>
                            </Checkbox>
                        </CheckboxGroup>
                    </div>
                    <span v-if="$access.can('admin.*|content-school-upd') || routerScope == 'private'" class="action-btn-wrap" @click="delFileBatch">
                        <Icon type="md-trash" class="toggle-btn-icon" />
                        {{$t('teachContent.delBatch')}}
                    </span>
                    <span v-if="$access.can('admin.*|content-school-upd') || routerScope == 'private'" @click="showUpload" class="action-btn-wrap">
                        <Icon type="md-cloud-upload" class="toggle-btn-icon" size="16" />
                        {{$t('teachContent.btnUpload')}}
                    </span>
                    <span @click="changeShowType()" :class="activeType === 'image' || activeType === 'video' ? 'action-btn-wrap' : 'disable-text-icon action-btn-wrap'">
                        <Icon v-show="showType" type="md-list" class="toggle-btn-icon" size="16" />
                        <Icon v-show="!showType" type="md-grid" class="toggle-btn-icon" />
                        {{showType ? $t('teachContent.viewport1'):$t('teachContent.viewport2')}}
                    </span>
                </div>
                <!--文件列表区域-->
                <div class="content-file-list dark-iview-loading" id="card-box">
                    <!--table形式-->
                    <div v-if="activeType === 'recent' || activeType === 'res' || activeType === 'doc' || activeType === 'other'|| activeType === 'audio' || !showType" class="animated fadeIn dark-iview-table">
                        <Table :columns="fileColumns" :data="fileListShow" class="animated fadeIn" @on-selection-change="handleSelect">
                            <template slot-scope="{ row, index }" slot="size">
                                <div>
                                    {{$jsFn.formatBytes(row.size)}}
                                </div>
                            </template>
                            <template slot-scope="{ row, index }" slot="createTime">
                                <div>
                                    {{formatDate(row.createTime)}}
                                </div>
                            </template>
                            <template slot-scope="{ row, index }" slot="name">
                                <div class="dark-iview-input disabled-iview-input teach-file-name">
                                    <div class="file-icon">
                                        <img v-if="row.extension == 'PPT' || row.extension == 'PPTX'" src="../../assets/icon/ppt50.png" width="15" />
                                        <img v-else-if="row.extension == 'DOC' || row.extension == 'DOCX'" src="../../assets/icon/word50.png" width="15" />
                                        <img v-else-if="row.extension == 'XLS' || row.extension == 'XLSX' || row.extension == 'CSV'" src="../../assets/icon/xls50.png" width="15" />
                                        <img v-else-if="row.extension == 'PDF'" src="../../assets/icon/pdf50.png" width="15" />
                                        <img v-else-if="row.extension == 'ZIP' || row.extension == 'RAR'" src="../../assets/icon/zip50.png" width="15" />
                                        <img v-else-if="row.type == 'image'" src="../../assets/icon/icon_img.png" width="15" />
                                        <img v-else-if="row.type == 'video'" src="../../assets/icon/icon_video.png" width="15" />
                                        <img v-else-if="row.type == 'res'" src="../../assets/icon/htex.png" width="15" />
                                        <img v-else src="../../assets/icon/prelearn50.png" width="15" />
                                    </div>
                                    <span v-show="editIndex !== index">{{row.name}}</span>
                                    <Input v-model="fileListShow[index].name" v-show="editIndex == index" style="width: 300px;" @on-change="checkName" />
                                    <span style="color:#ed4014" v-show="editIndex == index && formatErr">{{$t('teachContent.specialChart')}}(?*:"<>\/|)</span>
                                    <Icon type="md-checkmark" v-show="editIndex == index && !formatErr" @click="confirmRename" class="rename-action-icon" />
                                    <Icon type="md-close" v-show="editIndex == index" @click="cancelRename" class="rename-action-icon" />
                                </div>
                            </template>
                            <template slot-scope="{ row, index }" slot="knowledges">
                                <span style="cursor:pointer;" @click="getPointsByIds(index)">{{row.points == null ? 0 : row.points.length}}</span>
                            </template>
                            <template slot-scope="{ row,index }" slot="action">
                                <div class="item-tools">
                                    <Icon type="md-download" size="18" color="white" :title="$t('teachContent.tips3')" @click="downloadFile(index)" />
                                    <Icon v-if="activeType !== 'other' && activeType != 'res'" type="md-eye" size="18" color="white" :title="$t('teachContent.tips4')" @click="openPreviewFile(index)" />
                                    <Icon v-if="$access.can('admin.*|content-school-upd') || routerScope == 'private'" type="md-trash" size="18" color="white" :title="$t('teachContent.tips7')" @click="delFile(row,index)" />
                                    <Icon v-if="$access.can('admin.*|content-school-upd') || routerScope == 'private'" type="md-create" size="18" color="white" :title="$t('teachContent.tips6')" @click="rename(row,index)" />
                                </div>
                            </template>
                        </Table>
                    </div>
                    <div v-else class="card-box">
                        <!--card形式-->
                        <VueWaterfall v-if="fileListShow.length > 0" ref="vueWaterfall" :imgsArr="fileListShow" :maxCols="10" :gap="15" :imgWidth="240" :width="waterfallWidth" :loadingDotCount="0" srcKey="thum" @scrollReachBottom="scrollReachBottom()" :reachBottomDistance="0">
                            <div class="img-mask" slot-scope="props" @click="openPreviewFile(props.index)">
                                <span class="file-name">{{props.value.name}}</span>
                                <div class="item-tools">
                                    <Icon type="md-download" size="18" color="white" :title="$t('teachContent.tips3')" @click.stop="downloadFile(props.index)" />
                                    <Icon type="md-eye" size="18" color="white" :title="$t('teachContent.tips4')" @click="openPreviewFile(props.index)" />
                                    <Icon v-if="$access.can('admin.*|content-school-upd') || routerScope == 'private'" type="md-trash" size="18" color="white" :title="$t('teachContent.tips7')" @click.stop="delFile(props.value, props.index)" />
                                    <span style="color:white; float:right;margin-right:10px;">{{$jsFn.formatBytes(props.value.size)}}</span>
                                </div>
                            </div>
                            <div slot="waterfall-over">{{$t('teachContent.bottomTips')}}</div>
                        </VueWaterfall>
                        <EmptyData v-else :textContent="$t('teachContent.noData')" style="margin:auto;padding-top:120px;"></EmptyData>
                    </div>
                </div>
            </div>
        </div>
        <!--上传文件-->
        <UploadModal ref="uploadModal" :sasString="sasString" :urlString="urlString" :path="folder" :containerName="containerName" :quality="1" @successData="getFileUrl" :pdId="filterPeriod">
        </UploadModal>
        <!--文件预览-->
        <div v-if="previewStatus" class="image-viewer">
            <div style="width:fit-content;position:relative;margin:auto;">
                <Icon type="md-close" class="close-icon" @click="closePreview" />
                <video v-if="previewFile.type == 'video'" id="previewVideo" :src="previewFile.url" width="870" controls="controls" style="max-height: 800px;">
                    {{$t('teachContent.tips8')}}
                </video>
                <audio v-else-if="previewFile.type == 'audio'" controls>
                    <source :src="previewFile.url">
                    {{$t('teachContent.notAudio')}}
                </audio>
                <img v-else-if="previewFile.type == 'image'" :src="previewFile.url" style="border-radius: 5px;max-height: 800px;max-width:870px;" />
                <embed v-else-if="previewFile.extension == 'PDF'" :src="previewFile.url" width="870" height="720" />
                <iframe v-else :src="'https://view.officeapps.live.com/op/view.aspx?src=' + escapeBlobUrl" width='870' height='700' frameborder='1'></iframe>
            </div>
        </div>
    </div>
</template>
<script>
import { mapGetters } from 'vuex'
import BlobTool from '@/utils/blobTool.js';
import FileSaver from "file-saver";
import JSZip from "jszip";
import elementResizeDetectorMaker from "element-resize-detector"
import VueWaterfall from 'vue-waterfall-easy'
import ResBelong from './ResBelong.vue'
export default {
    components: {
        VueWaterfall, ResBelong
    },
    data() {
        return {
            filterPeriod: '',
            formatErr: false,
            sizeLoading: false,
            editIndex: -1,
            containerClient: undefined,
            waterfallWidth: 1000,
            isLoading: false,
            selections: [],
            escapeBlobUrl: '',
            extensions: [],
            sasString: '',
            urlString: '',
            folder: '',
            containerName: '',
            showType: true,
            extFilter: [],
            fileColumns: [],
            previewFile: {},
            previewStatus: false,
            storageSpace: 0,
            keyWord: '',
            activeType: 'recent',
            fileList: {},
            fileListShow: [],
            searchResult: [],
            searchBefore: [],
            routerScope: '',//0:校本 1：个人
            contentTypeList: [],
            mk: {},
            sizeInfo: {
                total: 0,   //所有
                image: 0,   //内容模块图片
                res: 0,     //内容模块教材
                video: 0,   //内容模块视频
                audio: 0,   //内容模块音频
                doc: 0,     //内容模块文档
                other: 0,   //内容模块其他文件
                data: 0      //除了内容模块之外的文件
            },
            preUpdFiles: [],
            isFirst: {
                image: true,
                video: true,
                audio: true,
                doc: true,
                other: true,
                res: true
            }
        }
    },
    methods: {
        //检查文件特殊字符
        checkName(data) {
            let reg = new RegExp('[?*:"<>\/|]')
            if (reg.test(this.fileListShow[this.editIndex].name)) {
                this.formatErr = true
            } else {
                this.formatErr = false
            }
        },
        rename(row, index) {
            this.editIndex = index
            this.renameBefore = row.name
        },
        cancelRename() {
            this.$set(this.fileListShow[this.editIndex], 'name', this.renameBefore)
            // 解决UI不刷新问题
            let dataTemp = JSON.stringify(this.fileListShow);
            this.fileListShow = JSON.parse(dataTemp);
            this.editIndex = -1
        },
        confirmRename() {
            let editIndex = this.editIndex
            if (this.fileListShow[this.editIndex].extension == 'HTEX') {
                let newName = this.fileListShow[editIndex].name
                this.containerClient.copyFolder(`res/${newName.replace('.HTEX', '/')}`, `res/${this.renameBefore.replace('.HTEX', '')}`).then(
                    res => {
                        this.$api.blob.deletePrefix({
                            cntr: this.routerScope == 'school' ? this.$store.state.userInfo.schoolCode : this.$store.state.userInfo.TEAMModelId,
                            prefix: `res/${this.renameBefore.replace('.HTEX', '')}`
                        }).then(
                            res => {
                                this.$Message.success(this.$t('teachContent.nameOk'))
                                let orginUrl = this.fileListShow[editIndex].url
                                this.fileListShow[editIndex].blob = `/res/${this.newName}/index.json`
                                this.fileListShow[editIndex].url = orginUrl.replace(this.renameBefore, this.fileListShow[editIndex].name)
                            }
                        )
                    },
                    err => {
                        this.$Message.error(this.$t('teachContent.nameErr'))
                    }
                ).finally(() => {
                    this.editIndex = -1
                })
            } else {
                let sourceUrl = this.fileListShow[this.editIndex].url.substring(0, this.fileListShow[this.editIndex].url.lastIndexOf('?')) //截取授权之前的，授权不能encode
                let targetUrl = this.fileListShow[this.editIndex].blob
                targetUrl = targetUrl.replace(this.renameBefore, this.fileListShow[this.editIndex].name)
                targetUrl = targetUrl.substring(1)
                this.containerClient.copyBlob(targetUrl, sourceUrl, this.sasString).then(
                    res => {
                        //这里虽然是复制，但是是重命名操作，所以空间不会变化，就设置为0
                        this.containerClient.deleteBlob(this.fileListShow[editIndex].blob, 0).then(
                            res => {
                                this.$Message.success(this.$t('teachContent.nameOk'))
                                let orginUrl = this.fileListShow[editIndex].url
                                this.fileListShow[editIndex].blob = '/' + targetUrl
                                this.fileListShow[editIndex].url = orginUrl.replace(this.renameBefore, this.fileListShow[editIndex].name)
                            }
                        )
                    },
                    err => {
                        this.$Message.error(this.$t('teachContent.nameErr'))
                    }
                ).finally(() => {
                    this.editIndex = -1
                })
            }
        },
        getFileUrl(files) { // 获取文件地址
            this.preUpdFiles.push(...files)
            this.confirmUpd()
        },
        //确认上传
        async confirmUpd() {
            this.cacheRecent(this.preUpdFiles)
            for (let file of this.preUpdFiles) {
                if (!this.fileList[file.type]) {
                    this.fileList[file.type] = []
                }
                let filterRes = this.fileList[file.type].filter(item => {
                    return item.blob == file.blob
                })
                if (filterRes.length == 0) {
                    file.url = file.url + this.sasString
                    if (!this.fileList[file.type]) {
                        this.fileList[file.type] = []
                    }
                    if (file.type == 'image') {
                        file['thum'] = file.url.replace('/image/', '/thum/')
                    }
                    else if (file.type == 'video') {
                        let n = file.blob
                        n = n.replace('/video/', '/thum/')
                        n = n.replace(file.name, file.name.slice(0, file.name.lastIndexOf('.'))) + '.png'
                        file['thum'] = file.url.replace(file.blob, n)
                    }
                    if (this.activeType == file.type || this.activeType == 'recent') {
                        this.fileListShow.unshift(file)
                        this.fileList[file.type].unshift(file)
                    } else {
                        this.fileList[file.type].unshift(file)
                    }
                    //更新空间
                    this.sizeInfo.total += file.size
                    switch (file.type) {
                        case 'res':
                            this.sizeInfo.res += file.size
                            break
                        case 'image':
                            this.sizeInfo.image += file.size
                            break
                        case 'video':
                            this.sizeInfo.video += file.size
                            break
                        case 'audio':
                            this.sizeInfo.audio += file.size
                            break
                        case 'doc':
                            this.sizeInfo.doc += file.size
                            break
                        case 'other':
                            this.sizeInfo.other += file.size
                            break
                        default:
                            break
                    }
                }
            }
            this.preUpdFiles = []
        },
        //通过localstorage存储最近上传的文件（默认最多20条）
        cacheRecent(files) {
            let cacheFiles = []
            if (this.routerScope == 'private') {
                cacheFiles = JSON.parse(localStorage.getItem('cachePrivFiles') || '[]')
            } else {
                cacheFiles = JSON.parse(localStorage.getItem('cacheSchoolFiles') || '[]')
            }
            let f = files.map(item => {
                return {
                    blob: item.blob,
                    createTime: item.createTime,
                    extension: item.extension,
                    name: item.name,
                    size: item.size,
                    thum: item.thum,
                    type: item.type,
                    url: item.url
                }
            })
            cacheFiles.push(...f)
            cacheFiles.sort((a, b) => {
                return b.createTime - a.createTime
            })
            let len = cacheFiles.length
            if (len > 20) {
                cacheFiles.splice(19, len - 20)
            }
            if (this.routerScope == 'private') {
                localStorage.setItem('cachePrivFiles', JSON.stringify(cacheFiles))
            } else {
                localStorage.setItem('cacheSchoolFiles', JSON.stringify(cacheFiles))
            }
        },
        //计算空间占比
        getPercent(size) {
            if (this.sizeInfo.total > this.storageSpace) {
                return '0%'
            } else {
                let p = (size * 100 / this.storageSpace).toFixed(2)
                p = p > 2 ? p : p > 0 ? 2 : p
                return p + '%'
            }
        },
        showUpload() {
            if (this.sizeInfo.total > this.storageSpace) {
                this.$Message.warning(this.$t('teachContent.fullTips'))
            } else {
                this.$refs['uploadModal'].uploadStatus = true
            }
        },
        /*
         * 瀑布流滚动到底部事件
         */
        scrollReachBottom() {
            this.$refs['vueWaterfall'].isPreloading = false
            this.$jsFn.debounce(() => {
                if (this.mk[this.activeType] == 'end') {
                    this.$Message.warning(this.$t('teachContent.loadAll'))
                    this.$refs['vueWaterfall'].setOverTipPos()
                    this.$refs['vueWaterfall'].over = true
                    this.$refs['vueWaterfall'].isPreloading = true
                } else {
                    this.findFileList()
                }
            }, 600)()
        },
        /**
         * table多选
         * @param selection
         * @param row
         */
        handleSelect(selection, row) {
            this.selections = selection
        },
        /**
         * 切换显示模式
         * */
        changeShowType() {
            if (this.activeType === 'image' || this.activeType === 'video') {
                this.showType = !this.showType
            }
        },
        initData() {
            this.fileColumns = [
                {
                    type: 'selection',
                    width: 60,
                    align: 'center'
                },
                {
                    title: this.$t('teachContent.tableC1'),
                    slot: 'name',
                    key: 'name',
                    sortable: true
                },
                {
                    title: this.$t('teachContent.tableC4'),
                    slot: 'size',
                    key: 'size',
                    width: 120,
                    align: 'center',
                    sortable: true
                },
                {
                    title: this.$t('teachContent.tableC6'),
                    slot: 'createTime',
                    key: 'createTime',
                    width: 150,
                    sortable: true,
                    align: 'center'
                },
                {
                    title: this.$t('teachContent.tableC2'),
                    slot: 'action',
                    width: 160,
                    align: 'center'
                }
            ]
            this.contentTypeList = [
                {
                    label: '最近',
                    type: 'recent',
                    icon: 'md-time',
                    tips: '临时缓存最近上传的资源，最多保存20条。退出账号或更换电脑缓存记录将会被清空。'
                },
                {
                    label: this.$t('teachContent.filterRes'),
                    type: 'res',
                    icon: 'iconfont icon-htex',
                    tips: this.$t('teachContent.resTips')
                },
                {
                    label: this.$t('teachContent.filterPicture'),
                    type: 'image',
                    icon: 'ios-image-outline'
                },
                {
                    label: this.$t('teachContent.filterVideo'),
                    type: 'video',
                    icon: 'logo-youtube'
                },
                {
                    label: this.$t('teachContent.filterAudio'),
                    type: 'audio',
                    icon: 'iconfont icon-audio2'
                },
                {
                    label: this.$t('teachContent.filterDoc'),
                    type: 'doc',
                    icon: 'logo-wordpress'
                },

                {
                    label: this.$t('teachContent.filterOther'),
                    type: 'other',
                    icon: 'md-filing'
                }
            ]
        },
        closePreview() {
            if (this.previewFile.type == 'video') {
                var myVideo = document.getElementById('previewVideo') // 获取视频video
                myVideo.pause()
            }
            this.escapeBlobUrl = ''
            this.previewStatus = false
        },

        /**
         * 根据后缀名筛选文件
         * @param filter
         */
        filterFileByExtension(filter) {
            if (filter.length === 0) {
                this.fileListShow = this._.cloneDeep(this.searchBefore)
            } else {
                let searchResult = this.searchBefore.filter(item => {
                    return this.extFilter.indexOf(item.extension) !== -1
                })
                this.fileListShow = this._.cloneDeep(searchResult)
            }
            if (this.showType) {
                if (this.$refs['vueWaterfall']) {
                    this.$refs['vueWaterfall'].reset()
                }
            }
        },
        /**
         * 获取blob授权信息
         * */
        async getSasStr() {
            let scope = ''
            let sasRes = undefined
            if (this.routerScope == 'school') {
                sasRes = await this.$tools.getSchoolSas()
                scope = 'school'
            } else {
                sasRes = await this.$tools.getPrivateSas()
                scope = 'private'
            }
            if (sasRes) {
                this.sasString = sasRes.sas
                this.urlString = sasRes.url
                this.containerName = sasRes.name
                this.containerClient = new BlobTool(this.urlString, this.containerName, this.sasString, scope)
                // this.findFileList()
            } else {
                this.$Message.error(this.$t('teachContent.authErr'))
            }
        },
        /**
         * 调整由后端计算容器空间
         */
        // 获取容器空间情况 
        getSize() {
            this.sizeLoading = true
            this.containerClient.getSize().then(
                res => {
                    this.sizeInfo = res
                },
                err => {
                    this.$Message.error(this.$t('teachContent.sizeErr'))
                }
            ).finally(() => {
                this.sizeLoading = false
            })
        },
        //批量删除
        delFileBatch() {
            if (this.selections.length == 0) {
                if (this.showType) {
                    this.$Message.warning(this.$t('teachContent.delBatchTips1'))
                } else {
                    this.$Message.warning(this.$t('teachContent.delBatchTips2'))
                }
                return
            }
            let names = this.selections.map((item) => { return item.name })
            this.$Modal.confirm({
                title: this.$t('teachContent.props1'),
                content: "<p class='dialog-p'>" + names.join(', ') + '</p>',
                onOk: () => {
                    if (this.activeType == 'res') {
                        //批量删除HTEX需要循环删除每个文件夹下面的文件
                        this.selections.forEach((item, index) => {
                            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 => {
                                    let fileNames = this.selections.map((item) => { return item.name })
                                    for (let i = 0; i < this.fileList[this.activeType].length; i++) {
                                        let index = fileNames.indexOf(this.fileList[this.activeType][i].name)
                                        if (index > -1) {
                                            this.sizeInfo[this.activeType] -= this.fileList[this.activeType][i].size
                                            this.sizeInfo.total -= this.fileList[this.activeType][i].size
                                            this.fileList[this.activeType].splice(i, 1)
                                            i--
                                        }
                                    }
                                    let fs = this.fileList[this.activeType] ? this.fileList[this.activeType] : []
                                    this.fileListShow = this._.cloneDeep(fs)
                                    this.$Message.success(this.$t('teachContent.props2'))
                                },
                                err => {
                                    this.$Message.error(this.$t('teachContent.props3'))
                                }
                            ).finally(() => {
                                this.isLoading = false
                            })
                        })
                    } else {
                        let blobs = this.selections.map((item) => {
                            return item.url.substring(0, item.url.lastIndexOf('?'))
                        })
                        this.$api.blob.deleteBlobs({
                            cntr: this.routerScope == 'school' ? this.$store.state.userInfo.schoolCode : this.$store.state.userInfo.TEAMModelId,
                            urls: blobs
                        }).then(
                            res => {
                                let thums = []
                                if (this.activeType == 'image') {
                                    thums = blobs.map((item) => { return item.replace('/image/', '/thum/') })
                                } else if (this.activeType == 'video') {
                                    thums = blobs.map((item) => {
                                        let n = item.replace('/video/', '/thum/')
                                        return n.slice(0, n.lastIndexOf('.')) + '.png'
                                    })
                                }
                                if (thums.length) {
                                    this.$api.blob.deleteBlobs({
                                        cntr: this.routerScope == 'school' ? this.$store.state.userInfo.schoolCode : this.$store.state.userInfo.TEAMModelId,
                                        urls: thums
                                    })
                                }

                                let files = this.selections.map((item) => { return item.blob })
                                for (let i = 0; i < this.fileList[this.activeType].length; i++) {
                                    let index = files.indexOf(this.fileList[this.activeType][i].blob)
                                    if (index != -1) {
                                        this.sizeInfo[this.activeType] -= this.fileList[this.activeType][i].size
                                        this.sizeInfo.total -= this.fileList[this.activeType][i].size
                                        this.fileList[this.activeType].splice(i, 1)
                                        i--
                                    }
                                }
                                let fs = this.fileList[this.activeType] ? this.fileList[this.activeType] : []
                                this.fileListShow = this._.cloneDeep(fs)
                            },
                        )
                    }
                }
            })
        },
        /**
         * 删除单个文件
         * @param index
         */
        delFile(file, index) {
            this.$Modal.confirm({
                title: this.$t('teachContent.props1'),
                content: "<p class='dialog-p'>" + file.name + '</p>',
                onOk: () => {
                    this.isLoading = true
                    //删除HTEX需要批量删除
                    if (file.extension == 'HTEX') {
                        this.$api.blob.deletePrefix({
                            cntr: this.routerScope == 'school' ? this.$store.state.userInfo.schoolCode : this.$store.state.userInfo.TEAMModelId,
                            prefix: `res/${file.name.replace('.HTEX', '')}`
                        }).then(
                            res => {
                                this.sizeInfo[this.activeType] -= file.size
                                this.sizeInfo.total -= file.size
                                this.fileListShow.splice(index, 1)
                                for (let i in this.fileList[this.activeType]) {
                                    if (this.fileList[this.activeType][i].url == file.url) {
                                        this.fileList[this.activeType].splice(i, 1)
                                    }
                                }
                                this.$Message.success(this.$t('teachContent.props2'))

                            },
                            err => {
                                this.$Message.error(this.$t('teachContent.props3'))
                            }
                        ).finally(() => {
                            this.isLoading = false
                        })
                    } else {
                        this.containerClient.deleteBlob(file.blob, file.size).then(
                            (res) => {
                                //删除缩略图或封面
                                if (this.activeType == 'image') {
                                    let thum = file.blob.replace('/image/', '/thum/')
                                    //这里暂时预设缩略图大小为60KB
                                    this.containerClient.deleteBlob(thum, 60 * 1024)
                                } else if (this.activeType == 'video') {
                                    let thum = file.blob.replace('/video/', '/thum/')
                                    thum = thum.slice(0, thum.lastIndexOf('.')) + '.png'
                                    //这里暂时预封面大小为60KB
                                    this.containerClient.deleteBlob(thum, 60 * 1024)
                                }
                                this.sizeInfo[this.activeType] -= file.size
                                this.sizeInfo.total -= file.size
                                this.fileListShow.splice(index, 1)
                                for (let i in this.fileList[this.activeType]) {
                                    if (this.fileList[this.activeType][i].url == file.url) this.fileList[this.activeType].splice(i, 1)
                                }
                                this.$Message.success(this.$t('teachContent.props2'))
                            },
                            (err) => {
                                this.$Message.error(this.$t('teachContent.props3'))
                            }
                        ).finally(() => {
                            this.isLoading = false
                        })
                    }
                }
            })
        },
        downloadFile(index) {
            let fileInfo = this.fileListShow[index]
            if (fileInfo.extension == 'HTEX') {
                this.containerClient.listBlob({
                    prefix: `res/${fileInfo.name.replace('.HTEX', '')}`
                }).then(
                    res => {
                        let fileList = res.blobList
                        this.handleBatchDownload(fileList, fileInfo.name)
                    }
                )
            } else {
                let curFile = this.fileListShow[index].url
                const downloadRes = async () => {
                    let response = await fetch(curFile); // 内容转变成blob地址
                    let blob = await response.blob();  // 创建隐藏的可下载链接
                    let objectUrl = window.URL.createObjectURL(blob);
                    let a = document.createElement('a');
                    a.href = objectUrl;
                    a.download = this.fileListShow[index].name;
                    a.click()
                    a.remove();
                }
                downloadRes();
            }
        },
        //批量下载（HTEX）
        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.url + this.sasString).then(dta => {
                    let file_name = item.name
                    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, name); // 利用file-saver保存文件
                    this.isLoading = false;
                }).catch(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);
            })
        },
        openPreviewFile(index) {
            // if (this.fileListShow[index].extension == 'HTEX') {
            //     this.$Message.warning('暂未处理HTEX文件预览功能')
            //     return
            // }
            this.previewFile = this._.cloneDeep(this.fileListShow[index])
            if (this.activeType == 'image' || this.activeType == 'video') {
                this.previewFile.url = this.previewFile.url.replace('thum/', '')
            }
            if (this.fileListShow[index].type == 'image' || this.fileListShow[index].type == 'video' || this.fileListShow[index].extension == 'pdf') {
            } else {
                this.escapeBlobUrl = escape(this.previewFile.url)
            }
            this.previewStatus = true
        },
        formatDate(timestamp) {
            let date = new Date(timestamp)
            return date.toLocaleString()
        },

        /**查询文件列表 */
        findFileList() {
            if (this.containerClient) {
                this.isLoading = true
                let option = {
                    //maxPageSize: 290
                }
                if (this.mk[this.activeType]) {
                    option.continuationToken = this.mk[this.activeType]
                }
                let prefix = this.activeType
                this.containerClient.listBlob({ prefix }, option).then(
                    (res) => {
                        this.mk[this.activeType] = res.continuationToken
                        //拼接授权字符串
                        for (let i in res.blobList) {
                            res.blobList[i].url = res.blobList[i].url + this.sasString
                            if (res.blobList[i].type == 'image') {
                                res.blobList[i].thum = res.blobList[i].url.replace('/image/', '/thum/')
                            } else if (res.blobList[i].type == 'video') {
                                let n = res.blobList[i].blob
                                n = n.replace('/video/', '/thum/')
                                n = n.replace(res.blobList[i].name, res.blobList[i].name.slice(0, res.blobList[i].name.lastIndexOf('.'))) + '.png'
                                res.blobList[i]['thum'] = res.blobList[i].url.replace(res.blobList[i].blob, n)
                            }
                        }
                        this.fileList[this.activeType] = res.blobList
                        this.fileListShow = this._.cloneDeep(this.fileList[this.activeType])
                        this.searchBefore = this.fileList[this.activeType]
                        this.getFilesExtension()
                    },
                    (err) => {

                    }
                ).finally(() => {
                    setTimeout(() => {
                        this.isLoading = false
                    }, 500)
                })
            }
        },

        /**
         * 关键词搜索
         * */
        searchKeyWord() {
            if (this.keyWord === '') {
                this.fileListShow = this._.cloneDeep(this.searchBefore)
            } else {
                let searchResult = this.searchBefore.filter(item => {
                    return item.name.indexOf(this.keyWord) !== -1
                })
                this.fileListShow = this._.cloneDeep(searchResult)
            }
            if (this.showType) {
                if (this.$refs['vueWaterfall']) {
                    this.$refs['vueWaterfall'].reset()
                }
            }
            if (this.showType) {
                if (this.$refs['vueWaterfall'] && this.fileListShow.length == 0) {
                    setTimeout(() => {
                        this.$refs['vueWaterfall'].isPreloading_c = false
                    }, 1000)
                }
            }
        },
        //获取本地缓存最近上传数据
        getCacheFiles() {
            let files = []
            if (this.routerScope == 'private') {
                files = JSON.parse(localStorage.getItem('cachePrivFiles') || '[]')
            } else {
                files = JSON.parse(localStorage.getItem('cacheSchoolFiles') || '[]')
            }
            files.forEach(item => {
                item.url = item.url + this.sasString
            })
            this.fileListShow = files
            this.searchBefore = this.fileListShow
            this.extensions = []
        },
        /**
         * 根据文件类型筛选
         * @param index
         */
        selectFileType(index) {
            this.extFilter = []
            this.selections.length = 0
            this.activeType = this.contentTypeList[index].type
            //最近上传文件读取本地storage
            if (this.activeType == 'recent') {
                this.getCacheFiles()
                return
            }
            if (this.isFirst[this.activeType]) {
                this.fileListShow.length = 0
                this.findFileList()
                this.isFirst[this.activeType] = false
            } else {
                let files = []
                files = this.fileList[this.activeType] ? this.fileList[this.activeType] : []
                this.fileListShow = this._.cloneDeep(files)
                this.getFilesExtension()
                this.searchBefore = this.fileListShow
                this.keyWord = ''
            }
        },
        /**
         * 动态生成文件后缀名筛选条件
         * */
        getFilesExtension() {
            this.extensions.length = 0
            for (let item of this.fileListShow) {
                let ext = item.name.substring(item.name.lastIndexOf('.') + 1)
                this.extensions.push(ext.toUpperCase())
            }
            this.extensions = [...new Set(this.extensions)]
        }
    },
    mounted() {
        let box = document.getElementById('card-box')
        this.waterfallWidth = box.clientWidth - 60
        Date.prototype.toLocaleString = function () {
            return this.getFullYear() + '/' + (this.getMonth() + 1) + '/' + this.getDate()
        }
        //处理瀑布流组件宽度
        this.erd = elementResizeDetectorMaker()
        this.erd.listenTo(document.getElementById("card-box"), () => {
            this.$nextTick(() => {
                //监听到事件后执行的业务逻辑
                let box = document.getElementById('card-box')
                this.waterfallWidth = box.clientWidth - 60
                if (this.$refs['vueWaterfall']) {
                    this.$refs['vueWaterfall'].response()
                }
            })
        })
    },
    created() {
        this.initData()
        let cont = ''
        if (this.$route.name == 'schoolcontent') {
            this.routerScope = 'school'
            cont = this.$store.state.userInfo.schoolCode
        } else {
            this.routerScope = 'private'
            cont = this.$store.state.userInfo.TEAMModelId
        }
        this.sizeLoading = true
        BlobTool.getSizeByServe(cont).then(
            res => {
                this.sizeInfo = res
            },
            err => {
                this.$Message.error(this.$t('teachContent.sizeErr'))
            }
        ).finally(() => {
            this.sizeLoading = false
        })
        this.getCacheFiles()
    },
    watch: {
        $route: {
            handler: function (to, from) {
                this.initData()
                if (this.$route.name == 'schoolcontent') {
                    this.routerScope = 'school'
                    this.storageSpace = this.$GLOBAL.SCHOOL_SPACE
                } else {
                    this.routerScope = 'private'
                    this.storageSpace = this.$GLOBAL.PRIVATE_SPACE
                }
                // this.activeType = 'recent'
                this.getSasStr()
            },
            immediate: true
        }
    }
}
</script>
<style scoped lang="less">
@import "./index.less";
</style>
<style>
.content-file-filter .ivu-input {
    background: none;
    border-radius: 16px;
    color: white;
}

.dialog-p {
    word-wrap: break-word;
}
.upload-modal .ivu-upload-drag {
    background: #404040;
    border-color: #606060;
    color: #dddddd;
}

.upload-modal .ivu-upload-drag:hover {
    border-color: #57a3f3;
    color: #57a3f3;
}

.file-action .ivu-btn-large,
.file-action .ivu-btn {
    padding: 0px 0px 0px 15px;
    border: 0px;
}

.file-action .ivu-select-dropdown {
    left: 62px !important;
}

.content-file-list .ivu-table,
.content-file-list .ivu-table td,
.content-file-list .ivu-table th,
.content-file-list .ivu-table:before {
    background: none;
    color: white;
    border-color: #424242;
}

.content-file-list .ivu-table-row-hover .item-tools {
    opacity: 1;
    transition: opacity 1s;
}

.content-file-list .ivu-table-row-hover {
    background: #303030;
}

.item-tools .ivu-icon {
    margin-right: 10px;
    cursor: pointer;
}

.binding-point .ivu-tabs {
    color: white;
}

.content-file-list #loadingBox {
    margin-top: 0px !important;
}
.teach-file-name .ivu-input[disabled],
.teach-file-name fieldset[disabled] .ivu-input {
    color: white;
    font-size: 14px;
}
</style>
