<template>
  <div>
    <el-upload :action="`${path}/cms/mediaFile/upload?category=${props.category}`" :show-file-list="false"
      :multiple="false" :before-upload="beforeUpload" :on-error="uploadFailure" :on-success="uploadSuccess">
      <el-button type="primary" plain icon="upload">{{ props.label }}</el-button>
    </el-upload>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { isVideoMime, isImageMime } from '@/utils/image'

defineOptions({
  name: 'UploadCommon',
})

const emit = defineEmits([
  'on-before-upload',
  'on-failure',
  'on-success',
])

const props = defineProps({
  category: { type: String, required: true },
  label: { type: String, default: '上传' }
})

const path = ref(import.meta.env.VITE_BASE_API)

const beforeUpload = (file) => {
  const isLt500K = file.size / 1024 / 1024 < 0.5 // 500K, @todo 应支持在项目中设置
  const isLt5M = file.size / 1024 / 1024 < 5 // 5MB, @todo 应支持项目中设置
  const isVideo = isVideoMime(file.type)
  const isImage = isImageMime(file.type)

  if (!isVideo && !isImage) {
    ElMessage.error('上传图片只能是 jpg,png,svg,webp 格式, 上传视频只能是 mp4,webm 格式!')
    return false
  }
  if (!isLt5M && isVideo) {
    ElMessage.error('上传视频大小不能超过 5MB')
    return false
  }
  if (!isLt500K && isImage) {
    ElMessage.error('未压缩的上传图片大小不能超过 500KB，请使用压缩上传')
    return false
  }

  emit('on-before-upload', file)

  return true
}

const uploadSuccess = (res) => {
  const { code, data, msg } = res
  if (code !== 0) {
    ElMessage({ type: 'error', message: msg })
    emit('on-failure')
  }
  if (!data.mediaFile) {
    ElMessage({ type: 'error', message: '返回错误，上传失败' })
    emit('on-failure')
  }
  emit('on-success', data.mediaFile)
}

const uploadFailure = () => {
  ElMessage({
    type: 'error',
    message: '上传失败'
  })
  emit('on-failure')
}

</script>
