import { defineComponent, nextTick, onMounted, reactive, 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'

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) : []
    const forms = reactive({
      coverImg: route.query.coverImg,
      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 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)
    }

    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>
          </div>
        </div>
        <div class={styles.videoCount}>
          <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>

          <Button class={styles.submitBtn} onClick={onSubmit}></Button>
        </div>
      </div>
    )
  }
})
