<template>
  <input type="file" ref="fileInput" :accept="accept" style="display: none;" @change="handleUploadFile"/>
</template>

<script setup>
defineOptions({ name: 'UploadFile'})
import { ref } from 'vue'
import { commonApi } from '@/api/menduner/common'
// import { commonApi } from '@/api/menduner/common/index'

const message = useMessage() // 消息弹窗

const emits = defineEmits(['success'])
const props = defineProps({
  accept: {
    type: String,
    default: '.pdf,.doc,.docx'
  },
  custom: {
    type: Boolean,
    default: false
  },
  customName: {
    type: String,
    default: ''
  },
  path: {
    type: String,
    default: 'attachment' // attachment附件， img， video
  }
})

const { t } = useI18n() // 国际化

const clicked = ref(false)
const fileInput = ref()

const trigger = () => {
  if (clicked.value) return
  clicked.value = true
  fileInput.value.click()
  clicked.value = false
}

const handleUploadFile = async (e) => {
  if (!e.target.files.length) return
  
  const file = e.target.files[0]
  const size = file.size
  if (size / (1024*1024) > 20) {
    message.warning('文件大小不能超过20M')
    return
  }
  const arr = file.name.split('.')

  // 效验文件格式是否正确
  const fileType = arr[arr.length - 1]
  const acceptArr = props.accept.split(',')
  if (!acceptArr.includes(`.${fileType}`)) return message.warning('请上传指定格式的文件')

  const formData = new FormData()
  formData.append(props.customName || 'file', file)
  // formData.append('path', props.path)
  if (props.custom) return emits('success', formData)
  const { data } = await commonApi.uploadFile(formData)
  if (!data) return
  emits('success', data, arr[0], file.name)
}

defineExpose({
  trigger
})
</script>

<style scoped lang="scss">

</style>
