<template>
  <div class="learning-page">
    <!-- 倒计时区域 -->
    <div class="countdown-timer">
      <h3>⏳ 观看倒计时</h3>
      <div class="time-display" :class="{ finished: remainingTime <= 0 }">
        {{ formattedTime }}
      </div>
    </div>

    <!-- 视频播放区域 -->
    <div v-if="currentVideo.src" class="video-wrapper">
      <h3>🎥 视频播放</h3>
      <video
        ref="videoRef"
        :src="currentVideo.src"
        controls
        playsinline
        webkit-playsinline
        x5-playsinline
        x5-video-player-type="h5"
      x5-video-player-fullscreen="true"
      preload="metadata"
      @loadeddata="onVideoLoaded"
      @error="onVideoError"
      style="width: 100%; height: auto; aspect-ratio: 16/9; background: #000;"
      >
      您的设备不支持视频播放。
      </video>

      <!-- 多视频控制 -->
      <div v-if="videoList.length > 1" class="video-controls">
        <van-button size="small" @click="prevVideo" :disabled="currentVideoIndex === 0">
          上一个
        </van-button>
        <span class="video-index">{{ currentVideoIndex + 1 }} / {{ videoList.length }}</span>
        <van-button size="small" @click="nextVideo" :disabled="currentVideoIndex === videoList.length - 1">
          下一个
        </van-button>
      </div>
    </div>

    <!-- 文档提示（H5 不支持内嵌预览，改为下载） -->
    <div v-if="previewList.length > 0" class="doc-tip">
      <van-notice-bar
        left-icon="volume-o"
        text="当前有文档资料，请点击下方按钮下载查看"
        color="#1989fa"
        background="#ecf9ff"
      />
      <div class="doc-list">
        <van-button
          v-for="item in previewList"
          :key="item.id"
          type="primary"
          plain
          block
          style="margin-top: 8px"
          @click="downloadFile(item)"
        >
          📄 下载 {{ item.fileName }}
        </van-button>
      </div>
    </div>

    <!-- 加载中 -->
    <van-loading v-if="loading" size="24px" vertical>加载中...</van-loading>

    <!-- 完成学习按钮 -->
    <div v-if="remainingTime <= 0" class="completion-actions">
      <van-button type="primary" block @click="goBackAndMarkComplete">
        ✅ 完成学习
      </van-button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, nextTick, getCurrentInstance } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { showToast } from 'vant'
import { Base64 } from 'js-base64'

const route = useRoute()
const router = useRouter()
const { proxy } = getCurrentInstance()

// ========== 响应式数据 ==========
const loading = ref(false)
const videoList = ref([])
const previewList = ref([])
const currentVideoIndex = ref(0)
const watchTime = ref(0) // 单位：秒
const remainingTime = ref(0)
const timer = ref(null)
const onVideoLoaded = () => {
  loading.value = false // 视频元数据加载完成，可隐藏全局 loading
}

const onVideoError = () => {
  loading.value = false
  showToast('视频加载失败，请检查网络')
}
// 视频引用
const videoRef = ref(null)

// ========== 计算属性 ==========
const currentVideo = computed(() => {
  return videoList.value[currentVideoIndex.value] || {}
})

const formattedTime = computed(() => {
  const mins = Math.floor(remainingTime.value / 60).toString().padStart(2, '0')
  const secs = (remainingTime.value % 60).toString().padStart(2, '0')
  return `${mins}:${secs}`
})

// ========== 倒计时逻辑 ==========
const startCountdown = () => {
  if (watchTime.value <= 0) return
  remainingTime.value = watchTime.value
  clearInterval(timer.value)
  timer.value = setInterval(() => {
    if (remainingTime.value > 0) {
      remainingTime.value--
    } else {
      clearInterval(timer.value)
      showToast('观看时间结束，学习已完成！')
    }
  }, 1000)
}

// ========== 视频控制 ==========
const prevVideo = () => {
  if (currentVideoIndex.value > 0) {
    currentVideoIndex.value--
    resetVideo()
  }
}

const nextVideo = () => {
  if (currentVideoIndex.value < videoList.value.length - 1) {
    currentVideoIndex.value++
    resetVideo()
  }
}

const resetVideo = () => {
  if (videoRef.value) {
    videoRef.value.load()
    videoRef.value.play().catch(() => {})
  }
}

const onVideoEnded = () => {
  // 可选：自动播放下一个
}

// ========== 文件处理 ==========
const downloadFile = (file) => {
  const link = document.createElement('a')
  link.href = file.downloadUrl
  link.download = file.fileName
  link.target = '_blank'
  link.click()
}

const createPreview = (file) => {
  const { id, fileName, fileType } = file
  const type = fileType?.toLowerCase()
  const bucket = import.meta.env.VITE_BUCKET
  const originUrl = `${import.meta.env.VITE_BASE_API}/framework/Common/downloadFileS3?bucket=${bucket}&id=${id}`
  const downloadUrl = `${originUrl}&fullfilename=${encodeURIComponent(fileName)}`

  if (type === 'mp4') {
    videoList.value.push({
      id,
      fileName,
      src: downloadUrl
    })
  } else if (['pdf', 'doc', 'docx'].includes(type)) {
    previewList.value.push({
      id,
      fileName,
      downloadUrl
    })
  }
}

// ========== 数据加载（保留 proxy.$axios）==========
const getFile = async (fileId) => {
  loading.value = true
  previewList.value = []
  videoList.value = []

  try {
    const response = await proxy.$axios.get('framework/Common/queryFileWithValues', {
      fId: fileId
    })

    if (response.data.code === 0) {
      const data = response.data.data
      if (!data || !Array.isArray(data) || data.length === 0) {
        showToast('暂无文件数据，请联系管理员')
        return
      }

      data.forEach(file => createPreview(file))

      await nextTick()
      if (videoList.value.length > 0) {
        resetVideo()
      }
    } else {
      showToast('获取文件失败：' + response.data.msg)
    }
  } catch (error) {
    console.error('文件加载异常:', error)
    showToast('网络错误，请重试')
  } finally {
    loading.value = false
  }
}

// ========== 页面初始化 ==========
onMounted(async () => {
  try {
    const rowData = JSON.parse(route.query.data)
    const fileId = rowData.fileId
    const timeInMinutes = Number(rowData.watchTime)
    console.log(timeInMinutes);
    if (!fileId || isNaN(timeInMinutes) || timeInMinutes <= 0) {
      showToast('参数无效')
      return
    }

    watchTime.value = Math.floor(timeInMinutes * 60)
    startCountdown()

    await getFile(fileId)
  } catch (error) {
    console.error('路由参数解析失败:', error)
    showToast('页面参数错误')
  }
})

// ========== 完成学习 ==========
const goBackAndMarkComplete = async () => {
  try {
    const rowData = JSON.parse(route.query.data)
    const taskId = rowData.id

    const res = await proxy.$axios.post('/sgsafe/Class/saveStatus', {
      json: taskId
    })

    if (res.data.code === 0) {
      showToast('学习记录已保存')
    } else {
      showToast(res.data.msg || '保存成功')
    }
  } catch (error) {
    console.error('保存失败:', error)
    showToast('保存学习状态失败')
  }

  router.back()
}

// ========== 清理定时器 ==========
onUnmounted(() => {
  if (timer.value) clearInterval(timer.value)
})
</script>

<style scoped>
.learning-page {
  padding: 16px;
  max-width: 100%;
  box-sizing: border-box;
}

.countdown-timer {
  text-align: center;
  margin-bottom: 20px;
}

.time-display {
  font-size: 28px;
  font-weight: bold;
  color: #333;
}

.time-display.finished {
  color: #ee0a24;
}

.video-wrapper {
  margin-bottom: 20px;
}

.video-controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 12px;
}

.video-index {
  font-size: 14px;
  color: #666;
}

.doc-tip {
  margin-top: 20px;
}

.doc-list {
  margin-top: 12px;
}

.completion-actions {
  margin-top: 30px;
}
</style>