import React from "react";
import { withRouter } from "react-router-dom";
import { Table, Popover, message, Button, Spin } from "antd";
import dealTimeDuration from "../utils/dealTimeDuration";
import { PageControl } from "@/components";
import CourseService from "@/domains/course-domain/CourseService";
import User from "@/common/js/user";
import "./DataList.less";
class DataList extends React.Component {
  constructor(props) {
    super(props);
    const courseId = getParameterByName("id"); // 课程ID
    const type = getParameterByName("type"); // 来源: 大班直播 large 互动班课 interactive
    this.state = {
      type,
      teacherData: [], // 老师上课数据
      studentData: [], // 学员上课数据
      current: 1,
      size: 10, // 添加扣课时学员弹窗回填所需 当前接口返回全部列表
      total: 0,
      loading: true,
      liveCourseId: courseId,
      storeId: User.getStoreId(),
    };
  }

  componentDidMount() {
    this.fetchLecturerData();
    this.fetchUserData();
  }

  // 获取学员上课数据
  fetchUserData = (current = 1) => {
    this.setState({ loading: true });
    const { liveCourseId, size } = this.state;
    const params = {
      liveCourseId,
      current,
      size,
    };
    CourseService.fetchUserData(params).then((res) => {
      if (res.result) {
        const { records = [], current, size, total } = res.result;

        this.setState({
          studentData: records,
          current,
          size,
          total,
          loading: false,
        });
      }
    });
  };
  // 获取老师上课数据
  fetchLecturerData = () => {
    const { liveCourseId } = this.state;
    CourseService.fetchLecturerData({ liveCourseId }).then((res) => {
      if (res.result) {
        this.setState({
          teacherData: res.result,
        });
      }
    });
  };

  // 进入直播次数列表
  getVisiterColumns() {
    const columns = [
      {
        title: "序号",
        dataIndex: "index",
        width: 50,
        render: (text, record, index) => {
          return <span>{index + 1}</span>;
        },
      },
      {
        title: "进入时间",
        dataIndex: "entryTime",
        width: 150,
        render: (text) => (
          <span>{formatDate("YYYY-MM-DD H:i", parseInt(text))}</span>
        ),
      },
      {
        title: "离开时间",
        dataIndex: "leaveTime",
        width: 150,
        render: (text) => (
          <span>{formatDate("YYYY-MM-DD H:i", parseInt(text))}</span>
        ),
      },
      {
        title: "在线时长",
        dataIndex: "lookingDuration",
        render: (text, record) => {
          return <span>{text ? dealTimeDuration(text) : "-"}</span>;
        },
      },
    ];
    return columns;
  }

  // 学员上课数据列表
  getStudentColumns() {
    const columns = [
      {
        title: "用户姓名",
        dataIndex: "userName",
      },
      {
        title: "手机号",
        dataIndex: "phone",
        render: (text, record) => {
          const { phone = "", bindingWeChat } = record;
          return <div>{phone}</div>;
        },
      },
      {
        title: "观看次数",
        dataIndex: "entryNum",
        render: (text, record) => {
          if (text > 0) {
            if (
              record.visitorInfoVOList &&
              record.visitorInfoVOList.length > 0
            ) {
              const table = (
                <Table
                  columns={this.getVisiterColumns()}
                  dataSource={record.visitorInfoVOList}
                  scroll={{ y: 75 }}
                  size={"small"}
                  style={{ width: 450 }}
                  pagination={false}
                />
              );
              return (
                <Popover content={table} trigger="click">
                  <span className="handel-btn">{text}</span>
                </Popover>
              );
            } else {
              return <div className="live-table--empty">暂无观看数据</div>;
            }
          } else {
            return <span>{text}</span>;
          }
        },
      },
      {
        title: "累计在线时长",
        dataIndex: "totalDuration",
        sorter: (a, b) => a.totalDuration - b.totalDuration,
        sortDirections: ["descend", "ascend"],
        render: (text, record) => {
          //如无离开时间，就置空
          return <span>{text ? dealTimeDuration(text) : "00:00:00"}</span>;
        },
      },
    ];

    return columns;
  }
  // 学员导出5.0
  handleExportV5 = () => {
    const { liveCourseId, storeId } = this.state;

    CourseService.exportStudentCourseData({
      liveCourseId: liveCourseId,
      exportLiveType: "VISITOR",
      storeId,
    }).then((res) => {
      const link = res.result;
      this.setState({
        link
      });
      document.getElementById("loadExcel").click();

      if (res.success) {
        message.success("导出成功！");
      }
    });
  };

  handleCheckEnterTimes = () => {
    const { teacherData } = this.state;
    if (teacherData.entryNum > 0) {
      if (
        teacherData.visitorInfoVOList &&
        teacherData.visitorInfoVOList.length > 0
      ) {
        const table = (
          <Table
            columns={this.getVisiterColumns()}
            dataSource={teacherData.visitorInfoVOList}
            scroll={{ y: 75 }}
            size={"small"}
            style={{ width: 450 }}
            pagination={false}
          />
        );
        return (
          <Popover content={table} trigger="click">
            <span className="times-num">{teacherData.entryNum}</span>
          </Popover>
        );
      } else {
        return <div className="live-table--empty">暂无观看数据</div>;
      }
    } else {
      return <span>{teacherData.entryNum}</span>;
    }
  };

  showTable = () => {
    return (
      <Table
        columns={this.getVisiterColumns()}
        dataSource={this.state.teacherData.visitorInfoVOList}
        scroll={{ y: 75 }}
        size={"small"}
        style={{ width: 450 }}
        pagination={false}
        className="visitor-num-table"
      />
    );
  };
  
  onShowSizeChange = (current, size) => {
    if (current == size) {
      return;
    }
    this.setState({ size }, this.fetchUserData)
  }

  render() {
    const {
      teacherData,
      studentData,
      current,
      size,
      total,
      loading,
      link
    } = this.state;
    return (
      <Spin spinning={loading}>
                <a
          href={link}
          target="_blank"
          download
          id="loadExcel"
          style={{ position: "absolute", left: "-10000px" }}
        >
          111
        </a>
        {/* 讲师上课数据 */}
        <div className="courseData-teacher">
          <p className="title">讲师上课数据</p>
          <div className="teacher-course-data">
            <div className="avatar-name-phone item-block">
              <img
                src={
                  teacherData.avatar ||
                  "https://image.xiaomaiketang.com/xm/rJeQaZxtc7.png"
                }
                alt=""
                className="avatar"
              />
              <div className="right">
                <div className="name">{teacherData.userName}</div>
                <div className="phone">
                  {teacherData.phone}
                </div>
              </div>
            </div>

            <div className="times item-block">
              <div
                className={`times-num ${
                  Number(teacherData.entryNum) > 0 ? "can-click" : ""
                }`}
              >{
                Number(teacherData.entryNum) > 0 ? 
                  <Popover content={this.showTable()} trigger="click">
                    <span className="times-num">{teacherData.entryNum || 0}</span>
                  </Popover>:
                  <span className="times-num">{0}</span>
              }
              </div>
              <div className="text">进入直播间次数</div>
            </div>

            <div className="online-duration item-block">
              <div className="duration">
                {teacherData.totalDuration
                  ? dealTimeDuration(teacherData.totalDuration)
                  : "00:00:00"}
              </div>
              <div className="text">累计在线时长</div>
            </div>
          </div>
        </div>

        {/* 用户上课数据 */}
        <div className="courseData-student">
          <p className="title">用户上课数据</p>
          <div className="filter-wrap">
            <div className="filter">
              <Button
                style={{ height: 32}}
                onClick={_.debounce(
                  () => {
                    if (!studentData.length) {
                      message.warning("暂无数据可导出");
                      return;
                    }
                    this.handleExportV5();
                  },
                  500,
                  true
                )}
              >
                导出
              </Button>
            </div>
          </div>

          <Table
            bordered
            size="small"
            scroll={{ y: 600 }}
            columns={this.getStudentColumns()}
            dataSource={studentData}
            pagination={false}
            style={{ margin: "16px 0" }}
          />
          { total > 0 &&
            <PageControl
              size="small"
              current={current - 1}
              pageSize={size}
              total={total}
              onShowSizeChange={this.onShowSizeChange}
              toPage={(page) => {
                this.fetchUserData(page + 1);
              }}
            />
          }
        </div>
      </Spin>
    );
  }
}

export default withRouter(DataList);
