/**
 * 视频通话页面
 */
import React, { Component } from "react";
import { connect } from "dva";
import { Icon, Checkbox } from "antd";
import "./index.less";
import RreactDom from 'react-dom';
import moment from "moment";
import BoxTool from "./BoxTool";
import MouseMovement from "../../../components/MouseMovement"
// import RecordVideo from './recordVideo';
import { initRecordRTC, stopRecord, startRecord, playRecord, downloadRecord } from '../Video/recordRTC';
import classNames from 'classnames';

@connect((state) => ({
  ownCid: state.im.v5Data.ownCid,
  videoMember: state.command.videoMember,
  videoType: state.command.videoType, // 布局类型 0: 九宫格 1: 右侧列表   2: 顶部列表   3: 十六宫格  4: 二十五宫格
  videoGenre: state.command.videoGenre, // 功能类型 0: 视频调度(一对多) 1: 视频上拉(一对一)
}))

export default class VideoBox extends Component {
  constructor(props) {
    super(props);
    this.state = {
      videoLocal: {
        isDown: false,
        offsetLeft: 0,
        offsetTop: 0,
      },
      isFullScreen: false,
      currentTime: "",
      toolTime: "", //处理刷新问题
      toolStatus: {
        mute: false,
        video: false,
        record: false,
        add: false,
        close: false,
        share: false,
      },
      canCamera: false,
      canMic: false,
      videoList: [1, 2, 3, 4, 5, 6, 7, 8, 9],
      mainVideo: "",
      videoMember: [],
      currentVideoNo: 0,
      isMainChecked: true,
      beforeCheckVideo: {},
      boxToolStyle: classNames("box-tool", "box-tool-default"),
    };
  }
  componentWillReceiveProps(nextProps) {
    if ( JSON.stringify(nextProps.videoMember) !== JSON.stringify(this.state.videoMember) ) {
      console.log("VideoBox");
      this.setState({
        videoMember: nextProps.videoMember,
      })
    }
  }

  componentDidMount() {
    const that = this;
    // 判断麦克风和摄像头是否可用
    TRTC.getCameras().then(res=>{
      console.log('getCameras', res)
      if(res.length>0){
        this.setState({
          canCamera: true,
          toolStatus: {
            ...this.state.toolStatus,
            video: false,
          }
        })
      }
    })
    TRTC.getMicrophones().then(res=>{
      console.log('getMicrophones', res)
      if(res.length>0){
        if (this.state.videoGenre != 0) {
          this.setState({
            canMic: true,
            toolStatus: {
              ...this.state.toolStatus,
              mute: true,
            }
          })
        } else {
          this.setState({
            canMic: true,
            toolStatus: {
              ...this.state.toolStatus,
              mute: false,
            }
          })
        }
      }
    })
    if (this.state.videoGenre != 0) {
      this.setState({
        toolStatus: {
          ...this.state.toolStatus,
          mute: true,
        }
      })
    }
    setInterval(() => {
      this.getCurrentTime()
    }, 1000)
    // initRecordRTC();
    setTimeout(()=>{
      that.setState({
        boxToolStyle: "box-tool"
      })
    }, 3700)
  }
  getCurrentTime() {
    let date = moment().format("YYYY-MM-DD");
    let time = moment().format("HH:mm:ss");
    let week = moment().day()
    switch (week) {
      case 1:
        week = '星期一';
        break;
      case 2:
        week = '星期二';
        break;
      case 3:
        week = '星期三';
        break;
      case 4:
        week = '星期四';
        break;
      case 5:
        week = '星期五';
        break;
      case 6:
        week = '星期六';
        break;
      case 0:
        week = '星期日';
        break;
    }
    this.setState({
      currentTime: `${date} ${week} ${time}`,
    })
  }
  switchVideoTool = (name) => {
    let { toolStatus } = this.state;
    toolStatus[name] = !toolStatus[name];
    this.setState({
      toolStatus,
      toolTime: moment().format('x')
    })
  }
  setScreen = () => {
    const { isFullScreen } = this.state
    let boxs = document.getElementById("video-boxs")
    boxs.style.left = `50vw`
    boxs.style.top = `50vh`
    this.setState({
      isFullScreen: !isFullScreen,
    })

  }
  onScrollVideo=(type)=>{
    const { videoType } = this.props;
    let { videoMember, currentVideoNo, isMainChecked } = this.state;
    let videoLen = videoMember.length;
    if (videoType == 0 && videoMember.length > 9 || videoType == 3 && videoMember.length > 16 || videoType == 4 && videoMember.length > 25) {
      videoLen = videoType == 0 ? 8 : videoType == 3 ? 15 : 24
      if (type == 'before' && currentVideoNo != 0) {
        currentVideoNo = currentVideoNo - videoLen < 0 ? 0 : currentVideoNo - videoLen;
      } else if(type == 'after'){
        currentVideoNo = videoLen + currentVideoNo >= videoMember.length ? currentVideoNo :  videoLen + currentVideoNo;
      }
    }
    console.log('currentVideoNo', currentVideoNo);

    this.setState({
      currentVideoNo
    })
  }
  onChangeVideo=(video)=>{
    console.log('onChangeVideo', video);
    const { beforeCheckVideo } = this.state;
    if (beforeCheckVideo.id) {
      this.props.dispatch({
        type:'command/fetchVideoMemberList',
        payload:{
          type:'peerJoin',
          memberList:{
            videoId: beforeCheckVideo.videoId,
            hasVideo: beforeCheckVideo.hasVideo,
            userName: beforeCheckVideo.userName,
            mobilePhone: beforeCheckVideo.mobilePhone,
            checked: false,
            status: beforeCheckVideo.status,
            id: beforeCheckVideo.id
          }
        }
      })
    }
    if (video == 'main') {
      this.setState({
        isMainChecked: true
      })
    } else {
      this.setState({
        beforeCheckVideo: video,
        isMainChecked: false
      })
      this.props.dispatch({
        type:'command/fetchVideoMemberList',
        payload:{
          type:'peerJoin',
          memberList:{
            videoId: video.videoId,
            hasVideo: video.hasVideo,
            userName: video.userName,
            mobilePhone: video.mobilePhone,
            checked: true,
            status: video.status,
            id: video.id
          }
        }
      })
    }
  }
  renderVideoList = () => {
    const { videoList, currentVideoNo, videoMember, isMainChecked } = this.state;
    const { _videoThis, videoType, videoGenre } = this.props;
    let hasShowOption = false;
    let videoingList = videoMember.filter(function(video, index){
      return video.status != "fail"
    });
    videoingList = videoingList.filter(function(video, index){
      return video.status != "no"
    });
    console.log('videoingList', videoingList);
    let videoLen = videoingList.length;
    let currentVideoList = [];
    if (videoType == 0 && videoingList.length > 9 || videoType == 3 && videoingList.length > 16 || videoType == 4 && videoingList.length > 25) {
      hasShowOption = true
      videoLen = videoType == 0 ? 8 : videoType == 3 ? 15 : 24
      if (currentVideoNo > 0) {
        currentVideoList = videoingList.filter(function(item, index){
          return (index >= currentVideoNo && index < currentVideoNo + videoLen)
        });
      } else {
        currentVideoList = videoingList.filter(function(item, index){
          return (index < videoLen)
        });
      }
    } else {
      currentVideoList = videoingList;
    }
    const hasVideoScheduling = videoGenre == 0 ? true : false;
    if (!hasVideoScheduling) {
      videoLen = 0
    }
    const clsString = classNames("col-div", "video-main", "video-container", isMainChecked ? "video-box-checked" : "", hasVideoScheduling ? "" : 'video-main-hidden');
    return (
      <div id="div-video-child" className={`video-layout${videoType} video-layout${videoType}-${videoLen}`} >
        <div id="div-video-local" className={clsString} onClick={this.onChangeVideo.bind(this, 'main')}>
          <div id="main-video" style={{ width: '100%', height: '100%' }} >
            {/* <!-- 主视频控制按钮 --> */}
            <div
              id="main-video-btns"
              className="row-div"
              style={{
                width: "156px",
                position: "absolute",
                zIndex: 10,
                justifyContent: "center",
                alignSelf: "flex-end",
                right: "0",
                bottom: "0",
              }}
            >

            </div>
            <div className="video-name">我</div>
            <div
              id="mask_main"
              className="mask col-div"
              style={{ display: "none" }}
            >
              {/* <!-- “如果摄像头未开启”遮罩 --> */}
              <img
                style={{ width: "63px", height: "69px", zIndex: 10 }}
                src={require("../../../assets/images/prevention/camera-max.png")}
                alt=""
              />
              <div style={{ height: "10px" }}></div>
              <div style={{ zIndex: 10 }}>摄像头未打开</div>
            </div>
            {/* <div className="video-name2">我</div> */}
          </div>
        </div>
        {
          hasShowOption ? <div className="video-option-left" onClick={this.onScrollVideo.bind(this, 'before')}>{"<"}</div> : null
        }
        {
          hasShowOption ? <div className="video-option-right" onClick={this.onScrollVideo.bind(this, 'after')}>{">"}</div> : null
        }
        {
          currentVideoList.map((video, i)=>{
            console.log('currentVideoList', video);
            const statusText = video.status == "no" ? "正在调度" : "摄像头未打开"
            const clsStr = classNames("video-box", "video-container", video.checked ? "video-box-checked" : "");
            return <div className={clsStr} id={video.videoId} onClick={this.onChangeVideo.bind(this, video)}>
              {
                !video.hasVideo ?
                <div
                  id={"mask_"+video.videoId}
                  className="mask col-div"
                >
                  {/* <!-- “如果摄像头未开启”遮罩 --> */}
                  <img
                    style={{ width: "63px", height: "69px", zIndex: 10 }}
                    src={require("@assets/images/prevention/camera-max.png")}
                    alt=""
                  />
                  <div style={{ height: "10px" }}></div>
                  <div style={{ zIndex: 10 }}>{ statusText }</div>
                </div>:null
              }
              <div className="video-name">
                {
                  video.hasVideo ?
                  <div>
                    <img src={require("@assets/images/prevention/camera-on.png")} />
                  </div> :
                  <div>
                  <img src={require("@assets/images/prevention/camera-off.png")} />
                </div>
                }
                {video.userName}
              </div>
            </div>
          })
        }
      </div>
    )
  }
  onMouseDown=()=>{
    const { isFullScreen } = this.state;
    if (isFullScreen) {
      return;
    }
    this.setState({
      videoLocal: {
        isDown: true,
        offsetLeft: document.getElementsByClassName('video-boxs')[0].offsetLeft,
        offsetTop: document.getElementsByClassName('video-boxs')[0].offsetTop
      }
    })
  }
  onMouseUp=()=>{
    const { isFullScreen } = this.state;
    if (isFullScreen) {
      return;
    }
    this.setState({
      videoLocal: {
        ...this.state.videoLocal,
        isDown: false,
      }
    })
  }
  render() {
    const { toolStatus, currentTime, isFullScreen,canCamera,canMic, boxToolStyle, recordStatus } = this.state;
    // console.log('canCamera', canCamera)
    // console.log('canMic', canMic)
    // console.log('videoMember', this.props);
    const { common, videoType, addMember, dissolutionRoomModal, videoSize, videoGenre } = this.props;
    const displayNode = videoSize != 2 ? 'none' : 'block';
    let videoWidth = isFullScreen ? "100%" : "70%";
    let videoHeight = isFullScreen ? "100%" : "85%";
    const hasVideoScheduling = videoGenre == 0 ? true : false;
    if (!hasVideoScheduling) {
      videoWidth = '375px';
      videoHeight = '667px';
    }

    return (
      <MouseMovement
        isDown={this.state.videoLocal.isDown}
        offsetLeft={this.state.videoLocal.offsetLeft}
        offsetTop={this.state.videoLocal.offsetTop}
      >
        {({ x, y, cursor = 'move' }) => (
          <div id="video-boxs" className="video-boxs" ref="video-boxs" style={{
            // width: "70%",
            // position: 'absolute',
            top: y == 0 ? '50%' : y,
            left: x == 0 ? '47%' : x,
            width: videoWidth,
            height: videoHeight,
            display: displayNode
            // top: '50%',
            // left: '50%'
          }}
            onMouseDown={this.onMouseDown.bind(this)}
            onMouseUp={this.onMouseUp.bind(this)}
          >
            {/* <div className="video-boxs"> */}
            {
              hasVideoScheduling ? <div className="box-header" style={{
                cursor: isFullScreen ? '' : 'move'
              }}>
                <div>{currentTime}</div>
                <Icon className="icon" style={{ margin: "0 16px" }} onClick={this.setScreen} type={isFullScreen ? "fullscreen-exit" : "fullscreen"} />
                <Icon className="icon" type="close" onClick={this.props.dissolutionRoomModal} />
              </div> : null
            }
            <div id="video-content" className="video-content">
              <div id="room-root" className="col-div">
                {/* <!-- content --> */}
                <div
                  className="row-div"
                  style={{
                    height: "100%",
                    width: "100%",
                    display: " flex",
                    alignItems: "center",
                  }}
                >
                  <div
                    className="col-div"
                    style={{
                      width: "340px",
                      height: "100%",
                      padding: "10px",
                      display: "none",
                    }}
                  >
                    <div
                      className="col-div card"
                      style={{ width: "100%", height: "100%" }}
                    >
                      <div
                        id="member-list"
                        className="col-div"
                        style={{
                          width: "100%",
                          justifyContent: "flex-start",
                          flex: 1,
                        }}
                      >
                        <div
                          id="member-me"
                          style={{ width: "100%", paddingLeft: "20px" }}
                        >
                          <div
                            className="row-div member"
                            style={{
                              width: "100%",
                              height: "50px",
                              justifyContent: "space-between",
                            }}
                          >
                            <div className="member-id">(我)</div>
                            <div
                              className="row-div"
                              style={{
                                width: "100%",
                                height: "27px",
                                justifyContent: "center",
                                display: "flex",
                                alignItems: "center",
                              }}
                            >
                              <img
                                className="member-video-btn"
                                style={{ height: "100%" }}
                                src={require("../../../assets/images/prevention/camera-on.png")}
                                alt=""
                              />
                              <div style={{ width: 18 }}></div>
                              <img
                                className="member-audio-btn"
                                style={{ height: "100%" }}
                                src={require("../../../assets/images/prevention/mic-on.png")}
                                alt=""
                              />
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                  {/* <!-- 视频网格 --> */}
                  <div id="remote-video-wrap" style={{ height: "100%", flex: 1 }}>
                    {/* <!-- 主视频 --> */}
                    {
                      this.renderVideoList()
                    }
                  </div>
                </div>
              </div>
            </div>
            {/* 工具栏 */}
            <BoxTool boxToolStyle={boxToolStyle} switchVideoTool={this.switchVideoTool.bind(this)} canMic={canMic} canCamera={canCamera} addMember={addMember} common={common} dissolutionRoomModal={dissolutionRoomModal} toolStatus={toolStatus} />
            {/* </div> */}
          </div>
        )}
      </MouseMovement>

    );
  }
}
