<template>
    <div>
        <el-upload
            multiple
            :limit="limit"
            :headers="headers"
            :data="uploadData"
            :action="actionUrl"
            :file-list="fileList"
            :on-exceed="handleExceed"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            :before-upload="beforeUpload"
            list-type="picture-card"
        >
            <i class="el-icon-plus avatar-uploader-icon"></i>
            <div class="el-upload__tip" slot="tip"
                >请上传png、jpg、jpeg类型图片，图片总数不能超过
                {{ limit }} 个，且单张图片不能超过5M</div
            >
        </el-upload>
    </div>
</template>

<script>
import { getToken } from '@/utils/auth'
export default {
    props: {
        limit: {
            type: Number,
            default: 1,
        },
        actionUrl: {
            type: String,
            default: '#',
        },
    },

    data() {
        return {
            fileList: [],
            headers: {
                Authorization: 'Bearer ' + getToken(),
            },
            uploadData: {
                fileType: 'ma',
            },
        }
    },
    methods: {
        handleRemove(file) {
            this.$emit('remove', file)
        },
        handleSuccess(response, file) {
            this.$emit('success', response, file)
        },
        handleExceed() {
            this.$message.error(`最多只能上传${this.limit}个图片！`)
        },
        beforeUpload(file) {
            const isJPGorPNG =
                file.type == 'image/png' ||
                file.type == 'image/jpg' ||
                file.type == 'image/jpeg'
            const isLt5M = file.size / 1024 / 1024 < 5 // 小于 5MB
            if (!isJPGorPNG) {
                this.$message.error('只能上传 jpg、jpeg、png 、 格式的图片！')
            }
            if (!isLt5M) {
                this.$message.error('上传的图片大小不能超过 5MB')
            }
            return isJPGorPNG && isLt5M
        },
    },
}
</script>

<style scoped>
::v-deep .el-upload {
    width: 140px;
    height: 140px;
    line-height: 150px;
}
.el-upload__tip {
    font-size: 16px;
    color: red;
}
</style>
