<script setup>
import { ref } from 'vue'
import { Plus, Upload } from '@element-plus/icons-vue'
import { ImgUploadService } from '@/api/user'
import DefaultImg from '@/assets/user-img.png'
const dialogVisible = ref(false)
const uploadRef = ref()
const imgUrl = ref()
const formData = new FormData()
const isImg = ref(false)
const onUploadFile = (file) => {
  // 基于 FileReader 读取图片做预览
  isImg.value = true
  const reader = new FileReader()
  reader.readAsDataURL(file.raw)
  reader.onload = () => {
    imgUrl.value = reader.result
  }
  console.log(imgUrl)
  formData.append('image', file.raw)

  // imgUrl.value = URL.createObjectURL(file.raw)
}

// 组件对外暴露一个方法 open
const open = (uid, isUpload, accessUrl) => {
  if (isUpload == 1) {
    isImg.value = true
    imgUrl.value = accessUrl
  }
  formData.append('id', uid)
  dialogVisible.value = true
}
// 向外暴露
defineExpose({
  open
})

const emit = defineEmits(['success'])
// 上传图片
const uploadPhoto = () => {
  ElMessageBox.confirm('确认上传图片', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const isFile = formData.get('image')
      if (isFile !== null) {
        const {
          data: { message }
        } = await ImgUploadService(formData)
        ElNotification({
          title: 'Success',
          message: message,
          type: 'success'
        })
        dialogVisible.value = false
        formData.delete('id')
        formData.delete('image')
      } else {
        ElMessage.error('请选择图片')
      }
      emit('success')
    })
    .catch(() => {
      ElNotification({
        title: 'Warning',
        message: '服务错误，请稍后重试',
        type: 'warning'
      })
    })
}
const close = () => {
  imgUrl.value = ''
  isImg.value = false
  formData.delete('id')
  formData.delete('image')
}
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    title="上传图片"
    width="30%"
    @closed="close"
    close-on-press-escape
  >
    <el-upload
      ref="uploadRef"
      class="avatar-uploader"
      :auto-upload="false"
      :show-file-list="false"
      :on-change="onUploadFile"
      drag
      limit="1"
    >
      <img :src="isImg ? imgUrl : DefaultImg" alt="" style="width: 100%" />
    </el-upload>
    <br />
    <el-button
      @click="uploadRef.$el.querySelector('input').click()"
      type="primary"
      :icon="Plus"
      size="large"
    >
      选择图片
    </el-button>
    <el-button type="success" :icon="Upload" size="large" @click="uploadPhoto">
      上传图片
    </el-button>
  </el-dialog>
</template>
