<template>
    <div>
        <el-upload
            class="avatar-uploader"
            action="http://115.238.57.190:8010/farm-huyang/common/pic"
            :headers="{'x-auth-token': token}"
            name="photo"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
        >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
    </div>
</template>


<script>
import { reqUploadImg } from "@/api/material.js";
// http://192.168.1.5:8016/files/2ceed3f6bfbfd9fc6d6c9b8c455158ec-1000.jpg  $attrs.value
// http://192.168.1.5:8016/files/v2-996be5e52e4b43d08ae6ca8cae80b0fd_r.jpg
// http://192.168.1.5:8016/files/v2-a862735c06feb9edce4369859daf5c12_r.jpg
export default {
    data() {
        return {
            imageUrl: ""
        };
    },
    props: {
        value: String
    },
    watch: {
        value(v, ov) {
            console.log(v);
        }
    },
    computed: {
        imgUrl() {
            return this.value;
        }
    },
    beforeCreate() {
        this.token = localStorage.getItem("token")
    },
    created() {},
    methods: {
        beforeUpload(file) {
            // let formData = new FormData();
            // formData.append("photo", file);
            // reqUploadImg(formData)
            //     .then(res => {
            //         console.log(res);
            //         // this.$attrs.value = res
            //         // this.value = res;
            //         this.dialogImageUrl = res;
            //         this.$emit("on-msg", res);
            //         // this.$set(this, 'value', res)
            //         console.log();
            //     })
            //     .catch(err => {
            //         console.log(err);
            //     });
            // return false;
        },
        handleAvatarSuccess(res, file) {
            console.log('===========')
            console.log(res)
            this.imageUrl = URL.createObjectURL(file.raw);
        },
        beforeAvatarUpload(file) {
            const isJPG = file.type === "image/jpeg";
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
                this.$message.error("上传头像图片只能是 JPG 格式!");
            }
            if (!isLt2M) {
                this.$message.error("上传头像图片大小不能超过 2MB!");
            }
            return isJPG && isLt2M;
        }
    }
};
</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;
    height: 178px;
    display: block;
}
</style>
