/*
 * @Description: 回放记录
 * @Author: zhangyi
 * @Date: 2020-05-12 09:43:48
 * @LastEditors: zhangleyuan
 * @LastEditTime: 2021-02-01 14:00:36
 */

import React, { useState, useEffect } from "react";
import { Modal, Table, Button, message } from "antd";

import Bus from '@/core/bus';
import { PageControl } from "@/components";

import hasExportPermission from '../utils/hasExportPermission';
import dealTimeDuration from '../utils/dealTimeDuration';

import "./ClassRecordModal.less";

const liveTypeMap = {
  USER: "学生",
  ANCHOR: "老师",
  ADMIN: "助教",
};

class PlayBackRecordModal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      playBackList: [],
      query: {
        current: 1,
        size: 10,
        liveCourseId: props.liveItem.liveCourseId,
      },
      total: 0,
      recordDuration: null,
      totalWatchNum: 0,
    };
  }
  
  componentDidMount() {
    this.fetchPlayBackList();
  }

  fetchPlayBackList = (page = 1) => {
    const params = _.clone(this.state.query);
    params.current = page;
    window.axios
      .Apollo("public/businessLive/queryUserReplayRecordPage", params)
      .then((res) => {
        const { records = [], total } = res.result;
        this.setState({
          query: params,
          total,
          playBackList: records,
        });
      });
  };

  fetchAllStatistics = () => {
    const { liveCourseId } = this.props.liveItem;
    window.axios
      .Apollo("public/businessLive/queryReplayStatistics", {
        liveCourseId,
      })
      .then((res) => {
        if (res.result) {
          const { recordDuration = 0, totalWatchNum = 0 } = res.result;
          this.setState({
            recordDuration,
            totalWatchNum,
          });
        }
      });
  };

  getLastTime = (time = 0) => {
    const diff = Math.floor(time % 3600);
    const hours = Math.floor(time / 3600);
    const mins = Math.floor(diff / 60);
    const seconds = Math.floor(time % 60);
    return hours + "小时" + mins + "分";
  };

  // 导出
  handleExport = () => {
    const { liveItem, type } = this.props;
    const { liveCourseId } = liveItem;
    const url = !type ? 'api-b/b/lesson/exportLargeClassLiveAsync' : 'api-b/b/lesson/exportClassInteractionLiveSync';
    window.axios.post(url, {
      liveCourseId,
      exportLiveType: 0
    }).then((res) => {
      Bus.trigger('get_download_count');
      Modal.success({
        title: '导出任务提交成功',
        content: '请前往右上角的“导出中心”进行下载',
        okText: '我知道了',
      });
    });
  }

  handleExportV5 = () => {
    const { liveItem, type } = this.props;
    const { liveCourseId } = liveItem;
    const url = !type ? 'public/businessLive/exportLargeClassLiveAsync' : 'public/businessLive/exportClassInteractionLiveSync';
    window.axios.Apollo(url, {
      liveCourseId,
      exportLiveType: 'PLAY_BACK'
    }).then((res) => {
      Bus.trigger('get_download_count');
      Modal.success({
        title: '导出任务提交成功',
        content: '请前往右上角的“任务中心”进行下载',
        okText: '我知道了',
      });
    });
  }

  render() {
    const columns = [
      {
        title: "观看者姓名",
        dataIndex: "userName",
      },
      {
        title: "观看者手机号",
        dataIndex: "phone",
        render: (text, record) => {
          return (
            <p>
              {!(
                (!window.NewVersion && !window.currentUserInstInfo.teacherId) ||
                (window.NewVersion && Permission.hasEduStudentPhone())
              )
                ? (text || "").replace(/(\d{3})(\d{4})(\d{4})/, "$1****$3")
                : text}
            </p>
          );
        },
      },
      {
        title: "观看者类型",
        dataIndex: "liveRole",
        key: "liveRole",
        render: (text) => <span>{liveTypeMap[text]}</span>,
      },
      {
        title: "开始观看时间",
        dataIndex: "entryTime",
        key: "entryTime",
        render: (text) => (
          <span>{text ? formatDate("YYYY-MM-DD H:i", parseInt(text)) : '-'}</span>
        ),
      },

      {
        title: "观看时长",
        dataIndex: "lookingDuration",
        key: "lookingDuration",
        render: (text) => {
          return <span>{text ? dealTimeDuration(text) : '-'}</span>;
        },
      },
    ];
    const {
      query,
      total,
      playBackList,
      totalWatchNum,
      recordDuration,
    } = this.state;
    const { type } = this.props;
    return (
      <Modal
        title="回放记录"
        className="play-back-modal"
        width={680}
        visible={true}
        maskClosable={false}
        closeIcon={<span className="icon iconfont modal-close-icon">&#xe6ef;</span>}
        footer={null}
        onCancel={() => {
          this.props.close();
        }}
      >
        {
          hasExportPermission(type) &&
          <Button onClick={_.debounce(() => {
            if (!playBackList.length) {
              message.warning('暂无数据可导出');
              return;
            }
            if (window.NewVersion) {
              this.handleExportV5();
            } else {
              this.handleExport();
            }
          }, 500, true)}>导出</Button>
        }
        <Table
          size="small"
          columns={columns}
          dataSource={playBackList}
          pagination={false}
          className="table-no-scrollbar"
        />
        <PageControl
          size="small"
          current={query.current - 1}
          pageSize={query.size}
          total={total}
          toPage={(page) => {
            this.fetchPlayBackList(page + 1);
          }}
        />
      </Modal>
    );
  }
}
export default PlayBackRecordModal;
