/**
 * 预约会议
 */
import React, { Component } from "react";
import { connect } from "dva";
import {
  Form,
  Select,
  Input,
  Radio,
  DatePicker,
  message,
  Modal,
  Checkbox,
  InputNumber
} from "antd";
import $perModal from '../../../utils/modal/perModal';
import {
  sendHuaweiMeetSms,
  getHuaweiManageResource,
  buildHuaweiMeet,
  getHuaweiUserDetail
} from "../../../services/api";
const { Option } = Select;
import moment from "moment";
import "../meeting.less";
const formItemLayout = {
  labelCol: {
    xs: { span: 12 },
    sm: { span: 8 }
  },
  wrapperCol: {
    xs: { span: 12 },
    sm: { span: 10 }
  }
};
const dateFormat = "YYYY-MM-DD HH:MM:SS";
@connect(state => ({
  client: state.client.client,
  name: state.user.currentUser.name,
  meetingSipName: state.client.meetingSipName,
  meetingAcount: state.client.meetingAcount,
  // mobilePhone: state.user.currentUser.mobilePhone,
  meetingToken: state.client.meetingToken
}))
@Form.create()
export default class Create extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      attenPhone: [],
      createVisible: this.props.createVisible,
      isNow: true, //选择会议是否立即开始按钮(true是选择“现在”，false是选择了“预约”)
      resourceList: {}, //资源列表
      vmrList: [],
      meetingPattern: false, //开会议的模式（只有有分配云会议资源的时候，才需要进行区分。不然开的都是并发模式的会议）
      startTime_string: null,
      mediaTypes: 'Video',//选择会议类型
    };
  }
  componentDidMount() {
    this._getHuaweiManageResource();
    this._getHuaweiUserDetail();
  }
  //用户查询自己的信息(主要拿取vmr)
  _getHuaweiUserDetail() {
    getHuaweiUserDetail({}).then(res => {
      if (res.retType === "0") {
        if (res.data.vmrList.length > 0) {
          const vmrList = [];
          /**
           * 去掉个人的云会议室，用个人的云会议室，创建出来的会议是并发模式的
           * 只有通过这两个参数都有的vmr，创建出来的会议才是云会议室模式
           */
          res.data.vmrList.forEach(item => {
            if (item.vmrPkgId && item.vmrPkgName && item.status == 0) {
              vmrList.push(item);
            }
          });
          this.setState({
            vmrList
          });
        }
      }
    });
  }
  _getHuaweiManageResource() {
    getHuaweiManageResource({}).then(res => {
      if (res.retType === "0" && !!res.data) {
        let resourceList = {
          confCallCount: res.data.confCallCount,
          vmr: res.data.vmr,
          recordCapability: res.data.recordCapability
        };
        this.setState({
          resourceList
        });
      }
    });
  }
  //时间+8小时
  addUTC(time, action) {
    const offset = 8 * 60 * 60 * 1000;
    time = new Date(Date.parse(time));
    time = time.getTime();
    if (action == 'add') {
      time = time + offset;
    } else {
      time = time - offset;
    }
    let newDate = new Date(parseInt(time))
    let month = parseInt(newDate.getMonth()) + 1
    const getMinutes = newDate.getMinutes()===0?'00':newDate.getMinutes()
    const startTime =
      newDate.getFullYear() +
      "-" +
      month +
      "-" +
      newDate.getDate() +
      " " +
      newDate.getHours() +
      ":" +
      // newDate.getMinutes()
      getMinutes
    return startTime
  }
  //提交创建会议
  handleSubmit() {
    this.props.form.validateFields((err, values) => {
      if (!err) {
        const localData = new Date();
        var dateTime = values.startTime;
        var utc_millisecond = Date.parse(dateTime);
        const time =
          localData.getTime() > new Date(utc_millisecond).getTime() ||
          localData.getTime() == new Date(utc_millisecond).getTime();
        if (!this.state.isNow && time) {
          //如果是预约的并且时间不能大于当前的时间
          message.warning("预约时间不能小于当前时间");
        } else {
          //判断是否还有录播的资源
          if (
            values.isAutoRecord === 1 &&
            this.state.resourceList.recordCapability.usedCount ===
            this.state.resourceList.recordCapability.sumCount
          ) {
            message.warning("当前已无录播资源,要使用请先购买");
          } else {
            //华为云传过去的时间是UTC格式（其实刚好是8个小时）
            const startTime = this.state.isNow ? '' : this.addUTC(this.state.startTime_string, 'educe')
            const attendees_array = this.state.arrayObj;
            let value = {
              subject: values.subject,
              startTime: this.state.isNow
                ? ""
                : // : values["startTime"].format(dateFormat),
                startTime,
              timeZoneID: "56",
              multiStreamFlag: 1, //设置多流会议，控制视频样式
              length: values.length,
              // subject: values.subject,
              mediaTypes: values.cloudec_is_HD_conf=='true'
                ? [values.cloudec_conf_type, "HDVideo"].join(",")
                : values.cloudec_conf_type,
              isAutoRecord: values.isAutoRecord,
              recordType: values.isAutoRecord === 1 ? 2 : 0, //录播的类型，如果是要录播，就设置为2，不要录播，设置为0禁用
              vmrFlag: this.state.meetingPattern ? 1 : 0
            };
            this.state.meetingPattern ? (value.vmrID = values.vmrID) : "";
            let attendeeList = [];
            // if (!this.state.isNow) {
            attendeeList.push({
              name: this.props.name,
              phone: this.props.meetingSipName,
              accountId: this.props.meetingAcount,
              userUUID: this.props.meetingToken,
              role: 1
            });
            // }
            for (let m in attendees_array) {
              const attendeeParam = {};
              attendeeParam.name = attendees_array[m].name;
              attendeeParam.phone = attendees_array[m].huaweiSipName;
              attendeeParam.role = 0;
              attendeeList.push({ ...attendeeParam });
            }
            const _this = this;
            buildHuaweiMeet({
              ...value,
              attendeesJSON: JSON.stringify(attendeeList)
            }).then(res => {
              if (res.retType === "0") {
                this.props.changeCreateStatus(false);
                this.props.form.resetFields();
                message.info("会议创建成功");
                _this.props.updateTable()
                _this.props.dispatch({
                  type: `client/setISRefreshMeetingList`,
                  payload: {
                    updateISRefreshMeetingList: true
                  }
                });
                if (values.inform.length === 2 && !!attendees_array) {
                  const data = {
                    meetTheme: res.data[0].subject,
                    meetStartTime: this.addUTC(res.data[0].startTime, 'add'),
                    meetId: res.data[0].conferenceID,
                    chairPwd: res.data[0].passwordEntry[0].password,
                    guestPwd: res.data[0].passwordEntry[1].password,
                    phones: _this.state.attenPhone.join(",")
                  };
                  sendHuaweiMeetSms({ ...data }).then(res => {
                    if (res.retType === "0") {
                      message.info("短信发送成功");
                    }
                  });
                }
              }
            });
          }
        }
      }
    });
  }
  componentWillReceiveProps(nextProps) {
    this.setState({
      createVisible: nextProps.createVisible
    });
  }
  render() {
    const { getFieldDecorator } = this.props.form;
    return (
      <div className="meeting">
        <Modal
          title="发起会议"
          visible={this.state.createVisible}
          onOk={() => this.handleSubmit()}
          onCancel={() => {
            this.props.form.resetFields();
            this.props.changeCreateStatus(false);
            this.setState({
              isNow: true
            });
          }}
          okText="发起"
        >
          <Form>
            <Form.Item {...formItemLayout} label="会议类型">
              {getFieldDecorator("cloudec_conf_type", {
                initialValue: "Video",
                rules: [{ required: true, message: "请选择会议类型" }]
              })(
                <Select style={{ width: 120 }}
                  onChange={(value) => {
                    this.setState({
                      mediaTypes: value
                    })
                  }}>
                  <Option value="Voice">语音</Option>
                  <Option value="Video">视频</Option>
                  {/* <Option value="2">语音+数据</Option>
                <Option value="3">视频+数据</Option> */}
                </Select>
              )}
            </Form.Item>
            {
              this.state.mediaTypes === 'Video' && <Form.Item {...formItemLayout} label="高清会议">
                {getFieldDecorator("cloudec_is_HD_conf", {
                  initialValue: "true",
                  rules: [{ required: true, message: "请选择会议质量" }]
                })(
                  <Select style={{ width: 120 }}>
                    <Option value="false">否</Option>
                    <Option value="true">是</Option>
                  </Select>
                )}
              </Form.Item>
            }
            <Form.Item {...formItemLayout} label="会议是否立即开始">
              {getFieldDecorator("isNow", {
                initialValue: true,
                rules: [{ required: true, message: "" }]
              })(
                <Radio.Group
                  onChange={value => {
                    this.setState({
                      isNow: value.target.value
                    });
                  }}
                >
                  <Radio value={true}>现在</Radio>
                  <Radio value={false}>预约</Radio>
                </Radio.Group>
              )}
            </Form.Item>
            {!this.state.isNow && (
              <span>
                <Form.Item {...formItemLayout} label="会议开始时间">
                  {getFieldDecorator("startTime", {
                    rules: [{ required: true, message: "请选择开始时间" }]
                  })(
                    <DatePicker
                      showTime
                      placeholder="请选择"
                      onChange={(date, dateString) => {
                        this.setState({ startTime_string: dateString })
                      }}
                      disabledDate={current => {
                        // return current < moment().subtract(1, "day");
                        return (current && current < moment(parseInt(sessionStorage.getItem('requestDate'))).startOf('day')) || (current && current > moment().add(1, 'y'));
                      }}
                    />
                  )}
                </Form.Item>
              </span>
            )}
            <Form.Item {...formItemLayout} label="会议持续的时间">
              {getFieldDecorator("length", {
                initialValue: "30",
                rules: [{ required: true, message: "请选择会议持续时间" }]
              })(
                <InputNumber
                  min={15}
                  max={1400}
                  formatter={value => `${value}分钟`}
                  parser={value => value.replace("分钟", "")}
                />
              )}
            </Form.Item>
            <Form.Item {...formItemLayout} label="会议主题">
              {getFieldDecorator("subject", {
                rules: [{ required: true, message: "请输入会议主题" }]
              })(<Input placeholder="请输入会议主题" maxLength={128} />)}
            </Form.Item>

            {/* 有云会议资源，让用户选择需要开什么模式的会议 */}
            {this.state.vmrList.length > 0 && (
              <Form.Item {...formItemLayout} label="会议模式">
                {getFieldDecorator("meetingPattern", {
                  initialValue: this.state.meetingPattern,
                  rules: [{ required: true, message: "请选择会议模式" }]
                })(
                  <Radio.Group
                    onChange={value => {
                      this.setState({
                        meetingPattern: value.target.value
                      });
                    }}
                  >
                    <Radio value={false}>个人会议模式</Radio>
                    <Radio value={true}>云会议模式</Radio>
                  </Radio.Group>
                )}
              </Form.Item>
            )}
            {/* 当用户选择云会议模式的会议，需要选择对应的云会议id */}
            {this.state.meetingPattern && (
              <Form.Item {...formItemLayout} label="会议ID类型">
                {getFieldDecorator("vmrID", {
                  initialValue: this.state.vmrList[0].id,
                  rules: [{ required: true, message: "请选择会议ID类型" }]
                })(
                  <Select>
                    {this.state.vmrList.map(item => {
                      return (
                        <Option value={item.id} key={item.id}>
                          {item.vmrName} {item.vmrId} ({item.vmrPkgParties}方)
                        </Option>
                      );
                    })}
                  </Select>
                )}
              </Form.Item>
            )}

            <Form.Item {...formItemLayout} label="成员">
              {getFieldDecorator("cloudec_input_attendees")(
                <Input
                  placeholder="请选择"
                  maxLength={30}
                  readOnly
                  onClick={() => {
                    $perModal({
                      fetchType: 'huawei',
                      value: this.state.arrayObj,
                      onOk: (values, close) => {
                        const attendees_str = [];
                        const arrName = [];
                        const attenPhone = [];
                        values.forEach(val => {
                          attendees_str.push(val.huaweiSipName);
                          arrName.push(val.name);
                          attenPhone.push(val.mobilePhone);
                        });
                        const { setFieldsValue } = this.props.form;
                        setFieldsValue({ cloudec_input_attendees: arrName.join(",") });
                        close();
                        this.setState({
                          attendees_str,
                          arrName,
                          arrayObj: values,
                          perId: values.map(({perId}) => perId),
                          attenPhone
                        });
                      }
                    });
                  }}
                />
              )}
            </Form.Item>
            <Form.Item {...formItemLayout} label="是否自动启动录制">
              {getFieldDecorator("isAutoRecord", {
                initialValue: 0,
                rules: [{ required: true, message: "" }]
              })(
                <Radio.Group >
                  <Radio value={1}>是</Radio>
                  <Radio value={0}>否</Radio>
                </Radio.Group>
              )}
            </Form.Item>
            <Form.Item {...formItemLayout} label="通知">
              {getFieldDecorator("inform", {
                initialValue: ["1", "2"] || ""
              })(
                <Checkbox.Group>
                  <Checkbox value="1" disabled>
                    App通知
                  </Checkbox>
                  <Checkbox value="2">短信通知</Checkbox>
                </Checkbox.Group>
              )}
            </Form.Item>
          </Form>
        </Modal>
        
      </div>
    );
  }
}
