/**
 * 视频通话页面
 */
import React, { Component } from "react";
import { connect } from "dva";
import { message, Tooltip, Modal, Row, Col, Button, Input } from "antd";
import "./video.less";
import CheckRTC from "./checkRTC";
import "./popper";
import { gup } from '../../../utils/utils';
// import Presetting from './presetting';
import Common from "./common";
// import { imKey } from "../../../utils/config";
import { trtcVideoRoom, getTencentYspSig, searchDeptUser, continueSendVideoRoomMsg } from "../../../services/api";
import $nModal from '../../../utils/modal/nModal';
import RreactDom from 'react-dom';
import VideoBox from "../VideoBox";
import RecordTimer from './RecordTimer';
import RecordMini from "./RecordMini";
import eventCenter from "@common/events";
const { Search } = Input;
const { confirm, warning, success, error } = Modal;

@connect((state) => ({
  ownCid: state.im.v5Data.ownCid,
  ownName: state.im.v5Data.ownName,
  videoMember: state.command.videoMember,
  recordStatus: state.command.recordStatus, // 0：未录制 1：录制中
  videoGenre: state.command.videoGenre, // 功能类型 0: 视频调度(一对多) 1: 视频上拉(一对一)
}))

export default class Video extends Component {
  constructor(props) {
    super(props);
    this.common = Common.call(this);
    this.state = {
      RTC: null,
      Room_No: props.Room_No, //房间号
      // MemberList: props.MemberList,
      mobilePhone: props.mobilePhone,
      imSig: props.imSig,
      height: null,
      rtc: null,
      isCamOn: true,
      isMicOn: true,
      //拖动
      text: {
        isDown: false,
        offsetLeft: 0,
        offsetTop: 0,
      },
      videoLocal: {
        isDown: false,
        offsetLeft: 0,
        offsetTop: 0,
      },
      videoSize: 2, // 0：只显示标题； 1：只显示当前发言人视频；2：最大化
    };
    this.videoTimer = null
    this.videoMaxTimeCount = 60;
    this.hasStop = false;
  }

  forceConnect(){
    console.log('强制连接', this.props.videoMember);
    const that = this;
    const mobilePhone = this.props.videoMember.length > 0 && this.props.videoMember[0]['mobilePhone']
    const status = this.props.videoMember.length > 0 && this.props.videoMember[0]['status']
    if (status == 'yes') {
      that.hasStop = true;
      return;
    }
    confirm({
      title: '视频上拉失败',
      okText: '再次上拉',
      cancelText: '取消',
      onOk() {
        // 强制关闭房间
        that.common.leave(that.state.Room_No);
        that.dissolutionRoom();
        setTimeout(() => {
          that.props.closeVideoState();
        }, 200);
        // 强制重新开启房间
        const data = { mobilePhone }
        setTimeout(()=>{
          eventCenter.emit('clickTextScheduling', {
            item: [data],
            type: "video",
            isNeedRecord: [mobilePhone]
          });
        }, 700)
        that._videoInterval()
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }

  _videoInterval(){
    const that = this;
    this.videoTimer = null;
    this.hasStop = false;
    let number = 0;
    this.videoTimer = setInterval(()=>{
      number++;
      console.log('videoTimer-number', number);
      if (number > that.videoMaxTimeCount){
        that.forceConnect()
        clearInterval(that.videoTimer)
      }
      if (that.hasStop) {
        clearInterval(that.videoTimer)
      }
    }, 1000)
  }

  componentDidMount() {
    const that = this;
    CheckRTC();
    const height = document.documentElement.clientHeight - 5;
    this.setState({
      height,
    });
    this.common.login(this.state.Room_No, this.state.mobilePhone, this.props.ownCid, this.props.ownName, this);
    if (this.props.videoGenre == 1) {
      this._videoInterval()
    }
  }

  onChangeVideoSize=(value)=>{
    this.setState({
      videoSize: value
    })
  }

  componentWillReceiveProps(nextProps) {
    console.log(nextProps)
  }
  //解散房间
  dissolutionRoom() {
    // window.close();
    trtcVideoRoom({ roomNo: this.state.Room_No }).then((res) => {
      console.log(res);
    });
  }
  // 解散房间弹窗
  dissolutionRoomModal = () => {
    const _this = this;
    const { recordStatus } = _this.props;
    if (recordStatus == 1) {
      return Modal.warning({
        title: '目前还在录制视频中，请先结束视频录制！',
        okText: '我知道了'
      });
    }
    Modal.confirm({
      title: "您将解散房间?",
      content: "注：其他人员也将退出房间",
      okText: "确定",
      cancelText: "取消",
      onOk() {
        Modal.destroyAll()
        // this.quitRTC();
        _this.common.leave(_this.state.Room_No);
        _this.dissolutionRoom();
        setTimeout(() => {
          _this.props.closeVideoState();
          _this.props.dispatch({
            type:'command/fetchVideoGenre',
            payload: 0
          })
          _this.props.dispatch({
            type:'command/fetchVideoType',
            payload: 0
          })
        }, 200);
        _this.hasStop = true;
      },
      onCancel() {
        console.log("Cancel");
      },
    });
  }
  //加入视频成员
  async joinMemberVideo(value) {
    console.log('joinMemberVideo', value);
    let memberList = value.split('/')
    let { isNeedRecord, schedulingName } = this.props
    let memberCidList = []//视频人员cid
    let uidList = []//视频人员uid
    let needRecordCidList = []//需要录屏的人员cid
    let videoMember = [];//用于记录是否已经进入房间使用
    for (let item of memberList) {
      if (item) {
        videoMember.push({
          mobilePhone: item,
          status: 'no',
          id: item + 'no'
        })
        const data = await searchDeptUser({
          keyWord: item
        })
        // console.log('searchDeptUser', data);
        if (data && data.data) {
          const persons = data.data[0]
          // uidList.push(item)
          uidList.push(`${persons.mobile};${persons.id};${persons.domainId}`)
          memberCidList.push(data.data[0].item_cid)
          if (isNeedRecord.length > 0) {
            for (let recordPhone of isNeedRecord) {
              if (recordPhone == item) {
                needRecordCidList.push(data.data[0].item_cid)
                break;
              }
            }
          }
        } else {
          return message.info('手机号:' + item + '的用户不属于平台用户，无法调度，请核对后重新调度')
        }
      }
    }
    this.props.dispatch({
      type: 'command/fetchVideoMemberList',
      payload: {
        type: 'add',
        memberList: videoMember
      }
    })
    continueSendVideoRoomMsg({
      RoomNo: this.state.Room_No, //房间号
      MemberList: memberCidList.join(","), //视频人员,cid，多个逗号隔开
      Yardman_Task_Name: schedulingName, //调度任务名称
      Transcriber: isNeedRecord ? needRecordCidList : '',//需要录制的人员的cid，多个逗号隔开
      UseList: uidList.join(","),//视频人员uid（手机号），跟MemberList一一对应
      ComId: gup('v5_comId', window.location.href),//v5的企业ID
    }).then(res => {
      if (res.retType === "0") {
        setTimeout(() => {
          const divs = document.getElementsByClassName('n_modal');
          Reflect.apply(Array.prototype.forEach, divs, [item => {
            RreactDom.unmountComponentAtNode(item);
            document.body.removeChild(item);
          }]);
        }, 300);
      }
    })
  }
  // 添加调度人员
  onAddMember=()=>{
    $nModal({
      title: '添加视频调度人员',
      footer: null,
      width: 500,
      content: (
        <div>
          <Search
            placeholder="请输入调度者完整手机号，如调度多人请使用“/”隔开"
            enterButton="调度"
            size="default"
            onSearch={value => {
              console.log(value)
              if (value) {
                this.joinMemberVideo(value)
              } else {
                message.warning('请输入完整手机号');
              }
            }}
          />
        </div>
      ),
    });
  }
  render() {
    const { videoMember, videoGenre } = this.props;
    const { videoSize, videoVisible } = this.state;
    const hasVideoScheduling = videoGenre == 0 ? true : false;
    return (
      <div>
        {/* <div className="ant-modal-mask" style={{ zIndex: 100 }}></div> */}
        <div id="video-section">
          {/* 呼叫人员状态展示*/}
          <div className='calling'>
            {
              videoMember.map(item => {
                return <div>
                  {
                    item.status == 'delete' ? '' : <div className='item' id={item.id}>
                      {
                        item.status == 'no' ? '等待' + item.mobilePhone + '接入' :
                          item.status == 'yes' ? item.mobilePhone + '接入成功' :
                            item.status == 'leave' ? item.mobilePhone + '已离开' :
                              item.status == 'fail' ? <span>{item.mobilePhone + '调度失败'}<span className="again" onClick={() => {
                                this.joinMemberVideo(item.mobilePhone)
                              }}>重新调度</span></span> : ''
                      }
                    </div>
                  }
                </div>
              })
            }
          </div>
          {/*  聊天室页面  */}
          <VideoBox _videoThis={this} dissolutionRoomModal={this.dissolutionRoomModal} common={this.common} videoSize={videoSize} addMember={this.onAddMember} ></VideoBox>

        </div>
        <RecordTimer />
        { hasVideoScheduling ? <RecordMini videoSize={videoSize} onChange={this.onChangeVideoSize.bind(this)} /> : null }
      </div>
    );
  }
}
