<template>
  <view>
    <Navbar title="视频学习" :showBack="false" />
    <div class="video">
      <video
        v-if="showVideo"
        id="myVideo"
        :src="videoUrl"
        :initial-time="videoInitialTime"
        :show-progress="false"
        :enable-progress-gesture="false"
        @error="videoErrorCallback"
        @timeupdate="videoTimeUpdate"
      />
    </div>

    <div style="padding: 60px 30px">
      <u-button type="primary" text="结束学习" shape="circle" @click="endStudy"></u-button>
    </div>
  </view>
</template>

<script>
import { updateProgress } from '@/api/educationTraining'
import config from '@/config'
import { getLearningTaskDetail } from '@/api/educationTraining'

export default {
  data() {
    return {
      opt: {},
      userId: uni.getStorageSync('userInfo').userId,
      showModal: false,
      video: null,
      // videoUrl: 'https://www.xbext.com/download/trailer.mp4', // 视频地址
      videoUrl: '', // 视频地址
      videoDuration: 0, // 视频时长
      videoInitialTime: 0, // 视频初始播放时间
      currentTimeInSeconds: 0, // 当前播放时间
      showVideo: false
    }
  },
  onLoad(opt) {
    this.opt = JSON.parse(opt.params)
    // this.videoUrl = config.fileUrl + this.opt.url
    this.videoUrl = config.coursewareUrl + this.opt.url
    console.log('🚀 ~ onLoad ~ this.videoUrl:', this.videoUrl)
    // this.videoDuration = this.opt.duration
    // this.videoInitialTime = this.opt.learningProgress
    this.getDetail()
    console.log('🚀 ~ onLoad ~ this.opt:', this.opt)
  },
  mounted() {
    this.video = uni.createVideoContext('myVideo')
    // 根据url获取当前视频时长
  },
  methods: {
    async getDetail() {
      console.log('🚀 ~ getDetail ~ this.opt:', this.opt)
      const res = await getLearningTaskDetail({ studyTaskId: this.opt.taskId })
      console.log('🚀 ~ getDetail ~ res:', res)
      // 查找 res.data 中 id 与 this.opt.coursewareId 相同的数据
      const data = res.data.find(item => item.id == this.opt.coursewareId)
      console.log('🚀 ~ getDetail ~ data:', data)
      if (data) {
        this.videoDuration = Number(data.duration)
        this.videoInitialTime = Number(data.learningProgress)
      } else {
        this.videoDuration = Number(this.opt.duration)
        this.videoInitialTime = Number(this.opt.learningProgress)
      }
      this.showVideo = true
      console.log('🚀 ~ getDetail ~ this.videoDuration:', this.videoDuration)
      console.log('🚀 ~ getDetail ~ this.videoInitialTime:', this.videoInitialTime)
      // this.video = uni.createVideoContext('myVideo')
    },
    videoErrorCallback(e) {
      console.log('视频错误', e)
    },
    videoTimeUpdate(e) {
      console.log('视频播放时间更新', e)
      const videoElement = e.target
      this.currentTimeInSeconds = Math.round(videoElement.currentTime)
      console.log('🚀 ~ videoTimeUpdate ~ this.currentTimeInSeconds:', this.currentTimeInSeconds)
    },
    // 结束学习
    endStudy() {
      console.log('结束学习')
      this.video.pause()
      // 弹框确认
      uni.showModal({
        title: '提示',
        content: '是否结束学习',
        success: async res => {
          if (res.confirm) {
            let studyProgress = 0
            if (this.currentTimeInSeconds > 0) {
              studyProgress = ((this.currentTimeInSeconds / this.videoDuration) * 100).toFixed(0)
              if (studyProgress > 100) {
                studyProgress = 100
              }
            }
            const params = {
              taskId: this.opt.taskId,
              type: this.opt.type,
              coursewareId: this.opt.coursewareId,
              userUuid: this.userId,
              studyTime: this.currentTimeInSeconds,
              studyProgress,
              taskLength: this.opt.taskLength,
              singId: this.opt.singId
            }
            console.log('用户点击确定', params)
            if (this.opt.studyProgress < 100) {
              const res = await updateProgress(params)
              console.log('🚀 ~ endStudy ~ 结束学习:', res)
            }
            setTimeout(() => {
              uni.navigateBack()
            }, 500)
          } else if (res.cancel) {
            console.log('用户点击取消')
            // 继续播放
            this.video.play()
          }
        }
      })
    },
    // 禁用手势返回 Android
    onBackPress(options) {
      console.log(options)
      if (options.from == 'backbutton') {
        // 来自手势返回
        console.log('手势返回')
        // 返回为 true 时，不会执行返回操作，可以自定义返回逻辑
        // 返回为 false 或者不返回时，则执行默认返回操作
        return true
      }
      // 返回为 false 或者不返回时，则执行默认返回操作
      return false
    }
  }
}
</script>

<style lang="scss">
.video {
  width: 100%;
  height: 260px;
  uni-video {
    width: 100%;
    height: 100%;
  }
}
</style>
