import { ref, computed } from 'vue'

/**
 * 章节和视频管理
 */
export function useChapters() {
  // ID生成器
  let idSeq = 1
  const nextId = () => `${Date.now()}_${idSeq++}`
  
  // 章节数据 - 初始为空
  const chapters = ref([])
  
  // 折叠面板状态
  const activeChapterPanels = ref([])
  
  // 章节操作
  const addChapter = () => {
    const newId = nextId()
    chapters.value.push({ id: newId, title: '', videos: [] })
    // 新增章节后默认展开该面板
    if (!activeChapterPanels.value.includes(newId)) {
      activeChapterPanels.value.push(newId)
    }
  }
  
  const removeChapter = (cIndex) => {
    const removed = chapters.value.splice(cIndex, 1)[0]
    if (removed) {
      activeChapterPanels.value = activeChapterPanels.value.filter(id => id !== removed.id)
    }
  }
  
  // 视频操作
  const addVideo = (cIndex, videoData = null) => {
    const chapter = chapters.value[cIndex]
    if (!chapter) return
    
    if (videoData) {
      // 从弹窗传来的数据
      chapter.videos.push({ 
        id: nextId(), 
        title: videoData.title || '', 
        file: videoData.videoFile?.file || null, 
        coverFile: null, // 这里需要处理封面文件
        coverPreviewUrl: videoData.coverPreview || '',
        previewUrl: ''
      })
    } else {
      // 默认空视频
      chapter.videos.push({ 
        id: nextId(), 
        title: '', 
        file: null, 
        coverFile: null, 
        coverPreviewUrl: '',
        previewUrl: ''
      })
    }
  }
  
  const removeVideo = (cIndex, vIndex) => {
    const chapter = chapters.value[cIndex]
    if (!chapter) return
    const video = chapter.videos[vIndex]
    // 清理预览URL
    if (video?.coverPreviewUrl) {
      try { URL.revokeObjectURL(video.coverPreviewUrl) } catch (e) {}
    }
    if (video?.previewUrl) {
      try { URL.revokeObjectURL(video.previewUrl) } catch (_) {}
    }
    chapter.videos.splice(vIndex, 1)
  }
  
  // 折叠面板控制
  const expandAllChapters = () => {
    activeChapterPanels.value = chapters.value.map(ch => ch.id)
  }
  
  const collapseAllChapters = () => {
    activeChapterPanels.value = []
  }
  
  const isChapterExpanded = (chapterId) => {
    return activeChapterPanels.value.includes(chapterId)
  }
  
  const toggleChapter = (chapterId) => {
    if (isChapterExpanded(chapterId)) {
      activeChapterPanels.value = activeChapterPanels.value.filter(id => id !== chapterId)
    } else {
      activeChapterPanels.value.push(chapterId)
    }
  }
  
  // 计算属性
  const totalVideos = computed(() => {
    return chapters.value.reduce((sum, ch) => sum + (ch.videos?.length || 0), 0)
  })
  
  const uploadTotalCount = computed(() => {
    let count = 0
    chapters.value.forEach(ch => {
      ch.videos?.forEach(v => { if (v.file) count++ })
    })
    return count
  })
  
  // 清理所有章节和视频数据
  const clearAllChaptersAndVideos = () => {
    chapters.value.forEach(chapter => {
      chapter.videos?.forEach(video => {
        // 清理视频预览URL
        if (video.previewUrl) {
          try {
            URL.revokeObjectURL(video.previewUrl)
          } catch (e) {}
        }
        // 清理视频封面预览URL
        if (video.coverPreviewUrl) {
          try {
            URL.revokeObjectURL(video.coverPreviewUrl)
          } catch (e) {}
        }
      })
    })
  }
  
  // 重置章节数据
  const resetChapters = () => {
    clearAllChaptersAndVideos()
    chapters.value = []
    activeChapterPanels.value = []
  }
  
  return {
    chapters,
    activeChapterPanels,
    totalVideos,
    uploadTotalCount,
    addChapter,
    removeChapter,
    addVideo,
    removeVideo,
    expandAllChapters,
    collapseAllChapters,
    isChapterExpanded,
    toggleChapter,
    clearAllChaptersAndVideos,
    resetChapters
  }
}
