<template>
    <div>
        <el-upload
            class="avatar-uploader"
            :action="serverAddress+'/publics/pic/upload'"
            :headers="{'x-auth-token': token}"
            name="pic"
            drag
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
        >
            <img v-if="imgUrl" :src="imgUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible" append-to-body>
            <img width="100%" :src="imgUrl" alt />
        </el-dialog>
        <el-link type="primary" @click="showBigImg">查看大图</el-link>
    </div>
</template>


<script>
import { reqUploadImg } from "@/api/material.js";
import config from "@/sdk/config";
const { serverAddress, IMG_BASE } = config;

export default {
    data() {
        return {
            serverAddress,
            dialogVisible: false
        };
    },
    props: {
        value: String
    },

    computed: {
        imgUrl() {
            if(this.value) {
                return IMG_BASE + this.value;
            } else {
                return ''
            }
        }
    },
    beforeCreate() {
        this.token = localStorage.getItem("token");
    },
    created() {},
    methods: {
        aa(a) {
            console.log(a);
        },
        handleAvatarSuccess(res, file) {
            console.log(res);
            this.$emit("on-msg", res);
            // let imageUrl = URL.createObjectURL(file.raw);
            // console.log(file)
            // console.log(file.raw)
            // console.log(imageUrl)
            // console.log(typeof imageUrl)
        },
        beforeAvatarUpload(file) {
            const isJPG = file.type === "image/jpeg" || "image/png";
            const isLt2M = file.size / 1024 / 1024 <= 10;
            console.log(file)
            if (!isJPG) {
                this.$message.error("上传图片只能是 JPG 或 png 格式!");
            }
            if (!isLt2M) {
                this.$message.error("上传图片大小不能超过 10MB!");
            }
            return isJPG && isLt2M;
        },
        showBigImg() {
            if(!this.imgUrl) {
                this.$message.warning('请上传图片！');
                return
            }
            this.dialogVisible = true
        }
    }
};
</script>


<style lang="scss" scope>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}
.avatar-uploader .el-upload:hover {
    border-color: #409eff;
}
.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}
.avatar {
    // width: 178px;
    width: 100%;
    // height: 178px;
    // height: 100%;
    display: block;
}
</style>
