import {BaseEventOrig, Video, VideoProps} from "@tarojs/components";
import {HVideoOptions} from "@/components/video/type";
import Taro from "@tarojs/taro";
import {FC, useEffect, useState} from "react";
import unique_ident from "@/hooks/unique_ident";
import videoEvents from "@/hooks/videoEvents";

const deviation: number = 1
const HVideo: FC<HVideoOptions> = (opt: HVideoOptions) => {
  let video: Taro.VideoContext
  const [currentTime, setCurrentTime] = useState(0)

  try {
    video = Taro.createVideoContext('myVideo')
  } catch (e) {
  }

  useEffect(() => {
    videoEvents.onSetVideoState(({name}) => {
      switch (name) {
        case "pause":
          video?.pause()
          break
        case "play":
          video?.play()
          break
      }
    })
  }, [])

  function onTimeUpdate(event: BaseEventOrig<VideoProps.onTimeUpdateEventDetail>) {
    const time = event.detail.currentTime

    /** 前进回退 */
    if (!opt.preview) {
      if (currentTime + deviation < time) {
        video?.seek(currentTime)
        return
      }
    }

    setCurrentTime(time)

    /** 判断是否进入断点 */
    opt.breakpoint.forEach(d => {
      if (time < d + deviation && time > d - deviation) {
        opt.onBreakpoint(d)
      }
    })
  }

  function onEnded() {
    if (currentTime + 1 > opt.duration) {
      opt.onEnded()
      videoEvents.videoState('pause')
    } else {
      video?.seek(currentTime)
      unique_ident.remove()
      video?.play()
    }
  }

  function onPlay() {
    videoEvents.videoState('play')
  }

  function onPause() {
    videoEvents.videoState('pause')
  }

  Taro.useDidHide(() => {
    video?.pause()
    unique_ident.put(Number(currentTime.toFixed(2)), Date.now())
  })


  Taro.useDidShow(() => {
    if (!video) {
      video = Taro.createVideoContext('myVideo')
      if (currentTime && currentTime < opt.duration - deviation) {
        video.play()
      }
    }
  })

  Taro.useUnload(() => {
    unique_ident.put(undefined, currentTime)
    unique_ident.upload().then()
  })


  return (
    <>
      <Video
        id={'myVideo'}
        autoplay
        enablePlayGesture
        autoPauseIfOpenNative
        vslideGestureInFullscreen
        showCenterPlayBtn
        style={{width: '100%', height: '100%', position: "relative"}}
        poster={opt?.poster || ''}
        src={opt.src}
        enableProgressGesture={opt.preview}
        onTimeUpdate={onTimeUpdate}
        onEnded={onEnded}
        onPlay={onPlay}
        onPause={onPause}
        onFullScreenChange={(event) => opt.fullChange((event.target as any).fullScreen)}
      >
        {opt.children}
      </Video>
    </>
  )
}

export default HVideo
