<template>
  <view class="content">
    <div style="margin: 10px; color: #2979ff">
      <span v-if="!isEnd">剩余学习时间：{{ time }}</span>
      <span v-else>已完成学习</span>
    </div>
    <u--image :showLoading="true" :src="path" width="300px" height="600px" @click="handleImage"></u--image>
  </view>
</template>

<script>
import config from '@/config'

export default {
  data() {
    return {
      isShow: true,
      path: '',
      params: {},
      timer: null,
      isEnd: false,
      isShowImg: false,
      time: ''
    }
  },
  onLoad(opt) {
    opt = JSON.parse(opt.params)
    console.log('🚀 ~ onLoad ~ opt:', opt)
    this.params = JSON.parse(JSON.stringify(opt))
    this.params.studyDuration = Number(opt.studyDuration)
    this.params.allStudyDuration = Number(opt.allStudyDuration)
    this.path = config.fileUrl + opt.path
    // this.path = opt.path
    console.log('🚀 ~ onLoad ~ this.params:', this.path)
    console.log('🚀 ~ onLoad ~ this.params:', Number(opt.studyDuration), Number(opt.allStudyDuration))

    if (Number(opt.studyDuration) < Number(opt.allStudyDuration)) {
      this.isEnd = false
      setTimeout(() => {
        this.countDown()
      }, 1000)
    } else {
      this.isEnd = true
      // 提示-学习时长已满
      uni.showToast({
        title: '学习时长已满, 随时可以结束学习',
        icon: 'none'
      })
    }
  },
  onShow() {
    console.log('🚀 ~ onShow ~ 页面显示')
    this.isShowImg = false
  },
  // 卸载 隐藏是调用 onHide
  onHide() {
    console.log('🚀 ~ onHide ~ 页面关闭')
    if (this.isEnd) {
      return
    }
    // 关闭页面时，修改项目进度
    if (!this.isShowImg) {
      clearInterval(this.timer)
      this.updStudyDuration()
    }
  },
  onUnload() {
    console.log('🚀 ~ onUnload ~ onUnload-页面关闭:')
    if (this.isEnd) {
      return
    }
    // 关闭页面时，修改项目进度
    if (!this.isShowImg) {
      clearInterval(this.timer)
      this.updStudyDuration()
    }
  },
  methods: {
    // 根据allStudyDuration 倒计时
    countDown() {
      let allStudyDuration = Number(this.params.allStudyDuration) - Number(this.params.studyDuration)
      // let studyDuration = Number(this.params.studyDuration)
      let minute = Math.floor(allStudyDuration / 60)
      minute = String(minute).padStart(2, '0')
      let second = allStudyDuration % 60
      this.time = minute + ':' + second
      this.timer = setInterval(() => {
        allStudyDuration--
        this.params.studyDuration++
        console.log('🚀 ~ countDown ~ this.params.studyDuration:', this.params.studyDuration)
        if (allStudyDuration <= 0) {
          this.params.studyDuration = this.params.allStudyDuration
          this.isEnd = true
          clearInterval(this.timer)
          // 提示-学习时长已满
          uni.showToast({
            title: '学习时长已满',
            icon: 'none'
          })
          setTimeout(() => {
            this.updStudyDuration()
          }, 1000)
        }
        let arr = this.time.split(':')
        let minute = parseInt(arr[0])
        let second = parseInt(arr[1])
        if (second == 0) {
          minute -= 1
          second = 59
          if (minute < 10) {
            minute = String(minute).padStart(2, '0')
          }
        } else {
          second -= 1
          if (minute < 10) {
            minute = String(minute).padStart(2, '0')
          }
          if (second < 10) {
            second = String(second).padStart(2, '0')
          }
        }
        this.time = minute + ':' + second
        console.log('🚀 ~ countDown ~ 剩余时间-->:', allStudyDuration)
        console.log('🚀 ~ countDown ~ this.params.studyDuration:', this.params.studyDuration)
      }, 1000)
    },
    // 修改项目进度
    updStudyDuration() {
      const params = {
        userId: this.params.userId,
        studyId: this.params.studyId,
        stageId: this.params.stageId,
        stageContentId: this.params.stageContentId,
        stageType: this.params.stageType,
        studyCourseId: this.params.studyCourseId,
        sourceId: this.params.sourceId,
        studyDuration: this.params.studyDuration,
        studyPercentage:
          Math.ceil((Number(this.params.studyDuration) / Number(this.params.allStudyDuration)) * 100).toFixed(2) > 100
            ? 100
            : Math.ceil((Number(this.params.studyDuration) / Number(this.params.allStudyDuration)) * 100).toFixed(2)
      }
      console.log('🚀 ~ updStudyDuration ~ params:', params)
      this.$verificationToken()
      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.isShow = false
          uni.reLaunch({
            url: '/pages/YNEduApp/learnProj/learnProjDetail?id=' + this.params.studyId
          })
        },
        fail: err => {
          console.log('🚀 ~ handleEnd ~ err:', err)
        }
      })
    },
    // 展示图片
    handleImage() {
      this.isShowImg = true
      uni.previewImage({
        urls: [this.path]
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.content {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
</style>
