import React from 'react';
import styles from './index.less';
import EZUIKit from 'ezuikit-js';
import flvjs from 'flv.js';
import {Spin} from 'antd';

export default class FlvVideoPlayer extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      loading: true
    };
  }
  componentDidMount() {
    const {playerType} = this.props;
    if (playerType == 0) {
      this.initEzuiVideo();
    } else {
      this.initFlvPlayer();
    }
  }

  listenerPlay = () => {
    this.setState({
      loading: false
    })
  }

  initFlvPlayer = () => {
    const {src} = this.props;
    if (flvjs.isSupported()) {
      const videoElement = document.getElementById('flv-video');
      const flvPlayer = flvjs.createPlayer({
        type: 'flv',
        url: src,
        isLive: true,
        hasAudio: false
      });
      flvPlayer.attachMediaElement(videoElement);
      flvPlayer.load();
      flvPlayer.play();
      videoElement.addEventListener('canplay', this.listenerPlay)
      this.videoElement = videoElement;
      this.player = flvPlayer;
    }
  }

  initEzuiVideo = () => {
    const {src, token} = this.props;

    this.player = new EZUIKit.EZUIKitPlayer({
      id: 'video-container', // 视频容器ID
      accessToken: token,
      url: src,
      audio: 0
    })
    this.player.play()
  }

  componentWillUnmount() {
    this.player && this.player.destroy && this.player.destroy();
    this.videoElement && this.videoElement.removeEventListener
      && this.videoElement.removeEventListener('canplay', this.listenerPlay);
  }

  render() {
    const {loading} = this.state;
    const {playerType} = this.props;

    return (
      <div>
        {+playerType === 0 && <div id="video-container"></div>}
        {+playerType === 1 && <Spin tip="Loading..." spinning={loading}>
          <video id="flv-video" />
        </Spin>}
      </div>
    )
  }
}
