import React, { useCallback, useEffect, useRef, useState } from 'react'
import styles from './index.module.scss'
import { baseURL, myData } from '@/utils/http'
import history from '@/utils/history'

function A1home() {
  const [videoOk, setVideoOk] = useState(false)
  const [loadOk, setLoadOk] = useState(false)
  const [progress, setProgress] = useState(0)

  const playerRef = useRef<any>(null)
  useEffect(() => {
    const params = {
      objectFit: 'cover', // 视频的object-fit样式, 默认 cover
      loop: false, // 是否循环, 默认false
      autoplay: false, // 自动播放, 默认false
      onPlay: () => { }, // 触发播放事件
      onPause: () => { }, // 触发暂停事件
      onEnded: () => {
        history.push('/base')
      }, // 触发播放结束事件
      onSourceEstablished: () => {
        setVideoOk(true)
      } //有足够的数据可以播放了
    }
    playerRef.current = F_Video('./myData/play.ts', params)
    const dom = document.querySelector('.A1video')!
    dom.append(playerRef.current.domElement)
  }, [])

  const timeRR = useRef(-1)
  useEffect(() => {
    if (videoOk) {
      if (progress === 98) setProgress(100)
      clearInterval(timeRR.current)
      timeRR.current = window.setInterval(() => {
        if (loadOk) {
          console.log('播放视频')
          playerRef.current.play()
          clearInterval(timeRR.current)
          return
        }
      }, 50)
    }
  }, [loadOk, progress, videoOk])

  const enter = useCallback(() => {
    if (progress === 100) setLoadOk(true)
  }, [progress])

  window.LoadingProgress = (progress: number) => {
    console.log('当前进度', progress)
    if (progress >= 98) {
      setProgress(98)
      return
    }
    setProgress(progress)
  }

  return (
    <div className={styles.A1home}>
      <div
        className='loadingP'
        style={{ display: loadOk ? 'none' : 'flex' }}
        onClick={() => window.LoadingProgress(progress + 20)}
      >
        <div className='btn' onClick={() => enter()}></div>
        <div className='progress'>加载{progress}%...</div>
      </div>
      {/* ------------微信浏览器不让视频自动播放，用ts的方式*/}
      <div className='A1videoBox'>
        <div className='A1video' style={{ opacity: 1 }}></div>
      </div>
    </div>
  )
}

const MemoA1home = React.memo(A1home)

export default MemoA1home
