<template>
    
    <div class="accessoriesBox" v-loading="loading">
        <div>
            <div v-if="!readonly && !disabled && allowUpload">
                <el-upload
                    ref="uploader"
                    class="upload-files"
                    drag
                    :action="(serverURL || $cookie.get('serverURL')) + uploadPath"
                    accept=".doc,.docx,.wps,.rtf,.txt,.uof,.ppt,.pptx,.xls,.xlsx,.et,.pdf,.jpg,.jpeg,.tif,.tiff,.bmp,.png,.html,.dps,.ofd"
                    :headers="{token: $cookie.get('token')}"
                    :on-success="handleUploadSuccess"
                    :on-error="handleUploadError"
                    :before-upload="handleBeforeUpload"
                    :on-progress="handleUploadProgress"
                    :show-file-list="false"
                    :data="additionalData"
                    multiple>
                    <i class="el-icon-upload"></i>
                    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                </el-upload>
            </div>
            <div class="cardBox">
                <el-card v-if="(readonly || disabled) && (!uploadedList || uploadedList.length === 0)" class="box-card fileCard" shadow="hover">
                    附件信息无内容...
                </el-card>
                <template v-else-if="!(!readonly && !disabled && allowUpload)">
                    <el-button v-if="allowPreviewAll && !disabled" type="text" size="medium" icon="el-icon-view" class="btn-preview-all" @click.native="handlePreviewAll()">全部预览</el-button>
                </template>
                <el-card class="box-card fileCard" shadow="hover" v-for="(item, index) in uploadedList">
                    <img :src="getIcon(item.type)" alt="" style="">
                    <div class="fileInfo">
                        <span :title="item.name">{{ item.name }}</span>
                        <span class="originalSize">{{ Number(item.size / 1024).toFixed(1) }}K</span>
                    </div>
                    <div class="handleBtns">
                        <el-button v-if="allowPreview && !disabled" :disabled="!item.supportPreview" type="text" size="medium" icon="el-icon-view" @click.native="handlePreview(item)">预览</el-button>
                        <el-button v-if="allowDownload && !disabled" type="text" size="medium" icon="el-icon-tickets" @click.native="handleDownload(item)">下载</el-button>
                        <el-button v-if="allowDelete && !readonly && !disabled" type="text" size="medium" icon="el-icon-delete" @click.native="handleDelete(item, index)">删除</el-button>
                    </div>
                </el-card>
                <el-card class="box-card fileCard" shadow="hover" v-for="item in beforeUploadList">
                    <div class="el-icon-loading"></div>
                    <div class="fileInfo">
                        <span :title="item.name">{{ item.name }}</span>
                        <span class="originalSize">{{ Number(item.size / 1024).toFixed(1) }}K</span>
                    </div>
                </el-card>
            </div>
        </div>
    </div>

</template>
<script>
import {EventBus} from "@/util/event-bus";

export default {
    data() {
        return {
            loading: false,
            uploading: 0,
            additionalData: {
                formDataId: ''
            },
            uploadedList: [],
            beforeUploadList: [],
            fileTypes: ['', '.doc', '.docx', '.ppt', '.pptx', '.ppts', '.xls', '.xlsx', '.wps', '.et', '.dps', '.pdf', '.xps', '.txt', '.ptx', '.win', '.rar', '.zip', '.7z', '.bmp', '.jpg', '.png', '.gif', '.jpeg', '.mp4', '.avi', '.wmv', '.3gp', '.rmvb', '.flv', '.mp3', '.wma', '.midi', '.ofd', '.ceb', '.sep']
        }
    },
    props: {
        value: {
            type: String,
            default: []
        },
        modelKey: {
            type: String,
            default: ''
        },
        serverURL: {
            type: String,
            default: ''
        },
        allowUpload: {
            type: Boolean,
            default: () => {
                return true
            }
        },
        uploadPath: {
            type: String,
            default: '',
        },
        allowDelete: {
            type: Boolean,
            default: () => {
                return true
            }
        },
        deletePath: {
            type: String,
            default: ''
        },
        allowDownload: {
            type: Boolean,
            default: () => {
                return true
            }
        },
        downloadPath: {
            type: String,
            default: ''
        },
        convertPath: {
            type: String,
            default: ''
        },
        allowPreview: {
            type: Boolean,
            default: () => {
                return true
            }
        },
        allowPreviewAll: {
            type: Boolean,
            default: () => {
                return true
            }
        },
        previewPath: {
            type: String,
            default: ''
        },
        limit: {
            type: Number,
            default: 10
        },
        fileSizeLimit: {
            type: Number,
            default: 50
        },
        readonly: {
            type: Boolean,
            default: () => {
                return false
            }
        },
        disabled: {
            type: Boolean,
            default: () => {
                return false
            }
        }
    },
    created() {
        if (this.value && this.value.length > 0) {
            try {
                this.uploadedList = JSON.parse(this.value)
            } catch (e) {
                console.error(e)
            }
        }
    },
    watch: {
        uploading: {
            async handler(value) {
                if (value === 0) {
                    await this.doSubmit(false)
                } else {
                    await this.doSubmit(true)
                }
                EventBus.$emit('on-upload-state-change', this.modelKey)
            },
            immediate: true,
            deep: false
        }
    },
    updated() {
    },
    methods: {
        handleBeforeUpload(file) {
            if (this.limit === 0 || this.uploadedList.length + this.beforeUploadList.length < this.limit) {
                
                if (!file.size / 1024 / 1024 > this.fileSizeLimit) {
                    this.$message.warning(`附件不允许超过${this.fileSizeLimit}MB！`)
                    return false;
                }
                let suffix = file.name.substring(file.name.lastIndexOf('.'))
                if (suffix === undefined || suffix === null) {
                    suffix = ''
                }
                if (this.fileTypes.indexOf(suffix) === -1) {
                    this.$message.warning(`不允许上传${suffix === '' ? '无' : suffix}类型的文件！`)
                    return false;
                }
                this.beforeUploadList.push({
                    uid: file.uid,
                    name: file.name,
                    size: file.size,
                    percentage: 0,
                    isSuccess: false
                })
                this.uploading++
                if ((!this.additionalData || !this.additionalData.formDataId) && this.uploadedList && this.uploadedList.length > 0) {
                    this.additionalData.formDataId = this.uploadedList[0].formDataId
                }
                return true;
            } else {
                this.$message({
                    showClose: true,
                    message: `仅允许上传 ${this.limit} 个附件!`,
                    type: 'warning'
                })
                return false
            }
        },
        handleUploadProgress(event, file, fileList) {
            let currentFile = this.beforeUploadList.filter(f => f.uid === file.uid)
            if (currentFile && currentFile.length > 0) {
                currentFile[0].percentage = parseInt(event.percent.toFixed(0))
            }
        },
        handleUploadSuccess(response, file, fileList) {
            this.uploading--;
            if (response.success && response.code === 200) {
                this.uploadedList.push(response.accessory)
                for (let i in this.beforeUploadList) {
                    if (this.beforeUploadList[i].uid === file.uid) {
                        this.beforeUploadList.splice(i, 1)
                        break;
                    }
                }
                if (response.formDataId) {
                    this.additionalData.formDataId = response.formDataId
                }
            }
            this.doSubmit()
        },
        handleUploadError(response, file, fileList) {
            this.uploading--;
            for (let i in this.beforeUploadList) {
                if (this.beforeUploadList[i].uid === file.uid) {
                    this.beforeUploadList.splice(i, 1)
                    this.$message({
                        showClose: true,
                        message: '文件上传失败，请您重新上传！',
                        type: 'warning'
                    })
                    return false
                }
            }
            this.doSubmit()
        },
        handleUploadCancel(id) {
            this.uploading--;
            let file = this.beforeUploadList.filter(f => f.uid === id)
            this.$refs.uploader.abort(file)
        },
        // 全部预览
        handlePreviewAll() {
            console.log('正在请求预览全部附件')
            if (this.uploadedList && this.uploadedList.length > 0) {
                let ofdIds = []
                let ofdNames = []
                this.uploadedList.forEach((file) => {
                    if (file.ofdId) {
                        ofdIds.push(file.ofdId)
                        ofdIds.push(file.name)
                    }
                })
                this.$events.$emit('form-accessory-preview-all', ofdIds, ofdNames, this.uploadedList)
            } else {
                this.$message({
                    showClose: true,
                    message: '没有可预览的文件!',
                    type: 'warning'
                })
            }
        },
        // 附件预览
        async handlePreview(file) {
            if (file.ofdConverted) {
                this.$events.$emit('form-accessory-preview', file.ofdId, file.name, file)
                console.log('正在请求预览附件, 当前附件id: ' + data.accessory.ofdId + ', name: ' + file.name)
            } else {
                await this.$http({
                    url: '/form/accessory/queryById',
                    method: 'get',
                    params: {
                        'id': file.id
                    }
                }).then(({data}) => {
                    if (data.accessory.ofdConverted) {
                        this.$events.$emit('form-accessory-preview', data.accessory.ofdId, file.name)
                        console.log('正在请求预览附件, 当前附件id: ' + data.accessory.ofdId + ', name: ' + file.name)
                    } else {
                        this.$message({
                            showClose: true,
                            message: '附件暂未完成转换, 请稍后再试!',
                            type: 'warning'
                        })
                    }
                })
            }
        },
        // 附件下载
        handleDownload(file) {
            console.log('正在请求下载附件, 当前附件id: ' + file.id + ', name: ' + file.name)
            let url = this.serverURL + this.downloadPath + '/' + file.id + '?token=' + this.$cookie.get('token');
            console.log(url)
            window.open(url)
            // this.downloadUseId(file.id)
        },
        handleDelete(file, index) {
            console.log('正在请求删除附件, 当前附件id: ' + file.id + ', index: ' + index)
            this.uploadedList.splice(index, 1)
            this.doSubmit()
        },
        // 附件图标
        getIcon(type) {
            return `static/img/uploader/${type}.png`
        },
        getUploadingStatus() {
            return new Promise((resolve, reject) => {
                if (this.uploading === 0) {
                    resolve(true)
                } else {
                    reject('文件正在上传中, 请耐心等待...')
                }
            })
        },
        async doSubmit(isUploading) {
            if (isUploading) {
                this.$emit('getValue', 'uploading')
            } else {
                this.$emit('getValue', this.uploadedList)
            }
        }
    }
}
</script>
<style scoped lang="scss">

ul {
    list-style: none;
    margin: 0;
    padding: 0;
}

.accessoriesBox {
    width: 100%;
    margin: 0 auto;
    
    .cardBox {
        .btn-preview-all {
            padding: 0;
        }
        
        .handleBtns {
            position: absolute;
            right: 10px;
            bottom: 15px;
        }
        
        .fileCard {
            margin-top: 10px;
            width: 100%;
            padding: 10px 20px !important;
            position: relative;
            margin-bottom: 10px;
            display: flex;
            border: 1px solid #D9D9D9;
            
            img {
                width: 25px;
                position: absolute;
                left: 10px;
                top: 17px;
            }
            
            .el-icon-loading {
                width: 20px;
                height: 24px;
                position: absolute;
                left: 10px;
                top: 17px;
                font-size: 24px;
            }
            
            .fileInfo {
                width: 990px;
                padding-left: 25px;
                
                span {
                    width: 100%;
                    display: block;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                    line-height: 20px;
                    color: #2E2E2E;
                }
                
                .originalSize {
                    color: #B0B0B0;
                    font-size: 12px;
                }
            }
        }
    }
    
}
</style>
<style lang="scss">
.el-form-item__content .el-input-group {
    vertical-align: middle;
}

.el-tag + .el-tag {
    margin-left: 5px;
    margin-bottom: 5px;
}

.accessories-list-content {
    flex: 1;
    
    .el-scrollbar__wrap {
        overflow-x: hidden;
    }
}

.accessoriesBox {
    .el-card__body {
        padding: 0;
    }
    
    .el-upload {
        display: block;
        width: 100%;
    }
    
    .el-upload-dragger {
        width: 100%;
        height: 50px;
        text-align: center;
        padding-top: 5px;
    }
    
    .el-icon-upload {
        font-size: 38px !important;
        line-height: 38px !important;
        margin: 0 10px 0 0 !important;
    }
    
    .el-upload__text {
        line-height: 38px;
        display: inline-block;
        position: relative;
        top: -7px;
    }
}

.upload-top-content {
    .upload-files {
        margin: 0;
        padding: 0;
        height: 118px;
        
        .el-upload-dragger {
            width: 678px !important;
            border: none;
            height: 118px;
            
            i {
                font-size: 40px;
                margin: 0;
                line-height: normal;
                padding-top: 10px;
            }
            
            .el-upload__text {
                line-height: 20px;
            }
        }
    }
}
</style>


