import { reactive, ref } from 'vue'
import { UploadFileInfo } from 'naive-ui'
import { UploadStatus } from '@/enums/upload-status'
import { fetchUpload } from '@/apis/upload'
import { AxiosProgressEvent } from 'axios'
import i18n from '@/locales'

interface FileInfoItem {
  id: string
  name: string
  size: number
  status: 'pending' | 'uploading' | 'finished' | 'removed' | 'error'
  url: string
  percentage: number
  type?: string
}

const { t } = i18n.global
export function useDialogueFile() {
  const uploadFileList = ref<FileInfoItem[]>([])

  function handleLimitUpload(data: { file: UploadFileInfo }) {
    const allowTypeList = ['md', 'doc', 'docx', 'pdf', 'txt']

    const fileType = (data.file.file && data.file.file?.name.split('.')?.pop()?.toLowerCase()) || ''

    if (fileType && !allowTypeList.includes(fileType)) {
      window.$message.error(
        t('personal_space_module.knowledge_module.upload_document_module.upload_format_error_message'),
      )
      return false
    }

    if (data.file.file && data.file.file?.size === 0) {
      window.$message.error(
        t('personal_space_module.knowledge_module.upload_document_module.empty_document_content_message'),
      )

      const fileData = reactive({
        id: data.file.id,
        name: data.file.name,
        status: UploadStatus.ERROR,
        size: data.file.file?.size || 0,
        type: fileType,
        percentage: 0,
        url: '',
      })

      uploadFileList.value = []
      uploadFileList.value.push(fileData)
      return false
    }

    if (data.file.file && data.file.file?.size > 10 * 1024 * 1024) {
      window.$message.error(
        t('personal_space_module.knowledge_module.upload_document_module.upload_size_error_message'),
      )

      const fileData = reactive({
        id: data.file.id,
        name: data.file.name,
        status: UploadStatus.ERROR,
        size: data.file.file?.size || 0,
        url: '',
        percentage: 0,
        type: fileType,
      })

      uploadFileList.value = []
      uploadFileList.value.push(fileData)
      return false
    }

    return true
  }

  async function handleUpload(file: any) {
    const formData = new FormData()
    formData.append('file', file.file.file)

    const fileData = reactive({
      id: file.file.id,
      name: file.file.name,
      status: UploadStatus.UPLOADING,
      size: file.file?.file?.size || 0,
      type: file.file?.name.split('.')?.pop()?.toLowerCase(),
      percentage: 0,
      url: '',
    })

    if (uploadFileList.value.length <= 1) {
      uploadFileList.value = []
      await uploadFileList.value.push(fileData)

      fetchUpload(formData, {
        onUploadProgress: (progressEvent: AxiosProgressEvent) => {
          if (progressEvent.total) {
            fileData.percentage = Number(((progressEvent.loaded / progressEvent.total) * 100).toFixed(1))
          } else {
            fileData.percentage = 0
          }
        },
      })
        .then((res) => {
          if (res.code === 0) {
            fileData.status = UploadStatus.FINISHED
            fileData.url = res.data as string
          }
        })
        .catch(() => {
          fileData.status = UploadStatus.ERROR
        })
    }
  }

  function handleRemoveFile(id: string) {
    uploadFileList.value = uploadFileList.value.filter((fileItem) => fileItem.id !== id)
  }

  return { uploadFileList, handleLimitUpload, handleUpload, handleRemoveFile }
}
