<template>
  <div class="h5-learning-page" style="padding: 12px; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;">

    <!-- 倒计时区域 -->
    <!-- 倒计时区域 -->
    <div class="countdown-card" style="background: #fff; border-radius: 8px; box-shadow: 0 1px 4px rgba(0,0,0,0.1); padding: 16px; margin-bottom: 16px;">
      <h3 v-if="!datiDisPlay" style="margin: 0 0 8px; color: #333; font-size: 16px;">
        ⏳ 观看倒计时
      </h3>
      <h3 v-else style="margin: 0 0 8px; color: #333; font-size: 16px;">
        📝 请进行答题
      </h3>

      <div
        class="time-display"
        :class="{ finished: remainingTime.value <= 0 }"
        style="font-size: 24px; font-weight: bold; color: #d00; margin: 8px 0;"
      >
        {{ formattedTime }}
      </div>

      <div v-show="datiDisPlay" style="margin-top: 12px;">
        <van-button plain type="primary" size="large" @click="handleSearch" block>
          开始答题
        </van-button>
      </div>
    </div>
    <!-- 文档预览区域 -->
    <div v-if="previewList.length > 0" class="office-preview-wrapper" style="margin-top: 16px;">
      <h3 style="color: #333; font-size: 16px; margin-bottom: 8px;">📄 文档预览（PDF / Word）</h3>
      <div v-for="item in previewList" :key="item.id" style="background: #fff; border-radius: 8px; overflow: hidden; box-shadow: 0 1px 4px rgba(0,0,0,0.1); margin-bottom: 12px;">
        <div style="padding: 12px; display: flex; align-items: center; border-bottom: 1px solid #f0f0f0;">
          <span style="display: inline-block; width: 32px; height: 32px; background: #1989fa; color: white; text-align: center; line-height: 32px; border-radius: 4px; font-size: 14px; margin-right: 8px;">
            {{ item.fileType.toUpperCase() }}
          </span>
          <h4 style="margin: 0; font-size: 14px; color: #333;">{{ item.fileName }}</h4>
        </div>
        <iframe :src="item.previewUrl" frameborder="0" style="width: 100%; height: 300px; border: none;"></iframe>
      </div>
    </div>

    <!-- 视频播放区域 -->
    <div v-if="videoList.length > 0" class="video-player-wrapper" style="margin-top: 16px;">
      <h3 style="color: #333; font-size: 16px; margin-bottom: 8px;">🎥 视频播放</h3>

      <!-- 播放器 -->
      <div v-if="isVideoPlayerVisible" style="width: 100%; background: #000;">
        <video
          ref="videoPlayer"
          class="video-js"
          controls
          preload="auto"
          style="width: 100%; height: 240px; background: #000;"
        >
          您的浏览器不支持视频播放。
        </video>
      </div>

      <!-- 视频切换控件 -->
      <div style="margin-top: 12px;">
        <div style="display: flex; width: 100%;">
          <button
            @click="prevVideo"
            :disabled="videoList.length <= 1"
            style="flex: 1; padding: 10px; border: 1px solid #ddd; background: #fff; color: #333; font-size: 14px; cursor: pointer; border-radius: 4px 0 0 4px;"
            :style="{ opacity: videoList.length <= 1 ? 0.5 : 1, cursor: videoList.length <= 1 ? 'not-allowed' : 'pointer' }"
          >
            上一个
          </button>
          <button
            @click="nextVideo"
            style="flex: 1; padding: 10px; border: 1px solid #ddd; border-left: none; background: #fff; color: #333; font-size: 14px; cursor: pointer; border-radius: 0 4px 4px 0;"
          >
            下一个
          </button>
        </div>

        <!-- 缩略图列表 -->
        <div style="margin-top: 12px; display: flex; gap: 8px; overflow-x: auto; padding: 4px 0;">
          <div
            v-for="(video, index) in videoList"
            :key="video.id"
            @click="jumpToVideo(index)"
            :style="[
              {
                padding: '8px 12px',
                background: '#f0f0f0',
                border: '1px solid #ddd',
                borderRadius: '6px',
                cursor: 'pointer',
                fontSize: '12px',
                whiteSpace: 'nowrap',
                minWidth: '80px'
              },
              index === currentVideoIndex ? { background: '#1989fa', color: 'white', borderColor: '#1989fa' } : {}
            ]"
          >
            {{ video.fileName }}
          </div>
        </div>
      </div>
    </div>

    <!-- 无内容提示 -->
    <div
      v-else-if="!loading && !previewList.length && !videoList.length && tableDataFile.length > 0"
      style="margin-top: 16px; text-align: center; color: #999; font-size: 14px; padding: 20px 0;"
    >
      当前没有 PDF、Word 或 MP4 文件可预览
    </div>

    <!-- 加载中 -->
    <van-loading v-if="loading" style="margin: 20px 0;" />
  </div>
</template>

<script setup>
import { useRoute, useRouter } from 'vue-router';
import { ref, reactive, onMounted, getCurrentInstance, watch, onUnmounted, computed, nextTick, onActivated } from 'vue'

// ✅ 正确方式：从 vant 直接导入组件（不要用 vant/es/xxx）
import { Dialog, showSuccessToast, showToast, Toast, Button, Card, Loading } from 'vant'

// ✅ 引入 Vant 组件样式（使用 lib 路径，稳定可靠）
import 'vant/lib/button/style'
import 'vant/lib/card/style'
import 'vant/lib/dialog/style'
import 'vant/lib/toast/style'
import 'vant/lib/loading/style'

// ✅ 修复 js-base64 的导入：不能用 default
import { Base64 } from 'js-base64'

// 视频播放器
import 'video.js/dist/video-js.css'
import videojs from 'video.js'

// 工具类
import tools from '@/tools'


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

// ========== 响应式数据 ==========
const tableDataFile = ref([])
const previewList = ref([])
const loading = ref(false)
const bucket = ref(import.meta.env.VITE_BUCKET)

// 注意力检测
const checkCount = ref(0)
const nextCheckTarget = ref(null)
const attentionCheckTimer = ref(null)
const isCheckingAttention = ref(false)
const lastCheckTime = ref(0)

// 视频相关
const videoPlayer = ref(null)
const videoList = ref([])
const currentVideoIndex = ref(0)
const isVideoPlayerVisible = ref(false)
const player = ref(null)

// 倒计时
const viewingDur = ref(0)
const remainingTime = ref(0)
const timer = ref(null)
const isCountdownActive = ref(false)
const datiDisPlay = ref(false)

// 其他
let assTypeId = ''
let id1 = ''
let headId = ''
const ruleData = ref([])
const fileIds = ref({ fileId: '' })
const questionData = ref([])

// ========== 计算属性 ==========
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 currentVideo = computed(() => {
  return videoList.value[currentVideoIndex.value] || {}
})

// ========== 方法 ==========
const startCountdown = () => {
  console.log('🔧 startCountdown 被调用')

  if (isCountdownActive.value) {
    console.log('⚠️ 倒计时已在运行，跳过')
    return
  }

  console.log('当前 ruleData:', ruleData.value)

  const rawDur = ruleData.value[0]?.viewingDur
  console.log('原始 viewingDur:', rawDur)

  const minutes = parseInt(rawDur)
  console.log('转换为分钟:', minutes)

  if (isNaN(minutes) || minutes <= 0) {
    console.warn('❌ 无效的观看时长，无法启动倒计时')
    showToast({
      type: 'fail',
      message: '观看时长无效，请检查配置'
    })
    return
  }

  viewingDur.value = minutes * 60
  remainingTime.value = minutes * 60
  isCountdownActive.value = true
  timer.value = setInterval(() => {
    remainingTime.value -= 1

    if (remainingTime.value <= 0) {
      console.log('🎉 倒计时结束！')
      clearInterval(timer.value)
      clearTimeout(attentionCheckTimer.value)
      timer.value = null
      attentionCheckTimer.value = null
      isCountdownActive.value = false
      handleCountdownEnd()
      return
    }

    checkAttentionPeriodically()
  }, 1000)
}

const checkAttentionPeriodically = () => {
  const totalSeconds = viewingDur.value
  const elapsed = totalSeconds - remainingTime.value

  if (totalSeconds <= 180) return
  if (checkCount.value >= 3) {
    nextCheckTarget.value = null
    return
  }

  if (nextCheckTarget.value === null || nextCheckTarget.value === undefined) {
    const minFirst = 120
    const maxFirst = Math.min(300, totalSeconds - 120)
    if (maxFirst < minFirst) return
    const randomDelay = Math.floor(Math.random() * (maxFirst - minFirst + 1)) + minFirst
    nextCheckTarget.value = randomDelay
  }

  if (elapsed < 60 || elapsed >= totalSeconds - 60) return

  if (elapsed >= nextCheckTarget.value && !isCheckingAttention.value) {
    triggerAttentionCheck()
    lastCheckTime.value = elapsed
    checkCount.value++

    if (checkCount.value < 3) {
      const minInterval = 120
      const maxInterval = 300
      const randomInterval = Math.floor(Math.random() * (maxInterval - minInterval + 1)) + minInterval
      let nextTarget = elapsed + randomInterval
      const latestSafeTime = totalSeconds - 60
      if (nextTarget > latestSafeTime) {
        nextCheckTarget.value = null
      } else {
        nextCheckTarget.value = nextTarget
      }
    } else {
      nextCheckTarget.value = null
    }
  }
}

let pendingDialog = null

const triggerAttentionCheck = () => {
  if (isCheckingAttention.value || pendingDialog) return

  isCheckingAttention.value = true

  pendingDialog = Dialog.alert({
    title: '注意力检测',
    message: '您仍在屏幕前吗？请确认以继续观看。',
    confirmButtonText: '我在',
    closeOnPopstate: false,
    showConfirmButton: true,
    closeOnClickOverlay: false,
    className: 'attention-dialog'
  }).then(() => {
    pendingDialog = null
    finishAttentionCheck()
  }).catch(() => {
    pendingDialog = null
  })

  attentionCheckTimer.value = setTimeout(() => {
    if (isCheckingAttention.value) {
      Dialog.close()
      pendingDialog = null
      resetAllTimers()
    }
  }, 30000)
}

const finishAttentionCheck = () => {
  clearTimeout(attentionCheckTimer.value)
  attentionCheckTimer.value = null
  isCheckingAttention.value = false
  showToast({
    type: 'success',
    message: '验证通过，继续计时'
  });
}

const resetAllTimers = () => {
  if (timer.value) clearInterval(timer.value)
  if (attentionCheckTimer.value) clearTimeout(attentionCheckTimer.value)
  timer.value = null
  attentionCheckTimer.value = null
  isCountdownActive.value = false
  isCheckingAttention.value = false

  Dialog.alert({
    title: '提示',
    message: '因长时间未响应，学习已中断，计时器将重新开始。',
    confirmButtonText: '确定'
  }).then(() => {
    remainingTime.value = viewingDur.value
    startCountdown()
  })
}

const handleCountdownEnd = () => {
  showToast({
    type: 'success',
    message: '观看时间结束，请进行答题'
  });

  datiDisPlay.value = true
}
const router = useRouter();
const headers = ref({
  token: localStorage.getItem('token'),
  userId: localStorage.getItem('userId'),
  dept: JSON.parse(localStorage.getItem('dept'))[0].deptCode
});
const today = new Date();
const year = today.getFullYear();
const month = String(today.getMonth() + 1).padStart(2, '0');
const day = String(today.getDate()).padStart(2, '0');
const todayStr = `${year}-${month}-${day}`;

// ========== 播放器初始化 ==========
const initPlayer = () => {
  const videoEl = videoPlayer.value
  if (!videoEl) {
    console.error('❌ 视频元素未找到')
    return
  }

  player.value = videojs(videoEl, {
    autoplay: false,
    controls: true,
    preload: 'auto',
    fluid: true,
    language: 'zh-CN',
    controlBar: {
      playToggle: true,
      progressControl: true,
      fullscreenToggle: true
    }
  }, () => {
    console.log('✅ 播放器初始化完成')
    const current = currentVideo.value
    if (current.src) {
      player.value.src({ src: current.src, type: current.type })
      player.value.load()
    }
  })

  player.value.on('error', () => {
    const error = player.value.error()
    console.error('播放器错误:', error)
    showFailToast(`视频加载失败: ${error?.message || '未知错误'}`)
  })
}

const resetPlayer = () => {
  if (!player.value) return
  const current = currentVideo.value
  if (!current || !current.src) return

  player.value.pause()
  player.value.src({ src: current.src, type: current.type })
  player.value.load()

  player.value.on('loadedmetadata', () => {
    console.log('元数据加载完成')
  })
}

// 把 onActivated 改成 onMounted
onMounted(async () => {
  console.log('✅ onMounted: 页面已挂载')
  console.log('route.query:', route.query)
  if (!route.query.data) {
    showFailToast('缺少参数 data')
    return
  }

  let rowData
  try {
    // ✅ 加上 decodeURIComponent 解码
    rowData = JSON.parse(decodeURIComponent(route.query.data))
  } catch (err) {
    console.error('解析 data 失败:', err)
    showFailToast('参数格式错误')
    return
  }

  assTypeId = rowData.assTypeId
  id1 = rowData.id
  headId = rowData.headId

  if (timer.value) clearInterval(timer.value)
  getTableByRule()
})

onUnmounted(() => {
  if (timer.value) clearInterval(timer.value)
  if (attentionCheckTimer.value) clearTimeout(attentionCheckTimer.value)
  if (player.value) {
    player.value.dispose()
    player.value = null
  }
})

// ========== 数据获取 ==========
const getTableByRule = async () => {
  const url = '/sgsafe/AssessmentRecord/getRuleByAssTypeId'
  const param = {
    params: assTypeId
  }
    const response = await proxy.$axios.get(url, param)
    if (response.data.code == '0') {
      ruleData.value = response.data.data
      if (ruleData.value.length > 0 && ruleData.value[0].fileId) {
        fileIds.value.fileId = ruleData.value[0].fileId
        getFile()
        startCountdown()
        prepareQuizData()
      } else {
        showToast({
          type: 'error',
          message: '操作失败！' + response.data.msg
        });
      }
    } else {
      showToast({
        type: 'error',
        message: '缺少参数 data'
      });
    }
}

const prepareQuizData = async () => {
  const url = '/sgsafe/AssessmentRecord/getQuestionByAssTypeId'
  const param = { params: headId }
  try {
    const response = await proxy.$axios.get(url, param)
    if (response.data.code == '0') {
      questionData.value = response.data.data
    }
  } catch (err) {
    console.error('题库加载失败', err)
  }
}

const getFile = async () => {
  if (!fileIds.value.fileId) {

    return
  }

  loading.value = true
  previewList.value = []
  videoList.value = []

  const url = 'framework/Common/queryFileWithValues'
  const param = { fId: fileIds.value.fileId }

  try {
    const response = await proxy.$axios.get(url, param)
    if (response.data.code == '0') {
      const data = response.data.data
      if (!data || !Array.isArray(data) || data.length === 0) {
        showToast({
          type: 'fail',
          message: '暂无文件数据'
        });

        return
      }

      tableDataFile.value = data
      console.log('tableDataFile:', tableDataFile.value);
      data.forEach(file => {
        createPreview(file)
      })

      await nextTick()
      if (videoList.value.length > 0) {
        isVideoPlayerVisible.value = true
        if (!player.value) {
          initPlayer()
        } else {
          resetPlayer()
        }
      }
    } else {
      showToast({
        type: 'fail',
        message: '获取文件失败'
      });
    }
  } catch (err) {
    showToast({
      type: 'fail',
      message: '网络错误'
    });
  } finally {
    loading.value = false
  }
}

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

  if (['pdf', 'doc', 'docx'].includes(type)) {
    const encodedUrl = Base64.encode(downloadUrl)
    const previewUrl = `${import.meta.env.VITE_PREVIEW_API}/onlinePreview?url=${encodeURIComponent(encodedUrl)}`
    previewList.value.push({ id, fileName, fileType: type, previewUrl })
  } else if (type === 'mp4') {
    videoList.value.push({
      id,
      fileName,
      src: downloadUrl,
      type: 'video/mp4'
    })
  }
}

// ========== 视频切换 ==========
const prevVideo = () => {
  currentVideoIndex.value = (currentVideoIndex.value - 1 + videoList.value.length) % videoList.value.length
  resetPlayer()
}
const nextVideo = () => {
  currentVideoIndex.value = (currentVideoIndex.value + 1) % videoList.value.length
  resetPlayer()
}
const jumpToVideo = (index) => {
  currentVideoIndex.value = index
  resetPlayer()
}

const handleSearch = () => {
  console.log(headId);
  router.push({
    path: "/datistart",
    query: {
      courseId: headId,
      userId: headers.value.userId,
      todayStr: todayStr,
    },
  });
}

</script>

<style>
/* H5 适配样式 */
.van-card {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0,0,0,0.1);
  margin-bottom: 12px;
}

.video-js {
  width: 100% !important;
  height: 240px !important;
  background: #000;
}

.attention-dialog .van-dialog__confirm {
  color: #1989fa;
}
</style>