import { joinApiUrl } from '@/config'
import { getToken } from '@/utils/auth'

/**
 * 上传图片/视频/语音到 /common/upload（与 ruoyi-ui 一致）
 * @returns {Promise<string>} 文件路径 url 或 fileName
 */
export function uploadNativeFile(file) {
  return new Promise((resolve, reject) => {
    const formData = new FormData()
    formData.append('file', file)
    const xhr = new XMLHttpRequest()
    xhr.open('POST', joinApiUrl('/common/upload'))
    const token = getToken()
    if (token) {
      xhr.setRequestHeader('Authorization', 'Bearer ' + token)
    }
    xhr.onload = () => {
      try {
        const body = JSON.parse(xhr.responseText || '{}')
        if (body.code === 200 && (body.url || body.fileName)) {
          resolve(body.url || body.fileName)
          return
        }
        reject(new Error(body.msg || '上传失败'))
      } catch (e) {
        reject(e)
      }
    }
    xhr.onerror = () => reject(new Error('上传失败'))
    xhr.send(formData)
  })
}

export function uploadFile(filePath, nativeFile) {
  if (nativeFile && typeof File !== 'undefined' && nativeFile instanceof File) {
    return uploadNativeFile(nativeFile)
  }
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: joinApiUrl('/common/upload'),
      filePath,
      name: 'file',
      header: {
        Authorization: 'Bearer ' + getToken()
      },
      success: (res) => {
        try {
          const body = typeof res.data === 'string' ? JSON.parse(res.data) : res.data
          if (body.code === 200 && (body.url || body.fileName)) {
            resolve(body.url || body.fileName)
            return
          }
          reject(new Error(body.msg || '上传失败'))
        } catch (e) {
          reject(e)
        }
      },
      fail: (err) => reject(err)
    })
  })
}
