import { defineComponent, onMounted, reactive, toRefs, watch } from 'vue'
import { ref } from 'vue'
import styles from './index.module.less'

import iconLoop from '../../image/icon-loop.svg'
import iconLoopActive from '../../image/icon-loop-active.svg'
import iconplay from '../../image/icon-play.svg'
import iconpause from '../../image/icon-pause.svg'
import { NSlider } from 'naive-ui'
import { getSecondRPM } from '@/helpers/utils'

export default defineComponent({
  name: 'video-play',
  props: {
    item: {
      type: Object,
      default: () => {
        return {}
      }
    },
    pageVisibility: {
      type: String,
      default: ''
    },
    show: {
      type: Boolean,
      default: false
    },
    showModel: {
      type: Boolean,
      default: false
    },
    isEmtry: {
      type: Boolean,
      default: false
    }
  },
  emits: ['loadedmetadata', 'togglePlay', 'ended', 'reset', 'close', 'error'],
  setup(props, { emit, expose }) {
    const videoItem = ref()
    const { item, isEmtry } = toRefs(props)
    const data = reactive({
      timer: null as any,
      currentTime: 0,
      duration: 0,
      loop: false,
      playState: 'pause' as 'play' | 'pause',
      vudio: null as any,
      reload: false
    })
    const contetRef = ref()

    // watch(
    //   () => props.show,
    //   () => {
    //     onToggleAudio('pause')
    //   }
    // )

    let playTimer = null as any
    // 切换音频播放
    const onToggleAudio = (state: 'play' | 'pause') => {
      clearTimeout(playTimer)
      if (state === 'play') {
        playTimer = setTimeout(() => {
          videoItem.value?.play()
          data.playState = 'play'
        }, 100)
      } else {
        videoItem.value?.pause()
        data.playState = 'pause'
      }
      emit('togglePlay', data.playState)
    }

    /** 改变播放时间 */
    const handleChangeTime = (val: number) => {
      data.currentTime = val
      clearTimeout(data.timer)
      data.timer = setTimeout(() => {
        videoItem.value.currentTime = val;
        data.timer = null;
      }, 300)
    }

    const handleLoadedmetadata = () => {
      data.reload = false
      // 获取时长
      data.duration = videoItem.value.duration()

      emit('loadedmetadata', videoItem.value)
    }
    const onTimeupdate = () => {
      if (data.timer) return
      data.currentTime = videoItem.value.currentTime()
    }
    const onEnded = () => {
      data.playState = 'pause'
      emit('ended')
    }
    const onPaused = () => {
      data.playState = 'pause'
    }
    const onPlaying = () => {
      data.playState = 'play'
    }
    return () => (
      <div class={styles.videoWrap}>
        <div class={styles.content}>
          <div ref={contetRef} class={styles.contentWrap}>
            <video
              ref={videoItem}
              style={{ width: '100%', height: '100%' }}
              poster={props.item.coverImg}
              src={isEmtry.value ? '' : item.value.content}
              preload="auto"
              playsinline
              webkit-playsinline
              onLoadedmetadata={handleLoadedmetadata}
              onTimeupdate={onTimeupdate}
              onEnded={onEnded}
              onPause={onPaused}
              onPlaying={onPlaying}
            ></video>
          </div>
          <div class={styles.videoSection}></div>
        </div>

        <div
          class={[styles.controls, props.showModel ? '' : styles.hide]}
          onClick={(e: Event) => {
            e.stopPropagation()
          }}
          onTouchmove={(e: TouchEvent) => {
            emit('close')
          }}
        >
          <div class={styles.time}>
            <div>{getSecondRPM(data.currentTime)}</div>
            <div>{getSecondRPM(data.duration)}</div>
          </div>
          <div class={styles.slider}>
            <NSlider
              tooltip={false}
              step={0.01}
              class={styles.timeProgress}
              value={data.currentTime}
              max={data.duration}
              onUpdate:value={(val) => handleChangeTime(val)}
            />
          </div>
          <div class={styles.actions} onClick={() => emit('close')}>
            <div
              class={styles.actionBtn}
              onClick={() => onToggleAudio(data.playState === 'pause' ? 'play' : 'pause')}
            >
              <img src={data.playState === 'pause' ? iconplay : iconpause} />
            </div>
            <div class={styles.actionBtn} onClick={() => (data.loop = !data.loop)}>
              <img src={data.loop ? iconLoopActive : iconLoop} />
            </div>
          </div>
        </div>
      </div>
    )
  }
})
