<script setup lang="ts" name="LearnRecord">
import { ref, onMounted, nextTick, onBeforeUnmount, getCurrentInstance, type ComponentInternalInstance } from 'vue'
import * as ww from '@wecom/jssdk'
import { onLoad } from '@dcloudio/uni-app'
import { getTmCourseSection, addTmTrainRecord, editTmTrainRecord, getStreamList } from '@/api/train/course.ts'
import previewPageSupplementFile from '@/components/previewPageSupplementFile.vue'
import {
  filePreview
} from '@/api/system/file'
// import router from '@/router'
const { proxy }:any = getCurrentInstance() as ComponentInternalInstance
// const route = useRoute()
onLoad((option)=>{
  sectionId.value = option.sectionId ? option.sectionId : ''
  courseId.value = option.courseId ? option.courseId : ''
  trainId.value = option.trainId ? option.trainId : ''
})
const sectionId = ref('') // 小节id
const courseId = ref('') // 课程id
const trainId = ref('') // 培训id


const fileUrl = ref('')
const realUrl = ref('')
const demo:any = ref(null)
const fileType:any = ref('')
const videoRef:any = ref(null)

// sectionId: item.id, // 小节id
// courseId: route.query.courseId, // 课程id
// trainId: route.query.trainId // 培训id

// 文件类型, 例如['png', 'jpg', 'jpeg']
const displayArry1:any = ref(['pptx', 'ppt'])
const displayArry2:any = ref(['pdf'])
const displayArry3:any = ref(['wmv', 'avi', 'mpg', 'mpeg', 'mp4'])
const count = ref(0)
const countSub = ref(0)
const totalDura = ref(0)
// 创建定时器
const timer:any = ref(null)
const timerSub:any = ref(null)
const newRecordId = ref('')
const detaillastPosition = ref('')
const urlList:any = ref([])
const activeLineIndex = ref(0)
onMounted(() => {

  // 查询课程详情
  getTmCourseSection(sectionId.value).then(res => {
    // console.log(res)
    fileUrl.value = res.data.sectionUrl
    totalDura.value = Number(res.data.totalDura)

    detaillastPosition.value = res.data.lastPosition


    let str = res.data.sectionType
    let arry = str.split('.')
    let filestr = arry[arry.length - 1]
    if (displayArry1.value.includes(filestr)) {
      console.log(123)
      fileType.value = 'ppt'
      addTmTrainRecord({
        sectionId: sectionId.value, // 小节id
        courseId: courseId.value, // 课程id
        trainId: trainId.value, // 培训id
        totalDura: Number(totalDura.value) * 1000,
        hasDura: Number(count.value) * 1000,
        fileType: 'ppt'
      }).then(res => {
        newRecordId.value = res.msg
        startTimer()
        startTimerSub()

        getStreamList({}).then(res => {
          console.log(res)
          let data = res.data
          urlList.value = data.map(item => {
            return {
              url: item.url + '' + fileUrl.value,
              name: item.name
            }
            // return {
            //   url: filePreview(item.url + '' + fileUrl.value),
            //   name: item.name
            // }
          })
          realUrl.value = urlList.value[0].url
          activeLineIndex.value = 0
            console.log('realUrl.value111',realUrl.value)
        })
      })
    }
    if (displayArry2.value.includes(filestr)) {
      fileType.value = 'pdf'
      addTmTrainRecord({
        sectionId: sectionId.value, // 小节id
        courseId: courseId.value, // 课程id
        trainId: trainId.value, // 培训id
        totalDura: Number(totalDura.value) * 1000,
        hasDura: Number(count.value) * 1000,
        fileType: 'pdf'
      }).then(res => {
        newRecordId.value = res.msg
        startTimer()
        startTimerSub()
        getStreamList({}).then(res => {
          console.log(res)
          let data = res.data
          urlList.value = data.map(item => {
            return {
              url: item.url + '' + fileUrl.value,
              name: item.name
            }
          })
          realUrl.value = urlList.value[0].url
          console.log('realUrl.value',realUrl.value)
          activeLineIndex.value = 0
        })
      })
    }
    if (displayArry3.value.includes(filestr)) {
      fileType.value = 'video'
      addTmTrainRecord({
        sectionId: sectionId.value, // 小节id
        courseId: courseId.value, // 课程id
        trainId: trainId.value, // 培训id
        totalDura: Number(totalDura.value) * 1000,
        lastPosition: Number(detaillastPosition.value) * 1000,
        fileType: 'video'
      }).then(res => {
        newRecordId.value = res.msg
        startTimer()
        startTimerSub()

        getStreamList({}).then(res => {
          console.log(res)
          let data = res.data
          urlList.value = data.map(item => {
            return {
              url: item.url + '' + fileUrl.value,
              name: item.name
            }
          })
          realUrl.value = urlList.value[0].url
          activeLineIndex.value = 0
        })
      })

      nextTick(() => {
        const videoDom = document.getElementById('videoRef') as any
        if (videoDom) {
          videoDom.addEventListener('canplay', function () {
            videoDom.currentTime = detaillastPosition.value
          })
        }
      })


    }



  })

})
function changeActiveLine(val:number) {
  realUrl.value = urlList.value[val].url
  activeLineIndex.value = val
}
function startTimer() {
  timer.value = setInterval(() => {
    // 执行某些操作
    count.value = count.value + 120
    if (fileType.value === 'ppt' || fileType.value === 'pdf') {
      editTmTrainRecord({
        sectionId: sectionId.value, // 小节id
        courseId: courseId.value, // 课程id
        trainId: trainId.value, // 培训id
        totalDura: Number(totalDura.value) * 1000,
        hasDura: Number(count.value) * 1000,
        id: newRecordId.value,
        fileType: fileType.value,
        duration: count.value
      }).then(res => {

      })
    }
    if (fileType.value === 'video') {
      editTmTrainRecord({
        sectionId: sectionId.value, // 小节id
        courseId: courseId.value, // 课程id
        trainId: trainId.value, // 培训id
        totalDura: Number(totalDura.value) * 1000,
        lastPosition: (Number(detaillastPosition.value) * 1000 + Number(count.value) * 1000) > Number(totalDura.value) * 1000 ? Number(totalDura.value) * 1000 : (Number(detaillastPosition.value) * 1000 + Number(count.value) * 1000),
        id: newRecordId.value,
        fileType: fileType.value,
        duration: count.value
      }).then(res => {

      })
    }
  }, 120000)
}

function startTimerSub() {
  timerSub.value = setInterval(() => {
    countSub.value = countSub.value + 1
  }, 1000)
}


function handleBack() {
  if (fileType.value === 'ppt' || fileType.value === 'pdf') {
    editTmTrainRecord({
      sectionId: sectionId.value, // 小节id
      courseId: courseId.value, // 课程id
      trainId: trainId.value, // 培训id
      totalDura: Number(totalDura.value) * 1000,
      hasDura: Number(count.value) * 1000,
      id: newRecordId.value,
      fileType: fileType.value,
      duration: countSub.value
    }).then(res => {
      uni.navigateBack({
        delta:1
      })
    })
  }
  if (fileType.value === 'video') {
    editTmTrainRecord({
      sectionId: sectionId.value, // 小节id
      courseId: courseId.value, // 课程id
      trainId: trainId.value, // 培训id
      totalDura: Number(totalDura.value) * 1000,
      lastPosition: (Number(detaillastPosition.value) * 1000 + Number(count.value) * 1000) > Number(totalDura.value) * 1000 ? Number(totalDura.value) * 1000 : (Number(detaillastPosition.value) * 1000 + Number(count.value) * 1000),
      id: newRecordId.value,
      fileType: fileType.value,
      duration: countSub.value
    }).then(res => {
       uni.navigateBack({
        delta:1
      })
    })
  }

}

// 在组件卸载时清除定时器，防止内存泄漏
onBeforeUnmount(() => {
  clearInterval(timer.value)
  count.value = 0
  countSub.value = 0
})


</script>

<template>
  <div class="container full">
    <div class="demo-container">

      <previewPageSupplementFile :fileUrl="realUrl" v-if="fileType === 'ppt' || fileType === 'pdf'"/>
      <video
        ref="videoRef"
        class="custom-video"
        controls="true"
        preload="auto"
        id="videoRef"
        :src="realUrl"
        v-if="fileType === 'video'"/>
    </div>
    <div class="url-line-container" v-if="fileType === 'video'">
      <div
        class="line-item"
        :class="[activeLineIndex === index ? 'active-line' : '']"
        v-for="(item,index) in urlList"
        :key="index"
        @click="changeActiveLine(index)">
        {{ item.name }}
      </div>
    </div>
    <uv-button
      class="button-submit float-bottom"
      shape="circle"
      color="linear-gradient(to bottom, #4773FC, #6D9BFD)"
      customStyle="margin-top: 200rpx" 
      @click="handleBack">退出学习</uv-button>


  </div>
</template>

<style lang="less" scoped>
.container {
  .demo-container{
    height: 40rem;
    width: 100%;

    .custom-video {
      width: 100%;
      height: 100%;
    }
  }
  .button-submit {
    margin-top: 3rem;
  }
  .url-line-container {
    display: flex;
    flex-wrap: wrap;
    margin-top: 3rem;
    .line-item {
      padding: 0.2rem 0.5rem;
      border: thin solid rgb(163, 160, 160);
      border-radius: 0.3rem;
      color: #333;
      margin-left: 1.5rem;
      &:first-child{
        margin-left: 0;
      }
    }
    .active-line{
      padding: 0.2rem 0.5rem;
      border: thin solid rgb(9, 158, 238);
      border-radius: 0.3rem;
      color: rgb(11, 134, 242);
    }
  }

}

</style>
