/*
 * @Description:
 * @Author: zangsuyun
 * @Date: 2021-03-13 14:38:49
 * @LastEditors: zangsuyun
 * @LastEditTime: 2021-03-16 15:20:51
 * @Copyright: © 2020 杭州杰竞科技有限公司 版权所有
 */

import React from "react";
import { Table, Modal, message, Dropdown, Button, Switch, Tooltip } from "antd";
import { Route, withRouter } from "react-router-dom";
import { PageControl } from "@/components";
import "./LiveList.less";
import TableSelectedData from "@/components/TableSelectedData";
import CourseService from "@/domains/course-domain/CourseService";
import User from "@/common/js/user";
import _ from "underscore";

const { confirm } = Modal;
const courseStateShow = {
  UN_START: {
    code: 1,
    title: "待开课",
    color: "#2966FF",
  },
  STARTING: {
    code: 2,
    title: "上课中",
    color: "#238FFF",
  },
  FINISH: {
    code: 3,
    title: "已完成",
    color: "#3BBDAA",
  },
  EXPIRED: {
    code: 4,
    title: "未成功开课",
    color: "#999",
  },
};
class LiveList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      columns: [],
      courseList: [], // 直播课列表
      selectedRowKeys: [],
      query: {
        current: 1,
        size: 10,
      },
      total: 0,
    };
  }

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

  componentWillMount() {
    this.handleFetchLiveList(this.state.query);
    this.parseColumns();
  }

  // 获取直播课列表
  handleFetchLiveList = (_query) => {
    const { query } = this.state;
    const params = {
      ...query,
      ..._query,
      storeId: User.getStoreId(),
    };
    this.setState({ query: params });
    CourseService.getLiveCloudCoursePage(params).then((res) => {
      const {
        result: { records = [], total },
      } = res;
      this.setState({
        total,
        courseList: records,
      });
    });
  };

  parseColumns = () => {
    let columns;
    columns = [
      {
        title: (
          <span>
            <span>课程信息</span>
            <Tooltip
              title={<div>已加入该分类的课程不支持重复选择，因此不显示。</div>}
            >
              <i
                className="icon iconfont"
                style={{
                  marginLeft: "5px",
                  cursor: "pointer",
                  color: "#bfbfbf",
                  fontSize: "14px",
                }}
              >
                &#xe61d;
              </i>
            </Tooltip>
          </span>
        ),
        width: 371,
        key: "course",
        dataIndex: "courseName",
        render: (val, record) => {
          let hasCover = false;
          return (
            <div className="record__item">
              {record.courseMediaVOS.map((item, index) => {
                if (item.contentType === "COVER") {
                  hasCover = true;
                  return <img className="course-cover" src={item.mediaUrl} />;
                }
              })}
              {!hasCover && (
                <img
                  className="course-cover"
                  src={"https://image.xiaomaiketang.com/xm/YNfi45JwFA.png"}
                />
              )}
              <div>
                {record.courseName.length > 17 ? (
                  <Tooltip title={record.courseName}>
                    <div className="course-name">{record.courseName}</div>
                  </Tooltip>
                ) : (
                  <div className="course-name">{record.courseName}</div>
                )}
                <div>
                  <span
                    className="course-status"
                    style={{
                      color: courseStateShow[record.courseState].color,
                      border: `1px solid ${
                        courseStateShow[record.courseState].color
                      }`,
                    }}
                  >
                    {courseStateShow[record.courseState].title}
                  </span>
                </div>
              </div>
            </div>
          );
        },
      },
      {
        title: "上课时间",
        // width: "10%",
        key: "couseCatalog",
        dataIndex: "couseCatalog",
        render: (val, item) => {
          return (
            <span className="course-time">
              {formatDate("YYYY-MM-DD", parseInt(item.startTime))} <br></br>
              {formatDate("H:i", parseInt(item.startTime))}~
              {formatDate("H:i", parseInt(item.endTime))}
            </span>
          );
        },
      },

      {
        title: "课程分类",
        // width: "10%",
        key: "couseCatalog",
        dataIndex: "couseCatalog",
        render: (val, item) => {
          return <div className="categoryName">{item.categoryName}</div>;
        },
      },
    ];

    this.setState({ columns });
  };

  onShowSizeChange = (current, size) => {
    if (current == size) {
      return;
    }
    let _query = this.state.query;
    _query.size = size;
    this.handleFetchLiveList(_query);
  };

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

  render() {
    const {
      columns,
      total,
      query,
      courseList,
      loading,
      selectedRowKeys,
    } = this.state;
    const { current, size } = query;

    const rowSelection = {
      selectedRowKeys: _.pluck(selectedRowKeys, "liveCourseId"),
      onSelect: this.selectVideoList,
      onSelectAll: (selected, _selectedRows, changeRows) => {
        let _list = [];
        if (selected) {
          _list = _.uniq(
            selectedRowKeys.concat(changeRows),
            false,
            (item) => item.liveCourseId
          );
        } else {
          _list = _.reject(selectedRowKeys, (item) =>
            _.find(
              changeRows,
              (data) => data.liveCourseId === item.liveCourseId
            )
          );
        }
        this.setState({ selectedRowKeys: _list });
      },
    };

    return (
      <div className="live-list">
        <TableSelectedData
          selectedNum={selectedRowKeys.length}
          clearSelectedData={() => {
            this.setState({
              selectedRowKeys: [],
            });
          }}
        />
        <Table
          bordered
          size="middle"
          pagination={false}
          columns={columns}
          rowSelection={rowSelection}
          loading={loading}
          dataSource={courseList}
          rowKey={(row) => row.liveCourseId}
        />
        {total > 0 && (
          <div className="box-footer">
            <PageControl
              current={current - 1}
              pageSize={size}
              total={parseInt(total)}
              toPage={(page) => {
                const _query = { ...query, current: page + 1 };
                this.handleFetchLiveList(_query);
              }}
              onShowSizeChange={this.onShowSizeChange}
            />
          </div>
        )}
      </div>
    );
  }
}

export default withRouter(LiveList);
