/*
 * @Author: 吴文洁
 * @Date: 2020-08-05 10:11:57
 * @LastEditors: fusanqiasng
 * @LastEditTime: 2021-05-28 20:14:37
 * @Description: 视频课-搜索模块
 * @Copyright: 杭州杰竞科技有限公司 版权所有
 */

import React from 'react'
import { Row, Input, Select, Tooltip, TreeSelect } from 'antd'

import RangePicker from '@/modules/common/DateRangePicker'
import _ from 'underscore'
import './VideoCourseFilter.less'
import moment from 'moment'
import StoreService from '@/domains/store-domain/storeService'
import User from '@/common/js/user'
import AidToolService from '@/domains/aid-tool-domain/AidToolService'

const { Search } = Input
const { Option } = Select

const DEFAULT_QUERY = {
  courseName: null, // 课程名称
  operatorId: null, // 创建人
  beginTime: null, // 开始日期
  endTime: null, // 结束日期
  shelfState: null,
  categoryId: null,
}
const defaultTeacherQuery = {
  size: 10,
  current: 1,
  nickName: null,
}
class VideoCourseFilter extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      query: { ...DEFAULT_QUERY }, // 使用扩展运算符,避免浅拷贝
      teacherQuery: defaultTeacherQuery,
      teacherList: [],
      expandFilter: false,
      categoryList: [],
    }
  }
  shouldComponentUpdate(nextProps) {
    if (nextProps.currentTabKey !== this.props.currentTabKey) {
      this.handleReset()
      return false
    }
    return true
  }
  componentDidMount() {
    this.getTeacherList()
    this.queryCategoryTree()
  }
  // 查询分类树
  queryCategoryTree = (categoryName = '') => {
    let query = {
      bizType: 'QUESTION',
      source: 2,
      categoryName,
      tenantId: User.getStoreId(),
      userId: User.getStoreUserId(),
      count: false,
    }
    AidToolService.queryExternalCategoryTree(query).then((res) => {
      const { categoryList = [] } = res.result
      console.log(this.renderTreeNodes(categoryList))
      this.setState({
        categoryList: this.renderTreeNodes(categoryList),
        categoryName,
      })
    })
  }

  renderTreeNodes = (data) => {
    let newTreeData = data.map((item) => {
      item.title = <span>{item.categoryName}</span>
      item.key = item.id
      if (item.sonCategoryList) {
        item.children = this.renderTreeNodes(item.sonCategoryList)
      }
      return item
    })
    return newTreeData
  }

  getTeacherList(current = 1, selectList) {
    const { teacherQuery, teacherList } = this.state
    const _query = {
      ...teacherQuery,
      current,
      size: 10,
    }
    StoreService.getStoreUserBasicPage(_query).then((res) => {
      const { result = {} } = res
      const { records = [], hasNext } = result
      const list = current > 1 ? teacherList.concat(records) : records
      this.setState({
        hasNext,
        teacherList: list,
      })
    })
  }
  // 滑动加载更多讲师列表
  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)
        }
      )
    }
  }
  // 改变搜索条件
  handleChangeQuery = (field, value) => {
    this.setState(
      {
        query: {
          ...this.state.query,
          [field]: value,

          current: 1,
        },
      },
      () => {
        if (field === 'courseName') return
        this.props.onChange(this.state.query)
      }
    )
  }

  handleChangeDates = (dates) => {
    console.log(dates)
    const query = _.clone(this.state.query)
    if (_.isEmpty(dates)) {
      delete query.beginTime
      delete query.endTime
    } else {
      query.beginTime = dates[0]?.startOf('day').valueOf()
      query.endTime = dates[1]?.endOf('day').valueOf()
    }
    this.setState(
      {
        query: {
          ...query,
          current: 1,
        },
      },
      () => {
        this.props.onChange(this.state.query)
      }
    )
  }

  // 重置搜索条件
  handleReset = () => {
    this.setState(
      {
        query: DEFAULT_QUERY,
      },
      () => {
        this.props.onChange(this.state.query)
      }
    )
  }

  render() {
    const { currentTabKey } = this.props
    const {
      query: { courseName, beginTime, endTime, operatorId, shelfState, categoryId },
      expandFilter,
      teacherList,
      teacherQuery,
      categoryList,
    } = this.state

    return (
      <div className='video-course-filter'>
        <Row type='flex' justify='space-between' align='top'>
          <div className='search-condition'>
            <div className='search-condition__item'>
              <span className='search-name'>视频课名称：</span>
              <Search
                value={courseName}
                placeholder='搜索视频课名称'
                onChange={(e) => {
                  this.handleChangeQuery('courseName', e.target.value)
                }}
                onSearch={() => {
                  this.props.onChange(this.state.query)
                }}
                style={{ width: 'calc(100% - 84px)' }}
                enterButton={<span className='icon iconfont'>&#xe832;</span>}
              />
            </div>
            <Choose>
              <When condition={currentTabKey === 'internal'}>
                <div className='search-condition__item'>
                  <span>创建人：</span>
                  <Select
                    placeholder='请选择创建人'
                    style={{ width: 'calc(100% - 70px)' }}
                    showSearch
                    allowClear
                    filterOption={(input, option) => option}
                    onPopupScroll={this.handleScrollTeacherList}
                    suffixIcon={
                      <span className='icon iconfont' style={{ fontSize: '12px', color: '#BFBFBF' }}>
                        &#xe835;
                      </span>
                    }
                    value={operatorId}
                    onChange={(value) => {
                      this.handleChangeQuery('operatorId', value)
                    }}
                    onSearch={(value) => {
                      teacherQuery.nickName = value
                      this.setState(
                        {
                          teacherQuery,
                        },
                        () => {
                          this.getTeacherList()
                        }
                      )
                    }}
                    onClear={(value) => {
                      this.setState(
                        {
                          teacherQuery: {
                            size: 10,
                            current: 1,
                            nickName: null,
                          },
                        },
                        () => {
                          this.getTeacherList()
                        }
                      )
                    }}>
                    {_.map(teacherList, (item, index) => {
                      return (
                        <Select.Option value={item.id} key={item.id}>
                          {item.nickName}
                        </Select.Option>
                      )
                    })}
                  </Select>
                </div>
              </When>
              <Otherwise>
                <div className='search-condition__item'>
                  <span className='shelf-status'>课程分类：</span>
                  <TreeSelect
                    treeNodeFilterProp='categoryName'
                    showSearch
                    value={categoryId || null}
                    style={{ minWidth: 'calc(100% - 75px)' }}
                    dropdownMatchSelectWidth={false}
                    treeData={categoryList}
                    placeholder='请选择课程分类'
                    allowClear
                    onChange={(value) => {
                      this.handleChangeQuery('categoryId', value)
                    }}
                  />
                </div>
              </Otherwise>
            </Choose>

            <div className='search-condition__item'>
              <span className='search-date'>创建日期：</span>
              <RangePicker
                id='course_date_picker'
                allowClear={false}
                value={beginTime ? [moment(beginTime), moment(endTime)] : null}
                format={'YYYY-MM-DD'}
                onChange={(dates) => {
                  this.handleChangeDates(dates)
                }}
                style={{ width: 'calc(100% - 70px)' }}
              />
            </div>

            <If condition={expandFilter}>
              <div className='search-condition__item'>
                <span className='shelf-status'>学院展示：</span>
                <Select
                  style={{ width: 'calc(100% - 84px)' }}
                  placeholder='请选择'
                  allowClear={true}
                  value={shelfState}
                  onChange={(value) => {
                    this.handleChangeQuery('shelfState', value)
                  }}
                  suffixIcon={
                    <span className='icon iconfont' style={{ fontSize: '12px', color: '#BFBFBF' }}>
                      &#xe835;
                    </span>
                  }>
                  <Option value='YES'>开启</Option>
                  <Option value='NO'>关闭</Option>
                </Select>
              </div>
            </If>
          </div>
          <div className='reset-fold-area'>
            <Tooltip title='清空筛选'>
              <span className='resetBtn iconfont icon' onClick={this.handleReset}>
                &#xe61b;{' '}
              </span>
            </Tooltip>
            <span
              style={{ cursor: 'pointer' }}
              className='fold-btn'
              onClick={() => {
                this.setState({ expandFilter: !expandFilter })
              }}>
              <Choose>
                <When condition={this.state.expandFilter}>
                  <span>
                    <span>收起</span>
                    <span className='iconfont icon fold-icon'>&#xe82d; </span>{' '}
                  </span>
                </When>
                <Otherwise>
                  <span>
                    展开<span className='iconfont icon fold-icon'>&#xe835; </span>
                  </span>
                </Otherwise>
              </Choose>
            </span>
          </div>
        </Row>
      </div>
    )
  }
}

export default VideoCourseFilter
