import { get } from '@vue2-client/services/api/restTools'

/**
 * 图片文件服务工厂
 *
 * 使用示例：
 *   import { createFileImageService } from '@vue2-client/utils/fileImageService'
 *   const svc = createFileImageService({ serviceName: 'af-safecheck' })
 *   const url = await svc.getImageUrl(fileId)
 */

const CACHE_TIMEOUT = 10 * 60 * 1000

/** 按 serviceName 分组的单例 Map，避免同一服务重复创建实例 */
const instanceMap = new Map()

class FileImageService {
  constructor (serviceName) {
    this.serviceName = serviceName
    this.cache = new Map()
  }

  /**
   * 获取图片 URL
   * @param {string|number|{id: string|number, url?: string}} fileData
   * @returns {Promise<string>}
   */
  async getImageUrl (fileData) {
    if (!fileData) throw new Error('文件数据不能为空')

    // 对象直接含 url 时不请求接口
    if (typeof fileData === 'object' && fileData.url) return fileData.url

    const fileId = typeof fileData === 'object' ? fileData.id : fileData
    if (!fileId) throw new Error('文件ID不能为空')

    const cacheKey = `file_${fileId}`
    const cached = this._getCache(cacheKey)
    if (cached) return cached

    try {
      const res = await get(`/api/${this.serviceName}/resource/byId/${fileId}`)
      let url = res?.f_downloadpath
      if (!url) throw new Error('接口返回数据中缺少 f_downloadpath 字段')
      if (!url.startsWith('http') && !url.startsWith('/')) url = '/' + url
      this._setCache(cacheKey, url)
      return url
    } catch (e) {
      console.error(`[FileImageService:${this.serviceName}] 获取文件 ${fileId} URL 失败:`, e)
      throw new Error(`图片获取失败: ${e.message}`)
    }
  }

  _getCache (key) {
    const c = this.cache.get(key)
    if (c && Date.now() - c.timestamp < CACHE_TIMEOUT) return c.data
    if (c) this.cache.delete(key)
    return null
  }

  _setCache (key, data) {
    this.cache.set(key, { data, timestamp: Date.now() })
  }
}

/**
 * 获取或创建指定 serviceName 的 FileImageService 单例
 * @param {{ serviceName: string }} options
 * @returns {FileImageService}
 */
export const createFileImageService = ({ serviceName }) => {
  if (!serviceName) throw new Error('serviceName 不能为空')
  if (!instanceMap.has(serviceName)) {
    instanceMap.set(serviceName, new FileImageService(serviceName))
  }
  return instanceMap.get(serviceName)
}

export default createFileImageService
