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

const { t } = i18n.global

export interface UploadImageItem {
  id: string
  url: string
  status: 'pending' | 'uploading' | 'finished' | 'error' | 'removed'
}

export function useUploadImage() {
  const uploadImageList = ref<UploadImageItem[]>([])

  function handleLimitUploadImage(data: { file: UploadFileInfo }) {
    if (data.file.file && data.file.file?.size > 1024 * 1024 * 5) {
      window.$message.error(t('common_module.dialogue_module.upload_image_size_error_message'))
      return false
    }

    const imageTypeList = ['image/png', 'image/jpeg', 'image/jpg', 'image/webp']

    if (data.file && data.file.type && !imageTypeList.includes(data.file.type)) {
      window.$message.error(t('common_module.dialogue_module.upload_image_format_error_message'))
      return false
    }
  }

  function handleUploadImage(data: { file: UploadFileInfo }) {
    uploadImageList.value = []

    if (data.file.file) {
      const formData = new FormData()
      formData.append('file', data.file.file)

      const currentUploadImage = reactive({
        id: data.file.id,
        status: UploadStatus.UPLOADING,
        url: '',
      })

      uploadImageList.value.push(currentUploadImage)

      fetchUpload<string>(formData)
        .then((res) => {
          if (res.code === 0) {
            currentUploadImage.status = UploadStatus.FINISHED
            currentUploadImage.url = res.data
          }
        })
        .catch(() => {
          currentUploadImage.status = UploadStatus.ERROR
        })
    }
  }

  function handleRemoveUploadImage(id: string) {
    uploadImageList.value = uploadImageList.value.filter((fileItem) => fileItem.id !== id)
  }

  return {
    uploadImageList,
    handleLimitUploadImage,
    handleUploadImage,
    handleRemoveUploadImage,
  }
}
