<template>
  <view>
    <div class="video">
      <video
        id="myVideo"
        :src="path"
        :initial-time="studyDuration"
        :show-progress="false"
        :enable-progress-gesture="false"
        @error="videoErrorCallback"
        @timeupdate="videoTimeUpdate"
      />
    </div>

    <u-modal
      :show="showModal"
      title="提示"
      :content="content"
      showCancelButton
      @cancel="showModal = false"
      @confirm="handleEnd"
    />

    <div class="btn">
      <u-button type="primary" shape="circle" text="结束学习" size="small" @click="openModal" />
    </div>
  </view>
</template>

<script>
import config from '@/config'
import { updStudyDuration } from '@/api/eduApp'

export default {
  props: {
    states: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      studyId: '', // 学习id
      stageId: '', // 阶段id
      stageContentId: '', // 阶段内容id
      stageType: '', // 阶段类型
      studyCourseId: '',
      sourceId: '', // 素材id
      path: '', // 视频路径
      studyDuration: 0, // 学习时长
      allStudyDuration: 0, // 总时长
      studyPercentage: 0, // 学习进度
      // 当前播放时间
      currentTime: 0,
      showModal: false, // 是否显示弹窗
      content: '是否确认结束学习？'
    }
  },
  onLoad(opt) {
    opt = JSON.parse(opt.params)
    console.log('🚀 ~ onLoad ~ :', opt)
    this.studyId = opt.studyId
    this.stageId = opt.stageId
    this.stageContentId = opt.stageContentId
    this.stageType = opt.stageType
    this.studyCourseId = opt.studyCourseId
    this.sourceId = opt.sourceId
    this.path = config.fileUrl + opt.path
    console.log('🚀 ~ onLoad ~ this.path:', this.path)
    this.studyDuration = this.currentTime = Number(opt.studyDuration)
    this.allStudyDuration = Number(opt.allStudyDuration)
  },
  onUnload() {
    console.log('🚀 ~ onUnload ~ 页面关闭')
    // 关闭页面时，修改项目进度
    this.handleEnd()
  },
  methods: {
    videoErrorCallback(e) {
      console.log('视频错误信息：', e)
    },
    // 视频播放时间更新
    videoTimeUpdate(e) {
      console.log('视频播放时间：', e.detail.currentTime)
      this.currentTime = Math.ceil(e.detail.currentTime)
    },
    openModal() {
      this.showModal = true
    },
    // 结束学习
    handleEnd() {
      // 手动暂停视频
      const video = uni.createVideoContext('myVideo')
      video.pause()
      // 获取当前播放时间 - 用于记录学习时长
      console.log('当前播放时间：', this.currentTime, this.allStudyDuration)
      this.studyDuration = this.currentTime
      // 计算学习进度
      this.studyPercentage = Math.ceil((this.studyDuration / this.allStudyDuration) * 100).toFixed(2)
      console.log('🚀 ~ handleEnd ~ this.studyPercentage:', this.studyPercentage)

      const params = {
        userId: uni.getStorageSync('userId'),
        studyId: this.studyId,
        stageId: this.stageId,
        stageContentId: this.stageContentId,
        stageType: this.stageType,
        studyCourseId: this.studyCourseId,
        sourceId: this.sourceId,
        studyDuration: this.studyDuration,
        studyPercentage: this.studyPercentage
      }
      console.log('🚀 ~ handleEnd ~ params:', params)
      // updStudyDuration(params).then(res => {
      //   console.log('🚀 ~ handleEnd ~ res:', res)
      //   this.showModal = false
      //   uni.navigateBack()
      // })
      uni.request({
        url: config.baseUrl + '/exam-student/student/updStudyDuration',
        method: 'post',
        data: params,
        header: {
          'Content-Type': 'application/x-www-form-urlencoded',
          Authorization: uni.getStorageSync('access_token')
        },
        success: res => {
          console.log('🚀 ~ handleEnd ~ res:', res)
          this.showModal = false
          uni.navigateTo({
            url: '/pages/YNEduApp/learnProj/learnProjDetail?id=' + this.studyId
          })
        },
        fail: err => {
          console.log('🚀 ~ handleEnd ~ err:', err)
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
// 隐藏 video 默认控制条
::v-deep .uni-video-controls {
  display: none !important;
}

.video {
  width: 100%;
  height: 260px;
  uni-video {
    width: 100%;
    height: 100%;
  }
}

.btn {
  margin: 60px auto;
  width: 100px;
}

::v-deep .u-modal__content {
  flex-direction: column;
  align-items: center;
}
</style>
