import { uploadFile } from '@/api'
import { push } from 'notivue'

// 类型定义
type BaseReturn = {
  handleFileChange: (e: Event) => Promise<void>
  uploadPercent: Ref<number>
  handleDeleteImg: (urlStr: string) => void
}

// 传单字符串时多返回 imgList
type UseUploadImgReturnString = BaseReturn & {
  imgList: ComputedRef<string[]>
}
// 传字符串数组时只返回基础
type UseUploadImgReturnArray = BaseReturn

// 直接传ref('imgs1,imgs2') 或者 ref(['img1','img2]) 传字符串的时候 会多返回一个imgList数组 便于模板使用遍历等
export function useUploadImg(imgs: Ref<string>): UseUploadImgReturnString
export function useUploadImg(imgs: Ref<string[]>): UseUploadImgReturnArray
export function useUploadImg(imgs: Ref<string> | Ref<string[]>) {
  const uploadPercent = ref(0)
  // 上传图片的change事件
  const handleFileChange = async (e: Event) => {
    try {
      const file = (e.target as HTMLInputElement).files?.[0]
      if (!file) return

      const { promise } = uploadFile(file, {
        onProgress: (progress) => {
          uploadPercent.value = progress
        },
      })
      const data = await promise
      if (Array.isArray(imgs.value)) {
        imgs.value = [...imgs.value, data.filePath]
      } else {
        imgs.value = [...imgs.value.split(',').filter(Boolean), data.filePath].join(',')
      }
    } catch (error) {
      console.error('上传失败:', error)
      push.error('上传失败，请重试')
    } finally {
      uploadPercent.value = 0
      // 重置input的value
      ;(e.target as HTMLInputElement).value = ''
    }
  }

  // 删除图片
  const handleDeleteImg = (urlStr: string) => {
    if (Array.isArray(imgs.value)) {
      imgs.value = imgs.value.filter((item) => item !== urlStr)
    } else {
      imgs.value =
        imgs.value
          .split(',')
          .filter((item) => item !== urlStr)
          .join(',') || ''
    }
  }

  const imgList = computed(() => {
    if (Array.isArray(imgs.value)) {
      return imgs.value
    } else {
      return imgs.value.split(',').filter(Boolean)
    }
  })

  if (Array.isArray(imgs.value)) {
    return {
      handleFileChange,
      uploadPercent,
      handleDeleteImg,
    }
  } else {
    return {
      handleFileChange,
      uploadPercent,
      handleDeleteImg,
      imgList,
    }
  }
}
