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,
      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: <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',
        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><span className="course-status">{courseStateShow[record.courseState].title}</span></div>
            </div>
          )
        }
      },
      {
        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>
          )
        }
      },
      {
        title: '店铺展示',
        key: 'shelfState',
        dataIndex: 'shelfState',
        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',
        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: 'shelfState',
        dataIndex: 'shelfState',
        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' class="link-create-course" href="https://dev.xiaomai5.com/xiaomai-cloud-class-web/index.html#/create-live-course?type=add">没有找到需要的直播课？<span>去创建</span></a>
              :
              <a target='_blank' class="link-create-course" href="https://dev.xiaomai5.com/xiaomai-cloud-class-web/index.html#/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>
                            <span>
                                <span className="iconfont">&#xe61d;</span>
                                <span>已选择{selectVideo.length + selectLive.length}个</span>
                                <span onClick={this.clearSelectCourse}>清空</span>
                            </span>
                            <span>该任务已关联{currentTaskCourseData.length}个课程，可继续选择{20- currentTaskCourseData.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));
                                      }
                                      if(_list.length + currentTaskCourseData.length + selectLive.length> 20){
                                        message.warning('无法继续选择，一个任务最多关联20个课程');
                                        return;
                                      }
                                      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="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>
                            <span>
                                <span className="iconfont">&#xe61d;</span>
                                <span>已选择{selectVideo.length + selectLive.length}个</span>
                                <span onClick={this.clearSelectCourse}>清空</span>
                            </span>
                            <span>该任务已关联{currentTaskCourseData.length}个课程，可继续选择{20- currentTaskCourseData.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));
                                    }
                                    if(_list.length + currentTaskCourseData.length + selectVideo.length> 20){
                                      message.warning('无法继续选择，一个任务最多关联20个课程');
                                      return;
                                    }
                                    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;