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

type ImageValue = string | string[]

export const toImageList = (value: ImageValue): string[] => {
  return Array.isArray(value) ? value.filter(Boolean) : value.split(',').filter(Boolean)
}

export function appendImageUrl(value: string, url: string): string
export function appendImageUrl(value: string[], url: string): string[]
export function appendImageUrl(value: ImageValue, url: string): ImageValue {
  const nextList = [...toImageList(value), url].filter(Boolean)
  return Array.isArray(value) ? nextList : nextList.join(',')
}

export function removeImageUrl(value: string, url: string): string
export function removeImageUrl(value: string[], url: string): string[]
export function removeImageUrl(value: ImageValue, url: string): ImageValue {
  const nextList = toImageList(value).filter((item) => item !== url)
  return Array.isArray(value) ? nextList : nextList.join(',')
}

// 直接传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 = appendImageUrl(imgs.value, data.filePath)
      } else {
        imgs.value = appendImageUrl(imgs.value, data.filePath)
      }
    } 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 = removeImageUrl(imgs.value, urlStr)
    } else {
      imgs.value = removeImageUrl(imgs.value, urlStr)
    }
  }

  const imgList = computed(() => {
    return toImageList(imgs.value)
  })

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