import { defineComponent, nextTick, onMounted, reactive, toRefs } from 'vue'
import TCPlayer from 'tcplayer.js'
import 'tcplayer.js/dist/tcplayer.min.css'
// import 'plyr/dist/plyr.css';
// import Plyr from 'plyr';
import { ref } from 'vue'
import styles from './index.module.less'

export default defineComponent({
  name: 'video-play',
  props: {
    styleValue: {
      type: Object,
      default: () => ({})
    },
    src: {
      type: String,
      default: ''
    },
    poster: {
      type: String,
      default: ''
    }
  },
  emits: ['loadedmetadata', 'togglePlay', 'ended', 'reset', 'play'],
  setup(props, { emit }) {
    const { src, poster } = toRefs(props)
    const videoRef = ref()
    const videoItem = ref()
    const videoID = 'video' + Date.now() + Math.floor(Math.random() * 100)

    onMounted(() => {
      const Button = TCPlayer.getComponent('Button')
      const BigPlayButton = TCPlayer.getComponent('BigPlayButton')
      BigPlayButton.prototype.createEl = function () {
        const el = Button.prototype.createEl.call(this)
        const _html =
          '<button><svg t="1644397862160" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="3095" width="64" height="64"><path d="M298.666667 247.04V682.666667a42.666667 42.666667 0 0 1-85.333334 0V170.666667a42.666667 42.666667 0 0 1 65.024-36.352l554.666667 341.333333a42.666667 42.666667 0 0 1 0 72.704l-554.666667 341.333333a42.666667 42.666667 0 0 1-44.714666-72.704L729.258667 512 298.666667 247.04z" p-id="3096" fill="#ffffff"></path></svg></button>'

        el.appendChild(
          TCPlayer.dom.createEl('div', {
            className: 'vjs-button-icon',
            innerHTML: _html
          })
        )
        return el
      }
      videoItem.value = TCPlayer(videoID, {
        appID: '',
        controls: true
      }) // player-container-id 为播放器容器 ID，必须与 html 中一致
      if (videoItem.value) {
        videoItem.value.src(src.value) // url 播放地址
        videoItem.value.poster(poster.value || '')

        videoItem.value.on('play', () => {
          emit('play')
        })

        // 初步加载时
        // videoItem.value.one('loadedmetadata', () => {
        //   console.log(' Loading metadata');
        // });

        // 视频播放时加载
        // videoItem.value.on('timeupdate', () => {
        // });

        // 视频播放结束
        videoItem.value.on('ended', () => {
          emit('ended')
        })
      }
    })
    return () => (
      <div class={styles.videoWrap}>
        <video
          style={{ width: '100%', height: '100%' }}
          src={src.value}
          ref={videoRef}
          id={videoID}
          preload="auto"
          playsinline
          webkit-playsinline
        ></video>
      </div>
    )
  }
})
