<!--注意element upload组件会给file-list里的每一项带上uid和status参数-->
<template>
    <div class="upload-container">
        <el-upload
            :disabled="isShow"
            :class="{ disabled: isShow }"
            class="upload-warp"
            ref="imagesUpload"
            :action="action"
            :headers="headers"
            accept=".png, .jpg, .jpeg"
            :name="fieldName"
            :data="data"
            list-type="picture-card"
            multiple
            :file-list="fileList"
            :limit="maxSize"
            :auto-upload="false"
            :on-success="handleSuccess"
            :on-change="handleChange"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-error="handleError"
            :before-upload="handleBefore"
            :on-progress="handleProgress">
            <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
        <el-image-viewer
            v-if="showImg"
            :url-list="[imgSrc]"
            @close="closeImgViewer"
            :z-index="3000" />
        <!-- <imgPreview class="imgprevView" :showImg.sync="showImg" :img="imgSrc"></imgPreview> -->
    </div>
</template>

<script>
import { ElImageViewer } from 'element-plus';
import { getToken } from '../utils/auth';
import { Plus } from '@element-plus/icons-vue';
import { artApi } from '../artApi';
import ArtImage from '../artImage';

export default {
    props: {
        isShow: {
            type: Boolean,
            default: false,
        },
        fieldName: {
            //文件的字段名
            type: String,
            default: 'file',
        },
        data: Object,
        imageList: {
            //文件列表，ArtImage的对象集合
            type: Array,
            default: () => {
                return [];
            },
        },
        /*fileList: {
            //文件列表，对象数组{fileName:xxx,url:xxx}
            type: Array,
            default: () => {
                return [];
            },
        },*/
        maxSize: {
            type: Number,
            default: 9,
        }, //文件大小
        filePath: {
            type: String,
            default: '',
        },
        type: {
            //返回的类型
            type: String,
            default: 'base64',
        },
    },
    data() {
        return {
            action: `/api/v2${artApi.artUploadPicture}`,
            headers: {
                Authorization: 'Bearer ' + getToken(),
            },
            dialogImageUrl: '',
            dialogVisible: false,
            disabled: false,
            result: [], //各种操作之后的图片结果
            filesObject: {},
            showImg: false,
            imgSrc: null,
            fileQueue: [], //上传文件队列，内容为文件的uid
            uploadQueue: [], //已上传的文件队列
            status: 0, //0-未开始上传 1-开始上传
            uploadData: null,
        };
    },
    components: {
        ElImageViewer,
    },
    computed: {
        fileList() {
            return this.imageList.map((artImage) => {
                return {
                    url: artImage.compressionUrl,
                    artImage: artImage, //自定义属性，保存artImage对象，作用于数据回显
                };
            });
        },
    },
    created() {
        if (this.data && this.data.id) {
            this.uploadData = this.data;
        }

        /* if (this.imageList.length > 0) {
            this.fileList = this.imageList.map((artImage) => {
                return {
                    url: artImage.compressionUrl,
                    artImage: artImage, //自定义属性，保存artImage对象，作用于数据回显
                };
            });
        }*/
    },
    methods: {
        submitUpload() {
            //使用nextTick为了等props里的data字段发送改变后才执行图片上传
            this.$nextTick(() => {
                this.$refs.imagesUpload.submit();
            });
        },
        handleRemove(file, fileList) {
            console.log(fileList, 'remove');
            let _res = [];
            for (let fileItem of fileList) {
                _res.push(fileItem.artImage);
            }
            this.$emit('handleImageRemove', _res);
        },
        handleChange(file, fileList) {
            this.imgSrc = file.url;
            if (this.status === 1) {
                this.uploadQueue.push(file);
                if (this.uploadQueue.length === this.fileQueue.length) {
                    //上传完成文件总数（无论成功失败）和队列数目相等，表示本次上传已全部文件上传完毕，可以执行成功回调
                    //注意：返回结果的路径里不带域名
                    this.result = [];
                    for (let fileItem of fileList) {
                        if (fileItem.response) {
                            if (fileItem.response.code === 200) {
                                let data = fileItem.response.data;
                                let artImage = new ArtImage(data['img_path']);
                                this.result.push(artImage);
                            } else {
                                this.$emit('uploadError', fileItem.response);
                                let uploadFiles = this.$refs['imagesUpload'].uploadFiles;
                                let index = uploadFiles.indexOf(file);
                                uploadFiles.splice(index, 1);
                                return;
                            }
                        } else {
                            let { artImage } = fileItem;
                            this.result.push(artImage);
                        }
                    }
                    //移除上传队列
                    this.fileQueue = [];
                    this.uploadQueue = [];
                    this.status = 0;
                    //最终将所有图片结果返回
                    this.$emit('uploadSuccess', this.result);
                }
            }
            this.$emit('uploadChange'); //表示图片列表里新加入了图片
        },
        handlePreview(file) {
            //预览用原图
            let imgPath = file.url;
            this.imgSrc = imgPath;
            this.showImg = true;
        },
        handleProgress(event) {
            this.$emit('imgProgress', event.percent);
        },
        handleSuccess(response, file, fileList) {
            //console.log(response)
        },
        handleError(err, file, fileList) {
            this.$message({
                message: '图片上传失败',
                type: 'error',
            });
        },
        uploadFile(files) {
            // console.log(files)
        },
        handleBefore(file) {
            this.fileQueue.push(file.uid);
            this.status = 1;
        },
        closeImgViewer() {
            this.showImg = false;
        },
    },
};
</script>

<style scoped>
.upload-warp {
    margin-bottom: 10px;
}
.imgprevView {
    position: fixed;
    z-index: 3;
}
:deep(.el-upload-list--picture-card .el-upload-list__item-thumbnail) {
    object-fit: contain;
}
.disabled :deep(.el-upload--picture-card) {
    display: none !important;
}
</style>
