<template>
  <vab-dialog v-model="dialogFormVisible" append-to-body :title="title" width="800px" @close="close">
    <el-form ref="formRef" label-width="80px" :model="form" :rules="rules" label-position="top">
      <el-form-item class="form-item-list active" label="图片上传">
        <el-upload v-model:file-list="fileList" action="" list-type="picture-card" accept=".jpg,.jpeg,.png,.webp" :before-upload="beforeUpload"
          :on-preview="handlePictureCardPreview" :on-remove="handleRemove" >
          <el-icon><Plus /></el-icon>
        </el-upload>

        <el-dialog v-model="dialogVisible">
          <img w-full :src="dialogImageUrl" alt="Preview Image" />
        </el-dialog>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="danger" @click="close">关闭</el-button>
      <el-button type="primary" @click="save">上传</el-button>
    </template>
  </vab-dialog>
</template>

<script setup>
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

defineOptions({ 
  name: 'ImageUpload',
})

const props = defineProps({
  url: {
    type: String,
    default: '',
  },
  limit: {
    type: Number,
    default: 1,
  },
  size: {
    type: Number,
    default: 10,
  },
})

const emit = defineEmits(['update:url'])

const uploadRef = ref()
const imgUrl = ref('')
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const headers = reactive({
  Authorization: `Bearer ${localStorage.getItem('token') || ''}`,
})
const fileList = ref([])

const handleExceed = () => {
  ElMessage.warning(`当前限制选择 ${props.limit} 个文件`)
}

const handleRemove = (uploadFile, uploadFiles) => {
  if (props.limit === 1) {
    imgUrl.value = ''
    emit('update:url', '')
  } else {
    fileList.value = uploadFiles
    const urls = uploadFiles.map((item) => item.url).join(',')
    emit('update:url', urls)
  }
}

const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  dialogVisible.value = true
}

const beforeUpload = (rawFile) => {
  if (rawFile.size / 1024 / 1024 > props.size) {
    ElMessage.error(`上传头像图片大小不能超过 ${props.size}MB!`)
    return false
  }
  return true
}

const handleSuccess = (response, uploadFile) => {
  if (response.code === 200) {
    if (props.limit === 1) {
      imgUrl.value = response.data
      emit('update:url', response.data)
    } else {
      fileList.value.push(uploadFile)
      const urls = fileList.value.map((item) => item.response ? item.response.data : item.url).join(',')
      emit('update:url', urls)
    }
  } else {
    ElMessage.error(response.msg || '上传失败')
  }
}

const validate = () => {
  // 供父组件调用
  return new Promise((resolve, reject) => {
    if (props.limit === 1) {
      if (imgUrl.value) resolve(true)
      else resolve(false)
    } else {
      if (fileList.value.length > 0) resolve(true)
      else resolve(false)
    }
  })
}

defineExpose({
  validate
})

watch(
  () => props.url,
  (val) => {
    if (val) {
      if (props.limit === 1) {
        imgUrl.value = val
        fileList.value = [{ name: 'img', url: val }]
      } else {
        const urls = val.split(',')
        fileList.value = urls.map((url, index) => ({ name: `img${index}`, url }))
      }
    } else {
      imgUrl.value = ''
      fileList.value = []
    }
  },
  { immediate: true }
)
</script>

<style lang="scss" scoped>
.form-item-list {
  box-sizing: border-box;
  display: inline-block;
  width: 50%;
  padding: 0 10px;
}
.form-item-list.active {
  width: 100%;
}
</style>
