<template>
  <view>
    <div>
      <PdfView v-if="isShow" :path="path" />
    </div>
  </view>
</template>

<script>
import PdfView from './components/PdfView.vue'
import config from '@/config'
import { pathToBase64, base64ToPath } from 'image-tools'

export default {
  components: { PdfView },
  data() {
    return {
      isShow: true,
      path: '',
      params: {},
      timer: null,
      // 剩余时间
      surplusTime: null,
      isHide: false,
      allStudyDuration: 0,
      random1: 0,
      random2: 0,
      // 失败次数
      failCount: 3
    }
  },
  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)
    if (Number(opt.studyDuration) < Number(opt.allStudyDuration)) {
      this.surplusTime = Number(opt.allStudyDuration) - Number(opt.studyDuration)
      this.allStudyDuration = Number(this.params.allStudyDuration) - Number(this.params.studyDuration)
      this.random1 = (this.allStudyDuration / 3).toFixed(0)
      this.random2 = ((this.allStudyDuration / 3) * 2).toFixed(0)
      console.log('🚀 ~ onLoad ~ surplusTime:', this.surplusTime)
      setTimeout(() => {
        this.countDown()
      }, 1000)
    } else {
      this.surplusTime = 0
      // 提示-学习时长已满
      uni.showToast({
        title: '学习时长已满, 随时可以结束学习',
        icon: 'none'
      })
    }
    // 如果路径中带有http或者https则直接使用路径，否则拼接路径
    if (opt.path.indexOf('http') !== -1) {
      this.path = opt.path + '?surplusTime=' + JSON.stringify(this.surplusTime)
    } else {
      this.path = config.fileUrl + opt.path + '?surplusTime=' + JSON.stringify(this.surplusTime)
    }
    console.log('🚀 ~ onLoad ~ this.params:', this.path)
    console.log('🚀 ~ onLoad ~ this.params:', Number(opt.studyDuration), Number(opt.allStudyDuration))
  },
  onHide() {
    if (!this.isHide) {
      console.log('🚀 ~ onHide ~ 页面隐藏')
      clearInterval(this.timer)
      // 关闭页面时，修改项目进度
      this.updStudyDuration()
    }
  },
  // 卸载
  onUnload() {
    if (!this.isHide) {
      console.log('🚀 ~ onHide ~ 页面隐藏')
      clearInterval(this.timer)
      // 关闭页面时，修改项目进度
      this.updStudyDuration()
    }
  },
  methods: {
    // 根据allStudyDuration 倒计时
    countDown() {
      // let allStudyDuration = Number(this.params.allStudyDuration) - Number(this.params.studyDuration)
      this.timer = setInterval(() => {
        if (!this.isHide) {
          this.allStudyDuration--
          this.params.studyDuration++
        }
        if (this.allStudyDuration == this.random1) {
          this.isShow = false
          clearInterval(this.timer)
          this.openPhotograph()
        }
        if (this.allStudyDuration == this.random2) {
          this.isShow = false
          clearInterval(this.timer)
          this.openPhotograph()
        }
        console.log('🚀 ~ countDown ~ this.params.studyDuration:', this.params.studyDuration)
        if (this.allStudyDuration <= 0) {
          this.params.studyDuration = this.params.allStudyDuration
          clearInterval(this.timer)
          setTimeout(() => {
            this.updStudyDuration()
            // 提示-学习时长已满
            uni.showToast({
              title: '学习时长已满',
              icon: 'none'
            })
          }, 1000)
        }
        console.log('🚀 ~ countDown ~ 剩余时间-->:', this.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)
        }
      })
    },
    // 拍照录入
    openPhotograph() {
      this.isHide = true
      setTimeout(() => {
        uni.chooseImage({
          count: 1,
          sizeType: ['compressed'],
          sourceType: ['camera'],
          success: res => {
            let url = ''
            console.log('🚀 ~ res-拍照:', res)
            this.imgToBase64(res.tempFilePaths[0]).then(base64 => {
              url = base64
              console.log('🚀 ~ this.imgToBase64 ~ base64:', url)
              this.getFaceRecognition({ userId: uni.getStorageSync('userId'), img: url })
            })
          },
          fail(err) {
            console.log('🚀 ~ openFaceScan ~ 人脸识别失败', err)
            uni.showToast({
              title: '人脸识别失败',
              icon: ''
            })
            setTimeout(() => {
              this.updStudyDuration()
            }, 1000)
          }
        })
      }, 500)
    },
    imgToBase64(data) {
      return new Promise((resolve, reject) => {
        pathToBase64(data)
          .then(base64 => {
            resolve(base64)
          })
          .catch(error => {
            console.error(error)
            reject(error)
          })
      })
    },
    // 发送请求
    getFaceRecognition(params) {
      console.log('🚀 ~ getFaceRecognition ~ params:', params)
      this.$verificationToken()
      uni.request({
        url: config.baseUrl + '/exam-student/personalCenter/getFaceRecognition',
        method: 'POST',
        header: {
          'content-type': 'application/json',
          Authorization: uni.getStorageSync('access_token')
        },
        data: params,
        success: res => {
          console.log('🚀 ~ openFaceScan ~ res-人脸识别:', res)
          res = res.data
          console.log('🚀 ~ openFaceScan ~ res-人脸识别:', res.code)
          if (res.code == 200) {
            // 提示
            uni.showToast({
              title: '人脸识别成功'
            })
            this.failCount = 3
            this.isHide = false
            // 重新计算 this.surplusTime
            this.surplusTime = this.allStudyDuration
            if (this.params.path.indexOf('http') !== -1) {
              this.path = this.params.path + '?surplusTime=' + JSON.stringify(this.surplusTime)
            } else {
              this.path = config.fileUrl + this.params.path + '?surplusTime=' + JSON.stringify(this.surplusTime)
            }
            this.isShow = true
            this.countDown()
          } else {
            this.failCount--
            if (this.failCount == 0) {
              uni.showToast({
                title: '人脸识别失败, 即将结束学习',
                icon: 'none'
              })
              setTimeout(() => {
                this.updStudyDuration()
              }, 1000)
            } else {
              uni.showToast({
                title: '人脸识别失败, 请重新录入, 剩余次数: ' + this.failCount + '次',
                icon: 'none',
                duration: 1500
              })
              setTimeout(() => {
                this.openPhotograph()
              }, 1500)
            }
          }
        },
        fail(err) {
          console.log('🚀 ~ openFaceScan ~ 人脸识别失败', err)
          uni.showToast({
            title: '人脸识别失败',
            icon: ''
          })
          setTimeout(() => {
            this.updStudyDuration()
          }, 1000)
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped></style>
