import { defineComponent, nextTick, onMounted, onUnmounted, reactive, ref, watch } from 'vue'
import styles from '../video.module.less'
import { Button } from 'vant'
import { browser } from '@/helpers/utils'
// import Plyr from 'plyr'
// import 'plyr/dist/plyr.css'
import { useRoute } from 'vue-router'
import deepClone from '@/helpers/deep-clone'
import TCPlayer from 'tcplayer.js'
import 'tcplayer.js/dist/tcplayer.css'

export default defineComponent({
  name: 'pre-register',
  emits: ['tabChange'],
  setup(props, { emit }) {
    const route = useRoute()
    const video = route.query.v ? JSON.parse(route.query.v as any) : []
    console.log(route.query, 'query')
    const forms = reactive({
      coverImg: route.query.coverImg,
      videoID: 'video' + Date.now() + Math.floor(Math.random() * 100),
      introductionVideo: route.query.introductionVideo as any,
      id: null as any,
      videoDetails: deepClone(video),
      player: null as any,
      currentTime: 0
    })

    /**
     * 视屏累计时长
     * 1、视屏开始播放时-开始计时
     * 2、视频暂停时暂停-停止计时
     * 3、视频加载时-停止计时
     * 4、视频倍数播放时，时间正常计时
     * 5、点击视频进度或拖动进度时，时间暂停
     */
    const _init = () => {
      // const controls = [
      //   'play-large',
      //   'play',
      //   'progress',
      //   'captions',
      //   'current-time',
      //   'duration',
      //   'settings',
      //   'fullscreen'
      // ]
      // const params: any = {
      //   controls: controls,
      //   settings: ['speed'],
      //   speed: { selected: 1, options: [0.5, 1, 1.5, 2] },
      //   i18n: {
      //     speed: '速度',
      //     normal: '默认'
      //   },
      //   invertTime: false
      // }

      // if (browser().iPhone) {
      //   params.fullscreen = {
      //     enabled: true,
      //     fallback: 'force',
      //     iosNative: true
      //   }
      // }

      // const times: any = []
      // deepClone(forms.videoDetails).forEach((item: any) => {
      //   times.push({
      //     time: item.startNode,
      //     label: item.desc
      //   })
      // })
      // params.markers = { enabled: true, points: times }

      // forms.player = new Plyr('#register-video', params)

      // forms.player.on('loadedmetadata', () => {
      //   checkVideoDetails(forms.player.currentTime)
      // })

      // // 如何视频在缓存不会触发
      // forms.player.on('timeupdate', (e: any) => {
      //   // 时间变化时更新每一段的状态
      //   console.log(forms.player.currentTime, 'forms.player.currentTime', e)
      //   checkVideoDetails(forms.player.currentTime)
      // })

      // forms.player.on('enterfullscreen', () => {
      //   console.log('fullscreen')
      //   const i = document.createElement('i')
      //   i.id = 'fullscreen-back'
      //   i.className = 'van-icon van-icon-arrow-left video-back'
      //   i.addEventListener('click', () => {
      //     forms.player.fullscreen.exit()
      //   })
      //   console.log(document.getElementsByClassName('plyr'))
      //   document.getElementsByClassName('plyr')[0].appendChild(i)
      // })

      // forms.player.on('exitfullscreen', () => {
      //   console.log('exitfullscreen')
      //   const i = document.getElementById('fullscreen-back')
      //   i && i.remove()
      // })
      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 width="41px"height="41px"viewBox="0 0 41 41"version="1.1"xmlns="http://www.w3.org/2000/svg"xmlns:xlink="http://www.w3.org/1999/xlink"><g stroke="none"stroke-width="1"fill="none"fill-rule="evenodd"><g transform="translate(-167.000000, -155.000000)"><g transform="translate(0.000000, 85.000000)"><g transform="translate(158.000000, 70.000000)"><g transform="translate(9.000000, 0.000000)"><circle id="椭圆形"stroke="#FFFFFF"fill-opacity="0.1"fill="#D8D8D8"cx="20.5"cy="20.5"r="20"></circle><path d="M14.5483871,27.6859997 L14.5483871,13.4342349 C14.5480523,12.8729571 14.8729597,12.356555 15.3949624,12.0887034 C15.9169651,11.8208518 16.5522696,11.8445472 17.0503046,12.1504437 L28.6530473,19.2778563 C29.1119763,19.5602271 29.3887725,20.0426422 29.3887725,20.5601173 C29.3887725,21.0775924 29.1119763,21.5600075 28.6530473,21.8423783 L17.0503046,28.9697909 C16.5522696,29.2756874 15.9169651,29.2993828 15.3949624,29.0315312 C14.8729597,28.7636796 14.5480523,28.2472775 14.5483871,27.6859997 Z"id="路径"fill="#FFFFFF"fill-rule="nonzero"></path></g></g></g></g></g></svg></button>'

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

        forms.player.on('loadedmetadata', () => {
          checkVideoDetails(forms.player.currentTime())
        })

        // 如何视频在缓存不会触发
        forms.player.on('timeupdate', (e: any) => {
          // 时间变化时更新每一段的状态
          console.log(forms.player.currentTime(), 'forms.player.currentTime()', e)
          checkVideoDetails(forms.player.currentTime())
        })

        forms.player.on('fullscreenchange', () => {
          if (forms.player.isFullscreen()) {
            console.log('fullscreen')
            const i = document.createElement('i')
            i.id = 'fullscreen-back'
            i.className = 'van-icon van-icon-arrow-left video-back'
            i.addEventListener('click', () => {
              forms.player.exitFullscreen()
            })
            document.getElementsByClassName('video-js')[0].appendChild(i)
          } else {
            console.log('exitfullscreen')
            const i = document.getElementById('fullscreen-back')
            i && i.remove()
          }
        })
      }
    }

    const checkVideoDetails = (time: number) => {
      forms.videoDetails.forEach((item: any) => {
        if (item.startNode <= time && time <= item.endNode) {
          forms.id = item.id
        }
      })
    }
    onMounted(() => {
      nextTick(() => {
        _init()
      })
    })

    const onSubmit = () => {
      // emit('tabChange', 3)
    }

    const messageContent = ref('')
    const registerDisplay = ref()

    const getMessage = (ev: any) => {
      if (ev.data.api === 'parent-notes') {
        console.log(ev.data, 'data')
        messageContent.value = ev.data.message || ''
        registerDisplay.value = ev.data.registerDisplay || false
      }
    }
    onMounted(() => {
      nextTick(() => {
        // 是否加载完成
        window.parent &&
          window.parent.postMessage(
            {
              api: 'onLoad',
              status: true
            },
            '*'
          )
      })

      window.addEventListener('message', getMessage)
    })

    onUnmounted(() => {
      window.removeEventListener('message', getMessage)
    })
    return () => (
      <div class={styles['pre-register-video']}>
        <div class={styles.videoContainer}>
          <div class={styles['video-content']}>
            {/* <video
              id="register-video"
              class={styles['video']}
              src={forms.introductionVideo}
              playsinline={true}
              poster={forms.coverImg as any}
              preload="auto"
            ></video> */}
            <img src={forms.coverImg as any} class={styles.coverImg} />
          </div>
        </div>
        <div class={styles.videoCount}>
          <div class={styles.videoTitle}></div>
          <div class={styles.videoCountContent}>
            {forms.videoDetails.map((item: any) => (
              <span
                class={[item.id === forms.id ? styles.active : '']}
                onClick={() => {
                  forms.player.currentTime(item.startNode)
                }}
              >
                {item.desc}
              </span>
            ))}
          </div>
        </div>
        <div class={styles.messageContainer}>
          <div class={styles.messageContent}>
            {/* <p>家长您好！</p>
            <p class={styles.c1}>
              请家长们合理安排时间，<span>认真观看</span>家长会内容。在<span>详细了解</span>
              所有要求后，有意向让孩子加入乐团的家长，请在<span>明晚20:00前</span>，为孩子完成
              <span>乐团报名</span>
            </p>
            <p class={styles.c1}>
              下周，专业老师将针对意向入团学员进行身体条件确认。谢谢各位的支持！
            </p>
            <p class={styles.bottom}>
              注：乐团于下学期正式开始训练，训练时间下 学期开学前另行通知，训练时间会与学校其他
              社团错开，家长无需担心时间冲突问题。
            </p> */}
            <div v-html={messageContent.value}></div>
            {registerDisplay.value && <Button class={styles.submitBtn} onClick={onSubmit}></Button>}
          </div>
        </div>
      </div>
    )
  }
})
