<!--
* @FileDescription:播放记时
* @Author: 黄琪勇
* @Date:2024-04-07 16:49:23
-->
<template>
   <div class="playRecordTime" :class="!isCurrentCoursewareMenu ? 'hide' : ''">
      <div class="drop"></div>
      <div class="time">{{ `${formatTime(playTime)}/${formatTime(props.coursewareTotalTime)}` }}</div>
   </div>
</template>

<script setup lang="ts">
import { formatTime } from "../../videoPlay/tools"
import { getCoursewarePlayTime_gyt, coursewarePlayTime_gyt } from "@/api/coursewarePlay.api"
import { httpAjax } from "@/plugin/httpAjax"
import { ref, onUnmounted, watch } from "vue"
const props = defineProps<{
   coursewareTotalTime: number
   isCurrentCoursewareMenu: boolean
   modeId: string
}>()

let _time: any
const timeNum = 5
const playTime = ref(0)
let timeRecord = 0
onUnmounted(() => {
   _time && clearInterval(_time)
})

watch(
   () => props.isCurrentCoursewareMenu,
   () => {
      if (!props.isCurrentCoursewareMenu) {
         handleCoursewarePlayTime(props.modeId, timeRecord)
         timeRecord = 0
         _time && clearInterval(_time)
      } else {
         timerCount()
      }
   }
)

getCoursewarePlayTime()
function getCoursewarePlayTime() {
   httpAjax(getCoursewarePlayTime_gyt, props.modeId).then(res => {
      if (res.code === 200) {
         playTime.value += res.data || 0
      }
   })
}
// 判断如果为同一个则计时
if (props.isCurrentCoursewareMenu) {
   timerCount()
}

function timerCount() {
   _time = setInterval(() => {
      // 播放时间大于总时间
      if (playTime.value >= props.coursewareTotalTime) {
         _time && clearInterval(_time)
         timeRecord > 0 && handleCoursewarePlayTime(props.modeId, timeRecord)
         return
      }
      timeRecord++
      playTime.value++
      if (timeRecord === timeNum) {
         handleCoursewarePlayTime(props.modeId, timeRecord)
         timeRecord = 0
      }
   }, 1000)
}
function handleCoursewarePlayTime(id: string, time: number) {
   httpAjax(coursewarePlayTime_gyt, id, time).then(() => {})
}
</script>

<style lang="scss" scoped>
.playRecordTime {
   // margin-left: 20px;
   display: flex;
   align-items: center;
   padding: 10px 16px;
   background: rgba(100, 100, 100, 0.5);
   border-radius: 28px;

   &.hide {
      opacity: 0;
   }
   .drop {
      margin-right: 12px;
      width: 8px;
      height: 8px;
      background: #f73434;
      // animation: loadFade 1s ease-in-out infinite;
      border-radius: 50%;
      @keyframes loadFade {
         0% {
            opacity: 0;
         }

         50% {
            opacity: 0.5;
         }

         100% {
            opacity: 1;
         }
      }
   }
   .time {
      font-weight: 400;
      font-size: 18px;
      color: #ffffff;
   }
}
</style>
