/*
 * @Author: 吴文洁 
 * @Date: 2020-07-15 17:44:24 
 * @Last Modified by: mikey.zhaopeng
 * @Last Modified time: 2020-11-23 22:06:33
 * @Description: 添加直播课-上课信息
 */

import React from 'react';
import {TimePicker, Select, Spin, Tooltip,DatePicker} from 'antd';
import {InfoCircleFilled} from '@ant-design/icons';
import StoreService from "@/domains/store-domain/storeService";

// import TeacherSelectV5 from "@/modules/classManage_V5/classDetail/TeacherSelectV5";

import ChargeExplainModal from '../modal/ChargeExplainModal';
import SelectStudent from '../modal/select-student/index';
import MultipleDatePicker from '@/components/MultipleDatePicker';
import moment from 'moment';
import './AddLiveClass.less';

const defaultTeacherQuery = {
  size: 15,
  current: 1,
  nickName:null
}
const defaultAssistantQuery = {
  size: 10,
  current: 1,
  nickName:null
}
class AddLiveClass extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      hasNext: false,
      assistantHasNext:false,
      teacherQuery: defaultTeacherQuery,
      teacherList:[],
      assistantQuery:defaultAssistantQuery,
      assistantList: [],     // 助教老师列表
      addLiveType: props.addLiveType
    }
  }

  componentDidMount() {
    this.getTeacherList();
    this.getAssistantList();
  }
  componentWillReceiveProps(nextProps) {
    if(nextProps.data.assistantStoreUserId.sort().toString() !== this.props.data.assistantStoreUserId.sort().toString()) {
      // 获取助教老师列表
      this.getAssistantList(1, nextProps.data.assistantStoreUserId);
    }
  }
  getTeacherList(current = 1, selectList){
    const { teacherQuery,teacherList} = this.state;
    const _query = {
      ...teacherQuery,
      current,
      size:15
    };
    StoreService.getStoreUserBasicPage( _query).then((res) => {
        const { result = {} } = res;
        const { records = [], total = 0, hasNext } = result;
        const list = current > 1 ? teacherList.concat(records) : records;
        this.setState({
          hasNext,
          teacherList: list,
          teacherQuery:{..._query}
        })
    });
  }
  // 获取助教老师列表
  getAssistantList = (current = 1, selectList) => {
    const { assistantQuery,assistantList} = this.state;
    const { assistantStoreUserId } = this.props.data;
    const idList = selectList ? selectList : assistantStoreUserId;
    const _query = {
      ...assistantQuery,
      current,
      idList,
      size: idList.length <= 10 ? 10 : idList.length + 10
    };
    StoreService.getStoreUserBasicPage( _query).then((res) => {
        const { result = {} } = res;
        const { records = [], total = 0, hasNext} = result;
        const { teacherId } = this.props.data
        let list = current > 1 ? assistantList.concat(records) : records;
        console.log("hasNext",typeof(hasNext),hasNext)
        this.setState({
          assistantHasNext:hasNext,
          assistantList: list,
          assistantQuery:{..._query}
        })
    });
  }

   // 滑动加载更多讲师列表
   handleScrollTeacherList = (e) => {
    const { hasNext } = this.state;
    const container = e.target;

    //判定元素是否滚动到底部
    const scrollToBottom = container &&  container.scrollHeight <= container.clientHeight + container.scrollTop;
    if (scrollToBottom && hasNext) {
      const { teacherQuery } = this.state;
      let _teacherQuery = teacherQuery;
      _teacherQuery.current = _teacherQuery.current + 1
      this.setState({
        teacherQuery:{..._teacherQuery}
      },()=>{this.getTeacherList(_teacherQuery.current)})
    }
  }

   // 滑动加载更多助教列表
   handleScrollAssistantList = (e) => {
    const { assistantHasNext } = this.state;
    const container = e.target;
    
    //判定元素是否滚动到底部
    const scrollToBottom = container &&  container.scrollHeight <= container.clientHeight + container.scrollTop;
    if (scrollToBottom && assistantHasNext) {
      const { assistantQuery } = this.state;
      let _assistantQuery = assistantQuery;
      _assistantQuery.current = _assistantQuery.current + 1
      this.setState({
        assistantQuery:{..._assistantQuery}
      },()=>{this.getAssistantList(_assistantQuery.current)})
    }
  }

  disabledDate = (current) => {
    return current.valueOf() < moment().subtract(1, "days")
  };

  selectMultiDate = (calendarTime) => {
    this.setState({
      calendarTime
    })
  }
  render() {
    const {
      loading,
      teacherList,
      assistantList,
      teacherQuery,
      assistantQuery
    } = this.state;

    const { pageType,data,isEdit} = this.props;
    const {
      endTime,
      startTime,
      calendarTime,
      teacherId,
      liveDate,
      timeHorizonStart,
      timeHorizonEnd,
      assistant,
      assistantNames,
      teacherName
    } = data;
    console.log("teacherId",teacherId);
    return (
      <Spin spinning={loading}>
        <div className="add-live__class-info">
           {pageType === 'add' &&
            <div className="course">
              <div className="day">
                <span className="label">
                  <span className="require">*</span>
                    上课日期
                    <Tooltip 
                      overlayStyle={{maxWidth: 300, zIndex: '9999'}} 
                      title={<div style={{width: '266px'}}>支持按上课日期批量创建直播课，创建后按“课程名称_日期”命名，例如：<br/>张三的语文课_9月18日<br/>张三的语文课_9月19日......</div>}>
                      <span className="iconfont">&#xe61d;</span>
                    </Tooltip>：
                  </span>
                <div>
                  <div className='select-day'>
                    已选 <span className="mark-day">{isLongArr(calendarTime) ? calendarTime.length : 0}</span> 天
                  </div>
                  <MultipleDatePicker
                    selectDateList={calendarTime}
                    onSelect={this.selectMultiDate}
                    canSelectTodayBefore={false}
                  />
                </div>
                
              </div>
              
              <div className="hour" id="hour">
                <span className="label"><span className="require">*</span>上课时间：</span>
                <TimePicker
                  className="time-picker"
                  format="HH:mm"
                  value={startTime ? moment(startTime) : null}
                  placeholder="开始时间"
                  showNow={false}
                  style={{ width: 100, minWidth: 100}}
                  onSelect={(time) => {
                    this.props.onChange('startTime', time);
                  }}
                  getPopupContainer={() =>
                    document.getElementById("hour")
                  }
                />&nbsp;&nbsp;~&nbsp;&nbsp; 
                <TimePicker
                  className="time-picker"
                  format="HH:mm"
                  value={endTime ? moment(endTime) : null}
                  placeholder="结束时间"
                  showNow={false}
                  style={{ width: 100, minWidth: 100 }}
                  onSelect={(time) => {
                    this.props.onChange('endTime', time)
                  }}
                  getPopupContainer={() =>
                    document.getElementById("hour")
                  }
                />
              </div>
            </div>
           
          }
          {pageType === 'edit' && 
            <div className="time" id="time">
            <div className="content">
              <span className="label"><span className="require">*</span>上课时间：</span>
              <DatePicker
                disabled={!isEdit}
                format="YYYY-MM-DD"
                value={liveDate ? moment(Number(liveDate)) : null}
                style={{ width: 160, minWidth: 130, marginRight: 10 }}
                placeholder="上课日期"
                getPopupContainer={() =>
                  document.getElementById("time")
                }
                disabledDate={this.disabledDate}
                onChange={(date) => { this.props.onChange('liveDate', date) }}
              />
              <TimePicker
                disabled={!isEdit}
                format="HH:mm"
                value={timeHorizonStart ? moment(Number(timeHorizonStart)) : null}
                defaultOpenValue={moment(new Date().setHours(0,0,0,0))}
                placeholder="开始时间"
                style={{ width: 100, minWidth: 100, marginRight: 10 }}
                getPopupContainer={() =>
                  document.getElementById("time")
                }
                onSelect={(time) => { this.props.onChange('timeHorizonStart', time) }}
                showNow={false}
              />
              <TimePicker
                disabled={!isEdit}
                format="HH:mm"
                value={timeHorizonEnd ? moment(Number(timeHorizonEnd)) : null}
                defaultOpenValue={moment(new Date().setHours(0,0,0,0))}
                placeholder="结束时间"
                style={{ width: 100, minWidth: 100 }}
                getPopupContainer={() =>
                  document.getElementById("time")
                }
                onSelect={(time) => { this.props.onChange('timeHorizonEnd', time) }}
                showNow={false}
              />
            </div>
            
          </div>
          }
          <div className="teacher" id="teacher">
            <span className="label"><span className="require">* </span>讲师：</span>
            <Select
              placeholder="请选择讲师"
              value={teacherName}
              style={{ width: 240, marginTop: 6 }}
              disabled={!isEdit ? true: false}
              showSearch
              allowClear
              filterOption={(input, option) => option}
              onPopupScroll={this.handleScrollTeacherList}
              suffixIcon={<span className="icon iconfont" style={{fontSize:'12px',color:'#BFBFBF'}}>&#xe835;</span>}
              onChange={(value,option) => {
                if(option){
                  this.props.onChange('teacherId',value,'teacherType',option.children) 
                }else{
                  this.props.onChange('teacherId',value,'teacherType',"")
                }
              }}
              onSearch={(value) => {
                teacherQuery.nickName = value
                this.setState({
                  teacherQuery
                }, () => {
                  this.getTeacherList()
                })
              }}
              onClear ={(value)=>{
                this.setState({
                  teacherQuery:{
                    size: 15,
                    current: 1,
                    nickName:null
                  }
                }, () => {
                  this.getTeacherList()
                })
              }
            }
              getPopupContainer={() =>
                document.getElementById("teacher")
              }
            >
              {_.map(teacherList, (item, index) => {
                if( !assistant.includes(item.userId) ){
                  return (
                    <Select.Option value={item.userId} key={item.userId}>{item.nickName}</Select.Option>
                  );
                }
              })}
            </Select>

          </div>
          <div className="assistant-teacher" id="assistant-teacher">
                <span className="label">助教：</span>
                <Select
                  id="assistant"
                  placeholder="请选择助教老师"
                  // key={assistantNames}
                  // defaultValue={assistantNames}
                  value={assistant}
                  disabled={!isEdit ? true: false}
                  mode={'multiple'}
                  showSearch
                  allowClear
                  style={{ width: 240, marginTop: 6 }}
                  filterOption={(input, option) => option}
                  onPopupScroll={this.handleScrollAssistantList}
                  onChange={(value,option) => {
                    if(!option.length){
                      assistantQuery.nickName = ""
                      this.setState({
                        assistantQuery
                      },()=>this.props.onChange('assistant',value,'assistantType',option) )
                    }else{
                      this.props.onChange('assistant',value,'assistantType',option)
                    }
                  }}
                  onSearch={(value) => {
                    assistantQuery.nickName = value
                    this.setState({
                      assistantQuery
                    }, () => {
                      this.getAssistantList()
                    })
                  }}
                  onClear ={(value)=>{
                    assistantQuery.nickName = ""
                    this.setState({
                      assistantQuery
                    }, () => {
                      this.getAssistantList()
                    })
                  }}
                  getPopupContainer={() =>
                    document.getElementById("assistant-teacher")
                  }
                >
                {_.map(assistantList, (item, index) => {
                  if(item.userId !== teacherId){
                    return (
                      <Select.Option value={item.userId} key={item.id}>{item.nickName}</Select.Option>
                    );
                  }
                  
                })}
              </Select>
          </div>
        </div>
      </Spin>
    )
  }
}

export default AddLiveClass;