import { useUserStore } from '@/store'

export function addBaseParams(params) {
  if (!params.userId) {
    params.userId = useUserStore().userId
  }
}

export function resolveResError(code, message) {
  switch (code) {
    case 400:
      message = message ?? '请求参数错误'
      break
    case 401:
      message = message ?? '登录已过期'
      break
    case 403:
      message = message ?? '没有权限'
      break
    case 404:
      message = message ?? '资源或接口不存在'
      break
    case 500:
      message = message ?? '服务器异常'
      break
    default:
      message = message ?? `【${code}】: 未知异常!`
      break
  }
  return message
}

export function parseFilenameFromDisposition(contentDisposition) {
  if (!contentDisposition) return 'download.xlsx';

  // 优先尝试 filename* (RFC 5987)
  const utf8FilenameMatch = contentDisposition.match(/filename\*=utf-8''([^;]+)/i);
  if (utf8FilenameMatch) {
    try {
      return decodeURIComponent(utf8FilenameMatch[1]);
    } catch (e) {
      console.warn('Failed to decode UTF-8 filename', e);
    }
  }

  // 回退到 filename (可能含引号)
  const asciiFilenameMatch = contentDisposition.match(/filename=("?)([^";]+)\1/i);
  if (asciiFilenameMatch) {
    return asciiFilenameMatch[2];
  }

  return 'download.xlsx';
}

export function downloadBlob(blob, filename) {
  const url = window.URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.download = filename
  link.click()
  link.remove()
  window.URL.revokeObjectURL(url)
}