/*
 * @Author: 吴文洁
 * @Date: 2020-08-05 10:12:45
 * @LastEditors: zhangleyuan
 * @LastEditTime: 2020-12-26 14:10:44
 * @Description: 视频课-列表模块
 * @Copyright: 杭州杰竞科技有限公司 版权所有
 */
import React from 'react';
import { Table, Modal, message } from 'antd';

import { PageControl } from "@/components";
import { LIVE_SHARE_MAP } from '@/common/constants/academic/cloudClass';

import StudentListModal from '../modal/StudentListModal';
import ShareLiveModal from '@/modules/course-manage/modal/ShareLiveModal';

import './VideoCourseList.less';

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

class VideoCourseList extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      id: '', // 视频课ID
      studentIds:[]
    }
  }

   componentDidMount() {
    const videoCourseItem = localStorage.getItem('videoCourseItem');
    if (videoCourseItem) {
      const _videoCourseItem = JSON.parse(videoCourseItem);
      this.handleShowShareModal(_videoCourseItem, true);
    }
  }

  // 请求表头
  parseColumns = () => {
    const columns = [
      {
        title: '视频课',
        key: 'scheduleName',
        dataIndex: 'scheduleName',
        width: '25%',
        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`} />
              <span className="course-name">{val}</span>
            </div>
          )
        }
      },
      {
        title: '学员人数',
        key: "stuNum",
        dataIndex: "stuNum",
        render: (val, record) => {
          return (
            <span
              className="operate-text"
              onClick={() => this.handleShowStudentListModal(record)}
            >
              {val}
            </span>
          );
        },
      },
      {
        title: '创建人',
        key: 'teacherName',
        dataIndex: 'teacherName'
      },
      {
        title: '创建时间',
        key: 'createTime',
        dataIndex: 'createTime',
        sorter: true,
        render: (val) => {
          return formatDate('YYYY-MM-DD H:i', val) 
        }
      },
      {
        title: '更新时间',
        key: 'updateTime',
        dataIndex: 'updateTime',
        sorter: true,
        render: (val) => {
          return formatDate('YYYY-MM-DD H:i', val) 
        }
      },
      {
        title: '操作',
        key: 'operate',
        dataIndex: 'operate',
        render: (val, record) => {
          return (
            <div className="operate">
              <div className="operate__item" onClick={() => this.handleShowShareModal(record)}>分享</div>
              <span className="operate__item split"> | </span>
              <div
                className="operate__item"
                onClick={() => {
                  RCHistory.push(`/cloudclass/video_course/create?type=edit&id=${record.id}`);
                }}
              >编辑</div>
              <span className="operate__item split"> | </span>
              <div
                className="operate__item"
                onClick={() => this.handleDeleteVideoCourse(record.id)}
              >删除</div>
            </div>
          )
        }
      }
    ];
    return columns;
  }

  // 删除视频课
  handleDeleteVideoCourse = (scheduleId) => {
    Modal.confirm({
      title: '你确定要删除此视频课吗？',
      content: '删除后，学员将不能进行观看。',
      icon: <span className="icon iconfont default-confirm-icon">&#xe6f4;</span>,
      onOk: () => {
        window.axios.Apollo('public/apollo/removeLessonSchedule', {
          scheduleId
        }).then(() => {
          message.success('删除成功');
          this.props.onChange();
        })
      }
    });
  }

  // 学员人数弹窗
  handleShowStudentListModal = (record) => {
    
    const { studentIds = [], id } = this.state;
    if (id !== record.id) {
      this.setState({
        id : record.id
      })
    }
    const studentListModal = (
      <StudentListModal
        type='videoCourseList'
        close={(studentIds) =>
          this.setState({
            studentListModal: null,
            studentIds
          })
        }
        studentIds={studentIds}
        data={record}
        refresh={() => {
          this.props.onChange();
        }}
      />
    );
    this.setState({ studentListModal });
  }

  // 显示分享弹窗
  handleShowShareModal = (record, needStr = false) => {
    const appId =  CONFIG.appId[ENV];
    const shareUrl = CONFIG.shareUrl[ENV];
    const { id, scheduleVideoUrl } = record;

    const htmlUrl = `${LIVE_SHARE_MAP[ENV]}videoShare?id=${id}`;
    const link = `${appId}&redirect_uri=${encodeURIComponent(htmlUrl)}%26appid%3D${appId}&response_type=code&scope=snsapi_base&state=state#wechat_redirect`;
    const longUrl = `${shareUrl}${link}`;

    const { coverUrl, scheduleName } = record;
    const shareData = {
      longUrl,
      coverUrl,
      scheduleVideoUrl,
      courseName: scheduleName,
    };

    const shareLiveModal = (
      <ShareLiveModal
        needStr={needStr}
        data={shareData}
        type="videoClass"
        close={() => {
          this.setState({
            shareLiveModal:  null
          });
          localStorage.setItem('videoCourseItem', '');
        }}
      />
    );

    this.setState({ shareLiveModal });
  }

  handleChangeTable = (pagination, filters, sorter) => {
    const { columnKey, order } = sorter;
    const { query } = this.props;
    let { order: _order } =query;
    // 按创建时间升序排序
    if (columnKey === 'createTime' && order === 'ascend') { _order = 'CREATED_ASC'; }
    // 按创建时间降序排序
    if (columnKey === 'createTime' && order === 'descend') { _order = 'CREATED_DESC'; }
    // 按更新时间升序排序
    if (columnKey === 'updateTime' && order === 'ascend') { _order = 'UPDATED_ASC'; }
    // 按更新时间降序排序
    if (columnKey === 'updateTime' && order === 'descend') { _order = 'UPDATED_DESC'; }

    const _query = {
      ...query,
      order: _order
    };
    this.props.onChange(_query);
  }
  
  render() {

    const { dataSource = [], totalCount, query } = this.props;
    const { current, size } = query;

    return (
      <div className="video-course-list">
        <Table
          rowKey={record => record.id}
          dataSource={dataSource}
          columns={this.parseColumns()}
          onChange={this.handleChangeTable}
          pagination={false}
        />

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

export default VideoCourseList;
