<template>
  <el-dialog
    v-model="visible"
    :title="title"
    :width="'60%'"
    :before-close="handleClose"
    center
  >
    <el-scrollbar style="max-height: 80vh">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="课程名称">{{ courseInfo.courseName }}</el-descriptions-item>
        <el-descriptions-item label="课程作者">{{ courseInfo.courseAuthor }}</el-descriptions-item>
        <el-descriptions-item label="课程老师">{{ courseInfo.courseTeacher }}</el-descriptions-item>
        <el-descriptions-item label="课程大小">{{ courseInfo.courseSize }} MB</el-descriptions-item>
        <el-descriptions-item label="课程时长">{{ courseInfo.courseTime }} 秒</el-descriptions-item>
        <el-descriptions-item label="课程类型">{{ courseInfo.courseType }}</el-descriptions-item>
        <el-descriptions-item label="课程状态">
          <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="courseInfo.courseStatus" />
        </el-descriptions-item>
        <el-descriptions-item label="是否检查">
          <dict-tag :type="DICT_TYPE.INFRA_BOOLEAN_STRING" :value="courseInfo.courseIsInspect" />
        </el-descriptions-item>
      </el-descriptions>

      <div class="video-container" style="margin-top: 20px">
        <video v-if="courseInfo.courseContentType === 'video'"
          ref="videoRef"
          :src="courseInfo.courseVideoPath"
          controls
          width="100%"
          height="450px"
          preload="metadata"
          @timeupdate="handleTimeUpdate"
        >
          您的浏览器不支持 HTML5 视频。
        </video>
      </div>
    </el-scrollbar>
  </el-dialog>


  <el-dialog
    v-model="showExamMask"
    title="提问"
    :width="'60%'"
    center
    class="exam-popup"
  >
    <div v-if="currentQuestion" class="question-item">
      <p class="question-text" v-html="currentQuestion.ccQuestContent"></p>
      <div v-for="option in currentQuestion.courseQuestOptionList" :key="option"
           class="option-item" 
           :class="{ 'selected': currentQuestion.selected === option.cqoValue }"
           @click="handleOptionSelect(option.cqoValue)"
           v-html="option.cqoOption">
      </div>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, defineProps } from 'vue'
import { DICT_TYPE } from '@/utils/dict'
import { CourseConfigApi } from '@/api/bjdx/courseconfig'
// 导入HLS库
import Hls from 'hls.js'

const props = defineProps({})
const visible = ref(false)
const courseInfo = ref({})
const title = ref('课程预览')


// 视频引用
const videoRef = ref<HTMLVideoElement | null>(null)// HLS控制器实例
let HLS_Controller = null
// 试题数据（示例，可根据实际接口调整）
const examQuestions = ref<any[]>([
  { id: 1, content: '问题1：这是测试题吗？', options: ['是', '否'], ccTime: 3 },
  { id: 2, content: '问题2：正确答案是？', options: ['A', 'B', 'C'], ccTime: 6 }
])
// 当前显示的试题
const currentQuestion = ref<any>(null);
// 遮挡层可见性
const showExamMask = ref(false)
// 当前待触发的试题索引
const currentQuestionIndex = ref(0) // 初始为0

// 打开弹窗方法
const open = async (row) => {
  visible.value = true
  courseInfo.value = row

  // 调用 API 并等待结果
  examQuestions.value = await CourseConfigApi.getCourseConfigQuestion(row.id)

  // 销毁之前的HLS实例（如果存在）
  if (HLS_Controller) {
    HLS_Controller.destroy()
    HLS_Controller = null
  }

  // 获取视频元素
  const videoElement = videoRef.value
  if (!videoElement) return

  // 视频地址从courseInfo获取（假设courseVideoPath是m3u8地址）
  const videoUrl = courseInfo.value.courseVideoPath

  // 处理HLS视频播放
  if (videoUrl && videoUrl.endsWith('.m3u8')) {
    if (Hls.isSupported()) {
      HLS_Controller = new Hls();
      HLS_Controller.loadSource(videoUrl)
      HLS_Controller.attachMedia(videoElement)
      HLS_Controller.on(Hls.Events.MANIFEST_PARSED, () => {
        videoElement.play().catch(err => console.error('视频播放失败:', err))
      })
    } else if (videoElement.canPlayType('application/vnd.apple.mpegurl')) {
      // Safari浏览器原生支持HLS
      videoElement.src = videoUrl
      videoElement.addEventListener('loadedmetadata', () => {
        videoElement.play().catch(err => console.error('视频播放失败:', err))
      })
    }
  } else {
    // 非m3u8格式视频直接播放
    videoElement.src = videoUrl
    videoElement.play().catch(err => console.error('视频播放失败:', err))
  }
}

// 关闭弹窗时销毁HLS实例
onUnmounted(() => {
  if (HLS_Controller) {
    HLS_Controller.destroy()
  }
})

// 关闭弹窗方法
const handleClose = () => {
  visible.value = false// 暂停视频播放并清理资源

  const videoElement = videoRef.value
  if (videoElement) {
    videoElement.pause()          // 暂停视频播放
    videoElement.src = ''         // 清除视频源，释放资源
    videoElement.load()           // 触发资源卸载
  }

  // 销毁HLS实例（如果存在）
  if (HLS_Controller) {
    HLS_Controller.destroy()
    HLS_Controller = null
  }

  // 重置试题相关状态
  currentQuestionIndex.value = 0
  currentQuestion.value = null
  showExamMask.value = false
}


// 时间更新监听
const handleTimeUpdate = () => {
  if (currentQuestionIndex.value >= examQuestions.value.length) return

  let currentTime = videoRef.value?.currentTime || 0
  currentTime = Math.floor(currentTime);

  console.log("--------------",examQuestions.value)

  // 遍历剩余未触发的试题（从当前索引开始）
  examQuestions.value.forEach(question => {
    if (currentTime == question.ccTime && !showExamMask.value) {
      videoRef.value?.pause()
      currentQuestion.value = question
      currentQuestion.value.selected = null
      showExamMask.value = true
      currentQuestionIndex.value += 1
      return // 找到第一个触发的试题后退出循环
    }
  })

}

// 选项点击处理
const handleOptionSelect = (option) => {
  currentQuestion.value.selected = option;
  showExamMask.value = false;
  currentQuestion.value = null;
  videoRef.value?.play();
}

// 暴露方法给父组件
defineExpose({ open })
</script>

<style scoped>
.video-container {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 10px;
}

video {
  background: #000;
}

.exam-popup {
  --el-dialog-bg-color: var(--el-bg-color-overlay);
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0,0,0,0.08);
}
.exam-popup .el-dialog__body {
  padding: 24px;
}
.question-item .el-radio {
  padding: 4px 8px;
  border-radius: 4px;
  transition: all 0.3s;
}
.question-item .el-radio:hover {
  background: var(--el-fill-color-light);
}
.question-item {
  font-size: 14px;
  width: 60%;
  margin: 0 auto;
  padding: 50px 0px;
}
.question-item p {
  font-weight: 500;
  font-size: 28px;
  margin-bottom: 28px;
}
.option-item {
  padding: 12px;
  margin-bottom: 8px;
  border: 1px solid #dcdfe6;
  border-radius: 5px;
  cursor: pointer;
  transition: all 0.5s;
  text-indent: 2em;
  font-size: 18px;
  font-weight: 400;
}
.option-item:hover {
  background-color: #f5f7fa;
  border-color: #409eff;
}
.option-item.selected {
  background-color: #ecf5ff;
  border-color: #409eff;
  color: #409eff;
}
</style>"}}}
