<template>
    <div>
        <el-upload
            ref="elUpload"
            :action="actionUrl"
            list-type="picture-card"
            :data="data"
            :multiple="multiple"
            :limit="limit"
            :fileList="fileList"
            :show-file-list="showFileList"
            :name="name"
            :accept="accept"
            :auto-upload="true"
            :before-upload="beforeUpload"
            :on-preview="handlePictureCardPreview"
            :on-success="handleImageSuccess"
            :on-remove="handleRemove"
            :on-exceed="handleExceed"
            class="upload-image"
            :class="{ 'hide-upload': hideUpload }"
            :httpaaa-request="httpRequestMain"
        >
            <div class="upload-tip">
                <i class="el-icon-plus"></i>
                <div class="el-upload__tip" v-if="description">
                    {{ description }}
                </div>
            </div>
        </el-upload>

        <el-image-viewer v-if="showViewer" :on-close="closeViewer" :url-list="viewImageUrl" />
    </div>
</template>
<script>
import { uploadFile } from '@/apps/mobile/api/files/index';
import emitter from 'element-ui/src/mixins/emitter';
import ElImageViewer from 'element-ui/packages/image/src/image-viewer';
import { uploadUrl } from '@/config';
export default {
    name: 'UploadImage',
    mixins: [emitter],
    components: {
        ElImageViewer,
    },
    props: {
        value: {
            type: String,
            default: '',
        },
        // 是否支持多选
        multiple: {
            type: Boolean,
            default: false,
        },
        // 上传时附带的额外参数
        data: {
            type: Object,
        },
        // 是否显示已上传文件列表
        showFileList: {
            type: Boolean,
            default: true,
        },
        // 最大允许上传个数
        limit: {
            type: Number,
        },
        // 设定文件域的字段名
        name: {
            type: String,
            default: 'file',
        },
        // 接受上传的文件类型
        accept: {
            type: String,
            default: 'image/jpeg, image/png, image/gif',
        },
        // 文件上传描述
        description: {
            type: String,
            default: '',
            // default: '请上传图片，只能上传jpg/png/gif文件',
        },
        validateEvent: {
            type: Boolean,
            default: true,
        },
        // 文件大小限制，单位KB，默认5MB
        size: {
            type: Number,
            default: 5 * 1024 * 1024,
        },
        // 自定义文件上传方法
        httpRequest: {
            type: Function,
        },
    },
    data() {
        return {
            actionUrl: uploadUrl,
            tempUrl: '',
            hideUpload: false,
            fileList: [],
            showViewer: false,
            viewImageUrl: [],
        };
    },
    inject: {
        elForm: {
            default: '',
        },
        elFormItem: {
            default: '',
        },
    },
    created() {
        this.watchValue();
    },
    watch: {
        value(val) {
            this.watchValue();
        },
    },
    methods: {
        httpRequestMain(f) {
            this.httpRequest ? this.httpRequest(f) : this.uploadImgRequest(f);
        },
        watchValue() {
            let valueArray = this.value ? this.value.split(',') : [];
            this.fileList = valueArray.map(item => {
                return {
                    name: item,
                    url: item,
                };
            });
            this.update();
        },
        uploadImgRequest(f) {
            let param = new FormData(); //创建form对象
            param.append('file', f.file); //通过append向form对象添加数据
            uploadFile(param)
                .then(res => {
                    f.onSuccess(res.data);
                })
                .catch(() => {
                    f.onError();
                });
        },
        update() {
            let valueArray = this.value ? this.value.split(',') : [];
            if (valueArray.length >= this.limit) {
                this.hideUpload = true;
            } else {
                this.hideUpload = false;
            }
        },
        emitInput(value) {
            this.$emit('input', value);
            this.dispatch('ElFormItem', 'el.form.change', value);
            this.$nextTick(() => {
                this.update();
            });
        },
        beforeUpload(file) {
            const fileMax = file.size < this.size;

            if (!fileMax) {
                this.$message.error(`上传图片大小不能超过 ${this.renderSize(this.size)}!`);
            }
            return !!fileMax;
        },
        handlePictureCardPreview(file) {
            this.viewImageUrl = [file.url];
            this.showViewer = true;
        },
        closeViewer() {
            this.showViewer = false;
        },
        handleRemove(file, fileList) {
            const fileArray = fileList.map(item => {
                return item.response.url;
            });
            this.emitInput(fileArray.join(','));
        },
        handleImageSuccess(res, file, fileList) {
            let pathUrl = res.data.pathUrl
            file.url = pathUrl;
            this.emitInput(this.value ? this.value + ',' + pathUrl :  pathUrl);
        },
        handleExceed() {
            this.$message.error(`最多上传${this.limit}张图片`);
        },
        clearFiles() {
            this.$refs.elUpload.clearFiles();
        },
        renderSize(value) {
            if (null == value || value == '') {
                return '0 Bytes';
            }
            let unitArr = new Array('Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
            let index = 0;
            let srcsize = parseFloat(value);
            index = Math.floor(Math.log(srcsize) / Math.log(1024));
            let size = srcsize / Math.pow(1024, index);
            size = size.toFixed(2); //保留的小数位数
            return size + unitArr[index];
        },
    },
};
</script>

<style lang="stylus" scoped>
/deep/ .el-upload-list--picture-card {
    display: flex;
    margin: 0;
    display: inline;
    vertical-align: top;
    
}
/deep/ .el-upload-list__item {
    transition: all .1s cubic-bezier(.55,0,.1,1);
}
.hide-upload /deep/ .el-upload--picture-card {
    display: none;
}
.upload-tip {
    height: 100%;
    line-height: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    padding: 10px;
}
.el-upload__tip {
    line-height: 20px;
    margin-top: 10px;
}
</style>
