import React from 'react';
import _ from 'underscore';
import { Table, Radio, Tabs, Modal, Input, message, Button, Tooltip } from 'antd';

import { PageControl, XMTable } from '@/components';
import college from '@/common/lottie/college';

import CourseService from '@/domains/course-domain/CourseService';
import User from '@/common/js/user';
import Service from '@/common/js/service';
import dealTimeDuration from '../../course-manage/utils/dealTimeDuration';

import './relatedCourseModal.less';

const { Search } = Input;
const { TabPane } = Tabs;
const courseStateShow = {
  UN_START: {
    code: 1,
    title: '待开课',
    color: '#FFB129',
  },
  STARTING: {
    code: 2,
    title: '上课中',
    color: '#238FFF',
  },
  FINISH: {
    code: 3,
    title: '已完成',
    color: '#3BBDAA',
  },
  EXPIRED: {
    code: 4,
    title: '未成功开课',
    color: '#999',
  },
};
class SelectOperatorModal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      liveDataSource: [],
      liveSize: 10,
      liveQuery: {
        current: 1,
      },
      liveTotalCount: 0,
      selectLive: [], //弹窗内已选择的直播课程
      currentCourseListData: [],
      currentLiveCourseListData: [], //页面中已关联的直播课程

      videoCourseDivision: 'internal',
      videoDataSource: {
        external: [],
        internal: [],
      },
      videoSize: {
        external: 10,
        internal: 10,
      },
      videoSearchName: {
        external: '',
        internal: '',
      },
      videoSearchDefalt: '',
      videoQuery: {
        external: {
          current: 1,
        },
        internal: {
          current: 1,
        },
      },
      videoTotalCount: {
        external: 0,
        internal: 0,
      },
      selectVideo: {
        external: [],
        internal: [],
      }, //弹窗内已选择的视频课程
      currentVideoCourseListData: {
        external: [],
        internal: [],
      }, //页面中已关联的视频课程

      pictureDataSource: [],
      pictureSize: 10,
      pictureQuery: {
        current: 1,
      },
      pictureTotalCount: 0,
      selectPicture: [], //弹窗内已选择的视频课程
      currentPictureCourseListData: [], //页面中已关联的视频课程

      activeKey: 'video',
      currentTaskCourseData: this.props.data[this.props.selectedTaskIndex].courseList || [],
    };
  }

  componentDidMount() {
    this.handleFetchLiveDataList();
    this.handleFetchVideoDataList();
    this.handleFetchPictureDataList();
  }

  // 获取直播课列表
  handleFetchLiveDataList = () => {
    const { liveQuery, liveSize } = this.state;
    const _data = [...this.props.data];
    let currentLiveCourseListData = [];
    _data.map((item) => {
      item.courseList.map((childItem, childIndex) => {
        if (childItem.courseType === 'LIVE') {
          currentLiveCourseListData.push(childItem.courseId);
        }
        return childItem;
      });
      return item;
    });
    const params = {
      ...liveQuery,
      size: liveSize,
      excludeCourseIdList: currentLiveCourseListData,
    };

    CourseService.getLiveCloudCourseBasePage(params).then((res) => {
      const { result = {} } = res;
      const { records = [], total = 0 } = result;
      this.setState({
        liveDataSource: records,
        liveTotalCount: Number(total),
        currentLiveCourseListData,
      });
    });
  };

  // 获取视频课列表
  handleFetchVideoDataList = () => {
    const { videoQuery, videoSize, videoDataSource, videoTotalCount, videoCourseDivision } = this.state;

    const _data = [...this.props.data];
    let currentVideoCourseListData = [];
    _data.map((item, index) => {
      item.courseList.map((childItem, childIndex) => {
        if (childItem.courseType === 'VOICE') {
          currentVideoCourseListData.push(childItem.courseId);
        }
        return childItem;
      });
      return item;
    });
    const params = {
      ...videoQuery[videoCourseDivision],
      size: videoSize[videoCourseDivision],
      courseDivision: videoCourseDivision === 'internal' ? 'INTERNAL' : 'EXTERNAL',
      excludeCourseIdList: currentVideoCourseListData,
    };
    CourseService.videoScheduleBasePage(params).then((res) => {
      const { result = {} } = res;
      console.log('result', result);

      const { records = [], total = 0 } = result;

      this.setState({
        videoDataSource: {
          ...videoDataSource,
          [videoCourseDivision]: records,
        },
        videoTotalCount: {
          ...videoTotalCount,
          [videoCourseDivision]: Number(total),
        },
        currentVideoCourseListData,
      });
    });
  };

  // 获取图文课列表
  handleFetchPictureDataList = () => {
    const { pictureQuery, pictureSize } = this.state;
    const _data = [...this.props.data];
    let currentPictureCourseListData = [];
    _data.map((item, index) => {
      item.courseList.map((childItem, childIndex) => {
        if (childItem.courseType === 'PICTURE') {
          currentPictureCourseListData.push(childItem.courseId);
        }
        return childItem;
      });
      return item;
    });
    const params = {
      ...pictureQuery,
      size: pictureSize,
      courseType: 'PICTURE',
      storeId: User.getStoreId(),
      excludeCourseIdList: currentPictureCourseListData,
    };

    Service.Hades('public/hades/mediaCoursePage', params).then((res) => {
      const { result = {} } = res;
      const { records = [], total = 0 } = result;
      this.setState({
        pictureDataSource: records,
        pictureTotalCount: Number(total),
        currentPictureCourseListData,
      });
    });
  };

  handleChangVideoCourseName = (value) => {
    const { videoQuery, videoCourseDivision, videoSearchName } = this.state;
    videoQuery[videoCourseDivision].courseName = value;
    videoQuery[videoCourseDivision].current = 1;
    this.setState({
      ...videoQuery,
      videoSearchDefalt: value,
      videoSearchName: {
        ...videoSearchName,
        [videoCourseDivision]: value,
      },
    });
  };

  handleChangLiveCourseName = (value) => {
    const { liveQuery } = this.state;
    liveQuery.courseName = value;
    liveQuery.current = 1;
    this.setState({
      liveQuery,
    });
  };

  handleChangPictureCourseName = (value) => {
    const { pictureQuery } = this.state;
    pictureQuery.courseName = value;
    pictureQuery.current = 1;
    this.setState({
      pictureQuery,
    });
  };

  onShowLiveSizeChange = (current, size) => {
    if (current === size) {
      return;
    }
    this.setState(
      {
        liveSize: size,
      },
      () => {
        this.handleFetchLiveDataList();
      }
    );
  };

  onShowVideoSizeChange = (current, size) => {
    if (current === size) {
      return;
    }
    this.setState(
      {
        videoSize: size,
      },
      () => {
        this.handleFetchLiveDataList();
      }
    );
  };

  onShowPictureSizeChange = (current, size) => {
    if (current === size) {
      return;
    }
    this.setState(
      {
        pictureSize: size,
      },
      () => {
        this.handleFetchPictureDataList();
      }
    );
  };

  // 请求表头
  parseLiveColumns = () => {
    const columns = [
      {
        title: (
          <span>
            <span>课程信息</span>
            <Tooltip title='仅显示未关联课程，已关联课程不支持重复选择'>
              <i className='icon iconfont' style={{ marginLeft: '5px', cursor: 'pointer', color: '#bfbfbf', fontSize: '14px', fontWeight: '400' }}>
                &#xe61d;
              </i>
            </Tooltip>
          </span>
        ),
        key: 'course',
        dataIndex: 'course',
        width: '40%',
        render: (val, record) => {
          let hasCover = false;
          return (
            <div className='course-info'>
              {record.courseMediaVOS.map((item) => {
                if (item.contentType === 'COVER') {
                  hasCover = true;
                  return <img className='course-cover' src={item.mediaUrl} alt='' />;
                }
                return null;
              })}
              <If condition={!hasCover}>
                <img className='course-cover' src={'https://image.xiaomaiketang.com/xm/Yip2YtFDwH.png'} alt='' />
              </If>

              <div>
                <div className='course-name'>{record.courseName}</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>
          );
        },
      },
      {
        title: '上课时间',
        key: 'courseTime',
        dataIndex: 'courseTime',
        width: '40%',
        render: (val, record) => {
          return (
            <div>
              <div>{formatDate('YYYY-MM-DD', record.startTime)}</div>
              <div>
                {formatDate('H:i', record.startTime)}~{formatDate('H:i', record.endTime)}
              </div>
            </div>
          );
        },
      },
      {
        title: '学院展示',
        key: 'shelfState',
        dataIndex: 'shelfState',
        width: '20%',
        render: (val, record) => {
          return (
            <span>
              <Choose>
                <When condition={record.shelfState === 'YES'}>
                  <span>开启</span>
                </When>
                <Otherwise>
                  <span>关闭</span>
                </Otherwise>
              </Choose>
            </span>
          );
        },
      },
    ];
    return columns;
  };

  // 请求表头
  parseVideoColumns = () => {
    const { videoCourseDivision } = this.state;
    const columns = [
      {
        title: (
          <span>
            <span>课程信息</span>
            <Tooltip title='仅显示未关联课程，已关联课程不支持重复选择'>
              <i className='icon iconfont' style={{ marginLeft: '5px', cursor: 'pointer', color: '#bfbfbf', fontSize: '14px', fontWeight: '400' }}>
                &#xe61d;
              </i>
            </Tooltip>
          </span>
        ),
        key: 'course',
        dataIndex: 'course',
        width: '60%',
        render: (val, record) => {
          const { coverUrl, scheduleVideoUrl } = record;
          return (
            <div className='course-info'>
              {/* 上传了封面的话就用上传的封面, 没有的话就取视频的第一帧 */}
              <img
                className='course-cover'
                src={
                  coverUrl ||
                  (videoCourseDivision === 'internal'
                    ? `${scheduleVideoUrl}?x-oss-process=video/snapshot,t_0,m_fast`
                    : 'https://image.xiaomaiketang.com/xm/mt3ZQRxGKB.png')
                }
                alt=''
              />

              <div className='course-name'>{record.courseName}</div>
            </div>
          );
        },
      },
      {
        title: '课程时长',
        key: 'courseTime',
        dataIndex: 'courseTime',
        width: '20%',
        render: (val, record) => {
          return <span className='course-status'>{dealTimeDuration(record.videoDuration)}</span>;
        },
      },
      {
        title: '学院展示',
        key: 'shelfState',
        dataIndex: 'shelfState',
        width: '20%',
        render: (val, record) => {
          return (
            <Choose>
              <When condition={record.shelfState === 'YES'}>
                <span>开启</span>
              </When>
              <Otherwise>
                <span>关闭</span>
              </Otherwise>
            </Choose>
          );
        },
      },
    ];
    return columns;
  };

  // 请求表头
  parsePictureColumns = () => {
    const columns = [
      {
        title: (
          <span>
            <span>课程信息</span>
            <Tooltip title='仅显示未关联课程，已关联课程不支持重复选择'>
              <i className='icon iconfont' style={{ marginLeft: '5px', cursor: 'pointer', color: '#bfbfbf', fontSize: '14px', fontWeight: '400' }}>
                &#xe61d;
              </i>
            </Tooltip>
          </span>
        ),
        key: 'course',
        dataIndex: 'course',
        width: '55%',
        render: (val, record) => {
          const { coverUrl } = record;
          return (
            <div className='course-info'>
              <img className='course-cover' src={coverUrl || 'https://image.xiaomaiketang.com/xm/wFnpZtp2yB.png'} alt='' />
              <div className='course-name'>{record.courseName}</div>
            </div>
          );
        },
      },
      {
        title: '更新时间',
        key: 'updated',
        dataIndex: 'updated',
        width: '25%',
        render: (val, record) => {
          return <span className='course-status'>{formatDate('YYYY-MM-DD', record.updated)}</span>;
        },
      },
      {
        title: '学院展示',
        key: 'shelfState',
        dataIndex: 'shelfState',
        width: '20%',
        render: (val, record) => {
          return <span>{record.shelfState === 'YES' ? '开启' : '关闭'}</span>;
        },
      },
    ];
    return columns;
  };
  selectLiveList = (record, selected) => {
    const { selectVideo, currentTaskCourseData, selectLive, selectPicture } = this.state;
    let _list = [];
    if (selected || !_.find(selectLive, (item) => item.liveCourseId === record.liveCourseId)) {
      _list = _.uniq(selectLive.concat([record]), false, (item) => item.liveCourseId);
    } else {
      _list = _.reject(selectLive, (item) => item.liveCourseId === record.liveCourseId);
    }
    if (_list.length + currentTaskCourseData.length + selectVideo.internal.length + selectVideo.external.length + selectPicture.length > 20) {
      message.warning('无法继续选择，一个任务最多关联20个课程');
      return;
    }
    this.setState({ selectLive: _list });
  };

  selectVideoList = (record, selected) => {
    const { selectVideo, currentTaskCourseData, selectLive, selectPicture, videoCourseDivision } = this.state;

    let { [videoCourseDivision]: selectList } = selectVideo;
    let otherVideoCourseDivision = videoCourseDivision === 'internal' ? 'external' : 'internal';
    let _list = [];
    if (selected || !_.find(selectList, (item) => item.id === record.id)) {
      _list = _.uniq(selectList.concat([record]), false, (item) => item.id);
    } else {
      _list = _.reject(selectList, (item) => item.id === record.id);
    }
    if (_list.length + selectVideo[otherVideoCourseDivision]?.length + currentTaskCourseData.length + selectLive.length + selectPicture.length > 20) {
      message.warning('无法继续选择，一个任务最多关联20个课程');
      return;
    }
    this.setState({
      selectVideo: {
        ...selectVideo,
        [videoCourseDivision]: _list,
      },
    });
  };

  selectPictureList = (record, selected) => {
    const { selectVideo, currentTaskCourseData, selectLive, selectPicture } = this.state;
    let _list = [];
    if (selected || !_.find(selectPicture, (item) => item.id === record.id)) {
      _list = _.uniq(selectPicture.concat([record]), false, (item) => item.id);
    } else {
      _list = _.reject(selectPicture, (item) => item.id === record.id);
    }
    if (_list.length + currentTaskCourseData.length + selectLive.length + selectVideo.internal.length + selectVideo.external.length > 20) {
      message.warning('无法继续选择，一个任务最多关联20个课程');
      return;
    }
    this.setState({ selectPicture: _list });
  };

  clearSelectCourse = () => {
    this.setState({
      selectLive: [],
      selectVideo: {
        internal: [],
        external: [],
      },
      selectPicture: [],
    });
  };
  handleSelectVideo = (selectVideo) => {
    return selectVideo.map((item) => {
      let _item = {};
      _item.courseId = item.id;
      _item.courseType = 'VOICE';
      _item.courseName = item.courseName;

      return _item;
    });
  };

  handleSelectLive = (selectLive) => {
    return selectLive.map((item, index) => {
      let _item = {};
      _item.courseId = item.liveCourseId;
      _item.courseType = 'LIVE';
      _item.courseName = item.courseName;
      _item.courseState = item.courseState;
      return _item;
    });
  };
  videoCourseDivisionChange = (e) => {
    const { videoSearchName } = this.state;
    this.setState(
      {
        videoCourseDivision: e.target.value,
        videoSearchDefalt: videoSearchName[e.target.value],
      },
      () => {
        this.handleFetchVideoDataList();
      }
    );
  };

  handleSelectPicture = (selectPicture) => {
    return selectPicture.map((item, index) => {
      let _item = {};
      _item.courseId = item.id;
      _item.courseType = 'PICTURE';
      _item.courseName = item.courseName;
      return _item;
    });
  };
  renderFooter = () => {
    const { activeKey } = this.state;
    let href = '';
    switch (activeKey) {
      case 'live':
        href = (
          <a
            target='_blank'
            rel='noopener noreferrer'
            className='link-create-course'
            href={window.location.origin + window.location.pathname + '#/create-live-course?type=add'}
            onClick={this.props.onClose}>
            没有找到需要的直播课？<span>去创建</span>
          </a>
        );
        break;
      case 'video':
        href = (
          <a
            target='_blank'
            rel='noopener noreferrer'
            className='link-create-course'
            href={window.location.origin + window.location.pathname + '#/create-video-course?type=add'}
            onClick={this.props.onClose}>
            没有找到需要的视频课？<span>去创建</span>
          </a>
        );
        break;
      case 'picture':
        href = (
          <a
            target='_blank'
            rel='noopener noreferrer'
            className='link-create-course'
            href={window.location.origin + window.location.pathname + '#/create-graphics-course?type=add'}
            onClick={this.props.onClose}>
            没有找到需要的图文课？<span>去创建</span>
          </a>
        );
        break;
      default:
        break;
    }
    return href;
  };

  render() {
    const { visible } = this.props;
    const {
      liveDataSource,
      liveSize,
      liveQuery,
      liveTotalCount,
      selectLive,
      videoDataSource,
      videoSize,
      videoQuery,
      videoSearchDefalt,
      videoTotalCount,
      selectVideo,
      currentTaskCourseData,
      selectPicture,
      pictureDataSource,
      pictureSize,
      pictureQuery,
      pictureTotalCount,

      videoCourseDivision,
    } = this.state;
    return (
      <Modal
        title='关联课程'
        onCancel={this.props.onClose}
        maskClosable={false}
        visible={visible}
        className='related-course-modal'
        closable={true}
        width={800}
        closeIcon={<span className='icon iconfont modal-close-icon'>&#xe6ef;</span>}
        footer={[
          // <If condition={videoCourseDivision === 'internal'}>{}</If>,
          this.renderFooter(),
          <Button
            onClick={() => {
              this.props.onClose();
            }}>
            取消
          </Button>,
          <Button
            type='primary'
            onClick={() =>
              this.props.onSelect([
                ...this.handleSelectVideo(selectVideo.internal),
                ...this.handleSelectVideo(selectVideo.external),
                ...this.handleSelectLive(selectLive),
                ...this.handleSelectPicture(selectPicture),
              ])
            }>
            确定
          </Button>,
        ]}>
        <div>
          <Tabs
            type='line'
            defaultActiveKey='live'
            onChange={(activeKey) => {
              this.setState({ activeKey: activeKey });
            }}>
            <TabPane tab='直播课' key='live'>
              <div className='search-container'>
                <Search
                  enterButton={<span className='icon iconfont'>&#xe832;</span>}
                  placeholder='搜索课程名称'
                  style={{ width: 200 }}
                  onChange={(e) => {
                    this.handleChangLiveCourseName(e.target.value);
                  }}
                  onSearch={() => {
                    this.handleFetchLiveDataList();
                  }}
                />
              </div>

              <div className='select-area'>
                <div className='select-box'>
                  <div>
                    <span className='icon iconfont tip-icon'>&#xe61d;</span>
                    <span className='select-num'>
                      已选择{selectVideo.internal.length + selectVideo.external.length + selectLive.length + selectPicture.length}个
                    </span>
                  </div>
                  <div>
                    <span className='clear-btn' onClick={this.clearSelectCourse}>
                      清空
                    </span>
                  </div>
                </div>
                <div className='related-box'>
                  该任务已关联{currentTaskCourseData.length}个课程，可继续选择{20 - currentTaskCourseData.length}个
                </div>
              </div>
              <div>
                <XMTable
                  renderEmpty={{
                    image: college,
                    description: '暂无数据',
                  }}
                  rowKey={(record) => record.liveCourseId}
                  dataSource={liveDataSource}
                  columns={this.parseLiveColumns()}
                  pagination={false}
                  bordered
                  rowSelection={{
                    type: 'checkbox',
                    selectedRowKeys: _.pluck(selectLive, 'liveCourseId'),
                    onSelect: (record, selected) => {
                      this.selectLiveList(record, selected);
                    },
                    onSelectAll: (selected, _selectedRows, changeRows) => {
                      let _list = [];
                      if (selected) {
                        _list = _.uniq(selectLive.concat(changeRows), false, (item) => item.liveCourseId);
                      } else {
                        _list = _.reject(selectLive, (item) => _.find(changeRows, (data) => data.liveCourseId === item.liveCourseId));
                      }
                      if (_list.length + currentTaskCourseData.length + selectVideo.internal.length + selectVideo.external.length + selectPicture.length > 20) {
                        message.warning('无法继续选择，一个任务最多关联20个课程');
                        const extraLength =
                          _list.length + currentTaskCourseData.length + selectVideo.internal.length + selectVideo.external.length + +selectPicture.length - 20;
                        _list.splice(_list.length - extraLength, extraLength);
                      }
                      this.setState({ selectLive: _list });
                    },
                  }}
                />
                {liveDataSource.length > 0 && (
                  <div className='box-footer'>
                    <PageControl
                      current={liveQuery.current - 1}
                      pageSize={liveSize}
                      size='small'
                      total={liveTotalCount}
                      toPage={(page) => {
                        const _query = { ...liveQuery, current: page + 1 };
                        this.setState(
                          {
                            liveQuery: _query,
                          },
                          () => {
                            this.handleFetchLiveDataList();
                          }
                        );
                      }}
                      onShowSizeChange={this.onShowLiveSizeChange}
                    />
                  </div>
                )}
              </div>
            </TabPane>

            <TabPane tab='视频课' key='video'>
              <Radio.Group value={videoCourseDivision} onChange={this.videoCourseDivisionChange} style={{ marginBottom: 16 }}>
                <Radio.Button value='internal'>内部课程</Radio.Button>
                <Radio.Button value='external'>外部课程</Radio.Button>
              </Radio.Group>
              <div className='search-container'>
                <Search
                  value={videoSearchDefalt}
                  enterButton={<span className='icon iconfont'>&#xe832;</span>}
                  placeholder='搜索课程名称'
                  style={{ width: 200 }}
                  onChange={(e) => {
                    this.handleChangVideoCourseName(e.target.value);
                  }}
                  onSearch={() => {
                    this.handleFetchVideoDataList();
                  }}
                />
              </div>
              <div className='select-area'>
                <div className='select-box'>
                  <div>
                    <span className='icon iconfont tip-icon'>&#xe61d;</span>
                    <span className='select-num'>
                      已选择{selectVideo.internal.length + selectVideo.external.length + selectLive.length + selectPicture.length}个
                    </span>
                  </div>
                  <div>
                    <span className='clear-btn' onClick={this.clearSelectCourse}>
                      清空
                    </span>
                  </div>
                </div>
                <div className='related-box'>
                  该任务已关联{currentTaskCourseData.length}个课程，可继续选择{20 - currentTaskCourseData.length}个
                </div>
              </div>
              <div>
                <XMTable
                  renderEmpty={{
                    image: college,
                    description: '暂无数据',
                  }}
                  rowKey={(record) => record.id}
                  dataSource={videoDataSource[videoCourseDivision]}
                  columns={this.parseVideoColumns()}
                  pagination={false}
                  bordered
                  rowSelection={{
                    type: 'checkbox',
                    selectedRowKeys: _.pluck(selectVideo[videoCourseDivision], 'id'),
                    onSelect: (record, selected) => {
                      this.selectVideoList(record, selected);
                    },
                    onSelectAll: (selected, _selectedRows, changeRows) => {
                      let _list = [];
                      let otherVideoCourseDivision = videoCourseDivision === 'internal' ? 'external' : 'internal';
                      if (selected) {
                        _list = _.uniq(selectVideo[videoCourseDivision].concat(changeRows), false, (item) => item.id);
                      } else {
                        _list = _.reject(selectVideo[videoCourseDivision], (item) => _.find(changeRows, (data) => data.id === item.id));
                      }
                      if (
                        _list.length + selectVideo[otherVideoCourseDivision]?.length + currentTaskCourseData.length + selectLive.length + selectPicture.length >
                        20
                      ) {
                        message.warning('无法继续选择，一个任务最多关联20个课程');
                        const extraLength =
                          _list.length +
                          selectVideo[otherVideoCourseDivision]?.length +
                          currentTaskCourseData.length +
                          selectLive.length +
                          selectPicture.length -
                          20;
                        _list.splice(_list.length - extraLength, extraLength);
                      }
                      this.setState({
                        selectVideo: {
                          ...selectVideo,
                          [videoCourseDivision]: _list,
                        },
                      });
                    },
                  }}
                />
                {videoDataSource[videoCourseDivision].length > 0 && (
                  <div className='box-footer'>
                    <PageControl
                      current={videoQuery[videoCourseDivision].current - 1}
                      pageSize={videoSize[videoCourseDivision]}
                      size='small'
                      total={videoTotalCount[videoCourseDivision]}
                      toPage={(page) => {
                        const _query = { ...videoQuery[videoCourseDivision], current: page + 1 };

                        this.setState(
                          {
                            videoQuery: {
                              ...videoQuery,
                              [videoCourseDivision]: _query,
                            },
                          },
                          () => {
                            this.handleFetchVideoDataList();
                          }
                        );
                      }}
                      onShowSizeChange={this.onShowVideoSizeChange}
                    />
                  </div>
                )}
              </div>
            </TabPane>
            <TabPane tab='图文课' key='picture'>
              <div className='search-container'>
                <Search
                  enterButton={<span className='icon iconfont'>&#xe832;</span>}
                  placeholder='搜索课程名称'
                  style={{ width: 200 }}
                  onChange={(e) => {
                    this.handleChangPictureCourseName(e.target.value);
                  }}
                  onSearch={() => {
                    this.handleFetchPictureDataList();
                  }}
                />
              </div>

              <div className='select-area'>
                <div className='select-box'>
                  <div>
                    <span className='icon iconfont tip-icon'>&#xe61d;</span>
                    <span className='select-num'>
                      已选择{selectVideo.internal.length + selectVideo.external.length + selectLive.length + selectPicture.length}个
                    </span>
                  </div>
                  <div>
                    <span className='clear-btn' onClick={this.clearSelectCourse}>
                      清空
                    </span>
                  </div>
                </div>
                <div className='related-box'>
                  该任务已关联{currentTaskCourseData.length}个课程，可继续选择{20 - currentTaskCourseData.length}个
                </div>
              </div>
              <div>
                <XMTable
                  renderEmpty={{
                    image: college,
                    description: '暂无数据',
                  }}
                  rowKey={(record) => record.id}
                  dataSource={pictureDataSource}
                  columns={this.parsePictureColumns()}
                  pagination={false}
                  bordered
                  rowSelection={{
                    type: 'checkbox',
                    selectedRowKeys: _.pluck(selectPicture, 'id'),
                    onSelect: (record, selected) => {
                      this.selectPictureList(record, selected);
                    },
                    onSelectAll: (selected, _selectedRows, changeRows) => {
                      let _list = [];
                      if (selected) {
                        _list = _.uniq(selectPicture.concat(changeRows), false, (item) => item.id);
                      } else {
                        _list = _.reject(selectPicture, (item) => _.find(changeRows, (data) => data.id === item.id));
                      }
                      if (_list.length + currentTaskCourseData.length + selectVideo.internal.length + selectVideo.external.length + selectLive.length > 20) {
                        message.warning('无法继续选择，一个任务最多关联20个课程');
                        const extraLength =
                          _list.length + currentTaskCourseData.length + selectVideo.internal.length + selectVideo.external.length + selectLive.length - 20;
                        _list.splice(_list.length - extraLength, extraLength);
                      }
                      this.setState({ selectPicture: _list });
                    },
                  }}
                />
                {pictureDataSource.length > 0 && (
                  <div className='box-footer'>
                    <PageControl
                      current={pictureQuery.current - 1}
                      pageSize={pictureSize}
                      size='small'
                      total={pictureTotalCount}
                      toPage={(page) => {
                        const _query = { ...pictureQuery, current: page + 1 };
                        this.setState(
                          {
                            pictureQuery: _query,
                          },
                          () => {
                            this.handleFetchPictureDataList();
                          }
                        );
                      }}
                      onShowSizeChange={this.onShowPictureSizeChange}
                    />
                  </div>
                )}
              </div>
            </TabPane>
          </Tabs>
        </div>
      </Modal>
    );
  }
}

export default SelectOperatorModal;
