import {Video, View} from "@tarojs/components";
import {FC, useState} from "react";
import Taro from "@tarojs/taro";
import styles from './videoFull.module.scss'
import {brandApi} from "@/api";
import Collect from "@/components/collect/collect";
import Spin from "@/components/spinner";

interface Params {
  id: string
}

const VideoFull: FC = () => {
  const {id} = Taro.useRouter().params as unknown as Params
  const video = Taro.createVideoContext('myVideo')
  const [palying, setpalying] = useState(false)
  const [data, setData] = useState<VideList | null>(null)
  const [enable, setEnable] = useState<boolean>(!Taro.getCurrentInstance().preloadData)

  Taro.useLoad(() => {
    const preloadData: VideList = Taro.getCurrentInstance().preloadData as VideList
    if (preloadData) {
      setData(preloadData)
    }
    brandApi.videoInfo(id).then(res => {
      if (!res?.resource?.url) {
        Taro.showModal({
          title: '加载资源失败',
          confirmText: '退出',
          showCancel: true,
          success() {
            Taro.navigateBack()
          }
        })
      }
      setData(res)
    }).catch(() => {
      if (!preloadData) {
        Taro.showModal({
          title: '加载资源失败',
          confirmText: '退出',
          showCancel: true,
          success() {
            Taro.navigateBack()
          }
        })
      }
    }).finally(() => {
      setEnable(false)
    })
  })

  function click() {
    if (palying) {
      video.pause()
    } else {
      video.play()
    }
  }

  function onError() {
    Taro.showModal({
      title: '视频播放错误',
      confirmText: '退出',
      showCancel: true,
      success() {
        Taro.navigateBack()
      }
    })
  }

  return (
    <View>
      {
        data ? <>
          <Video
            posterSize='100%'
            id={'myVideo'}
            onClick={click}
            className={styles.video}
            controls
            src={data?.resource?.url}
            autoplay
            showCenterPlayBtn
            autoPauseIfOpenNative
            autoPauseIfNavigate
            playBtnPosition='center'
            showFullscreenBtn={false}
            enableProgressGesture={false}
            onPlay={() => setpalying(true)}
            onPause={() => setpalying(false)}
            onError={onError}
          />
          <View className={styles.title}>
            <View className='flex'>
              <View className='font-36 font-weight flex-1 pr-3 text-row1'>{data.title}</View>
              <Collect owner_id={Number(id)} owner_type={2} styles={{color: '#fff'}} select={data.collects}/>
            </View>
            <View className='font-32 mt-1 text-ellipsis-2'>{data.introduction}</View>
          </View>
        </> : <Spin enable={enable} overlay/>
      }

    </View>
  )
}

export default VideoFull
