/*
 * @Author: leehu
 * @Date: 2017-10-12 16:24:11
 * @Last Modified by: mikey.zhaopeng
 * @Last Modified time: 2020-03-20 10:43:55
 */
import React from 'react';
import { Tooltip, Input, Spin, Select, Avatar, Row, Col } from 'antd';
import _ from 'underscore';
import "./CommonSelect.less";
import "./TeacherSearchSelect.less";
import classNames from 'classNames'
const baseImg ='https://image.xiaomaiketang.com/xm/rJeQaZxtc7.png'

class TeacherSearchSelect extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      close: true,
      dataSource: [],
      query: {
        month: null,
        current: 1,
        size: 10,
        nameOrPhone: '',
        status: 'ON',
        CustomOrderType: 2,
        courseId: props.courseId,
        instId: window.currentUserInstInfo.instId,
      },
      dataSet: [],
      visible: false,
      loading: false,
      selectedIds: _.pluck(props.selected, 'teacherId') || [],
      selected: props.selected || [],
      isAll: false,
      oldDataSet: [],
    }
    this.reset = () => {
      this.handleQueryReset();
    }
  }

  componentWillMount() {
    this.fetchServerData();
  }

  componentWillReceiveProps(nextProps) {

    if (this.props.courseId !== nextProps.courseId) {
      this.state.query.courseId = nextProps.courseId;
      if (!nextProps.courseId) {
        delete this.state.query.courseId
      }
      this.fetchServerData();
    }
  }

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

  handleQueryReset = () => {
    this.setState({
      query: {
        current: 1,
        size: 10,
        nameOrPhone: '',
        status: 'ON',
        CustomOrderType: 2,
        courseId: this.props.courseId,
      }
    }, () => {
      this.fetchServerData();
    });
  }


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

  fetchServerData(current = 1) {
    this.state.query.current = current;
    const self = this;
    const url = this.props.url || 'public/teacher/getTeacherDigestPage'
    const param = _.extend(this.state.query, this.props.query);
    // param.courseId =  this.props.courseId || null
    this.setState({ fetching: true }, () => {
      setTimeout(() => {
        this.setState({ fetching: false })
      })
    })
    // axios.Business(url, param).then((res) => {
    //   let data = this.props.filter ? this.props.filter(res.result.records) : res.result.records;
    //   if (current > 1) {
    //     data = this.state.dataSet.concat(data)
    //   }
    //   if (this.props.multiple && (current == 1)) {
    //     _.map(this.props.defaultValue, (item) => {
    //       const list = _.filter(data, (_item) => {
    //         return item.teacherId == _item.teacherId
    //       })
    //       if (!list.length) {
    //         data.push(item)
    //       }
    //     })
    //   }
    //   if (this.props.noTeacher) {
    //     if (data[0] && data[0].teacherId != '-1') {
    //       data.unshift(
    //         { teacherId: '-1', name: '待分配' }
    //       )
    //     }
    //   }

    //   data = _.uniq(data, (item) => {
    //     return item.teacherId;
    //   })

    //   this.setState({
    //     dataSet: data,
    //     totalCount: res.result.total,
    //     isAll: !res.result.hasNext,
    //     fetching: false
    //   });
    // }).finally((res) => {
    //   this.setState({ loading: false });
    // });
  }

  handleTeacherSelect = (teacher) => {
    const query = this.state.query;
    const { oldDataSet, dataSet } = this.state;
    const data = _.find(dataSet, item => item.teacherId == teacher);
    if (data) {
      oldDataSet.push(data);
      const _oldDataSet = _.uniq(oldDataSet, item => item.teacherId);
      this.setState({ oldDataSet: _oldDataSet });
    }
    if (query.name) {
      query.name = '';
      this.setState({ query }, this.fetchServerData);
    }
    if (!this.props.multiple) {
      const items = _.filter(this.state.dataSet, (_item) => {
        return _item.teacherId == teacher;
      })
      this.props.onSelect({ teacherId: teacher, name: !!items[0] && items[0].name ? items[0].name : '' });
      return;
    } else {
      const list = [];
      _.map(teacher, (item) => {
        const _list = _.filter(this.state.dataSet, (_item) => {
          return _item.teacherId == item;
        })
        list.push({
          name: _list[0].name,
          teacherId: item
        })
      })
      this.props.onSelect(list);
    }
  }

  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'
    }

    let value = [];
    value = this.props.defaultValue
    const list = _.filter(this.state.dataSet, (item) => {
      return item.teacherId == this.props.defaultValue
    })

    if (!list.length) {
      value = this.props.teacherName || undefined
    }
    if (this.props.multiple) {
      value = _.pluck(this.props.defaultValue, 'teacherId')
    }
    let data = _.filter(this.state.dataSet, item => item.name);
    data = _.uniq(data, item => item.teacherId);
    return (
      <div className={("common-select staticSelect teacher-search-select")} style={this.props.style}>
        {
          !!this.props.label && <div className='label'> {this.props.label}:</div>
        }
        <Select
          id={this.props.id}
          ref='teacher'
          {...defprops}
          showSearch
          // style={{ width: '100%' }}
          allowClear
          notFoundContent={this.state.fetching ? <Spin size="small" /> : null}
          onSearch={
            (value) => {
              const query = this.state.query;
              query.nameOrPhone = value
              this.setState({ query }, this.searchName)
            }
          }
          // open
          onPopupScroll={(dom) => {
            this.hasmore(dom)
          }}
          placeholder={this.props.placeholder}
          value={value}
          onChange={this.handleTeacherSelect}
          filterOption={(input, option) => option}
        >
          {
            _.map(data, (item, index) => {
              if (this.props.showAvatar) {
                return <Select.Option id={'teacher_select_item_' + index} key={item.teacherId} value={item.teacherId} title={item.name}>
                  <Row align="middle">
                    <Col span={6}>
                      <Avatar icon="user" src={item.avatar || baseImg} />
                    </Col>
                    <Col span={18}>
                      <div className="teacher-name" title={item.name}>
                        {item.name}
                      </div>
                      <div className="subject-name" title={item.subjectName || ''}>
                        {item.subjectName || ''}
                      </div>
                    </Col>
                  </Row>
                </Select.Option>
              } else {
                return <Select.Option id={'teacher_select_item_' + index} key={item.teacherId} value={item.teacherId} title={item.name}>
                  <Tooltip title={`科目：${item.subjectName || '未设置'}`}>{item.name}</Tooltip>
                </Select.Option>
              }
            })
          }
          {!this.state.isAll &&
            <Select.Option disabled style={{ textAlign: 'center' }} value="spin">
              <Spin size="small" />
            </Select.Option>
          }
        </Select>

      </div>
    )
  }
}

TeacherSearchSelect.propTypes = {};
TeacherSearchSelect.defaultProps = {
  onSelect: () => { },
  name: '选择老师',
  courseId: null,
  selected: [],
  multiple: false,
  query: {},
  filter: null,
  renderItem: null,
  limit: false,
  async: false,
  showAvatar: false
}

export default TeacherSearchSelect;
