<script setup>
import { ref, watch } from 'vue'
import { uploadImgAPi } from '@/api/common'
import { showToast } from 'vant'

const props = defineProps({
  defaultVal: ''
})
const emit = defineEmits(['close','confirm'])

watch(() => props.defaultVal,
  (newval) => {
    fileList.value = newval ? [{url:newval}] : []
  }
)

const fileList = ref(props.defaultVal?[{url: props.defaultVal}]:[])
async function uploadAfter(e){
    // console.log(e);
   
    let form = new FormData();
        form.append('file',e.file);  //hostfile.name

    const res = await uploadImgAPi(form)
    if( res.Ret !== 200 ) return
    fileList.value = [{url:res.Data.ResourceUrl}]
}



function handleCancle() {
  fileList.value = []
  emit('close')
}

function handleConfirm() {
  if(!fileList.value[0]) return showToast('请上传图片')
  emit('confirm',fileList.value[0].url)
}
</script>
<template>
  <div>
  <div class="top-box">
      <span style="color:#666666" @click="handleCancle">取消</span>
      <span style="font-size:18px;font-weight:bold">插入图片</span>
      <span style="color:#0052D9" @click="handleConfirm">确定</span>
  </div>
  <div class="img-box">
    <van-uploader 
      v-model="fileList"
      accept="image/*"
      :after-read="uploadAfter"
      :max-count="1"
    />
  </div>
</div>
</template>
<style scoped lang="scss">
.top-box{
    padding:32px;
    display: flex;
    justify-content: space-between;
    border-bottom: 1px solid #DCDFE6;
    .close{
        color:#666666;
    }
    .title{
        font-size: 36px;
    }
    .add-btn{
        color:$theme-color;
    }
    
}
.img-box {
  height: 50vh;
  padding: 10px;
}
@media screen and (min-width:$media-width){
  .top-box{
      padding:16px;
      .title{
          font-size: 18px;
      }
  }
}
</style>