import { FileListType } from '@/components/Z3upFiles/data'
import { baseURL } from './http'

// 上传文件自动归类
type FileObjType = {
  [key: string]: string[]
}
export const fileImgArr = [
  'jpg',
  'jpeg',
  'png',
  'gif',
  'bmp',
  'tiff',
  'webp',
  'svg',
  'psd',
  'ai',
  'ico'
]
export const fileVideoArr = ['mp4', 'mov', 'avi', 'mkv', 'flv', 'wmv', 'mpeg', 'webm']

const fileObj: FileObjType = {
  img: fileImgArr,
  video: fileVideoArr,
  model: ['4dage', 'obj', 'stl', 'fbx', 'gltf', '3ds', 'blend', 'dae', 'step'],
  audio: ['mp3', 'wav', 'flac', 'aac', 'ogg', 'm4a'],
  doc: ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'csv', 'md', 'html']
  // 'other':[]
}

export const fileTypeRes = (fileName: string) => {
  const txtArr = fileName.split('.')
  const txt = txtArr[txtArr.length - 1]

  let type = 'other'

  for (const k in fileObj) {
    if (fileObj[k].includes(txt.toLowerCase())) type = k
  }
  return type
}

// 处理附件id顺序-把图片放在前面
export const fileIdsResFu = (listTemp: FileListType[]) => {
  const files = listTemp || []
  const fileImgArr = files.filter(v => v.type === 'img')
  const fileOtherArr = files.filter(v => v.type !== 'img')
  const fileIds = [...fileImgArr, ...fileOtherArr].map(v => v.id).join(',')
  return fileIds
}

// 简化版本：通过URL下载同域文件
export const downloadFileByUrl = async (fileUrl: string, fileName?: string, back?: () => void) => {
  const a = document.createElement('a')
  a.href = baseURL + fileUrl
  a.target = '_blank'

  // 设置下载文件名
  if (fileName) {
    a.download = fileName
  } else {
    // 自动从URL提取文件名
    const urlParts = fileUrl.split('/')
    const originalName = urlParts[urlParts.length - 1]
    a.download = originalName || 'download'
  }

  // 触发下载
  a.style.display = 'none'
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  if (back) back()
}

// 过滤数组重复的`label`字段
export function arrFiltersFu(data: any[], label: string) {
  const seenLabels = new Set<string>()
  const result: any[] = []

  for (const item of data) {
    if (!seenLabels.has(item[label])) {
      seenLabels.add(item[label])
      result.push(item)
    }
  }

  return result
}
