/*
 * @Author: leehu 
 * @Date: 2017-09-04 11:52:25 
 * @Last Modified by: wangxiang
 * @Last Modified time: 2020-11-06 14:09:38
 */
import React from 'react';
import { Spin, Select } from 'antd';
import Bus from '@/core/bus';

class CourseSelect extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      close: true,
      dataSource: [],
      query: {
        month: null,
        current: 0,
        size: 10,
        courseNameLike: null,
        showNumber: 100,
      },
      dataSet: [],
      visible: false,
      loading: false,
      selectedIds: [],
      selected: props.selected || [],
    }
    this.reset = () => {
      this.handleQueryReset();
    }
  }

  componentWillMount() {
    Bus.bind('reset', this.handleQueryReset)
    this.fetchServerData();
  }

  componentWillReceiveProps(nextProps) {
    if ((this.props.courseId !== nextProps.courseId) ||
      (this.props.queryOneToOne !== nextProps.queryOneToOne) ||
      (this.props.queryOneTomore !== nextProps.queryOneTomore)) {
      this.props = nextProps
      this.fetchServerData();
    }
  }

  handleQuery = () => {
    this.fetchServerData();
  }


  handleQueryReset = () => {
    this.setState({
      query: {
        current: 0,
        size: 10000,
        showNumber: 100,
        courseNameLike: null,
      }
    }, () => {
      this.fetchServerData();
    });
  }

  fetchServerData(current = 1) {
    const self = this;
    const url = 'public/course/digestList'
    let query = _.clone(this.state.query)
    query.current = current;
    const param = _.extend(query, this.props.query);
    if (self.props.queryAll) {
      delete param.status;
    } else {
      // 排除一对一
      param.status = 'ON';
    }
    if (self.props.queryOneToOne) {
      param.courseType = 'ONEVONE'
      delete param.status;
    }
    if (self.props.queryOneTomore) {
      param.courseType = 'ONE2MANY'
      delete param.status;
    }
    param.teacherId = self.props.teacherId;
    param.studentId = self.props.studentId;
    this.setState({
      query: param
    })
    window.axios.Business(url, param).then((res) => {
      let data = res.result.records;
      data.map(function (item, index) {
        item.title = item.name;
        item.desc = item.name;
      });
      if (current >1) {
        data = this.state.dataSet.concat(data)
      }
      this.setState({
        dataSet: data,
        totalCount: res.result.total,
        isAll: !res.result.hasNext,
        loading: false
      });

    })
  }


  searchName = () => {
    clearTimeout(this.timer)
    this.timer = setTimeout(() => {
      this.fetchServerData()
    }, 500)
  }

  handleCourseSelect = (course) => {
    const query = this.state.query;
    if (query.courseNameLike) {
      query.courseNameLike = '';
      this.setState({ query }, this.fetchServerData);
    }
    if (!this.props.multiple) {
      if (this.props.needName) {
        let list = _.filter(this.state.dataSet, (item) => {
          return item.id == course;
        })
        this.props.onSelect(list[0] || {});
        return;
      }
      this.props.onSelect({ id: course });
      return;
    }
    this.props.onSelect(course);
  }


  hasmore = (dom) => {
    clearTimeout(this.scroll)
    let height = $(dom.currentTarget).find('ul li').last().position().top
    this.scroll = setTimeout(() => {
      if (height < 500 && !this.state.isAll) {
        this.fetchServerData(this.state.query.current + 1)
      }
    }, 300)
  }


  render() {
    let defprops = {}
    if (this.props.multiple) {
      defprops.mode = 'multiple'
    }
    return (
      <div className={classNames("common-select staticSelect", { 'common-select-active': this.state.visible })} style={this.props.style}>
        {
          !!this.props.label && <div className='label'>{ `${this.props.label}:`}</div>
        }
        <Select
          id={this.props.id}
          ref='course'
          {...defprops}
          showSearch
          allowClear
          onSearch={(value) => {
            const query = this.state.query;
            query.courseNameLike = value
            this.setState({ query }, this.searchName)
          }}
          onBlur={() => {
            const query = this.state.query;
            query.courseNameLike = null
            this.setState({ query }, this.searchName)
          }}
          // open
          onPopupScroll={(dom) => {
            this.hasmore(dom)
          }}
          placeholder={this.props.placeholder}
          value={this.props.defaultValue || undefined}
          onChange={this.handleCourseSelect}
          filterOption={(input, option) => option}
        >
          {
            _.map(this.state.dataSet, (item, index) => {
              return <Select.Option id={'course_select_item_' + index} key={item.id} value={item.id} title={item.name}>
                {item.name}
              </Select.Option>
            })
          }
          {!this.state.isAll &&
            <Select.Option disabled style={{ textAlign: 'center' }} value="spin">
              <Spin size="small" />
            </Select.Option>
          }
        </Select>

      </div>
    )
  }
}

CourseSelect.propTypes = {

};


CourseSelect.defaultProps = {
  onSelect: () => { },
  placeholder: '选择课程',
  teacherId: null,
  selected: [],
  multiple: false,
  query: {},
  renderItem: null,
  filter: null,
  isAll: false
}

export default CourseSelect;