<template>
    <div>
        <el-upload ref="upload" :action="qiNiuUploadApi" :headers="headers" :file-list="fileList" :limit="limit"
            :list-type="type" :on-preview="handlePictureCardPreview" :multiple="limit > 1" :on-success="handleSuccess"
            :on-error="handleError" :on-exceed="onExceed" :on-remove="handleRemove">
            <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible" :z-index="99">
            <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
    </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getToken } from '@/utils/auth'
import { Notification } from 'element-ui'
export default {
    computed: {
        ...mapGetters([
            'qiNiuUploadApi'
        ])
    },
    props: {
        type: {
            type: String,
            default: 'picture-card'
        },
        limit: {
            type: Number,
            default: 1
        }
    },
    data() {
        return {
            dialogImageUrl: '',
            dialogVisible: false,
            fileList: [],
            // files: [],
            headers: {
                'Authorization': getToken()
            }
        }
    },
    methods: {
        handleSuccess(response, file, fileList) {
            // console.log('上传成功', response)
            setTimeout(() => {
                this.fileList.push({
                    url: response.data[0],
                    id: response.data.id
                })
            }, 100);
            // this.files = response.data
            this.$emit('success', response.data)
        },
        // 监听上传失败
        handleError(e, file, fileList) {
            // console.log(e)
            const m = JSON.parse(e.message)
            Notification.error({
                title: m.message,
                duration: 5000
            })
        },
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },
        onExceed() {
            this.$notify.error({
                title: '错误',
                message: `最多上传${this.limit}张图片`
            })
        },
        handleRemove(file, fileList) {
            let arr = fileList.map(item => item.url)
            // 删除数据
            let index = this.fileList.findIndex(ele => ele.url == file.url)
            this.fileList.splice(index, 1);
            this.$emit('remove', arr)
        },
        clearFiles() {
            this.$refs.upload.clearFiles()
        }
    }
}
</script>
<style>
.el-upload-list__item {

    transition: none;

}
</style>