/**
 * 会议录播列表页面
 */
import React, { Component } from "react";
import { connect } from "dva";
import moment from 'moment';
import PTable from '../../../components/Pro/PTable';
import { getHuaweiManageResource, batchDeleteTranscribeFile } from '../../../services/api';
import { Form, Input, Button, DatePicker, Alert, Tabs, Modal, Popconfirm, Popover } from "antd";
const dateFormat = 'YYYY-MM-DD';
const { RangePicker } = DatePicker;
const { TabPane } = Tabs;
const { confirm } = Modal;
import "../meeting.less";
@connect(state => ({
}))
@Form.create()
export default class Recordlist extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      forceUpdate: false,
      pageParm: {
        meetTheme: "",
        startTime: moment(new Date()).subtract(1, 'months').format(dateFormat),
        endTime: moment().format(dateFormat),
        pageSize: 10,
        pageNumber: 1
      },
      meetTheme: "",
      startTime: moment(new Date()).subtract(1, 'months').format(dateFormat),
      endTime: moment().format(dateFormat),
      // recordData: '',//资源数据
      selectedRowKeys: [],
      selectedRows: []//选中哪些需要删除的列表
    }
  }
  componentDidMount() {
    // this._getHuaweiManageResource();
  }
  //获取资源数据
  _getHuaweiManageResource() {
    getHuaweiManageResource({}).then(res => {
      if (res.retType === "0" && !!res.data) {
        this.setState({
          recordData: res.data.recordCapability
        });
      }
    });
  }
  //删除录制资源
  _delete(confUUIDs) {
    batchDeleteTranscribeFile({ confUUIDs }).then(res => {
      if (res.retType === '0') {
        this.setState(
          {
            forceUpdate: true,
            selectedRowKeys: [],
            selectedRows: []
          },
          () => {
            this.setState({
              forceUpdate: false
            });
          }
        );
      }
    })
  }
  //拆分天时分秒
  _formatSeconds(value) {
    var theTime = parseInt(value);// 需要转换的时间秒 
    var theTime1 = 0;// 分 
    var theTime2 = 0;// 小时 
    var theTime3 = 0;// 天
    if (theTime > 60) {
      theTime1 = parseInt(theTime / 60);
      theTime = parseInt(theTime % 60);
      if (theTime1 > 60) {
        theTime2 = parseInt(theTime1 / 60);
        theTime1 = parseInt(theTime1 % 60);
        if (theTime2 > 24) {
          //大于24小时
          theTime3 = parseInt(theTime2 / 24);
          theTime2 = parseInt(theTime2 % 24);
        }
      }
    }
    var result = '';
    if (theTime > 0) {
      result = "" + parseInt(theTime) + "秒";
    }
    if (theTime1 > 0) {
      result = "" + parseInt(theTime1) + "分" + result;
    }
    if (theTime2 > 0) {
      result = "" + parseInt(theTime2) + "小时" + result;
    }
    if (theTime3 > 0) {
      result = "" + parseInt(theTime3) + "天" + result;
    }
    return result;
  }
  //将unix时间戳转成普通的时间
  unitTimestamp(time) {
    var unixTimestamp = new Date(time);
    var commonTime = unixTimestamp.toLocaleString()
    return commonTime
  }
  //时间+8小时
  addUTC(time) {
    time= time.replace(' ','T');//为了兼容safari的Date.parse()方法
    const offset = 8 * 60 * 60 * 1000;
    time = Date.parse(time) + offset;
    const newDate = new Date(time)
    const month = parseInt(newDate.getMonth()) + 1
    const startTime =
      newDate.getFullYear() +
      "-" +
      month +
      "-" +
      newDate.getDate() +
      " " +
      newDate.getHours() +
      ":" +
      newDate.getMinutes();
    return startTime
  }
  render() {
    const columns = [
      {
        title: "会议ID",
        dataIndex: "confID",
        key: "confID",
      },
      {
        title: "会议主题",
        dataIndex: "subject",
        key: "subject",
      }, {
        title: "会议开始时间",
        dataIndex: "startTime",
        key: "startTime",
        render: (text, record) => {
          return (
            <span>{this.addUTC(text)}</span>
          )
        }
      }, {
        title: "会议预定者",
        dataIndex: "scheduserName",
        key: "scheduserName",
      },
      {
        title: "录制时长",
        dataIndex: "rcdTime",
        key: "rcdTime",
        render: (text, record) => (
          <span>
            {this._formatSeconds(text)}
          </span>
        )
      }, {
        title: "录制文件大小（MB）",
        dataIndex: "rcdSize",
        key: "rcdSize",
      },
      // {
      //   title: "录制文件是否转码完成",
      //   dataIndex: "isDecodeFinish",
      //   key: "isDecodeFinish",
      // }, {
      //   title: "录制文件预计转码完成时间",
      //   dataIndex: "decodeEndTime",
      //   key: "decodeEndTime",
      // }, {
      //   title: "录播文件是否可观看",
      //   dataIndex: "available",
      //   key: "available",
      // }
      {
        title: '操作',
        dataIndex: "action",
        key: "action",
        render: (text, record) => (
          <span>
            {
              !record.isDecodeFinish ? <span>录制视频转码中,预计{this.unitTimestamp(record.decodeEndTime)}转码结束，请耐心等待。</span> :
                <span>
                  {
                    /**
                     * 播放设备出现错误时，华为会返回多个播放地址，供我们选择
                     * 这时候就需要做列表展示多个路径
                     */
                    record.url.length > 1 ?
                      <Popover placement="topLeft"
                        title='播放地址'
                        content={
                          <div style={{ padding: '5px 15px' }}>{
                            record.url.map((item, index) => {
                              return <a href={item} target='_blank' rel='noopener noreferrer'>播放视频{index + 1}</a>
                            })}
                          </div>
                        }
                        trigger="click">
                        <a className="action-span">播放</a>
                      </Popover> : <a className="action-span"
                        href={record.url[0]}
                        target='_blank'
                        rel='noopener noreferrer'>播放</a>
                  }
                  <Popconfirm
                    overlayClassName="change-clock-pop "
                    title="确定删除该条信息？"
                    onConfirm={() => {
                      this._delete(record.confUUID)
                    }}
                    okText="确定"
                    cancelText="取消"
                  >
                    <span className="action-span"
                    >删除</span>
                  </Popconfirm>
                </span>
            }
          </span>
        )
      },
    ]
    const rowSelection = {
      onChange: (selectedRowKeys, selectedRows) => {
        this.setState({
          selectedRowKeys,
          selectedRows
        });
      },
      selectedRowKeys: this.state.selectedRowKeys
    };
    return (
      <div className='meeting'>
        <Tabs defaultActiveKey="1" className="3">
          <TabPane tab="录屏会议管理" key="1">
            <Alert
              message={
                <div style={{ color: "#333" }}>
                  <span>录屏空间需要购买，当您资源不足时，请在会议资源管理页面进行购买；</span>
                </div>
              }
              type="warning"
              showIcon
              style={{ marginBottom: "15px" }}
            />
            <div className="form">
              <label style={{ marginRight: 16 }}>
                关键字：
              <Input
                  style={{ width: "214px", marginBottom: "10px" }}
                  placeholder="请输入会议ID/会议主题/预定人"
                  value={this.state.meetTheme}
                  onChange={e => {
                    this.setState({
                      meetTheme: e.target.value
                    });
                  }}
                />
              </label>
              <label style={{ marginRight: 16 }}>
                会议开始时间：
                <RangePicker
                  allowClear={false}
                  placeholder={['开始时间', '结束时间']}
                  onChange={(date, dateString) => {
                    if (dateString[0] !== "") {
                      this.setState({
                        startTime: dateString[0],
                        endTime: dateString[1]
                      });
                    } else {
                      this.setState({
                        startTime: "",
                        endTime: ""
                      });
                    }
                  }}
                  value={[
                    this.state.startTime
                      ? moment(this.state.startTime, dateFormat)
                      : null,
                    this.state.endTime ? moment(this.state.endTime, dateFormat) : null
                  ]}
                />
              </label>
              <Button
                style={{
                  marginRight: "16px",
                  marginBottom: "16px"
                }}
                type="primary"
                onClick={() => {
                  const pageParm = { ...this.state.pageParm };
                  let { meetTheme, startTime, endTime } = this.state;
                  pageParm.meetTheme = meetTheme;
                  pageParm.startTime = startTime;
                  pageParm.endTime = endTime;
                  this.setState(
                    {
                      pageParm
                    },
                    () => {
                      this.setState({
                        forceUpdate: false
                      });
                    }
                  );
                }}
              >
                搜索
              </Button>
              <Button
                onClick={() => {
                  const pageParm = {
                    ...this.state.pageParm,
                    meetTheme: "",
                    startTime: moment(new Date()).subtract(1, 'months').format(dateFormat),
                    endTime: moment().format(dateFormat),
                  };
                  this.setState(
                    {
                      pageParm,
                      meetTheme: "",
                      startTime: moment(new Date()).subtract(1, 'months').format(dateFormat),
                      endTime: moment().format(dateFormat),
                      forceUpdate: true
                    },
                    () => {
                      this.setState({
                        forceUpdate: false
                      });
                    }
                  );
                }}
              >
                重置
              </Button>
            </div>
            <Button type="primary"
              disabled={!this.state.selectedRows.length > 0}
              onClick={() => {
                if (this.state.selectedRows.length > 0) {
                  const selectedUUID = []
                  this.state.selectedRows.forEach(item => {
                    selectedUUID.push(item.confUUID)
                  })
                  const _this = this
                  confirm({
                    title: '确定删除所有选中的录屏?',
                    okText: '确定',
                    cancelText: '取消',
                    onOk() {
                      _this._delete(selectedUUID.join(','))
                    },
                    onCancel() {
                      console.log('Cancel');
                    },
                  });
                }
              }}>删除</Button>
            {/* <div style={{ float: "right" }}>
              录播空间
                <span className="green">
                {this.state.recordData && this.state.recordData.usedCount}
              </span>
              G/
                <span>
                {this.state.recordData && this.state.recordData.sumCount}
              </span>
              G
            </div> */}
            <PTable
              style={{ marginTop: 20 }}
              columns={columns}
              url="getTranscribeFileList"
              pageParm={this.state.pageParm}
              forceUpdate={this.state.forceUpdate}
              rowSelection={rowSelection}
            />
          </TabPane>
        </Tabs>
      </div>
    );
  }
}
