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
  format: 'document' | 'image'
}

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

  function handleLimitUpload(data: { file: UploadFileInfo }) {
    const documentTypeList = ['md', 'doc', 'docx', 'pdf', 'txt'] // 文件类型
    const imageTypeList = ['png', 'jpeg', 'jpg', 'webp'] // 图片类型

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

    if (fileType && !documentTypeList.includes(fileType) && !imageTypeList.includes(fileType)) {
      window.$message.error(
        t(
          'personal_space_module.agent_module.agent_setting_module.agent_config_module.upload_file_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: '',
        format: documentTypeList.includes(fileType) ? ('document' as const) : ('image' as const),
      })

      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,
        format: documentTypeList.includes(fileType) ? ('document' as const) : ('image' as const),
      })

      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 fileFormat = file.file?.name.split('.')?.pop()?.toLowerCase()
    const documentTypeList = ['md', 'doc', 'docx', 'pdf', 'txt']

    const fileData = reactive({
      id: file.file.id,
      name: file.file.name,
      status: UploadStatus.UPLOADING,
      size: file.file?.file?.size || 0,
      type: fileFormat,
      percentage: 0,
      url: '',
      format: documentTypeList.includes(fileFormat) ? ('document' as const) : ('image' as const),
    })

    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 }
}
