import React from 'react';
import ReactDOM from 'react-dom';
import CloudPlate from './components/CloudPlate';
import style from './App.less';

// import pubsub from 'pubsub-js'

class App extends React.Component {
  constructor(props) {
    super(props);
    this.jessibuca = null;
    this.outTime = null;
    this.showOperateBtns = true;
    this.$container = null;
    this.forceNoOffscreen = false;
    this.domRef = React.createRef();

    this.state = {
      isPlaying: false,
      isShowControl: false,
      dataRate: props?.VideoInfo?.dataRate === 'Sub' ? '标清' : '高清',
    };
  }
  createAll() {
    let { VideoInfo, JessibucaObj } = this.props;
    this.destroy();
    if (VideoInfo.url) {
      this.create(this.refs[`myVideo` + VideoInfo.id], `key`, JessibucaObj);
      setTimeout(() => {
        let code = window.independence ? window.siteCode : window.globalConfig?.userInfo?.site;
        let siteInfo = !code ? '' : `?_site=${code}`;
        this.play(VideoInfo.url + `/${VideoInfo.dataRate == 'Sub' ? 2 : 1}${siteInfo}`, `key`);
      }, 10);
    }
  }
  componentDidMount() {
    this.createAll();

    this.jessibuca.on('pause', function (data) {
      // console.log('pause:', data);
    });
  }
  componentWillUnmount() {
    this.destroy();
  }
  create(dom, key, obj) {
    if (this.jessibuca) this.jessibuca.destroy();

    let jsc = {
      videoBuffer: 0.2, // 缓存时长
      isResize: false,
      text: '',
      isFlv: false,
      debug: false,
      recordType: 'mp4',
      loadingTimeout: 10,
      loadingText: '视频加载中',
      loadingTimeoutReplay: true,
      loadingTimeoutReplayTimes: -1,
      timeout: 10,
      controlAutoHide: true,
      heartTimeout: 10,
      heartTimeoutReplay: true,
      heartTimeoutReplayTimes: -1,
      showBandwidth: true, // 显示网速
      operateBtns: {
        fullscreen: true,
        screenshot: true,
        play: true,
        record: true,
        audio: true,
      },
      isNotMute: false,
    };
    jsc = {
      ...jsc,
      ...obj,
      container: dom,
    };
    if (dom) {
      this.jessibuca = new window.Jessibuca(jsc);
      this.jessibuca.on("error", (error) => {
        if (error === 'fetchError' || error === 'websocketError') {
          // 这里统一的做重连
          this.outTime = setTimeout(() => {
            this.jessibuca.pause().then(()=>{
              this.jessibuca.play().then().catch((e)=>{
              })
            })
          }, 5000);
        }
      })
    }
  }

  play(url, key) {
    if (this.jessibuca) {
      this.jessibuca.play(url);
      this.setState({
        isPlaying: true,
      });
      this.jessibuca.on("start", () => {
        this.appendControl();
        this.appendDataRate();
      })
    }
  }

  pause() {
    if (this.jessibucaArr) {
      debugger;
      for (let key in this.jessibucaArr) {
        this.jessibucaArr[key].pause();
      }
      this.setState({
        isPlaying: false,
      });
    }
  }

  destroy() {
    if (this.jessibuca) {
      this.jessibuca.destroy();
      this.setState({
        isPlaying: false,
      });
    }
    if (this.outTime) {
      clearTimeout(this.outTime);
      this.outTime = null;
    }
  }

  appendControl() {
    const { VideoInfo } = this.props;
    const type = VideoInfo?.type || '';
    if(type === 'rec') return false;
    try {
      if(!this.domRef.current || this.domRef.current.getElementsByClassName('jessibuca-control').length) return false;
      const parentElement = this.domRef.current.getElementsByClassName("jessibuca-controls-right")[0];
      const childElement = document.createElement("div");
      childElement.className = 'jessibuca-control';
      const childChildElement = document.createElement("i");
      childElement.addEventListener("click", () => {
        // 点击 childElement 时触发的代码  
        this.setState({ isShowControl: !this.state.isShowControl });
      });
      // 将子元素添加到子元素的子元素中  
      parentElement.insertBefore(childElement, parentElement.firstChild);
      childElement.appendChild(childChildElement);
    } catch (err) {}
  }

  appendDataRate() {
    const { VideoInfo } = this.props;
    const type = VideoInfo?.type || '';
    if(type === 'rec') return false;
    try {
      if(!this.domRef.current || this.domRef.current.getElementsByClassName('jessibuca-datarate').length) return false;
      const parentElement = this.domRef.current.getElementsByClassName("jessibuca-controls-right")[0];
      const childElement = document.createElement("div");
      childElement.className = `jessibuca-datarate ${this.state.dataRate === '高清' ? 'jessibuca-datarate-hd' : ''}`; 
      parentElement.insertBefore(childElement, parentElement.firstChild);
      ReactDOM.render(<><span>高清</span><span>标清</span></>, childElement);
      childElement.addEventListener("click", (e) => {
        const text = e.target.innerText;
        switch (text) {
          case '高清':
            if(this.state.dataRate !== '高清') {
              this.setState({dataRate: '高清'});
              e.currentTarget.className = 'jessibuca-datarate jessibuca-datarate-hd';
              this.changeRate(text);
            }
            break;
          case '标清':
            if(this.state.dataRate !== '标清') {
              this.setState({dataRate: '标清'});
              e.currentTarget.className = 'jessibuca-datarate';
              this.changeRate(text);
            }
            break;
          default:
            break;
        }
      });
    } catch (err) {}
  }

  changeRate(text) {
    const { VideoInfo } = this.props;
    if (VideoInfo.url && this.jessibuca) {
      let code = window.independence ? window.siteCode : window.globalConfig?.userInfo?.site;
      let siteInfo = !code ? '' : `?_site=${code}`;
      this.jessibuca.play(VideoInfo.url + `/${text == '标清' ? 2 : 1}${siteInfo}`);
      this.setState({
        isPlaying: true,
      });
    }
  }

  closeCloudPlate() {
    this.setState({
      isShowControl: false,
    })
  }

  renderCheckedArr() {
    let { VideoInfo } = this.props;
    const { isShowControl } = this.state;
    return (
      <div className={style.containerOut}>
        {<div className={style.container} key={VideoInfo.id} ref={`myVideo` + VideoInfo.id}>
          {isShowControl && <CloudPlate videoInfo={VideoInfo} onClose={() => this.closeCloudPlate()} />}
        </div>}

      </div>
    );
  }
  render() {
    return <div className={style.root} ref={this.domRef}>{this.renderCheckedArr()}</div>;
  }
}

export default App;
