<template>
  <div class="course-study-page">
    <div class="study-container">
      <!-- 左侧主要内容 -->
      <div class="main-content">
        <!-- 面包屑导航 -->
        <div class="breadcrumb-section">
          <span class="breadcrumb-item" @click="$router.push('/')">首页</span>
          <span class="breadcrumb-separator">></span>
          <span class="breadcrumb-item" @click="$router.push('/')">课程</span>
          <span class="breadcrumb-separator">></span>
          <span class="breadcrumb-item" @click="goToCourseDetail">{{ course?.title || '课程详情' }}</span>
          <span class="breadcrumb-separator">></span>
          <span class="breadcrumb-item current">{{ currentVideoTitle || '视频学习' }}</span>
        </div>

        <!-- 视频播放器区域 -->
        <div class="video-player-section">
          <div v-if="currentVideoUrl" class="video-container">
            <VideoPlayer
              :video-url="currentVideoUrl"
              :title="currentVideoTitle"
              :description="currentVideoDescription"
              :poster="videoPoster"
              :autoplay="autoplay"
              :show-controls="true"
              @play="onVideoPlay"
              @pause="onVideoPause"
              @ended="onVideoEnded"
              @timeupdate="onVideoTimeUpdate"
              @error="onVideoError"
            />
          </div>
          <div v-else class="video-placeholder">
            <div class="placeholder-content">
              <svg width="80" height="80" viewBox="0 0 80 80" fill="none">
                <circle cx="40" cy="40" r="30" stroke="#ccc" stroke-width="2"/>
                <path d="M32 25L32 55L55 40L32 25Z" fill="#ccc"/>
              </svg>
              <p>请选择要播放的视频</p>
            </div>
          </div>
        </div>

        <!-- 视频信息和控制 -->
        <div class="video-info-section">
          <div class="video-header">
            <h1 class="video-title">{{ currentVideoTitle }}</h1>
            <div class="video-meta">
              <span class="video-category">分类：<span class="category-tag">信息技术</span></span>
              <span class="video-stats">{{ videoDuration > 0 ? formatDuration(videoDuration) : '0:00' }}</span>
              <button class="btn-notes" @click="takeNotes">📝 记笔记</button>
            </div>
          </div>

          <!-- 视频描述 -->
          <div class="video-description" v-if="currentVideoDescription">
            <p>{{ currentVideoDescription }}</p>
          </div>

          <!-- 视频控制按钮 -->
          <div class="video-controls-section">
            <div class="controls-left">
              <button class="control-btn" @click="previousVideo" :disabled="!hasPrevious">
                <svg width="16" height="16" viewBox="0 0 16 16">
                  <path d="M10 3L5 8L10 13V3Z" fill="currentColor"/>
                </svg>
                上一节
              </button>
              
              <button class="control-btn primary" @click="togglePlay">
                <svg v-if="!isPlaying" width="16" height="16" viewBox="0 0 16 16">
                  <path d="M3 2L13 8L3 14V2Z" fill="currentColor"/>
                </svg>
                <svg v-else width="16" height="16" viewBox="0 0 16 16">
                  <path d="M3 2H6V14H3V2ZM10 2H13V14H10V2Z" fill="currentColor"/>
                </svg>
                {{ isPlaying ? '暂停' : '播放' }}
              </button>
              
              <button class="control-btn" @click="nextVideo" :disabled="!hasNext">
                下一节
                <svg width="16" height="16" viewBox="0 0 16 16">
                  <path d="M6 3L11 8L6 13V3Z" fill="currentColor"/>
                </svg>
              </button>
            </div>

            <div class="controls-right">
              <button class="control-btn" @click="markAsCompleted" v-if="!isCurrentLessonCompleted">
                <svg width="16" height="16" viewBox="0 0 16 16">
                  <path d="M13.5 3L6 10.5L2.5 7" stroke="currentColor" stroke-width="2" fill="none"/>
                </svg>
                标记为已完成
              </button>
              <span v-else class="completed-badge">
                <svg width="16" height="16" viewBox="0 0 16 16">
                  <circle cx="8" cy="8" r="8" fill="#52c41a"/>
                  <path d="M5 8L7 10L11 6" stroke="white" stroke-width="2" fill="none"/>
                </svg>
                已完成
              </span>
            </div>
          </div>
        </div>

        <!-- 课程标签页 -->
        <div class="course-tabs">
          <div class="tab-nav">
            <button class="tab-btn" :class="{ active: activeTab === 'intro' }" @click="activeTab = 'intro'">课程介绍</button>
            <button class="tab-btn" :class="{ active: activeTab === 'comments' }" @click="activeTab = 'comments'">评论</button>
            <button class="tab-btn" :class="{ active: activeTab === 'notes' }" @click="activeTab = 'notes'">笔记</button>
          </div>

          <!-- 标签页内容区域 -->
          <div class="tab-content">
            <!-- 课程介绍内容 -->
            <div v-if="activeTab === 'intro'" class="tab-pane">
              <div class="intro-content">
                <h4>课程详情</h4>
                <div class="course-description" v-html="formatDescription(course?.description)"></div>

                <h4>学习目标</h4>
                <ul>
                  <li>掌握课程核心知识点</li>
                  <li>提高实际应用能力</li>
                  <li>获得相关技能认证</li>
                </ul>
              </div>
            </div>

            <!-- 评论内容 -->
            <div v-if="activeTab === 'comments'" class="tab-pane">
              <div class="comments-content">
                <!-- 评论统计 -->
                <div class="comments-stats">
                  <span class="comments-count">课程讨论 ({{ comments.length }})</span>
                  <div class="comments-sort">
                    <button class="sort-btn active">最新</button>
                    <button class="sort-btn">最热</button>
                  </div>
                </div>

                <!-- 发表评论 -->
                <div class="comment-input-section">
                  <div class="comment-input-wrapper">
                    <div class="user-avatar">
                      <img src="https://via.placeholder.com/40x40/1890ff/ffffff?text=我" alt="用户头像" />
                    </div>
                    <div class="comment-input-area">
                      <textarea
                        v-model="newComment"
                        placeholder="写下你的评论..."
                        rows="3"
                        class="comment-textarea"
                      ></textarea>
                      <div class="comment-actions">
                        <button class="btn-submit" @click="submitComment" :disabled="!newComment.trim()">
                          发表评论
                        </button>
                      </div>
                    </div>
                  </div>
                </div>

                <!-- 评论列表 -->
                <div class="comments-list">
                  <div v-if="comments.length === 0" class="no-comments">
                    <div class="no-comments-icon">💬</div>
                    <p>暂无评论，快来发表第一条评论吧！</p>
                  </div>

                  <div v-for="comment in comments" :key="comment.id" class="comment-item">
                    <div class="comment-avatar">
                      <img :src="comment.avatar || 'https://via.placeholder.com/40x40/52c41a/ffffff?text=' + comment.author.charAt(0)" :alt="comment.author" />
                    </div>
                    <div class="comment-main">
                      <div class="comment-header">
                        <span class="comment-author">{{ comment.author }}</span>
                        <span class="comment-time">{{ comment.time }}</span>
                      </div>
                      <div class="comment-content">{{ comment.content }}</div>
                      <div class="comment-footer">
                        <button class="comment-action" @click="likeComment(comment.id)">
                          <svg width="14" height="14" viewBox="0 0 14 14" :class="{ liked: comment.liked }">
                            <path d="M7 12.5L6.125 11.75C3.5 9.375 1.75 7.75 1.75 5.75C1.75 4.25 2.875 3.125 4.375 3.125C5.25 3.125 6.125 3.5 7 4.25C7.875 3.5 8.75 3.125 9.625 3.125C11.125 3.125 12.25 4.25 12.25 5.75C12.25 7.75 10.5 9.375 7.875 11.75L7 12.5Z" fill="currentColor"/>
                          </svg>
                          <span>{{ comment.likes || 0 }}</span>
                        </button>
                        <button class="comment-action" @click="replyToComment(comment.id)">
                          <svg width="14" height="14" viewBox="0 0 14 14">
                            <path d="M7 1.75C10.5 1.75 12.25 3.5 12.25 7C12.25 10.5 10.5 12.25 7 12.25H3.5L1.75 14V7C1.75 3.5 3.5 1.75 7 1.75Z" stroke="currentColor" stroke-width="1" fill="none"/>
                          </svg>
                          回复
                        </button>
                      </div>

                      <!-- 回复列表 -->
                      <div v-if="comment.replies && comment.replies.length > 0" class="replies-list">
                        <div v-for="reply in comment.replies" :key="reply.id" class="reply-item">
                          <div class="reply-avatar">
                            <img :src="reply.avatar || 'https://via.placeholder.com/32x32/fa8c16/ffffff?text=' + reply.author.charAt(0)" :alt="reply.author" />
                          </div>
                          <div class="reply-main">
                            <div class="reply-header">
                              <span class="reply-author">{{ reply.author }}</span>
                              <span class="reply-time">{{ reply.time }}</span>
                            </div>
                            <div class="reply-content">
                              <span v-if="reply.replyTo" class="reply-to">@{{ reply.replyTo }}</span>
                              {{ reply.content }}
                            </div>
                            <div class="reply-footer">
                              <button class="comment-action" @click="likeReply(comment.id, reply.id)">
                                <svg width="12" height="12" viewBox="0 0 14 14" :class="{ liked: reply.liked }">
                                  <path d="M7 12.5L6.125 11.75C3.5 9.375 1.75 7.75 1.75 5.75C1.75 4.25 2.875 3.125 4.375 3.125C5.25 3.125 6.125 3.5 7 4.25C7.875 3.5 8.75 3.125 9.625 3.125C11.125 3.125 12.25 4.25 12.25 5.75C12.25 7.75 10.5 9.375 7.875 11.75L7 12.5Z" fill="currentColor"/>
                                </svg>
                                <span>{{ reply.likes || 0 }}</span>
                              </button>
                              <button class="comment-action" @click="replyToReply(comment.id, reply.id, reply.author)">
                                <svg width="12" height="12" viewBox="0 0 14 14">
                                  <path d="M7 1.75C10.5 1.75 12.25 3.5 12.25 7C12.25 10.5 10.5 12.25 7 12.25H3.5L1.75 14V7C1.75 3.5 3.5 1.75 7 1.75Z" stroke="currentColor" stroke-width="1" fill="none"/>
                                </svg>
                                回复
                              </button>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 笔记内容 -->
            <div v-if="activeTab === 'notes'" class="tab-pane">
              <div class="notes-content">
                <div class="notes-input">
                  <textarea 
                    v-model="newNote" 
                    placeholder="记录学习笔记..."
                    rows="5"
                  ></textarea>
                  <button class="btn-submit" @click="saveNote" :disabled="!newNote.trim()">
                    保存笔记
                  </button>
                </div>
                
                <div class="notes-list">
                  <div v-if="notes.length === 0" class="no-notes">
                    暂无笔记，开始记录你的学习心得吧！
                  </div>
                  <div v-for="note in notes" :key="note.id" class="note-item">
                    <div class="note-header">
                      <span class="note-time">{{ note.time }}</span>
                      <button class="btn-delete" @click="deleteNote(note.id)">删除</button>
                    </div>
                    <div class="note-content">{{ note.content }}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧边栏 -->
      <div class="sidebar">
        <!-- 学习进度 -->
        <div class="progress-section">
          <h3>学习进度</h3>
          <div class="progress-chart">
            <div class="progress-circle">
              <svg width="100" height="100" viewBox="0 0 100 100">
                <circle cx="50" cy="50" r="40" stroke="#e8f4fd" stroke-width="8" fill="none"/>
                <circle cx="50" cy="50" r="40" stroke="#1890ff" stroke-width="8" fill="none"
                  :stroke-dasharray="251" :stroke-dashoffset="251 - (251 * progress / 100)" stroke-linecap="round"/>
              </svg>
              <div class="progress-text">
                <span class="percentage">{{ progress }}%</span>
                <span class="label">已完成</span>
              </div>
            </div>
          </div>
          <div class="progress-details">
            <div class="progress-item">
              <span class="label">已学习</span>
              <span class="value">{{ completedLessons }}/{{ totalLessons }}节</span>
            </div>
            <div class="progress-item">
              <span class="label">学习时长</span>
              <span class="value">{{ formatDuration(totalStudyTime) }}</span>
            </div>
          </div>
        </div>

        <!-- 课程章节 -->
        <div class="course-sections">
          <div class="sections-header">
            <h3>课程章节</h3>
            <button class="sort-btn" @click="toggleSortOrder">
              {{ sortOrder === 'asc' ? '正序' : '倒序' }}
            </button>
          </div>
          
          <div class="sections-list">
            <div v-if="sortedChapters.length === 0" class="no-chapters">
              <p>正在加载课程章节...</p>
            </div>
            <div v-for="(chapter, chapterIndex) in sortedChapters" :key="chapterIndex" class="chapter-section">
              <div class="chapter-header" @click="toggleChapter(chapterIndex)">
                <div class="chapter-info">
                  <span class="chapter-number">第{{ chapterIndex + 1 }}章</span>
                  <span class="chapter-title">{{ chapter.title }}</span>
                </div>
                <span class="chapter-toggle" :class="{ 'expanded': chapter.expanded }">
                  <svg width="12" height="12" viewBox="0 0 12 12">
                    <path d="M4 3l4 3-4 3" stroke="currentColor" stroke-width="1.5" fill="none"/>
                  </svg>
                </span>
              </div>
              
              <div v-if="chapter.expanded" class="chapter-lessons">
                <div 
                  v-for="lesson in chapter.lessons" 
                  :key="lesson.id" 
                  class="lesson-item"
                  :class="{ 
                    active: currentLessonId === lesson.id,
                    completed: lesson.completed 
                  }"
                  @click="selectLesson(lesson)"
                >
                  <div class="lesson-info">
                    <span class="lesson-type" :class="getLessonTypeClass(lesson)">
                      {{ getLessonTypeText(lesson) }}
                    </span>
                    <span class="lesson-title">{{ lesson.name }}</span>
                  </div>
                  <div class="lesson-actions">
                    <span class="lesson-duration">{{ lesson.duration || '' }}</span>
                    <div class="lesson-status">
                      <svg v-if="lesson.completed" width="16" height="16" viewBox="0 0 16 16">
                        <circle cx="8" cy="8" r="8" fill="#52c41a"/>
                        <path d="M5 8L7 10L11 6" stroke="white" stroke-width="2" fill="none"/>
                      </svg>
                      <svg v-else-if="currentLessonId === lesson.id" width="16" height="16" viewBox="0 0 16 16">
                        <circle cx="8" cy="8" r="8" fill="#1890ff"/>
                        <path d="M6 5L11 8L6 11V5Z" fill="white"/>
                      </svg>
                      <svg v-else width="16" height="16" viewBox="0 0 16 16">
                        <circle cx="8" cy="8" r="8" stroke="#d9d9d9" stroke-width="1" fill="none"/>
                      </svg>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 消息提示 -->
    <div v-if="showToast" class="toast-message">
      {{ toastMessage }}
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import VideoPlayer from '@/components/VideoPlayer.vue'
import { CourseApi } from '@/api/modules/course'
import type { Course, CourseSection } from '@/api/types'

const route = useRoute()
const router = useRouter()
const courseId = ref(Number(route.params.id))

// 从URL查询参数获取视频信息
const currentVideoUrl = ref(route.query.videoUrl ? decodeURIComponent(route.query.videoUrl as string) : '')
const currentVideoTitle = ref(route.query.sectionName ? decodeURIComponent(route.query.sectionName as string) : '')
const currentSectionId = ref(route.query.sectionId ? Number(route.query.sectionId) : null)

// 调试信息
console.log('CourseStudy初始化:')
console.log('- 视频URL:', currentVideoUrl.value)
console.log('- 视频标题:', currentVideoTitle.value)
console.log('- 章节ID:', currentSectionId.value)
console.log('- 路由查询参数:', route.query)

// 课程数据
const course = ref<Course | null>(null)
const courseSections = ref<CourseSection[]>([])
const currentLessonId = ref(currentSectionId.value || 1)

// 视频播放状态
const isPlaying = ref(false)
const videoDuration = ref(0)
const autoplay = ref(false)
const videoPoster = ref('')
const currentVideoDescription = ref('')

// 学习进度
const progress = ref(0)
const completedLessons = ref(0)
const totalLessons = ref(0)
const totalStudyTime = ref(0)

// 章节数据
interface ChapterGroup {
  title: string
  lessons: CourseSection[]
  expanded: boolean
}

const groupedSections = ref<ChapterGroup[]>([])
const sortOrder = ref<'asc' | 'desc'>('asc')

// 标签页状态
const activeTab = ref('intro')

// 评论和笔记
const newComment = ref('')
const comments = ref<any[]>([
  {
    id: 1,
    author: '学霸小王',
    avatar: 'https://via.placeholder.com/40x40/52c41a/ffffff?text=王',
    content: '老师讲得很好，特别是关于指针的部分，通俗易懂！受益匪浅，感谢老师的精彩讲解。',
    time: '2小时前',
    likes: 12,
    liked: false,
    replies: [
      {
        id: 11,
        author: '编程新手',
        avatar: 'https://via.placeholder.com/32x32/fa8c16/ffffff?text=新',
        content: '同感！老师的例子很生动',
        time: '1小时前',
        likes: 3,
        liked: false,
        replyTo: null
      }
    ]
  },
  {
    id: 2,
    author: '代码爱好者',
    avatar: 'https://via.placeholder.com/40x40/722ed1/ffffff?text=码',
    content: '关于数组的那个例子能再详细讲解一下吗？',
    time: '3小时前',
    likes: 8,
    liked: false,
    replies: []
  },
  {
    id: 3,
    author: '程序员小李',
    avatar: 'https://via.placeholder.com/40x40/13c2c2/ffffff?text=李',
    content: '这个课程真的很棒！从零基础到现在能写简单程序了，感谢老师！',
    time: '5小时前',
    likes: 15,
    liked: true,
    replies: []
  }
])
const newNote = ref('')
const notes = ref<any[]>([])

// 消息提示
const showToast = ref(false)
const toastMessage = ref('')

// 计算属性
const sortedChapters = computed(() => {
  const chapters = [...groupedSections.value]
  if (sortOrder.value === 'desc') {
    return chapters.reverse()
  }
  return chapters
})

const hasPrevious = computed(() => {
  // 检查是否有上一节课
  return currentLessonId.value > 1
})

const hasNext = computed(() => {
  // 检查是否有下一节课
  return currentLessonId.value < totalLessons.value
})

const isCurrentLessonCompleted = computed(() => {
  const currentLesson = courseSections.value.find(s => s.id === currentLessonId.value)
  return currentLesson?.completed || false
})

// 监听路由变化
watch(() => route.query, (newQuery) => {
  if (newQuery.videoUrl) {
    currentVideoUrl.value = decodeURIComponent(newQuery.videoUrl as string)
  }
  if (newQuery.sectionName) {
    currentVideoTitle.value = decodeURIComponent(newQuery.sectionName as string)
  }
  if (newQuery.sectionId) {
    currentLessonId.value = Number(newQuery.sectionId)
  }
})

// 方法
const loadCourseData = async () => {
  try {
    const [courseResponse, sectionsResponse] = await Promise.all([
      CourseApi.getCourseById(courseId.value),
      CourseApi.getCourseSections(courseId.value)
    ])

    course.value = courseResponse.data
    courseSections.value = sectionsResponse.data.list
    totalLessons.value = courseSections.value.length

    generateChapterGroups()
    calculateProgress()
  } catch (error) {
    console.error('加载课程数据失败:', error)
    showToastMessage('加载课程数据失败')

    // 设置默认数据
    setDefaultCourseInfo()
    generateChapterGroups()
    calculateProgress()
  }
}

const generateChapterGroups = () => {
  const groups: ChapterGroup[] = []
  const parentSections = courseSections.value.filter(section => section.level === 0)

  if (parentSections.length === 0) {
    // 如果没有数据，创建默认的章节结构
    groups.push({
      title: '课前准备',
      lessons: [
        {
          id: 1,
          lessonId: courseId.value,
          outline: currentVideoUrl.value,
          name: currentVideoTitle.value || '开课彩蛋：新开始新征程',
          parentId: 1,
          sort: 0,
          level: 1,
          revision: 0,
          createdAt: Date.now(),
          updatedAt: null,
          deletedAt: null,
          completed: false
        }
      ],
      expanded: true
    })
  } else {
    parentSections.forEach((parentSection, index) => {
      const childSections = courseSections.value.filter(section =>
        section.level === 1 && section.parentId === parentSection.id
      )

      groups.push({
        title: parentSection.name,
        lessons: childSections,
        expanded: index === 0
      })
    })
  }

  groupedSections.value = groups
}

const calculateProgress = () => {
  const completed = courseSections.value.filter(s => s.completed).length
  completedLessons.value = completed
  progress.value = totalLessons.value > 0 ? Math.round((completed / totalLessons.value) * 100) : 0
}

const goToCourseDetail = () => {
  router.push(`/course/${courseId.value}`)
}

// 设置默认课程信息
const setDefaultCourseInfo = () => {
  if (!course.value) {
    course.value = {
      id: courseId.value,
      title: 'C语言程序设计',
      description: '<p>本课程将带你从零开始学习C语言程序设计，掌握编程基础知识。</p>',
      content: '详细的C语言课程内容',
      category: {
        id: 3,
        name: '信息技术',
        slug: 'it',
        description: '信息技术相关课程'
      },
      instructor: {
        id: 4,
        name: '教师',
        title: 'C语言专家',
        bio: '资深C语言开发工程师',
        avatar: '',
        rating: 4.5,
        studentsCount: 1000,
        coursesCount: 3,
        experience: '10年C语言教学经验',
        education: ['计算机科学博士'],
        certifications: ['C语言认证']
      },
      thumbnail: '',
      coverImage: '',
      duration: '60小时',
      level: 'beginner',
      price: 0,
      originalPrice: 0,
      currency: 'CNY',
      rating: 4.5,
      ratingCount: 100,
      studentsCount: 1000,
      totalLessons: 20,
      language: 'zh-CN',
      skills: ['C语言', '程序设计', '算法'],
      requirements: ['计算机基础'],
      objectives: ['掌握C语言语法', '学会程序设计', '理解算法思维'],
      tags: ['编程', 'C语言'],
      status: 'published',
      createdAt: '2024-01-01',
      updatedAt: '2024-01-01',
      publishedAt: '2024-01-01'
    }
  }
}

// 视频播放控制
const onVideoPlay = () => {
  isPlaying.value = true
}

const onVideoPause = () => {
  isPlaying.value = false
}

const onVideoEnded = () => {
  isPlaying.value = false
  markAsCompleted()
  if (hasNext.value) {
    nextVideo()
  }
}

const onVideoTimeUpdate = (_time: number) => {
  // 记录学习时长
  totalStudyTime.value += 1
}

const onVideoError = (error: Event) => {
  console.error('视频播放错误:', error)
  console.error('当前视频URL:', currentVideoUrl.value)
  showToastMessage('视频播放失败，请检查网络连接或视频格式')
}

const togglePlay = () => {
  if (isPlaying.value) {
    // 暂停逻辑
  } else {
    // 播放逻辑
  }
}

const previousVideo = () => {
  if (hasPrevious.value) {
    const currentIndex = courseSections.value.findIndex(s => s.id === currentLessonId.value)
    if (currentIndex > 0) {
      selectLesson(courseSections.value[currentIndex - 1])
    }
  }
}

const nextVideo = () => {
  if (hasNext.value) {
    const currentIndex = courseSections.value.findIndex(s => s.id === currentLessonId.value)
    if (currentIndex < courseSections.value.length - 1) {
      selectLesson(courseSections.value[currentIndex + 1])
    }
  }
}

const selectLesson = (lesson: CourseSection) => {
  currentLessonId.value = lesson.id
  currentVideoTitle.value = lesson.name

  if (lesson.outline && lesson.outline.includes('.m3u8')) {
    currentVideoUrl.value = lesson.outline

    // 更新URL
    router.replace({
      name: 'CourseStudy',
      params: { id: courseId.value },
      query: {
        videoUrl: encodeURIComponent(lesson.outline),
        sectionName: encodeURIComponent(lesson.name),
        sectionId: lesson.id
      }
    })
  }
}

const markAsCompleted = () => {
  const currentLesson = courseSections.value.find(s => s.id === currentLessonId.value)
  if (currentLesson && !currentLesson.completed) {
    currentLesson.completed = true
    calculateProgress()
    showToastMessage('已标记为完成')
  }
}

// 章节控制
const toggleChapter = (chapterIndex: number) => {
  groupedSections.value[chapterIndex].expanded = !groupedSections.value[chapterIndex].expanded
}

const toggleSortOrder = () => {
  sortOrder.value = sortOrder.value === 'asc' ? 'desc' : 'asc'
}

// 课时类型判断
const getLessonTypeClass = (lesson: CourseSection): string => {
  if (lesson.outline?.includes('.m3u8')) return 'lesson-type-video'
  if (lesson.outline?.includes('ppt')) return 'lesson-type-document'
  if (lesson.name.includes('作业')) return 'lesson-type-homework'
  if (lesson.name.includes('考试')) return 'lesson-type-exam'
  return 'lesson-type-video'
}

const getLessonTypeText = (lesson: CourseSection): string => {
  if (lesson.outline?.includes('ppt')) return '资料'
  if (lesson.name.includes('作业')) return '作业'
  if (lesson.name.includes('考试')) return '考试'
  return '视频'
}

// 评论和笔记
const submitComment = () => {
  if (newComment.value.trim()) {
    comments.value.push({
      id: Date.now(),
      author: '当前用户',
      avatar: 'https://via.placeholder.com/40x40/1890ff/ffffff?text=我',
      content: newComment.value,
      time: formatCommentTime(new Date()),
      likes: 0,
      liked: false,
      replies: []
    })
    newComment.value = ''
    showToastMessage('评论发表成功')
  }
}

const likeComment = (commentId: number) => {
  const comment = comments.value.find(c => c.id === commentId)
  if (comment) {
    if (comment.liked) {
      comment.likes = (comment.likes || 0) - 1
      comment.liked = false
    } else {
      comment.likes = (comment.likes || 0) + 1
      comment.liked = true
    }
  }
}

const replyToComment = (commentId: number) => {
  // 这里可以实现回复功能，比如显示回复输入框
  console.log('回复评论:', commentId)
  showToastMessage('回复功能开发中...')
}

const likeReply = (commentId: number, replyId: number) => {
  const comment = comments.value.find(c => c.id === commentId)
  if (comment && comment.replies) {
    const reply = comment.replies.find((r: any) => r.id === replyId)
    if (reply) {
      if (reply.liked) {
        reply.likes = (reply.likes || 0) - 1
        reply.liked = false
      } else {
        reply.likes = (reply.likes || 0) + 1
        reply.liked = true
      }
    }
  }
}

const replyToReply = (commentId: number, replyId: number, replyToAuthor: string) => {
  console.log('回复回复:', commentId, replyId, replyToAuthor)
  showToastMessage('回复功能开发中...')
}

const formatCommentTime = (date: Date): string => {
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  const minutes = Math.floor(diff / (1000 * 60))
  const hours = Math.floor(diff / (1000 * 60 * 60))
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))

  if (minutes < 1) return '刚刚'
  if (minutes < 60) return `${minutes}分钟前`
  if (hours < 24) return `${hours}小时前`
  if (days < 7) return `${days}天前`

  return date.toLocaleDateString()
}

const saveNote = () => {
  if (newNote.value.trim()) {
    notes.value.push({
      id: Date.now(),
      content: newNote.value,
      time: new Date().toLocaleString()
    })
    newNote.value = ''
    showToastMessage('笔记保存成功')
  }
}

const deleteNote = (noteId: number) => {
  const index = notes.value.findIndex(note => note.id === noteId)
  if (index > -1) {
    notes.value.splice(index, 1)
    showToastMessage('笔记删除成功')
  }
}

const takeNotes = () => {
  activeTab.value = 'notes'
}

// 工具方法
const formatDuration = (seconds: number): string => {
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = Math.floor(seconds % 60)

  if (hours > 0) {
    return `${hours}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  }
  return `${minutes}:${secs.toString().padStart(2, '0')}`
}

const formatDescription = (description: string | undefined): string => {
  if (!description) {
    return '<p>暂无课程描述</p>'
  }

  // 如果已经包含HTML标签，直接返回
  if (description.includes('<') && description.includes('>')) {
    return description
  }

  // 如果是纯文本，包装在p标签中
  return `<p>${description}</p>`
}

const showToastMessage = (message: string) => {
  toastMessage.value = message
  showToast.value = true
  setTimeout(() => {
    showToast.value = false
  }, 3000)
}

// 生命周期
onMounted(() => {
  loadCourseData()

  // 如果没有视频URL，设置默认标题
  if (!currentVideoTitle.value) {
    currentVideoTitle.value = '请选择要学习的课程'
  }
})
</script>

<style scoped>
.course-study-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20px;
}

.study-container {
  max-width: 1400px;
  margin: 0 auto;
  display: flex;
  gap: 30px;
}

.main-content {
  flex: 1;
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 面包屑导航 */
.breadcrumb-section {
  padding: 16px 24px;
  background: white;
  border-bottom: 1px solid #f0f0f0;
  font-size: 14px;
}

.breadcrumb-item {
  color: #666;
  cursor: pointer;
  transition: color 0.3s;
}

.breadcrumb-item:hover:not(.current) {
  color: #1890ff;
}

.breadcrumb-item.current {
  color: #333;
  font-weight: 500;
}

.breadcrumb-separator {
  margin: 0 8px;
  color: #ccc;
}

/* 视频播放器区域 */
.video-player-section {
  background: #000;
  min-height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.video-container {
  width: 100%;
  height: 100%;
}

.video-placeholder {
  width: 100%;
  height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #1a1a1a;
}

.placeholder-content {
  text-align: center;
  color: #999;
}

.placeholder-content p {
  margin-top: 16px;
  font-size: 16px;
}

/* 视频信息区域 */
.video-info-section {
  padding: 24px;
}

.video-header {
  margin-bottom: 16px;
}

.video-title {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin: 0 0 12px 0;
}

.video-meta {
  display: flex;
  align-items: center;
  gap: 16px;
  font-size: 14px;
  color: #666;
}

.category-tag {
  background: #e6f7ff;
  color: #1890ff;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.btn-notes {
  background: #f0f0f0;
  border: none;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  transition: background-color 0.3s;
}

.btn-notes:hover {
  background: #e0e0e0;
}

.video-description {
  margin: 16px 0;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;
  color: #666;
  line-height: 1.6;
}

/* 视频控制区域 */
.video-controls-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0;
  border-top: 1px solid #f0f0f0;
}

.controls-left,
.controls-right {
  display: flex;
  align-items: center;
  gap: 12px;
}

.control-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  border: 1px solid #d9d9d9;
  background: white;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.control-btn:hover:not(:disabled) {
  border-color: #1890ff;
  color: #1890ff;
}

.control-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.control-btn.primary {
  background: #1890ff;
  color: white;
  border-color: #1890ff;
}

.control-btn.primary:hover {
  background: #40a9ff;
  border-color: #40a9ff;
}

.completed-badge {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #52c41a;
  font-size: 14px;
  font-weight: 500;
}

/* 标签页 */
.course-tabs {
  border-top: 1px solid #f0f0f0;
}

.tab-nav {
  display: flex;
  background: #fafafa;
  border-bottom: 1px solid #f0f0f0;
}

.tab-btn {
  padding: 16px 24px;
  border: none;
  background: none;
  cursor: pointer;
  font-size: 14px;
  color: #666;
  transition: all 0.3s;
  border-bottom: 2px solid transparent;
}

.tab-btn:hover {
  color: #1890ff;
}

.tab-btn.active {
  color: #1890ff;
  border-bottom-color: #1890ff;
  background: white;
}

.tab-content {
  min-height: 300px;
}

.tab-pane {
  padding: 24px;
}

/* 标签页内容样式 */
.intro-content h4 {
  color: #333;
  margin: 0 0 12px 0;
  font-size: 16px;
}

.intro-content p {
  color: #666;
  line-height: 1.6;
  margin: 0 0 20px 0;
}

.intro-content ul {
  color: #666;
  line-height: 1.6;
  padding-left: 20px;
}

.intro-content li {
  margin-bottom: 8px;
}

.course-description {
  color: #666;
  line-height: 1.6;
  margin: 0 0 20px 0;
}

.course-description p {
  margin: 0 0 12px 0;
}

.course-description:last-child {
  margin-bottom: 0;
}

/* 评论样式 */
.comments-content {
  padding: 0;
}

.comments-stats {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  border-bottom: 1px solid #f0f0f0;
  background: #fafafa;
}

.comments-count {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.comments-sort {
  display: flex;
  gap: 8px;
}

.comments-sort .sort-btn {
  background: none;
  border: none;
  color: #666;
  cursor: pointer;
  font-size: 14px;
  padding: 6px 12px;
  border-radius: 4px;
  transition: all 0.3s;
}

.comments-sort .sort-btn:hover {
  background: #f0f0f0;
  color: #333;
}

.comments-sort .sort-btn.active {
  background: #1890ff;
  color: white;
}

/* 评论输入区域 */
.comment-input-section {
  padding: 20px 24px;
  border-bottom: 1px solid #f0f0f0;
}

.comment-input-wrapper {
  display: flex;
  gap: 12px;
}

.user-avatar img {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

.comment-input-area {
  flex: 1;
}

.comment-textarea {
  width: 100%;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  padding: 12px;
  font-size: 14px;
  resize: vertical;
  margin-bottom: 12px;
  font-family: inherit;
}

.comment-textarea:focus {
  outline: none;
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.comment-actions {
  display: flex;
  justify-content: flex-end;
}

.btn-submit {
  background: #1890ff;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.btn-submit:hover:not(:disabled) {
  background: #40a9ff;
}

.btn-submit:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  background: #f5f5f5;
  color: #bfbfbf;
}

/* 评论列表 */
.comments-list {
  padding: 0 24px;
}

.no-comments {
  text-align: center;
  color: #999;
  padding: 60px 0;
}

.no-comments-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.no-comments p {
  margin: 0;
  font-size: 16px;
}

.comment-item {
  display: flex;
  gap: 12px;
  padding: 20px 0;
  border-bottom: 1px solid #f0f0f0;
}

.comment-item:last-child {
  border-bottom: none;
}

.comment-avatar img {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

.comment-main {
  flex: 1;
  min-width: 0;
}

.comment-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 8px;
}

.comment-author {
  font-weight: 500;
  color: #333;
  font-size: 14px;
}

.comment-time {
  font-size: 12px;
  color: #999;
}

.comment-content {
  color: #333;
  line-height: 1.6;
  font-size: 14px;
  margin-bottom: 12px;
  word-wrap: break-word;
}

.comment-footer {
  display: flex;
  align-items: center;
  gap: 16px;
}

.comment-action {
  display: flex;
  align-items: center;
  gap: 4px;
  background: none;
  border: none;
  color: #666;
  cursor: pointer;
  font-size: 12px;
  padding: 4px 8px;
  border-radius: 4px;
  transition: all 0.3s;
}

.comment-action:hover {
  background: #f5f5f5;
  color: #333;
}

.comment-action.liked {
  color: #ff4d4f;
}

.comment-action svg.liked {
  color: #ff4d4f;
}

/* 回复样式 */
.replies-list {
  margin-top: 16px;
  padding-left: 20px;
  border-left: 2px solid #f0f0f0;
}

.reply-item {
  display: flex;
  gap: 8px;
  padding: 12px 0;
  border-bottom: 1px solid #f8f8f8;
}

.reply-item:last-child {
  border-bottom: none;
}

.reply-avatar img {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  object-fit: cover;
}

.reply-main {
  flex: 1;
  min-width: 0;
}

.reply-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
}

.reply-author {
  font-weight: 500;
  color: #333;
  font-size: 13px;
}

.reply-time {
  font-size: 11px;
  color: #999;
}

.reply-content {
  color: #333;
  line-height: 1.5;
  font-size: 13px;
  margin-bottom: 8px;
  word-wrap: break-word;
}

.reply-to {
  color: #1890ff;
  font-weight: 500;
  margin-right: 4px;
}

.reply-footer {
  display: flex;
  align-items: center;
  gap: 12px;
}

.reply-footer .comment-action {
  font-size: 11px;
  padding: 2px 6px;
}

/* 笔记样式 */
.notes-input {
  margin-bottom: 24px;
}

.notes-input textarea {
  width: 100%;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  padding: 12px;
  font-size: 14px;
  resize: vertical;
  margin-bottom: 12px;
  font-family: inherit;
}

.notes-input textarea:focus {
  outline: none;
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.no-notes {
  text-align: center;
  color: #999;
  padding: 40px 0;
}

.note-item {
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;
}

.note-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.note-time {
  font-size: 12px;
  color: #999;
}

.btn-delete {
  background: none;
  border: none;
  color: #ff4d4f;
  cursor: pointer;
  font-size: 12px;
  padding: 4px 8px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.btn-delete:hover {
  background: #fff1f0;
}

.note-content {
  color: #666;
  line-height: 1.6;
}

/* 右侧边栏 */
.sidebar {
  width: 350px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

/* 学习进度 */
.progress-section {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.progress-section h3 {
  margin: 0 0 20px 0;
  font-size: 16px;
  color: #333;
}

.progress-chart {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.progress-circle {
  position: relative;
  width: 100px;
  height: 100px;
}

.progress-text {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
}

.percentage {
  display: block;
  font-size: 20px;
  font-weight: 600;
  color: #1890ff;
}

.label {
  display: block;
  font-size: 12px;
  color: #999;
}

.progress-details {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.progress-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.progress-item .label {
  color: #666;
  font-size: 14px;
}

.progress-item .value {
  color: #333;
  font-weight: 500;
  font-size: 14px;
}

/* 课程章节 */
.course-sections {
  background: white;
  border-radius: 8px;
  padding: 0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  flex: 1;
}

.sections-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background: #fafafa;
  border-bottom: 1px solid #f0f0f0;
}

.sections-header h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.sort-btn {
  background: none;
  border: none;
  color: #666;
  cursor: pointer;
  font-size: 12px;
  padding: 4px 8px;
  border-radius: 4px;
  transition: all 0.3s;
}

.sort-btn:hover {
  background: #f0f0f0;
  color: #333;
}

.sections-list {
  max-height: 600px;
  overflow-y: auto;
}

.no-chapters {
  padding: 40px 20px;
  text-align: center;
  color: #999;
}

.no-chapters p {
  margin: 0;
  font-size: 14px;
}

.chapter-section {
  border-bottom: 1px solid #f0f0f0;
}

.chapter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.chapter-header:hover {
  background: #fafafa;
}

.chapter-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.chapter-number {
  font-size: 14px;
  font-weight: 600;
  color: #333;
  min-width: 60px;
}

.chapter-title {
  font-size: 14px;
  color: #333;
}

.chapter-toggle {
  color: #999;
  transition: transform 0.3s;
}

.chapter-toggle.expanded {
  transform: rotate(90deg);
}

.chapter-lessons {
  background: white;
}

.lesson-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px 12px 40px;
  border-bottom: 1px solid #f8f8f8;
  cursor: pointer;
  transition: all 0.3s;
}

.lesson-item:hover {
  background: #f9f9f9;
}

.lesson-item.active {
  background: #e6f7ff;
  border-left: 3px solid #1890ff;
}

.lesson-item.completed {
  background: #f6ffed;
}

.lesson-info {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
}

.lesson-type {
  font-size: 11px;
  padding: 3px 6px;
  border-radius: 3px;
  font-weight: 500;
  min-width: 32px;
  text-align: center;
}

.lesson-type-video {
  background: #e6f7ff;
  color: #1890ff;
  border: 1px solid #b3d8ff;
}

.lesson-type-document {
  background: #fff7e6;
  color: #fa8c16;
  border: 1px solid #ffd591;
}

.lesson-type-homework {
  background: #f6ffed;
  color: #52c41a;
  border: 1px solid #b7eb8f;
}

.lesson-type-exam {
  background: #fff1f0;
  color: #ff4d4f;
  border: 1px solid #ffb3b3;
}

.lesson-title {
  font-size: 13px;
  color: #333;
  flex: 1;
}

.lesson-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.lesson-duration {
  font-size: 12px;
  color: #999;
  font-family: monospace;
  min-width: 50px;
  text-align: right;
}

.lesson-status {
  display: flex;
  align-items: center;
}

/* 消息提示 */
.toast-message {
  position: fixed;
  top: 20px;
  right: 20px;
  background: #52c41a;
  color: white;
  padding: 12px 20px;
  border-radius: 6px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  z-index: 1000;
  animation: slideIn 0.3s ease;
}

@keyframes slideIn {
  from {
    transform: translateX(100%);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .study-container {
    flex-direction: column;
  }

  .sidebar {
    width: 100%;
    flex-direction: row;
  }

  .progress-section {
    flex: 1;
  }

  .course-sections {
    flex: 2;
  }
}

@media (max-width: 768px) {
  .course-study-page {
    padding: 10px;
  }

  .study-container {
    gap: 15px;
  }

  .sidebar {
    flex-direction: column;
  }

  .video-controls-section {
    flex-direction: column;
    gap: 12px;
  }

  .controls-left,
  .controls-right {
    width: 100%;
    justify-content: center;
  }
}
</style>
