'use strict';

import React from 'react';
import { observer } from 'mobx-react';
import './videopop.less';
import VideoPlayer from '../VideoPlayer/VideoPlayer';
import modalStore from '@src/store/modal';
import { Button } from '../Button';

@observer
class Videopop extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isPlay: false,
      countdownTime: 10, // 单位s
    }
    this.videoRef = React.createRef();
    this.timer = ''
  }

  componentDidMount() {
  }

  componentWillUnmount() {
    if (this.timer) clearInterval(this.timer)
  }

  playVideo = () => {
    this.startInterval()
    this.setState({
      isPlay: true
    })
    this.player?.play();
  }

  /** 开始倒计时 */
  startInterval = () => {
    if (this.timer) clearInterval(this.timer)
    this.timer = setInterval(async () => {
      if (this.state.countdownTime === 0) {
        this.setState({
          isFinish: true
        })
        clearInterval(this.timer)
        this.timer = ''
        // 完成任务
        const { taskSucCb } = this.props?.popData || {}
        taskSucCb && await taskSucCb()
        return
      }
      this.setState({
        countdownTime: this.state.countdownTime - 1,
      })
    }, 1000);
  }

  /** 关闭 */
  closeHandle = () => {
    this.props.popData?.closeCb?.()
    modalStore.closePop();
  }
  render() {
    const { url } = this.props.popData || {}
    const { countdownTime, isPlay, isFinish } = this.state
    return (
      <div className="videopop modal_center">
        <div className="video_box">
          <VideoPlayer
            videoRefCb={r => this.player = r}
            controls
            playsinline
            webkitPlaysinline
            // poster={RES_PATH + 'playPopup/cover.png'}
            preload="none"
            // muted
            sources={[{
              src: url,
              // type: 'video/mp4'
            }]}
            userActions={{
              click: false
            }}
            style={{
              width: '100%',
              height: '100%',
            }} />
          {!isPlay && <span className="play_btn" onClick={this.playVideo}></span>}
        </div>
        {!isFinish && <div className="countdown">{countdownTime}s</div>}
        <Button className="close" onClick={this.closeHandle}></Button>
      </div>
    );
  }
}
export default Videopop;
