import { getOssConfig } from '../config'

/**
 * 格式化日期
 * @param {Date|string|number} date
 * @param {string} format
 * @returns {string}
 */
export function formatDate(date, format = 'YYYY-MM-DD HH:mm:ss') {
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  const hours = String(d.getHours()).padStart(2, '0')
  const minutes = String(d.getMinutes()).padStart(2, '0')
  const seconds = String(d.getSeconds()).padStart(2, '0')

  return format
    .replace('YYYY', year)
    .replace('MM', month)
    .replace('DD', day)
    .replace('HH', hours)
    .replace('mm', minutes)
    .replace('ss', seconds)
}

/**
 * 防抖函数
 * @param {Function} fn
 * @param {number} delay
 * @returns {Function}
 */
export function debounce(fn, delay = 300) {
  let timer = null
  return function(...args) {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this, args)
    }, delay)
  }
}

/**
 * 节流函数
 * @param {Function} fn
 * @param {number} delay
 * @returns {Function}
 */
export function throttle(fn, delay = 300) {
  let last = 0
  return function(...args) {
    const now = Date.now()
    if (now - last >= delay) {
      last = now
      fn.apply(this, args)
    }
  }
}

/**
 * 深拷贝
 * @param {any} obj
 * @returns {any}
 */
export function deepClone(obj) {
  if (obj === null || typeof obj !== 'object') return obj
  if (obj instanceof Date) return new Date(obj)
  if (obj instanceof Array) return obj.map(item => deepClone(item))

  const clonedObj = {}
  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      clonedObj[key] = deepClone(obj[key])
    }
  }
  return clonedObj
}

/**
 * 获取 OSS 资源 URL
 * @param {string} path - OSS 对象路径,如 'demo/ylzg/单兵视角.mp4'
 * @returns {string} 完整的 OSS 资源 URL
 * @example
 * getAssetUrl('demo/ylzg/单兵视角.mp4')
 * // => 'http://183.221.225.106:9001/6251daf8-4127-40e0-980d-c86f8a765b20/demo/ylzg/单兵视角.mp4'
 */
export function getAssetUrl(path) {
  const { url, bucket } = getOssConfig()
  return `${url}/${bucket}/${path}`
}

/**
 * 获取视频 URL (getAssetUrl 的别名,用于语义化)
 * @param {string} path - 视频文件路径
 * @returns {string} 完整的视频 URL
 */
export function getVideoUrl(path) {
  return getAssetUrl(path)
}

/**
 * 获取图片 URL (getAssetUrl 的别名,用于语义化)
 * @param {string} path - 图片文件路径
 * @returns {string} 完整的图片 URL
 */
export function getImageUrl(path) {
  return getAssetUrl(path)
}
