<template>
    <div class="img-upload">
        <input v-show="0 != 0" ref="input" type="file" name="image" accept="image/*" @change="upload" :v-model="file">
        <!-- <el-button type="" @click="uploadClick">上传</el-button> -->
        <!-- <div v-if="imageUrl == ''" class="img-upload-box" @click="uploadClick">
            <p>+</p>
        </div> -->
        <!-- <img class="img-img" v-if="imageUrl!=''" :src="imageUrl" alt="" style="height: 100%;"> -->
        <el-image class="img-img" v-if="imageUrl != ''" style="height:100%" :src="imageUrl" :zoom-rate="1.2" :max-scale="7" :min-scale="0.2"
            :preview-src-list="[imageUrl]" fit="cover" />
        <el-button v-if="imageUrl != ''" type="primary" class="img-button" @click="uploadClick">修改头像</el-button>
    </div>
</template>
<style lang="scss" scoped>
.img-upload {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    position: relative;
    border: 1px solid #ebeef5;
}

.img-img:hover + .img-button {
    display: block;
}

.img-button{
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    margin: 0 auto;
    width: 100px;
    height: 30px;
    margin-bottom: 10px;
    display: none;
}
.img-upload-box {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #ffffff;
}
</style>
<script setup>
import { uploadImage } from '@/api/upload/upload';
import { ref, watch } from 'vue';
// 抛出事件
const emit = defineEmits(['upload']);
const props=defineProps({
    img:{
        type:String,
        default:''
    }
})
watch(props.img,(newV)=>{
    if(newV!=null){
        console.log("传入了图片")
        imageUrl.value=newV;
    }
},{
deep: true})
// const 
// eslint-disable-next-line no-unused-vars
//文件对象
const file = ref(null);
//上传框dom
const input = ref(null);
//图片url
const imageUrl = ref('');
//点击开启上传
const uploadClick = () => {
    input.value.click();
}
//上传
const toUploadImage = async () => {
    let res = await uploadImage(file.value);
    if (res.code == 1) {
        //成功
        return res.data;
    }
    return null;
}
const upload = async (e) => {
    let imgMaxSize = 1024 * 1024 * 4;
    if (e.target.files[0].size > imgMaxSize) {
        alert("图片大小不能超过4M");
        return;
    }
    if (['jpeg', 'png', 'gif', 'jpg'].indexOf(e.target.files[0].type.split("/")[1]) < 0) {
        //用你选择组件的报错弹窗就行，报出以下提醒
        alert("上传的文件必须是图片格式");
        return;
    }
    file.value = e.target.files[0];
    // alert("上传文件");
    let url = await toUploadImage();
    if (url != null) {
        imageUrl.value = url;
        emit('upload', url);
    } else {
        alert("上传失败");
    }
}
const updateUrl=(img)=>{
    file.value=null;
    if(img==null){
        imageUrl.value='';
        return ;
    }
    imageUrl.value=img;
}
//暴露方法
defineExpose(
    {
        updateUrl
    }
)
</script>
