import request from '@/helpers/request'
import { browser } from '@/helpers/utils'
import { state } from '@/state'
import Plyr from 'plyr'
import 'plyr/dist/plyr.css'
import { NoticeBar } from 'vant'
import { defineComponent, onMounted, reactive, nextTick, computed } from 'vue'
import { useRoute } from 'vue-router'
import styles from './index.module.less'
export default defineComponent({
  name: 'exercise-after-class',
  setup() {
    const route = useRoute()
    const data = reactive({
      loading: true,
      recordLoading: false,
      video: '',
      currentTime: 0,
      duration: 0
    })
    console.log(route.query)
    const getLessonTraining = async () => {
      let details = []
      try {
        const res: any = await request.get(
          state.platformApi + `/lessonTraining/courseSchedule/${route.query.courseScheduleId}`
        )
        if (Array.isArray(res?.data)) {
          const studentLevel = state.user?.data?.studentLevel || 1
          details = res.data.find((n: any) => n.studentLevel === studentLevel)?.details || []
          console.log('🚀 ~ details', details)
        }
      } catch (error) {
        console.log('error')
      }
      if (details.length) {
        data.video =
          (details.find((n: any) => n.materialId == route.query.materialId) as any)?.content || ''
        console.log('🚀 ~ data.video', data.video)
        nextTick(() => {
          initVideo()
        })
      }
    }
    const initVideo = () => {
      const player = new Plyr('#player', {
        clickToPlay: true,
        invertTime: true,
        controls: ['play-large', 'play', 'current-time', 'restart', 'fullscreen']
      })
      player.on('loadeddata', () => {
        data.duration = player.duration
        console.log('🚀 ~ player', player.duration)
        data.loading = false
      })
      player.on('timeupdate', () => {
        data.currentTime = player.currentTime
        // console.log(timeRemaining.value)
        if (timeRemaining.value === 0) {
          if (data.recordLoading || data.currentTime === 0) return
          console.log('完成观看次数')
          addTrainingRecord()
        }
      })
    }
    const timeRemaining = computed(() => {
      return Math.ceil(data.duration - data.currentTime)
    })
    onMounted(() => {
      getLessonTraining()
    })
    // 达到指标,记录
    const addTrainingRecord = async () => {
      data.recordLoading = true
      const browserInfo = browser()
      const body = {
        materialType: 'VIDEO',
        record: {
          sourceTime: data.duration,
          clientType: state.platformType,
          feature: 'LESSON_TRAINING',
          deviceType: browserInfo.android ? 'ANDROID' : browserInfo.isApp ? 'IOS' : 'WEB'
        },
        courseScheduleId: route.query.courseScheduleId,
        lessonTrainingId: route.query.lessonTrainingId,
        materialId: route.query.materialId
      }
      try {
        const res: any = await request.post(
          state.platformApi + '/studentLessonTraining/lessonTrainingRecord',
          {
            data: body
          }
        )
      } catch (error) {}
      data.recordLoading = false
    }
    return () => (
      <div class={styles['exercise-after-class']}>
        <video id="player" src={data.video}></video>
        {!data.loading && (
          <>
            {timeRemaining.value === 0 ? (
              <NoticeBar background="green" color="#fff" text={`已完成本次训练`} />
            ) : (
              <NoticeBar text={`还需要观看 ${timeRemaining.value} 秒,就可以完成课后训练了`} />
            )}
          </>
        )}
      </div>
    )
  }
})
