/*
 * @Author: 吴文洁 
 * @Date: 2020-07-14 15:41:30 
 * @Last Modified by: 吴文洁
 * @Last Modified time: 2020-07-23 13:45:16
 * @Description: 大班直播、互动班课列表的筛选组件
 */

import React, { useState, useRef, useEffect } from 'react';
import { withRouter } from 'react-router-dom';
import { Row, Input, Select ,Tooltip} from 'antd';
import RangePicker from "@/modules/common/DateRangePicker";
import moment from 'moment';
import StoreService from "@/domains/store-domain/storeService";
import User from '@/common/js/user'
import Bus from '@/core/bus';
import './UserLearningDataFilter.less';

const { Search } = Input;
const { Option } = Select;
const userRole =  User.getUserRole();
const DEFAULT_QUERY = {
  customerName: null,
  startTime: null,
  endTime:null,
  learnState:null,
  operateId: null
}
const defaultCreatorQuery = {
  size: 10,
  current: 1,
  nickName:null
}
function UserLearningDataFilter(props) {

  const [expandFilter, setExpandFilter] = useState(false);
  const [query,setQuery] = useState(DEFAULT_QUERY);
  const [hasNext,setHasNext] = useState(false);
  const [creatorQuery,setCreatorQuery] = useState(defaultCreatorQuery);
  const [creatorList,setCreatorList] =  useState([]);

  useEffect(() => {
    Bus.bind('watchDataView',(value) => handleChangeCreatorQuery(value))
  }, []);
  useEffect(() => {
    getCreatorList();
  }, [creatorQuery]);

  function handleChangeCreatorQuery (value){
    const _creatorQuery = {...creatorQuery};
    _creatorQuery.operateId = value;
    setCreatorQuery(_creatorQuery);
  }
    // 改变搜索条件
  function handleChangeQuery(field, value){
    const _query ={
      ...query,
      [field]: value,
      current: 1,
    } 
    setQuery(_query);
    if (field === 'customerName') return;
    props.onChange( _query);
  }

   

  function handleChangeDates (dates){
    const _query = _.clone(query);
    if (_.isEmpty(dates)) {
      delete _query.startTime;
      delete _query.endTime;
    } else {
      _query.startTime = dates[0].valueOf();
      _query.endTime = dates[1].valueOf();
    }
    const param ={
      ..._query,
      current: 1,
    }
    setQuery(param);
    props.onChange(param);
  }

  // 重置搜索条件
  function  handleReset(){
    setQuery(DEFAULT_QUERY);
    props.onChange(DEFAULT_QUERY);
  }

  function getCreatorList(current = 1, selectList){
    const _query = {
      ...creatorQuery,
      current,
      size:10
    };
    StoreService.getStoreUserBasicPage( _query).then((res) => {
        const { result = {} } = res;
        const { records = [], total = 0, hasNext } = result;
        const list = current > 1 ? creatorList.concat(records) : records;
        setHasNext(hasNext);
        setCreatorList(list);
    });
  }

   // 滑动加载更多讲师列表
  function handleScrollCreatorList(e){
    const container = e.target;
    const scrollToBottom = container &&  container.scrollHeight <= container.clientHeight + container.scrollTop;
    if (scrollToBottom && hasNext) {
      getCreatorList(creatorQuery.current + 1);
    }
  }


  return (
      <div className="user-learn-data-filter">
        <Row>
            <div className="search-condition">
              <div className="search-condition__item">
                <span className="label customer-label">用户：</span>
                <Search
                  value={query.customerName}
                  placeholder="搜索用户名称"
                  onChange={(e) => { handleChangeQuery('customerName', e.target.value)}}
                  onSearch={ () => { props.onChange(query) } }
                  style={{ width: "calc(100% - 70px)" }}
                  enterButton={<span className="icon iconfont">&#xe832;</span>}
                />
              </div>
              {(User.getUserRole() === "CloudManager" || User.getUserRole() === "StoreManager")&&
                <div className="search-condition__item">
                    <span className="label lead-label">负责人：</span>
                    <Select
                      id="leadSelect"
                      placeholder="请选择创建人"
                      style={{width:"calc(100% - 70px)"}}
                      showSearch
                      allowClear
                      filterOption={(input, option) => option}
                      suffixIcon={<span className="icon iconfont" style={{fontSize:'12px',color:'#BFBFBF'}}>&#xe835;</span>}
                      onPopupScroll={handleScrollCreatorList}
                      value={query.operateId}
                      onChange={(value) => {
                        handleChangeQuery('operateId', value) 
                      }}
                      onSearch={(value) => {
                          creatorQuery.nickName = value
                          setCreatorQuery(creatorQuery)
                          getCreatorList();
                        }
                      }
                      onClear ={(value)=>{
                        setCreatorQuery({
                          size: 10,
                          current: 1,
                          nickName:null
                        })
                        getCreatorList()
                      }
                    }
                    >
                      {_.map(creatorList, (item, index) => {
                        return (
                          <Select.Option value={item.id} key={item.id}>{item.nickName}</Select.Option>
                        );
                      })}
                    </Select>
                </div>
              }
              <div className="search-condition__item">
                <span  className="label learn-date-label">最近学习日期：</span>
                <RangePicker
                  id="course_date_picker"
                  allowClear={false}
                  value={ query.startTime ? [moment(query.startTime), moment(query.endTime)] : null }
                  format={"YYYY-MM-DD"}
                  onChange={(dates) => { handleChangeDates(dates) }}
                  style={{ width: "calc(100% - 98px)" }}
                />
              </div>
              { ((expandFilter && (User.getUserRole() === "CloudManager" || User.getUserRole() === "StoreManager")) ||   User.getUserRole === "CloudOperator")&&
                <div className="search-condition__item">
                  <span  className="label learn-status-label">学习状态：</span>
                  <Select
                    style={{ width: "calc(100% - 70px)" }}
                    placeholder="请选择当前状态"
                    allowClear={true}
                    value={query.learnState}
                    onChange={(value) => { handleChangeQuery('learnState', value) }}
                    suffixIcon={<span className="icon iconfont" style={{fontSize:'12px',color:'#BFBFBF'}}>&#xe835;</span>}
                  >
                    <Option value="UN_PLAY">未开始</Option>
                    <Option value="UNDER_WAY">进行中</Option>
                    <Option value="FINISH">已完成</Option>
                  </Select>
                </div>
              }
            </div>  
          {( User.getUserRole() === "CloudManager" ||  User.getUserRole() === "StoreManager")&&
            <div className="reset-fold-area">
              <Tooltip title="清空筛选"><span className="resetBtn iconfont icon" onClick={handleReset}>&#xe61b; </span></Tooltip>
              <span style={{ cursor: 'pointer' }} className="fold-btn" onClick={() => {
                setExpandFilter(!expandFilter)
              }}>{expandFilter ? <span><span>收起</span><span className="iconfont icon fold-icon" >&#xe82d; </span> </span> : <span>展开<span className="iconfont icon fold-icon" >&#xe835; </span></span>}</span>
          </div>
          }
        </Row>
      </div>
    )
 
}

export default withRouter(UserLearningDataFilter);