/*
 * @Author: sunbingqing
 * @Date: 2019-08-05 11:05:00
 * @Last Modified by: zhujian
 * @Last Modified time: 2020-05-26 19:50:20
 */

import React, { useEffect, useState } from 'react';
import { Spin, Select } from 'antd';
import "./CommonSelect.less";
import Bus from '@/core/bus';
import _ from 'underscore';

interface ClassSearchSelectProps {
  style?: any;
  label?: string;
  id?: string;
  multiple?: boolean;
  query?: any;
  courseId?: string;
  courseIds?: Array<number>;
  states?: any;
  placeholder?: string;
  defaultValue?: any;
  className?: string;
  classType?: number;
  url?: string;
  filter?: (value: any) => void;
  hasNoneClass?: boolean;
  needName?: boolean;
  instId?: any;
  hasNoClass?: any;
  onSelect?: (val1: any, val2?: any) => void;
  teacherId?: any;
  mode?:  "multiple" | "tags" | undefined
}

interface ItemTypes {
  name: string,
  classId: string,
}

const ClassSearchSelect = (props: ClassSearchSelectProps) => {
  const { style, label, id, placeholder, defaultValue, className, classType, url, filter, hasNoneClass, needName, onSelect, hasNoClass } = props;
  const multiple = props.multiple || false;
  let timer: any;
  let scroll: any;

  const [query, setQuery] = useState(_.extend({
    current: 1,
    size: 10,
    showNumber: 100,
    classNameLike: '',
    states: props.states || ['INIT', 'STUDYING', 'END'],
    courseId: props.courseId,
    courseIds: props.courseIds,
    instId: props.instId
  }, props.query));

  const [dataSet, setDataSet] = useState([]);
  const [isAll, setIsAll] = useState(false);

  useEffect(() => {
    // Bus.bind('reset', handleQueryReset);
    // fetchServerData();

    return () => {
      // Bus.unbind('reset');
      clearTimeout(timer);
      clearTimeout(scroll);
    };
  }, []);

  useEffect(() => {
    setQuery((query: any) => ({ ...query, courseId: props.courseId }));
    setTimeout(() => {
      fetchServerData();
    }, 300)
  }, [props.courseId]);

  let defprops = _.pick(props, 'open', 'getPopupContainer');
  if (multiple) {
    defprops.mode = 'multiple';
  }

  let selectValue = defaultValue;
  if (!multiple && defaultValue != '-1') {
    const list = _.filter(dataSet, (item: any) => {
      return item.classId === defaultValue;
    });

    if (!list.length) {
      selectValue = className || undefined;
    }
  }

  function handleQueryReset() {
    setQuery(() =>
      _.extend({
        current: 1,
        size: 10,
        showNumber: 100,
        classNameLike: '',
        states: props.states || ['INIT', 'STUDYING', 'END'],
        courseId: null,
      }, props.query),
    );
    fetchServerData();
  }

  function fetchServerData(current = 1) {
    let queryTemp = { ...query, current, courseId: props.courseId || '' };
    setQuery((query: any) => ({ ...query, current }));

    if (!classType) {
      queryTemp = { ...queryTemp, classType: '' };
      setQuery((query: any) => ({ ...query, classType: '' }));
    }

    const urlTemp = url || 'public/class/digestList';

    const param = _.extend(queryTemp, props.query);


    // if (url == "public/homework/getTeacherClassPage") {
    //   window.axios.post(urlTemp, param).then((res: any) => {
    //     const data = res.result.records;
    //     _.map(data, (item: any) => {
    //       item.name = item.className;
    //       item.formatName = item.className;
    //     });
    //     let dataSetTemp = [];
    //     if (current === 1) {
    //       dataSetTemp = filter ? filter(data) : data;
    //       if (hasNoneClass) {
    //         dataSetTemp.unshift({ classId: "1", name: '未选班' });
    //       }
    //     } else {
    //       dataSetTemp = dataSet.concat(filter ? filter(data) : data);
    //     }
    //     setDataSet(dataSetTemp);
    //     setIsAll(!res.result.hasNext);
    //   });
    // } else {
    //   window.axios.Business(urlTemp, param).then((res: any) => {
    //     const data = res.result.records;
    //     _.map(data, (item: any) => {
    //       item.formatName = item.name;
    //     });
    //     let dataSetTemp = [];
    //     if (current === 1) {
    //       dataSetTemp = filter ? filter(data) : data;
    //       if (hasNoneClass) {
    //         dataSetTemp.unshift({ classId: "1", name: '未选班' });
    //       }
    //     } else {
    //       dataSetTemp = dataSet.concat(filter ? filter(data) : data);
    //     }
    //     setDataSet(dataSetTemp);
    //     setIsAll(!res.result.hasNext);
    //   });
    // }
  }

  function searchName() {
    clearTimeout(timer);
    timer = setTimeout(() => {
      fetchServerData();
    }, 500);
  }

  function hasmore(e: any) {
    clearTimeout(scroll);
    const ulDom = e.currentTarget.getElementsByTagName("ul")[0];
    if (ulDom.length <= 0) {
      return;
    }

    scroll = setTimeout(() => {
      if (ulDom.scrollTop + ulDom.clientHeight > ulDom.scrollHeight - 30 && !isAll) {
        fetchServerData(query.current + 1);
      }
    }, 300);
  }

  function handleClassSelect(classId: string) {
    if (!classId) { // 清空选项
      const queryTemp = query;
      queryTemp.classNameLike = "";
      setQuery(() => queryTemp);
      searchName();
    }
    // console.log(classId)
    const queryTemp = query;
    if (queryTemp.name) {
      queryTemp.classNameLike = '';
      setQuery(() => queryTemp);
      fetchServerData();
    }

    if (!multiple) {
      if (needName) {
        const items:Array<ItemTypes> = _.filter(dataSet, (item: ItemTypes) => {
          return item.classId === classId;
        });
        const formatName = items[0] ?  items[0].name ? items[0].name :"": "";
        onSelect && onSelect({ classId, formatName });
        return;
      }
      onSelect && onSelect({ classId });
      return;
    }
    onSelect && onSelect(classId);
  }

  return (
    <div className={"common-select staticSelect"} style={style}>
      {
        !!label && <div className='label'> {label}:</div>
      }
      <Select
        id={id}
        {...defprops}
        showSearch
        allowClear
        onSearch={(value: string) => {
          const queryTemp = query;
          queryTemp.classNameLike = value;
          setQuery(() => queryTemp);
          searchName();
        }}
        // open
        onPopupScroll={hasmore}
        placeholder={placeholder}
        value={selectValue}
        onChange={handleClassSelect}
        filterOption={(_input: any, option: any) => option}
      >
        {
          hasNoClass && <Select.Option key={'-1'} value={'-1'} >未选班</Select.Option>
        }
        {
          _.map(dataSet, (item: any, index: number) => {
            return <Select.Option id={'class_select_item_' + index} key={item.classId} value={item.classId} title={item.name}>{item.name}</Select.Option>;
          })
        }
        {!isAll &&
          <Select.Option disabled style={{ textAlign: 'center' }} value="spin">
            <Spin size="small" />
          </Select.Option>
        }
      </Select>
    </div>
  );
};

export default ClassSearchSelect;
