import React from 'react';
import {Table, Modal,Input,message} from 'antd';
import { PageControl } from "@/components";
import CourseService from "@/domains/course-domain/CourseService";
import User from '@/common/js/user';
import { Tabs } from 'antd';
import './SelectOperatorModal.less';
import _ from "underscore";
import dealTimeDuration from "../../course-manage/utils/dealTimeDuration";

const { Search } = Input;
const { TabPane } = Tabs;
const courseStateShow = {
  UN_START: {
    code: 1,
    title: "待开课",
    color: "#FFB714",
  },
  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:[], //页面中已关联的直播课程
        videoDataSource:[],
        videoSize:10,
        videoQuery: {
          current: 1,
        },
        videoTotalCount:0,
        selectVideo:[], //弹窗内已选择的视频课程 
        currentVideoCourseListData:[], //页面中已关联的视频课程
     }
  }

  componentDidMount() {
    this.handleFetchLiveDataList();
    this.handleFetchVideoDataList();
    console.log('courseLisData',this.props.data)
  }

  // 获取直播课列表
  handleFetchLiveDataList = () => {
    const {liveQuery,liveSize} = this.state;
    const { selectedTaskIndex } =this.props;
    const _data = [...this.props.data];
    let  currentLiveCourseListData = [];
    _data.map((item,index) => {
      item.courseList.map((childItem,childIndex)=>{
        if(childItem.courseType ==="LIVE"){
          currentLiveCourseListData.push(childItem.courseId)
        }
        return childItem
      })
      return item
    });
    const params ={
      ...liveQuery,
      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,videoTotalCount} = this.state;
    const { selectedTaskIndex } =this.props;
    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,
      videoSize,
      excludeCourseIdList:currentVideoCourseListData
    }
    CourseService.videoScheduleBasePage(params).then((res) => {
      const { result = {} } = res ;
      const { records = [], total = 0 } = result;

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

  handleChangVideoCourseName = (value)=>{
    const { videoQuery } =  this.state;
    videoQuery.courseName = value;
    videoQuery.current = 1;
    this.setState({
      videoQuery
    })
  }
  handleChangLiveCourseName = (value)=>{
    const { liveQuery } =  this.state;
    liveQuery.courseName = value;
    liveQuery.current = 1;
    this.setState({
      liveQuery
    })
  }
  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()})
  }

  // 请求表头
  parseLiveColumns = () => {
    const columns = [
      {
        title: '课程信息',
        key: 'course',
        dataIndex: 'course',
        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} style={{width:'100px',height:'50px'}}/>
                  }    
                })
              }
              { !hasCover  && 
                <img className="course-cover" src={'https://image.xiaomaiketang.com/xm/YNfi45JwFA.png'}  style={{width:'100px',height:'50px'}} />
              }
              <div className="course-name">{record.courseName}</div>
            </div>
          )
        }
      },
      {
        title: '课程状态',
        key: 'courseState',
        dataIndex: 'courseState',
        render: (val, record) => {
          return (
            <span className="course-status">{courseStateShow[record.courseState].title}</span>
          )
        }
      },
      {
        title: '上课时间',
        key: 'courseTime',
        dataIndex: 'courseTime',
        render: (val, record) => {
          return (
            <span>{formatDate('YYYY-MM-DD H:i', record.startTime)} ~ {formatDate('YYYY-MM-DD H:i', record.endTime)}</span>
          )
        }
      }

    ];
    return columns;
  }

  // 请求表头
  parseVideoColumns = () => {
    const columns = [
      {
        title: '课程信息',
        key: 'course',
        dataIndex: 'course',
        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`} style={{width:'100px',height:'50px'}}/>
              <div className="course-name">{record.courseName}</div>
            </div>
          )
        }
      },
      {
        title: '课程时长',
        key: 'courseTime',
        dataIndex: 'courseTime',
        render: (val, record) => {
          return (
            <span className="course-status">{dealTimeDuration(record.videoDuration)}</span>
          )
        }
      },
      {
        title: '课程大小',
        key: 'size',
        dataIndex: 'size',
        render: (val, record) => {
          return (
            <span>{(val/1024).toFixed(1)}M</span>
          )
        }
      }

    ];
    return columns;
  }
  selectLiveList = (record,selected) =>{
    const {selectVideo,currentVideoCourseListData,currentLiveCourseListData,selectLive} = 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 + currentVideoCourseListData.length + currentLiveCourseListData.length + selectVideo> 20){
        message.warning('无法继续选择，一个任务最多关联20个课程');
      return;
    }
    this.setState({selectLive:_list});
  }

  selectVideoList = (record,selected) =>{
    const {selectVideo,currentVideoCourseListData,currentLiveCourseListData,selectLive} = this.state;
    let _list = [];
    if (selected || !_.find(selectVideo, (item) => item.id == record.id)) {
        _list = _.uniq(selectVideo.concat([record]), false, (item) => item.id);
    } else {
        _list = _.reject(selectVideo, (item) => item.id === record.id);
    }
    if(_list.length + currentVideoCourseListData.length + currentLiveCourseListData.length + selectLive> 20){
        message.warning('无法继续选择，一个任务最多关联20个课程');
      return;
    }
    this.setState({selectVideo:_list});
  }
  clearSelectCourse = ()=>{
    this.setState({
      selectLive:[],
      selectVideo:[]
    })
  }
  handleSelectVideo = (selectVideo)=>{
      return  selectVideo.map((item,index)=>{
          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;
        return  _item;
    })
}
  render() {
    const { visible } = this.props;
    const { liveDataSource,liveSize,liveQuery,liveTotalCount,selectLive,currentLiveCourseListData,videoDataSource,videoSize,videoQuery,videoTotalCount,selectVideo,currentVideoCourseListData} = this.state;

    return (
        <Modal
          title="关联课程"
          onCancel={this.props.onClose}
          maskClosable={false}
          visible={visible}
          className="select-operator-modal"
          closable={true}
          width={800}
          onOk={() => this.props.onSelect([...this.handleSelectVideo(selectVideo),...this.handleSelectLive(selectLive)]) } 
          closeIcon={<span className="icon iconfont modal-close-icon">&#xe6ef;</span>} 
        >
            
            <div>
                <Tabs defaultActiveKey="1">
                    <TabPane tab="视频课" key="1">
                        <div className="search-container">
                            <Search placeholder="搜索课程名称"  style={{ width: 200 }} onChange={(e) => { this.handleChangVideoCourseName(e.target.value)}}  onSearch={ () => { this.handleFetchVideoDataList()}}/>
                        </div>
                        <div>
                            <span>
                                <span className="iconfont">&#xe61d;</span>
                                <span>已选择{selectVideo.length + selectLive.length}个</span>
                                <span onClick={this.clearSelectCourse}>清空</span>
                            </span>
                            <span>该任务已关联{currentVideoCourseListData.length + currentLiveCourseListData.length}个课程，可继续选择{20-(currentVideoCourseListData.length + currentLiveCourseListData.length )}个</span>
                        </div>
                        <div>
                            <Table
                                rowKey={record => record.id}
                                dataSource={videoDataSource}
                                columns={this.parseVideoColumns()}
                                pagination={false}
                                rowSelection={{
                                    type: 'checkbox',
                                    selectedRowKeys: _.pluck(selectVideo, 'id'),
                                    onSelect: (record, selected) => {
                                      this.selectVideoList(record, selected);
                                    },
                                    onSelectAll: (selected, _selectedRows, changeRows) => {
                                      let _list = [];
                                      if (selected) {
                                          _list = _.uniq(selectVideo.concat(changeRows), false, (item) => item.id);
                                      } else {
                                          _list = _.reject(selectVideo, (item) => _.find(changeRows, (data) => data.id === item.id));
                                      }
                                      this.setState({selectVideo:_list});
                                    },
                                }}
                            />
                                {videoDataSource.length >0 &&
                                <div className="box-footer">
                                    <PageControl
                                      current={videoQuery.current - 1}
                                      pageSize={videoSize}
                                      total={videoTotalCount}
                                      toPage={(page) => {
                                          const _query = {...videoQuery, current: page + 1};
                                          this.setState({
                                            videoQuery:_query
                                          },()=>{ this.handleFetchVideoDataList()})
                                      }}
                                      onShowVideoSizeChange={this.onShowVideoSizeChange}
                                    />
                                </div>
                                }
                        </div>
                    </TabPane>
                    <TabPane tab="直播课" key="2">
                        <div className="search-container">
                            <Search placeholder="搜索课程名称"  style={{ width: 200 }}  onChange={(e) => { this.handleChangLiveCourseName(e.target.value)}}  onSearch={ () => { this.handleFetchLiveDataList()}} />
                        </div>
                        <div>
                            <span>
                                <span className="iconfont">&#xe61d;</span>
                                <span>已选择{selectVideo.length + selectLive.length}个</span>
                                <span onClick={this.clearSelectCourse}>清空</span>
                            </span>
                            <span>该任务已关联{currentVideoCourseListData.length + currentLiveCourseListData.length}个课程，可继续选择{20-(currentVideoCourseListData.length + currentLiveCourseListData.length )}个</span>
                        </div>
                        <div>
                          <Table
                              rowKey={record => record.liveCourseId}
                              dataSource={liveDataSource}
                              columns={this.parseLiveColumns()}
                              pagination={false}
                              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));
                                    }
                                    this.setState({selectLive:_list});
                                  },
                              }}
                          />
                            {liveDataSource.length >0 &&
                            <div className="box-footer">
                                <PageControl
                                  current={liveQuery.current - 1}
                                  pageSize={liveSize}
                                  total={liveTotalCount}
                                  toPage={(page) => {
                                      const _query = {...liveQuery, current: page + 1};
                                      this.setState({
                                        liveQuery:_query
                                      },()=>{ this.handleFetchLiveDataList()})
                                  }}
                                  onShowLiveSizeChange={this.onShowLiveSizeChange}
                                />
                            </div>
                            }
                        </div>
                    </TabPane>
                </Tabs>
            </div>
        </Modal>
    )
  }
}

export default SelectOperatorModal;