import { ref } from 'vue'
import { genFileId } from 'element-plus'
import type { UploadFile, UploadProps, UploadRawFile, UploadInstance } from 'element-plus'

const useUploadFile = () => {
  const upload = ref<UploadInstance>()
  const fileList = ref<UploadFile[]>([])
  const percentage = ref<number>(0)

  const onExceed: UploadProps['onExceed'] = (fileList) => {
    upload.value?.clearFiles()
    const file = fileList[0] as UploadRawFile
    file.uid = genFileId()
    upload.value?.handleStart(file)
  }

  const setPercentage = (n: number) => {
    percentage.value = n
  }

  const onUploadProgress = (event: ProgressEvent) => {
    setPercentage(Math.min(parseFloat(((((event.loaded / event.total) * 10000) | 0) / 100).toFixed(2)), 99))
  }

  const reset = () => {
    fileList.value = []
  }

  return {
    upload,
    fileList,
    onExceed,
    percentage,
    setPercentage,
    onUploadProgress,
    reset,
  }
}

export default useUploadFile
