<template>
  <!-- <video ref="videoPlay" oncontextmenu="return false;" :src="safeUrl" :poster="coverUrl" @timeupdate="timeupdateAction" @ended="recordCommit(src)" controls controlslist="nodownload" disablePictureInPicture style="width: 100%; height: 100%"></video> -->
  <video-player
    v-if="hasUrl"
    ref="videoPlayer"
    class="video-player vjs-custom-skin"
    :playsinline="true"
    :options="playerOptions"
    @timeupdate="timeupdateAction"
    @ended="recordCommit(src)"
  />
</template>

<script>
import {
  getVideoPlayInfo,
  saveWatchRecord
} from '../../api/webApi/webVideo.js'

export default {
  props: {
    aliIdType: {
      type: Number | String,
      default: ''
    },
    src: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      safeUrl: '',
      coverUrl: '/static/images/eval-center/img_fengminan.png',
      //
      playerOptions: {
        // playbackRates: [0.7, 1.0, 1.5, 2.0], //播放速度
        autoplay: false, // 如果true,浏览器准备好时开始回放。
        muted: false, // 默认情况下将会消除任何音频。
        loop: false, // 导致视频一结束就重新开始。
        preload: 'auto', // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
        language: 'zh-CN',
        aspectRatio: '16:9', // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
        fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
        sources: [{ type: '', src: '' }],
        hls: true,
        poster: '', // 你的封面地址
        width: document.documentElement.clientWidth, // 播放器宽度
        notSupportedMessage: '此视频暂无法播放，请稍后再试', // 允许覆盖Video.js无法播放媒体源时显示的默认信息。
        controlBar: {
          timeDivider: true,
          durationDisplay: true,
          remainingTimeDisplay: false,
          fullscreenToggle: true // 全屏按钮
        }
      },
      // 播放统计日志字段
      recordCommitted: false,
      recordDuration: 0,
      recordPercent: 0
    }
  },
  computed: {
    hasUrl() {
      return this.playerOptions.sources?.length &&
        !!this.playerOptions.sources.first().src
    }
  },
  watch: {
    src: {
      handler: function(newV, oldV) {
        console.log('mx video received id:', newV)
        // save if needed
        this.recordCommit(oldV)
        this.toggleSrc(newV)
        // record reset
        this.recordReset()
      },
      immediate: true
    }
  },
  beforeDestroy() {
    this.recordCommit(this.src)
  },
  methods: {
    toggleSrc(videoId) {
      if (this.isPlayUrl(videoId)) {
        this.safeUrl = videoId
        this.setPlayerUrl(this.safeUrl)
      } else {
        this.getSafeUrl(videoId)
      }
    },
    getSafeUrl(id) {
      if (!id) return
      getVideoPlayInfo(id).then((res) => {
        this.coverUrl = res.data.coverUrl
        if (this.isPlayUrl(res.data.palyUrl)) {
          this.safeUrl = res.data.palyUrl
          this.setPlayerUrl(this.safeUrl, this.coverUrl)
        }
        this.recordCommitted = false // ensure committed status
      })
    },
    isPlayUrl(str) {
      return str?.toLowerCase().startsWith('http')
    },
    setPlayerUrl(url, poster) {
      let mediaType = 'video/mp4'
      if (url.toLowerCase().endsWith('m3u8')) {
        mediaType = 'application/x-mpegURL'
      }
      this.playerOptions.sources = [
        {
          src: url,
          type: mediaType
        }
      ]
      this.playerOptions.poster = poster || this.coverUrl
    },
    // 日志记录
    timeupdateAction(player) {
      const currentTime = player.currentTime()
      const duration = player.duration()
      this.recordDuration = duration
      this.recordPercent = 0
      if (this.recordDuration > 0) {
        this.recordPercent = (currentTime * 100) / duration
      }
    },
    recordReset() {
      this.recordCommitted = false
      this.recordDuration = 0
      this.recordPercent = 0
    },
    recordCommit(id) {
      console.log('record commit:', id)
      if (this.recordCommitted) return // 已提交
      if (!this.recordPercent) return // 无效数据
      if (this.recordPercent < 2) return // <3%播放太短，也不记，防止过度触发提交
      saveWatchRecord(
        id,
        this.recordDuration,
        this.recordPercent,
        this.aliIdType
      ).then((_) => {
        this.recordCommitted = true
        console.log('saveWatchRecord committed')
      })
    }
  },
};
</script>

<style>
</style>
