/*
 * @Description:
 * @Author: zangsuyun
 * @Date: 2021-03-13 11:48:24
 * @LastEditors: wufan
 * @LastEditTime: 2021-05-30 10:08:09
 * @Copyright: © 2020 杭州杰竞科技有限公司 版权所有
 */

import React from "react";
import { Table, Modal, message, Tooltip, Switch, Dropdown } from "antd";

import { PageControl } from "@/components";
import _ from "underscore";
import { LIVE_SHARE_MAP } from "@/common/constants/academic/cloudClass";
import { appId, shareUrl, LIVE_SHARE } from "@/domains/course-domain/constants";
import TableSelectedData from "@/components/TableSelectedData";
import "./LiveList.less";
import CourseService from "@/domains/course-domain/CourseService";
import User from "@/common/js/user";

const ENV = process.env.DEPLOY_ENV || "dev";

class VideoList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      id: "", // 线上课ID
      studentIds: [],
      selectedRowKeys: [],
      query: {
        size: 10,
        current: 1,
        storeId: User.getStoreId(),
      },
      dataSource: [], // 线上课列表
      totalCount: 0, // 线上课数据总条数
    };
  }

  componentDidUpdate(prevProps, prevState) {
    //必须写在if里面并且重新进行一次this.props !== prevProps的判断
    if (
      ((this.props.courseName || this.props.courseType) &&
        this.props.courseName !== prevProps.courseName) ||
      this.props.courseType !== prevProps.courseType
    ) {
      this.handleFetchScheduleList(this.props);
    }
  }

  componentWillMount() {
    // 获取线上课列表
    this.handleFetchScheduleList();
  }

  // 获取线上课列表
  handleFetchScheduleList = (_query = {}) => {
    const query = {
      ...this.state.query,
      ..._query,
    };

    // 更新请求参数
    this.setState({ query });

    CourseService.videoSchedulePage(query).then((res) => {
      const { result = {} } = res || {};
      const { records = [], total = 0 } = result;
      this.setState({
        dataSource: records,
        totalCount: Number(total),
      });
    });
  };

  dealTimeDuration = (time) => {
    const diff = Math.floor(time % 3600);
    let hours = Math.floor(time / 3600);
    let mins = Math.floor(diff / 60);
    let seconds = Math.floor(time % 60);
    hours = hours < 10 ? "0" + hours : hours;
    mins = mins < 10 ? "0" + mins : mins;
    seconds = seconds < 10 ? "0" + seconds : seconds;
    return hours + ":" + mins + ":" + seconds;
  };
  // 请求表头
  parseColumns = () => {
    const columns = [
      {
        title: (
          <span>
            <span>课程信息</span>
            <Tooltip
              title={
                <div>
                  已加入该分类的课程不支持重复选择，因此不显示。
                </div>
              }
            >
              <i
                className="icon iconfont"
                style={{
                  marginLeft: "5px",
                  cursor: "pointer",
                  color: "#bfbfbf",
                  fontSize: "14px",
                  fontWeight:"400"
                }}
              >
                &#xe61d;
              </i>
            </Tooltip>
          </span>
        ),
        key: "scheduleName",
        dataIndex: "scheduleName",
        width: 371,
        render: (val, record) => {
          const { coverUrl, scheduleVideoUrl } = record;
          return (
            <div className="record__item">
              {/* 上传了封面的话就用上传的封面, 没有的话就取视频的第一帧 */}
              <img
                className="course-cover"
                src={
                  coverUrl ||
                  `${scheduleVideoUrl}?x-oss-process=video/snapshot,t_0,m_fast`
                }
              />
              {record.courseName.length > 25 ? (
                <Tooltip title={record.courseName}>
                  <div className="course-name">{record.courseName}</div>
                </Tooltip>
              ) : (
                <div className="course-name">{record.courseName}</div>
              )}
            </div>
          );
        },
      },
      {
        title: "课程时长",
        key: "videoDuration",
        dataIndex: "videoDuration",
        render: (text, item) => {
          return <span>{text ? this.dealTimeDuration(text) : "-"}</span>;
        },
      },
      {
        title: "课程分类",
        key: "categoryName",
        dataIndex: "categoryName",
        render: (val, record) => {
          return (
            <div className="record__item">
              {record.categoryOneName}
              {record.categoryTwoName ? `-${record.categoryTwoName}` : ""}
            </div>
          );
        },
      },
    ];
    return columns;
  };

  selectLiveList = (record, selected) => {
    let { selectedRowKeys } = this.state;
    let _list = [];
    if (selected || !_.find(selectedRowKeys, (item) => item.id == record.id)) {
      _list = _.uniq(
        selectedRowKeys.concat([record]),
        false,
        (item) => item.id
      );
    } else {
      _list = _.reject(selectedRowKeys, (item) => item.id === record.id);
    }
    this.setState({ selectedRowKeys: _list });
  };

  render() {
    const { dataSource = [], totalCount, query, selectedRowKeys } = this.state;
    const { current, size } = query;
    const rowSelection = {
      selectedRowKeys: _.pluck(selectedRowKeys, "id"),
      onSelect: this.selectLiveList,
      onSelectAll: (selected, _selectedRows, changeRows) => {
        let _list = [];
        if (selected) {
          _list = _.uniq(
            selectedRowKeys.concat(changeRows),
            false,
            (item) => item.id
          );
        } else {
          _list = _.reject(selectedRowKeys, (item) =>
            _.find(changeRows, (data) => data.id === item.id)
          );
        }
        this.setState({ selectedRowKeys: _list });
      },
    };

    return (
      <div className="live-list">
        <TableSelectedData
          selectedNum={selectedRowKeys.length}
          clearSelectedData={() => {
            this.setState({
              selectedRowKeys: [],
            });
          }}
        />
        <Table
          rowKey={(record) => record.id}
          dataSource={dataSource}
          columns={this.parseColumns()}
          size="middle"
          rowSelection={rowSelection}
          pagination={false}
          bordered
          className="video-list-table"
        />

        <div className="box-footer">
          {totalCount > 0 && (
            <PageControl
              current={current - 1}
              pageSize={size}
              total={totalCount}
              toPage={(page) => {
                const _query = { ...query, current: page + 1 };
                this.handleFetchScheduleList(_query);
              }}
            />
          )}
        </div>
      </div>
    );
  }
}

export default VideoList;
