/**
 * 会议控制
 */
import React, { Component } from "react";
import { connect } from "dva";
import {
  Form,
  Tabs,
  Input,
  Button,
  Table,
  Breadcrumb,
  message,
  Modal,
  Icon,
} from "antd";
const { confirm } = Modal;
import { joinState } from "../SDK/reasonCode";
import $perModal from "../../../utils/modal/perModal";
@connect((state) => ({
  client: state.client.client,
  attenList: state.client.attenList,
  meetingSipName: state.client.meetingSipName,
}))
@Form.create()
export default class Control extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      addAttenAccount: "",
      attenDetail: props.location.state,
      inputVisible: false, //输入主席输入框
      passInputValue: null, //输入的主席密码
      myseleft: null, //当前用户的信息
      roleDetail: null, //当前会议的主席是谁（具体信息）
    };
  }
  componentDidMount() {
    let roleDetail = null;
    this.props.attenList.forEach((item) => {
      if (item.isSelf === 1) {
        this.setState({
          myseleft: item,
        });
      }
      if (item.role === 1) {
        roleDetail = item;
      }
    });
    this.setState({
      roleDetail,
    });
  }
  componentWillReceiveProps(nextProps) {
    let roleDetail = null;
    if (nextProps.attenList !== this.props.attenList) {
      nextProps.attenList.forEach((item) => {
        if (item.isSelf === 1) {
          this.setState({
            myseleft: item,
          });
        }
        if (item.role === 1) {
          roleDetail = item;
        }
      });
    }
    this.setState({
      roleDetail,
    });
  }
  //邀请成员加入会议
  addAtten(arrayObj, close) {
    var conference = this.props.client.getConfHandler();
    if (conference == null) {
      message.error("会议还没开始");
      return;
    } else if (arrayObj == null || arrayObj == "") {
      message.error("与会者不能为空");
      return;
    }
    var cloudecAttendees = new Array();
    for (var i = 0; i < arrayObj.length; i++) {
      cloudecAttendees[i] = {
        number: arrayObj[i].huaweiSipName,
        name: arrayObj[i].name,
        role: 0,
      };
    }
    close && close();
    message.info("正在呼叫...");
    this.props.client.addAttendee(cloudecAttendees);
  }

  //静音（取消）对应的成员
  mute(number, isSelf, value) {
    var conference = this.props.client.getConfHandler();
    if (conference == null) {
      alert("Meeting has not yet started");
      return;
    }
    this.props.client.muteAttendee(number, value);
    if (isSelf === 1) {
      this.props.client.micMute(true);
    }
  }
  //静音所有成员
  muteAll() {
    var conference = this.props.client.getConfHandler();
    if (conference == null) {
      // alert("Meeting has not yet started");
      message.error("会议尚未开始");
      return;
    }
    // message.info("全员静音")
    this.props.client.muteConference(true);
  }
  //取消静音所有成员
  cancelMuteAll() {
    var conference = this.props.client.getConfHandler();
    if (conference == null) {
      // alert("Meeting has not yet started");
      message.error("会议尚未开始");
      return;
    }
    // message.info("全员取消静音")
    this.props.client.muteConference(false);
  }
  //释放主席
  releaseChairman() {
    var conference = this.props.client.getConfHandler();
    if (conference == null) {
      // alert("Meeting has not yet started");
      message.error("会议尚未开始");
      return;
    }
    this.props.client.releaseChairman();
  }
  //申请主席
  requestChairman(chairmanPasswd) {
    // console.log(chairmanPasswd);
    var conference = this.props.client.getConfHandler();
    if (conference == null) {
      // alert("Meeting has not yet started");
      message.error("会议尚未开始");
      return;
    }
    // this.props.client.requestChairman(this.state.attenDetail.chairmanPasswd);
    this.props.client.requestChairman(chairmanPasswd);
  }
  //(点对点)呼叫
  // call(calleeNum) {
  //   var isVideoCall = 0;
  //   console.log(this.state.attenDetail);
  //   if (
  //     this.state.attenDetail.mediaType === 1 ||
  //     this.state.attenDetail.mediaType === 3
  //   ) {
  //     var isVideoCall = 1;
  //   }
  //   this.props.client.makeCall(calleeNum, isVideoCall, function(data) {
  //     if (data.result) {
  //       // document.getElementById("callState").innerHTML = "call state: make call";
  //     }
  //   });
  // }
  //声控模式（版本更新，服务端创建默认就是声控模式）
  // setConfMode() {
  //   this.props.client.setConfMode(1);
  //   message.info("声控模式开启")
  // }
  //结束会议
  endConf() {
    var conference = this.props.client.getConfHandler();
    if (conference == null) {
      // alert("Meeting has not yet started");
      message.error("会议尚未开始");
      return;
    }
    const _this = this;
    confirm({
      title: "确定结束当前会议?",
      okText: "确定",
      cancelText: "取消",
      // content: 'Some descriptions',
      onOk() {
        _this.props.client.endConf();
      },
      onCancel() {
        // console.log('Cancel');
      },
    });
  }
  //离开会议
  leaveConf() {
    var conference = this.props.client.getConfHandler();
    if (conference == null) {
      // alert("Meeting has not yet started");
      message.error("会议尚未开始");
      return;
    }
    const _this = this;
    confirm({
      title: "确定离开当前会议?",
      okText: "确定",
      cancelText: "取消",
      // content: 'Some descriptions',
      onOk() {
        _this.props.client.leaveConf();
      },
      onCancel() {
        // console.log('Cancel');
      },
    });
  }
  render() {
    const columns = [
      {
        title: "名称",
        dataIndex: "name",
        key: "name",
      },
      {
        title: "角色",
        dataIndex: "role",
        key: "role",
        render: (text, record) => <span>{text === 0 ? "来宾" : "主席"}</span>,
      },
      {
        title: "静音",
        dataIndex: "isMute",
        key: "isMute",
        render: (text, record) => <span>{text === 0 ? "否" : "是"}</span>,
      },
      {
        title: "信息",
        dataIndex: "joinState",
        key: "joinState",
        render: (text, record) => (
          <span>
            {joinState[text]}
          </span>
        ),
      },
      {
        title: "操作",
        dataIndex: "action",
        key: "action",
        render: (text, record) => (
          <span>
            {/* 该人在会议中,才能对他静音 */}
            {record.joinState === 0 && (
              <span
                className="action-span"
                onClick={() => {
                  let value = record.isMute === 1 ? false : true;
                  this.mute(record.number, record.isSelf, value);
                }}
                disabled={
                  record.isSelf === 0 &&
                  this.state.myseleft &&
                  this.state.myseleft.role === 0
                }
              >
                {record.isMute === 1 ? "取消静音" : "静音"}
              </span>
            )}

            {record.isSelf === 1 ? (
              record.role === 1 ? (
                <span
                  className="action-span"
                  onClick={() => {
                    this.releaseChairman();
                  }}
                >
                  释放主席
                </span>
              ) : (
                <span
                  className="action-span"
                  onClick={() => {
                    if (this.state.attenDetail.chairmanPasswd) {
                      this.requestChairman(
                        this.state.attenDetail.chairmanPasswd
                      );
                    } else {
                      this.setState({
                        inputVisible: !this.state.inputVisible,
                      });
                    }
                  }}
                  style={{ margin: "0 5px" }}
                  disabled={this.state.roleDetail}
                >
                  申请主席
                </span>
              )
            ) : (
              ""
            )}
            {record.joinState !== 0 && record.joinState !== 1 ? (
              <span
                className="action-span"
                onClick={() => {
                  const arr = [
                    { huaweiSipName: record.number, name: record.name },
                  ];
                  this.addAtten(arr);
                }}
                disabled={
                  record.isSelf === 0 &&
                  this.state.myseleft &&
                  this.state.myseleft.role === 0
                }
              >
                呼叫
              </span>
            ) : (
              ""
            )}
          </span>
        ),
      },
    ];
    return (
      <div className="meeting">
        <Breadcrumb
          style={{
            padding: "0px 0px 10px 10px",
            borderBottom: "1px solid #E9E9E9",
          }}
        >
          <Breadcrumb.Item>
            <a
              onClick={() => {
                this.props.history.go(-1);
              }}
            >
              会议列表
            </a>
          </Breadcrumb.Item>
          <Breadcrumb.Item>会议控制</Breadcrumb.Item>
        </Breadcrumb>
        <div style={{ margin: "10px" }}>
          <div>
            <h1>{this.state.attenDetail.topic}</h1>
            <span>会议ID：{this.state.attenDetail.conferenceID}</span>
            <span style={{ margin: "0 10px" }}>
              主席密码：{this.state.attenDetail.chairmanPasswd}
            </span>
            <span>来宾密码：{this.state.attenDetail.generalPasswd}</span>
          </div>
          <div style={{ margin: "10px 0" }}>
            <span style={{ fontSize: "16px" }}>与会方列表</span>
            <div style={{ float: "right" }}>
              <Button
                type="primary"
                onClick={() => {
                  $perModal({
                    fetchType: "huawei",
                    onOk: (values, close) => {
                      this.addAtten(values, close);
                    },
                  });
                }}
                style={{ margin: "0 5px" }}
                disabled={this.state.myseleft && this.state.myseleft.role === 0}
              >
                <Icon type="user-add" />
                添加与会者
              </Button>
              <Button
                type="primary"
                style={{ margin: "0 5px" }}
                onClick={() => {
                  const arr = [];
                  this.props.attenList.forEach((val) => {
                    if (val.joinState !== 0 && val.joinState !== 1) {
                      arr.push({
                        huaweiSipName: val.number,
                        name: val.name,
                      });
                    }
                  });
                  if (arr.length > 0) {
                    this.addAtten(arr);
                  } else {
                    message.info("暂未有未入会成员需要呼叫");
                  }
                }}
                disabled={this.state.myseleft && this.state.myseleft.role === 0}
              >
                <Icon type="phone" />
                呼叫未入会与会方
              </Button>
              <Button
                type="primary"
                onClick={() => {
                  this.muteAll();
                }}
                style={{ margin: "0 5px" }}
                disabled={this.state.myseleft && this.state.myseleft.role === 0}
              >
                <Icon type="disconnect" />
                全员静音
              </Button>
              <Button
                type="primary"
                onClick={() => {
                  this.cancelMuteAll();
                }}
                style={{ margin: "0 5px" }}
                disabled={this.state.myseleft && this.state.myseleft.role === 0}
              >
                <Icon type="audio" />
                全员取消静音
              </Button>
              {/* <Button
                type="primary"
                onClick={() => {
                  this.setConfMode();
                }}
                style={{ margin: "0 10px" }}
                disabled={this.state.myseleft && this.state.myseleft.role === 0}
              >
                <Icon type="appstore" />
                声控模式
              </Button> */}
              <Button
                type="danger"
                onClick={() => {
                  this.leaveConf();
                }}
                style={{ margin: "0 5px" }}
                // disabled={this.state.myseleft && this.state.myseleft.role === 0}
              >
                离开会议
              </Button>
              <Button
                type="danger"
                onClick={() => {
                  this.endConf();
                }}
                style={{ margin: "0 5px" }}
                disabled={this.state.myseleft && this.state.myseleft.role === 0}
              >
                结束会议
              </Button>
            </div>
          </div>
          <Table
            dataSource={this.props.attenList}
            columns={columns}
            rowKey={(record) => record.startTime}
          />
        </div>
        <Modal
          title="申请主席"
          visible={this.state.inputVisible}
          onOk={() => {
            if (this.state.passInputValue) {
              this.requestChairman(this.state.passInputValue);
              this.setState({
                inputVisible: !this.state.inputVisible,
              });
            } else {
              message.warning("请输入密码");
            }
          }}
          onCancel={() => {
            this.setState({
              inputVisible: !this.state.inputVisible,
            });
          }}
        >
          <Input
            placeholder="输入主席密码"
            onChange={(e) => {
              this.setState({
                passInputValue: e.target.value,
              });
            }}
          />
        </Modal>
      </div>
    );
  }
}
