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

<script setup>
defineOptions({ name: 'upload-file'})
import { ref } from 'vue'
import Snackbar from '@/plugins/snackbar'
import { useI18n } from '@/hooks/web/useI18n'
import { uploadFile } from '@/api/common'

const emits = defineEmits(['success'])
defineProps({
  accept: {
    type: String,
    default: '.pdf, .doc, .docx'
  }
})

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) > 10) {
    Snackbar.warning(t('common.fileSizeExceed'))
    return
  }
  const arr = file.name.split('.')
  const formData = new FormData()
  formData.append('file', file)
  const { data } = await uploadFile(formData)
  if (!data) return
  emits('success', data, arr[0])
}

defineExpose({
  trigger
})
</script>

<style scoped lang="scss">

</style>
