import React from 'react';
import {Table, Modal,Input,message,Button,Tooltip} from 'antd';
import { PageControl } from "@/components";
import CourseService from "@/domains/course-domain/CourseService";
import User from '@/common/js/user';
import { Tabs } from 'antd';
import './relatedCourseModal.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:[], //页面中已关联的视频课程
        activeKey:'video',
        currentTaskCourseData:this.props.data[this.props.selectedTaskIndex].courseList || []
     }
  }

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

  // 获取直播课列表
  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,
      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,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,
      size: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: <span><span>课程信息</span><Tooltip  title="以下为该培训计划暂未关联的课程。 已关联的课程不支持重复选择，因此不显示。"><i className="icon iconfont" style={{ marginLeft: '5px',cursor:'pointer',color:'#bfbfbf',fontSize:'14px'}}>&#xe61d;</i></Tooltip></span>,
        key: 'course',
        dataIndex: 'course',
        width:'45%',
        render: (val, record) => {
          let hasCover = false;
          return (
            <div className="course-info">
              { 
                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>
                <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 (
            <span>{formatDate('YYYY-MM-DD H:i', record.startTime)}</span>
          )
        }
      },
      {
        title: '店铺展示',
        key: 'shelfState',
        dataIndex: 'shelfState',
        width:'15%',
        render: (val, record) => {
          return (
            <span>
              {record.shelfState==="YES"?
                <span>开启</span>
                :
                <span>关闭</span>
              }
          </span>
          )
        }
      },

    ];
    return columns;
  }

  // 请求表头
  parseVideoColumns = () => {
    const columns = [
      {
        title: <span><span>课程信息</span><Tooltip  title="以下为该培训计划暂未关联的课程。 已关联的课程不支持重复选择，因此不显示。"><i className="icon iconfont" style={{ marginLeft: '5px',cursor:'pointer',color:'#bfbfbf',fontSize:'14px'}}>&#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 || `${scheduleVideoUrl}?x-oss-process=video/snapshot,t_0,m_fast`}/>
              <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 (
            <span>
              {record.shelfState==="YES"?
                <span>开启</span>
                :
                <span>关闭</span>
              }
            </span>
          )
        }
      }

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

  selectVideoList = (record,selected) =>{
    const {selectVideo,currentTaskCourseData,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 + currentTaskCourseData.length + selectLive.length> 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;
        _item.courseState = item.courseState;
        return  _item;
    })
}
  render() {
    const { visible } = this.props;
    const { liveDataSource,liveSize,liveQuery,liveTotalCount,selectLive,videoDataSource,videoSize,videoQuery,videoTotalCount,selectVideo,currentTaskCourseData,activeKey} = this.state;

    return (
        <Modal
          title="关联课程"
          onCancel={this.props.onClose}
          maskClosable={false}
          visible={visible}
          className="related-course-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>} 
          footer={[
            activeKey ==='live'?
              <a target='_blank' className="link-create-course" href={window.location.origin + window.location.pathname + '#/create-live-course?type=add'}>没有找到需要的直播课？<span>去创建</span></a>
              :
              <a target='_blank' className="link-create-course" href={window.location.origin + window.location.pathname + '#/create-video-course?type=add'}>没有找到需要的视频课？<span>去创建</span></a>
            ,
            <Button
              onClick={() => {
                this.props.onClose()
              }}
            >
              取消
            </Button>,
            <Button type="primary" onClick={() => this.props.onSelect([...this.handleSelectVideo(selectVideo),...this.handleSelectLive(selectLive)]) }>
              确定
            </Button>
          ]}
        >
            
            <div>
                <Tabs defaultActiveKey="video" onChange={(activeKey)=>{this.setState({activeKey:activeKey})}}>
                    <TabPane tab="视频课" key="video">
                        <div className="search-container">
                            <Search 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.length + selectLive.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>
                            <Table
                                rowKey={record => record.id}
                                dataSource={videoDataSource}
                                columns={this.parseVideoColumns()}
                                pagination={false}
                                bordered
                                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));
                                      }
                                      if(_list.length + currentTaskCourseData.length + selectLive.length> 20){
                                        message.warning('无法继续选择，一个任务最多关联20个课程');
                                        console.log('1111');
                                        const extraLength = (_list.length + currentTaskCourseData.length + selectLive.length) -20;
                                        _list.splice(_list.length - extraLength,extraLength);
                                      }
                                      this.setState({selectVideo:_list});
                                    },
                                }}
                            />
                                {videoDataSource.length >0 &&
                                <div className="box-footer">
                                    <PageControl
                                      current={videoQuery.current - 1}
                                      pageSize={videoSize}
                                      size="small"
                                      total={videoTotalCount}
                                      toPage={(page) => {
                                          const _query = {...videoQuery, current: page + 1};
                                          this.setState({
                                            videoQuery:_query
                                          },()=>{ this.handleFetchVideoDataList()})
                                      }}
                                      onShowSizeChange={this.onShowVideoSizeChange}
                                    />
                                </div>
                                }
                        </div>
                    </TabPane>
                    <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.length + selectLive.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>
                          <Table
                              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.length> 20){
                                      message.warning('无法继续选择，一个任务最多关联20个课程');
                                      const extraLength = (_list.length + currentTaskCourseData.length + selectVideo.length) -20;
                                      _list.splice(_list.length - extraLength,extraLength);
                                      console.log('_list',_list);

                                    }
                                    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>
                </Tabs>
            </div>
        </Modal>
    )
  }
}

export default SelectOperatorModal;