import axios from 'axios'
import OSS from 'ali-oss'
import { getSTSToken } from '@/api/base'

let ossInstance = null

// 获取STS Token的包装函数
async function getOSSConfig() {
  try {
    const { data } = await getSTSToken()
    return {
      ...data,
      accessKeyId: data.AccessKeyId,
      accessKeySecret: data.AccessKeySecret,
      stsToken: data.SecurityToken,
    }
  } catch (error) {
    handleError(error, 'Failed to retrieve STS token')
  }
}

// 创建OSS实例
async function createOSSInstance() {
  if (ossInstance) {
    return ossInstance
  }
  try {
    const config = await getOSSConfig()
    ossInstance = new OSS({
      bucket: 'zxts-book-file',
      ...config,
      refreshSTSToken: async () => {
        return await getOSSConfig()
      },
      refreshSTSTokenInterval: 14 * 60 * 1000,
    })
    return ossInstance
  } catch (error) {
    handleError(error, 'Failed to create OSS instance')
  }
}

// 上传文件
export async function uploadFile(file) {
  try {
    const oss = await createOSSInstance()
    const fileName = typeof file.name === 'string' ? file.name : ''
    const lastDotIndex = fileName.lastIndexOf('.')
    const extFromName = lastDotIndex > -1 ? fileName.slice(lastDotIndex).toLowerCase() : ''

    const mimeType = (file.type || '').toLowerCase()
    const mimeExtMap = {
      'image/jpeg': '.jpg',
      'image/png': '.png',
      'image/gif': '.gif',
      'image/webp': '.webp',
      'image/svg+xml': '.svg',
      'audio/mpeg': '.mp3',
      'audio/wav': '.wav',
      'audio/ogg': '.ogg',
      'audio/mp4': '.m4a',
      'video/mp4': '.mp4',
      'video/webm': '.webm',
      'video/ogg': '.ogv',
      'video/quicktime': '.mov',
    }

    const fileExt = extFromName || mimeExtMap[mimeType] || '.bin'
    const generatedFileName = `${new Date().getTime()}-${Math.random() * 1000}${fileExt}`
    const result = await oss.put(generatedFileName, file)
    return result.url
  } catch (error) {
    handleError(error, 'Failed to upload file')
  }
}

// 上传通过URL获取的文件
export async function uploadFileByUrl(url) {
  try {
    url = url.replace('https://ark-content-generation-cn-beijing.tos-cn-beijing.volces.com', '/api/volcano_file')
    const res = await axios.get(url, { responseType: 'blob' })
    return await uploadFile(res.data)
  } catch (error) {
    handleError(error, 'Failed to upload file from URL')
  }
}

// 通用错误处理函数
function handleError(error, message) {
  console.error(message, error)
  throw new Error(`${message}: ${error.message}`)
}
