import { resolveResourceUrl } from '@/utils/resourceUrl'

const IMAGE_RE = /\.(png|jpe?g|gif|webp|bmp)$/i
const VIDEO_RE = /\.(mp4|mov|m4v|webm|avi)$/i
const PDF_RE = /\.pdf$/i

/** 根据路径后缀判断附件类型 */
export function resolveMediaKind(path) {
  const raw = (path || '').trim()
  if (!raw) return 'none'
  const p = raw.split('?')[0]
  if (IMAGE_RE.test(p)) return 'image'
  if (VIDEO_RE.test(p)) return 'video'
  if (PDF_RE.test(p)) return 'pdf'
  return 'file'
}

/** 从 URL 取文件名 */
export function fileNameFromPath(path) {
  const p = (path || '').split('?')[0]
  const seg = p.split('/').filter(Boolean)
  if (!seg.length) return 'attachment'
  try {
    return decodeURIComponent(seg[seg.length - 1])
  } catch (e) {
    return seg[seg.length - 1]
  }
}

/** 在线预览完整 URL（/profile/** 后端 permitAll，可直接访问） */
export function getOnlinePreviewUrl(path) {
  return resolveResourceUrl(path)
}

const FILE_PREVIEW_PAGE = '/package-a/file-preview/index'

/**
 * 在线打开附件（不下载到本地）
 * H5：新窗口；小程序/App 跳转 web-view 页
 */
export function openOnlinePreview(path, { title } = {}) {
  const url = getOnlinePreviewUrl(path)
  if (!url) {
    return Promise.reject(new Error('empty url'))
  }

  // #ifdef H5
  if (typeof window !== 'undefined') {
    window.open(url, '_blank')
    return Promise.resolve()
  }
  return Promise.reject(new Error('unsupported'))
  // #endif

  // #ifdef APP-PLUS
  if (typeof plus !== 'undefined' && plus.runtime) {
    plus.runtime.openURL(url)
    return Promise.resolve()
  }
  // #endif

  const q = [`url=${encodeURIComponent(url)}`]
  if (title) {
    q.push(`title=${encodeURIComponent(title)}`)
  }
  return new Promise((resolve, reject) => {
    uni.navigateTo({
      url: `${FILE_PREVIEW_PAGE}?${q.join('&')}`,
      success: () => resolve(),
      fail: reject
    })
  })
}
