<template>
  <el-upload :action="path" :show-file-list="false" :data="uploadData" :multiple="false" :before-upload="beforeUpload"
    :on-error="uploadFailure" :on-success="uploadSuccess">
    <el-button type="primary" plain icon="upload">{{ props.label }}</el-button>
  </el-upload>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { isVideoMime, isImageMime, isDocumentMime, isZipMime } 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 + '/cms/mediaFile/upload')
const uploadData = ref({
  category: props.category
})
const beforeUpload = (file) => {
  console.log('file.type', file.type)
  const isDocument = isDocumentMime(file.type)
  const isZip = isZipMime(file.type)
  const isLt500K = file.size / 1024 / 1024 < 0.5 // 500K, @todo 应支持在项目中设置
  const isLt5M = file.size / 1024 / 1024 < 5 // 5MB, @todo 应支持项目中设置
  const isLt20M = file.size / 1024 / 1024 < 20 // 20MB, @todo 应支持项目中设置
  const isVideo = isVideoMime(file.type)
  const isImage = isImageMime(file.type)

  if (!isVideo && !isImage && !isDocument && !isZip) {
    ElMessage.error('上传图片只能是 jpg,png,svg,webp 格式, 上传视频只能是 mp4,webm 格式，上传文件只能是 txt,pdf,doc,docx,xls,xlsx,ppt,pptx,wps,et,dps,zip,rar!')
    return false
  }
  if (isDocument && !isLt20M) {
    ElMessage.error('上传文档不能超过 20MB')
    return false
  }
  if (!isLt5M && isVideo) {
    ElMessage.error('上传视频大小不能超过 5MB')
    return false
  }
  if (!isLt500K && isImage) {
    ElMessage.error('未压缩的上传图片大小不能超过 500KB，请使用压缩上传')
    return false
  }

  let category = props.category
  if (isDocument) {
    category = 'media_document'
  }
  if (isZip) {
    category = 'media_zip'
  }
  uploadData.value.category = category

  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>
