// utils/videoStorage.ts

interface VideoPosition {
  id: number
  time: number
  updateTime: string
  [key: string]: any
}

/**
 * 视频播放位置本地存储服务
 */
class VideoStorageService {
  private readonly STORAGE_KEY = 'videoOssList'
  private readonly MAX_STORAGE_COUNT = 50

  /**
   * 获取视频播放位置
   * @param videoId 视频ID
   * @returns 播放位置（秒）或 null
   */
  getVideoPosition(videoId: number): number | null {
    const list = this.getVideoList()
    const video = list.find((v) => v.id === videoId)
    return video?.time || null
  }

  /**
   * 保存视频播放位置
   * @param videoId 视频ID
   * @param time 播放位置（秒）
   * @param videoData 视频数据
   */
  saveVideoPosition(videoId: number, time: number, videoData: any): void {
    const list = this.getVideoList()
    const index = list.findIndex((v) => v.id === videoId)

    const newItem = {
      ...videoData,
      id: videoId,
      time,
      updateTime: new Date().toISOString()
    }

    if (index >= 0) {
      list[index] = newItem
    } else {
      list.push(newItem)
    }

    this.setVideoList(list)
    
    // 自动清理旧数据
    this.cleanOldData()
  }

  /**
   * 清理旧数据（保留最近 50 个）
   */
  cleanOldData(): void {
    const list = this.getVideoList()
    
    if (list.length > this.MAX_STORAGE_COUNT) {
      // 按更新时间排序，保留最新的
      const sorted = list.sort((a, b) => {
        const timeA = new Date(b.updateTime || 0).getTime()
        const timeB = new Date(a.updateTime || 0).getTime()
        return timeA - timeB
      })
      
      this.setVideoList(sorted.slice(0, this.MAX_STORAGE_COUNT))
    }
  }

  /**
   * 清除指定视频的播放位置
   * @param videoId 视频ID
   */
  clearVideoPosition(videoId: number): void {
    const list = this.getVideoList()
    const filtered = list.filter((v) => v.id !== videoId)
    this.setVideoList(filtered)
  }

  /**
   * 清除所有播放位置
   */
  clearAll(): void {
    uni.removeStorageSync(this.STORAGE_KEY)
  }

  /**
   * 获取视频列表
   */
  private getVideoList(): VideoPosition[] {
    try {
      const data = uni.getStorageSync(this.STORAGE_KEY)
      return data ? JSON.parse(data) : []
    } catch (error) {
      console.error('Failed to get video list from storage:', error)
      return []
    }
  }

  /**
   * 设置视频列表
   */
  private setVideoList(list: VideoPosition[]): void {
    try {
      uni.setStorageSync(this.STORAGE_KEY, JSON.stringify(list))
    } catch (error) {
      console.error('Failed to set video list to storage:', error)
    }
  }
}

// 导出单例
export const videoStorage = new VideoStorageService()
