/*
 * @Author: 吴文洁
 * @Date: 2020-08-05 10:12:45
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-06-11 16:44:42
 * @Description: 视频课-列表模块
 * @Copyright: 杭州杰竞科技有限公司 版权所有
 */
import Service from '@/common/js/service';
import User from '@/common/js/user';
import college from '@/common/lottie/college';
import { PageControl, XMTable } from '@/components';
import { LIVE_SHARE } from '@/domains/course-domain/constants';
import CourseService from '@/domains/course-domain/CourseService';
import ShareLiveModal from '@/modules/course-manage/modal/ShareLiveModal';
import OfflineCourseData from '@/modules/course-manage/offline-course/OfflineCourseData';
import { Dropdown, message, Modal, Switch, Tooltip } from 'antd';
import moment from 'moment';
import React from 'react';
import { Route, withRouter } from 'react-router-dom';
import ENUM from '../../../knowledge-base/ENUM.js';
import PreviewOfflineModal from '../modal/PreviewOfflineModal';
import QRCodeModal from '../modal/QRCodeModal';
import './OfflineCourseList.less';

const defaultCoverUrl = 'https://image.xiaomaiketang.com/xm/pxbWKsYA87.png';

class OfflineCourseList 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);
    }
  }

  handlePlanName = (planArray) => {
    let planStr = '';
    planArray.map((item, index) => {
      if (index < planArray.length - 1) {
        planStr = planStr + item.planName + '、';
      } else {
        planStr = planStr + item.planName;
      }
    });
    return planStr;
  };
  // 请求表头
  parseColumns = () => {
    const columns = [
      {
        title: '线下课',
        key: 'scheduleName',
        dataIndex: 'scheduleName',
        width: 321,
        fixed: 'left',
        render: (val, record) => {
          const { courseMediaVOS, courseName, offlinePlace, calendarTime, startTime, endTime } = record;
          const coverUrl = (_.find(courseMediaVOS, (data) => data.contentType === 'COVER') || {}).mediaUrl;
          let isContinue = calendarTime.length > 1;
          _.reduce(calendarTime, (a, b) => {
            isContinue = isContinue && b - a === 86400000;
            return b;
          });
          const lastTime = _.last(calendarTime);
          const time = `${
            !isContinue
              ? calendarTime.map((item) => moment(item).format('MM-DD')).join('、')
              : `${moment(calendarTime[0]).format('MM-DD')}~${moment(lastTime).format('MM-DD')}`
          } ${moment(startTime).format('HH:mm')} ~ ${moment(endTime).format('HH:mm')}`;
          return (
            <div className='record__item'>
              <img className='course-cover' src={coverUrl || defaultCoverUrl} alt='' />
              <div style={{ width: 175 }}>
                <Tooltip title={courseName}>
                  <div className='course-name'>{courseName}</div>
                </Tooltip>
                <Tooltip title={`地点：${offlinePlace}`}>
                  <div className='course-text'>地点：{offlinePlace}</div>
                </Tooltip>
                <Tooltip title={time}>
                  <div className='course-text'>{time}</div>
                </Tooltip>
              </div>
            </div>
          );
        },
      },
      {
        title: '课程状态',
        key: 'courseState',
        dataIndex: 'courseState',
        width: 120,
        render: (val, record) => {
          return (
            <div className='course-state'>
              <div style={{ width: 6, height: 6, borderRadius: '50%', background: ENUM.offlineStateShow[val].color, marginRight: 8 }}></div>
              {ENUM.offlineStateShow[val].title}
            </div>
          );
        },
      },
      {
        title: '课程分类',
        key: 'categoryName',
        dataIndex: 'categoryName',
        width: 120,
        render: (val, record) => {
          return <div className='record__item'>{record.categorySonName}</div>;
        },
      },
      {
        title: (
          <span>
            <span>学院展示</span>
            <Tooltip
              title={
                <div>
                  开启后，学员可在学院内查看到此课程。若课程“取消”，则系统会自动“关闭”学院展示。
                  <br />
                  关闭后，学院内不再展示此课程，但学员仍可通过分享的海报/链接查看此课程。
                </div>
              }>
              <i className='icon iconfont' style={{ marginLeft: '5px', cursor: 'pointer', color: '#bfbfbf', fontSize: '14px', fontWeight: 'normal' }}>
                &#xe61d;
              </i>
            </Tooltip>
          </span>
        ),
        width: 120,
        dataIndex: 'courseware',
        render: (val, item, index) => {
          return <Switch disabled={item.courseState === 'EXPIRED'} checked={item.shelfState === 'YES'} onChange={() => this.changeShelfState(item)} />;
        },
      },
      {
        title: '讲师',
        width: 200,
        key: 'teacher',
        dataIndex: 'teacher',
        render: (val, item) => {
          return <div>{item.teacherName}</div>;
        },
      },
      {
        title: '报名时间',
        width: 200,
        key: 'apply',
        dataIndex: 'apply',
        sorter: true,
        render: (val, item) => {
          return (
            <div style={{ whiteSpace: 'nowrap' }}>
              {item.startTimeApply ? `${window.formatDate('MM-DD H:i', item.startTimeApply)} ~ ${window.formatDate('MM-DD H:i', item.endTimeApply)}` : '-'}
              {item.whetherApplyFull === 'YES' && (
                <span
                  style={{
                    marginLeft: 4,
                    color: '#FF4F4F',
                    background: 'rgba(255, 79, 79, 0.1)',
                    padding: '0 8px',
                    fontSize: '12px',
                    height: '18px',
                    lineHeight: '18px',
                  }}>
                  已报满
                </span>
              )}
            </div>
          );
        },
      },
      {
        title: '创建时间',
        width: 181,
        key: 'created',
        dataIndex: 'created',
        sorter: true,
        render: (val) => {
          return <span style={{ whiteSpace: 'nowrap' }}>{window.formatDate('YYYY-MM-DD H:i', val)}</span>;
        },
      },
      {
        title: '操作',
        key: 'operate',
        dataIndex: 'operate',
        width: 210,
        fixed: 'right',
        render: (val, record) => {
          return (
            <div className='operate'>
              <div className='operate__item' onClick={() => window.RCHistory.push(`/offline-course/data?id=${record.courseId}`)}>
                参与数据
              </div>
              {record.courseState !== 'EXPIRED' && <span className='operate__item split'> | </span>}
              {record.courseState !== 'EXPIRED' && (
                <div className='operate__item' onClick={() => this.handleShowShareModal(record)}>
                  分享
                </div>
              )}
              <span className='operate__item split'> | </span>
              <Dropdown overlay={this.renderMoreOperate(record)}>
                <span className='more-operate'>
                  <span className='operate-text'>更多</span>
                  <span className='iconfont icon' style={{ color: '#2966FF' }}>
                    &#xe824;
                  </span>
                </span>
              </Dropdown>
            </div>
          );
        },
      },
    ];
    return columns;
  };

  // 显示预览弹窗
  handleShowPreviewModal = (courseId) => {
    const previewOfflineModal = (
      <PreviewOfflineModal
        courseId={courseId}
        close={() => {
          this.setState({
            previewOfflineModal: null,
          });
        }}
      />
    );
    this.setState({ previewOfflineModal });
  };

  renderMoreOperate = (item) => {
    return (
      <div className='live-course-more-menu'>
        {item.courseState !== 'EXPIRED' && (item.whetherSetSignIn === 'YES' || item.whetherSetSignOut === 'YES') && (
          <div
            className='operate__item'
            key='qrcode'
            onClick={() => {
              this.setState({ openQRCodeModal: true, qrcodeData: item });
            }}>
            考勤二维码
          </div>
        )}
        <div
          className='operate__item'
          key='preview'
          onClick={() => {
            this.handleShowPreviewModal(item.courseId);
          }}>
          预览
        </div>
        {(User.getUserRole() === 'CloudManager' || User.getUserRole() === 'StoreManager') &&
          (item.courseState === 'UN_START' || item.courseState === 'STARTING') && (
            <div
              className='operate__item'
              key='cancel'
              onClick={() => {
                this.handleDeleteOfflineCourse(item.courseId);
              }}>
              取消课程
            </div>
          )}
        {item.courseState === 'UN_START' && window.ctx.xmState.storeUserPermissionList.includes('EditOfflineClass') && (
          <div
            className='operate__item'
            key='edit'
            onClick={() => {
              RCHistory.push(`/create-offline-course?type=edit&id=${item.courseId}`);
            }}>
            编辑
          </div>
        )}
        {(User.getUserRole() === 'CloudManager' || User.getUserRole() === 'StoreManager') && (
          <div className='operate__item' key='delete' onClick={() => this.handleDeleteOfflineCourse(item.courseId, true)}>
            删除
          </div>
        )}
      </div>
    );
  };
  //改变上架状态
  changeShelfState = (item) => {
    if (!window.ctx.xmState.storeUserPermissionList.includes('EditOfflineClass')) {
      message.warning('无【编辑线下课】权限，请联系管理员');
      return;
    }
    let _shelfState = item.shelfState;
    if (_shelfState === 'NO') {
      _shelfState = 'YES';
      item.shelfState = 'YES';
    } else {
      _shelfState = 'NO';
      item.shelfState = 'NO';
    }
    const params = {
      courseId: item.courseId,
      shelfState: _shelfState,
    };
    CourseService.changeVideoShelfState(params).then((res) => {
      if (res.success) {
        if (_shelfState === 'YES') {
          message.success('已开启展示');
        } else {
          message.success('已取消展示');
        }
        this.props.onChange();
      }
    });
  };
  // 删除视频课
  handleDeleteOfflineCourse = (courseId, isDelete) => {
    if (isDelete) {
      Modal.confirm({
        title: '删除课程',
        content: '确定删除该课程吗？删除后学员数据和课程数据将无法恢复。',
        icon: <span className='icon iconfont default-confirm-icon'>&#xe6f4;</span>,
        okText: '确定',
        okType: 'danger',
        cancelText: '取消',
        onOk: () => {
          const param = {
            courseId: courseId,
          };
          Service.Hades('public/hades/delOfflineCourse', param).then(() => {
            message.success('删除成功');
            this.props.onChange();
          });
        },
      });
    } else {
      Modal.confirm({
        title: '取消课程',
        content: '确定要取消该课程吗？取消后课程将失效，仅保留已有数据。',
        icon: <span className='icon iconfont default-confirm-icon'>&#xe6f4;</span>,
        okText: '确定',
        cancelText: '取消',
        onOk: () => {
          const param = {
            courseId: courseId,
          };
          Service.Hades('public/hades/cancelOfflineCourse', param).then(() => {
            message.success('取消成功');
            this.props.onChange();
          });
        },
      });
    }
  };

  // 显示分享弹窗
  handleShowShareModal = (record, needStr = false) => {
    const { courseId } = record;
    const htmlUrl = `${LIVE_SHARE}offline_detail/${courseId}?id=${User.getStoreId()}`;
    const longUrl = htmlUrl;
    const { courseName, courseMediaVOS } = record;
    const coverUrl = (_.find(courseMediaVOS, (data) => data.contentType === 'COVER') || {}).mediaUrl;
    const shareData = {
      longUrl,
      coverUrl,
      courseName,
    };

    const shareLiveModal = (
      <ShareLiveModal
        needStr={needStr}
        data={shareData}
        type='offlineClass'
        title='线下课'
        close={() => {
          this.setState({
            shareLiveModal: null,
          });
          localStorage.setItem('videoCourseItem', '');
        }}
      />
    );

    this.setState({ shareLiveModal });
  };

  handleChangeTable = (pagination, filters, sorter) => {
    const { columnKey, order } = sorter;
    const { query } = this.props;
    let _columnKey;
    let _order;
    // 按创建时间升序排序
    if (columnKey === 'apply' && order === 'ascend') {
      _columnKey = 'START_APPLY_DESC';
      _order = 'SORT_ASC';
    }
    if (columnKey === 'created' && order === 'ascend') {
      _columnKey = 'CREATED';
      _order = 'SORT_ASC';
    }
    // 按创建时间降序排序
    if (columnKey === 'apply' && order === 'descend') {
      _columnKey = 'START_APPLY_DESC';
      _order = 'SORT_DESC';
    }
    if (columnKey === 'created' && order === 'descend') {
      _columnKey = 'CREATED';
      _order = 'SORT_DESC';
    }
    const _query = {
      ...query,
      sortMap: {},
    };
    _query.sortMap[_columnKey] = _order;
    this.props.onChange(_query);
  };

  render() {
    const { openQRCodeModal, qrcodeData } = this.state;
    const { dataSource = [], totalCount, query, match } = this.props;
    const { current, size } = query;
    return (
      <div className='offline-course-list'>
        <XMTable
          renderEmpty={{
            image: college,
            description: '暂无数据',
          }}
          rowKey={(record) => record.courseId}
          dataSource={dataSource}
          columns={this.parseColumns()}
          onChange={this.handleChangeTable}
          pagination={false}
          scroll={{ x: 1300 }}
          bordered
          className='offline-list-table'
        />

        <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.previewOfflineModal}
        <QRCodeModal
          visible={openQRCodeModal}
          data={qrcodeData}
          onCancel={() => {
            this.setState({ openQRCodeModal: false });
          }}
        />
        <Route path={`${match.url}/data`} component={OfflineCourseData} />
      </div>
    );
  }
}

export default withRouter(OfflineCourseList);
