import React from 'react';
import { Icon, WingBlank, WhiteSpace, } from 'antd-mobile';
import api from './apiConfig';
import { getWebInfo, getMobileInfo } from './utils';
import style from './index.less';
import PropTypes from 'prop-types';

const queryOptions = async() => {
  const gradeList = await getWebInfo({},api.GETGRADELIST);
  return {
    gradeList,
  }
}

export default class Filter extends React.Component{
  constructor(props){
    super(props);
    this.state ={
      role: 2,
      inputValue: '',
      formValues: {
        institutionIds: [],
        majorIds:[],
        clazzIds: [],
      },
      options: {
        gradeList:[],
        institutionList: [],
        majorList:[],
        clazzList: [],
      },
    }
  }

  componentDidMount() {
    this.fetchOptions();
    this.fetchRoleType();
  }

  // 获取角色类型信息
  fetchRoleType = async() => {
    const res = await getMobileInfo({},'/CommonApi/currentUser');
    if(res && !res.errCode) {
      const { options } = this.state;
      var role = res.type;
      options.institutionList = res.institutionModelList.map(i=> ({key: i.name,value: i.id}));
        if(role === 0 || role === 1) {
          this.setState({
          role,
          options
        })
      }
    }
  }

  // 获取 key value 
  fetchOptions = async() => {
    const res = await queryOptions();
    if(!res || !res.gradeList) return false;

    const gradeList = res.gradeList.map(i=> ({key: i.name,value: i.id}));
    this.setState({
      options: {
        gradeList,
        institutionList: [],
        majorList:[],
        clazzList: [],
      }
    })
  }

  // 获取专业
  fetchMajorList = (params={}) => {
    const { options } = this.state;
    getWebInfo(params,api.GETMAJOR).then(res=> {
      if(res && !res.errCode) {
        const majorList = res.map(i=> ({key: i.name,value: i.id}));
        options.majorList = majorList;
        this.setState({
          options
        })
      }
    })
  }

  // 通过系ids获取专业
  fetchMajorListByIds = (params={}) => {
    const { options } = this.state;
    getWebInfo(params,api.GETMAJORBYIDS).then(res=> {
      if(res && !res.errCode) {
        const majorList = res.map(i=> ({key: i.name,value: i.id}));
        options.majorList = majorList;
        this.setState({
          options
        })
      }
    })
  }

  // 获取班级列表
  fetchClazzList = (params={}) => {
    const { options } = this.state;
    getWebInfo(params,api.GETCLAZZLIST).then(res=> {
      if(res && !res.errCode) {
        const clazzList = res.map(i=> ({key: i.fullName,value: i.id}));
        options.clazzList = clazzList;
        this.setState({
          options
        })
      }
    })
  }

   // 通过专业ids获取班级列表
  fetchClazzListByIds = (params={}) => {
    const { options } = this.state;
    getWebInfo(params,api.GETCLAZZLISTBYIDS).then(res=> {
      if(res && !res.errCode) {
        const clazzList = res.map(i=> ({key: i.fullName,value: i.id}));
        options.clazzList = clazzList;
        this.setState({
          options
        })
      }
    })
  }

  // 搜索条件变化处理
  formChange = (key,value) => {
    let { formValues , role } = this.state;
    // 判断是否第二次取消
    if(key === 'clazzIds' || key === 'institutionIds' || key === 'majorIds') {
      if(formValues[key].indexOf(value) !== -1){
        formValues[key] = formValues[key].filter(i=> i!==value);
      }
      else{
         formValues[key].push(value);
      }
    }
    else{
      if(formValues[key] === value) delete formValues[key];
      else formValues[key]= value;
    }

    if(key === 'gradeId') {
      formValues.majorIds = [];
      formValues.clazzIds= [];
    }

    if(key === 'institutionIds') {
      this.fetchMajorListByIds({institutionIds:formValues.institutionIds.join(',')});
      formValues.majorIds = [];
      formValues.clazzIds = [];
    }

    if(key === 'majorIds') {
      this.fetchClazzListByIds({majorIds: formValues.majorIds.join(',')});
      formValues.clazzIds = [];
    }

    this.setState({
      formValues
    })
  }

  // 搜索框输入处理
  inputChange = (e) => {
    const { formValues } = this.state;
    if(e.target.value !== "") {
      var value = Number(e.target.value);
      if(isNaN(value)){
        formValues.name = e.target.value;
        if(formValues.studentNo) delete formValues.studentNo;
      }
      else{
        formValues.studentNo = value;
        if(formValues.name) delete formValues.name;
      }
    }
    else{
        delete formValues.name;
        delete formValues.studentNo
    }
    this.setState({
      formValues,
      inputValue: e.target.value,
    })
  }

  // 搜索条件DOM生成
  generateItem = (keyName,dataList) => {
    const { formValues } = this.state;
    // 判断类名
    const isSelect =(value) => {
      if(keyName === 'institutionIds' || keyName === 'majorIds' || keyName === 'clazzIds') {
        if(formValues[keyName].indexOf(value) !== -1) return true;
      }
      else if(formValues[keyName] === value){
        return true;
      }
      return false;
    }
    return (
      <div className='optionsBox'>
      {dataList.map(i=> (
        <div className={isSelect(i.value)? 'cusLabelFocus' : 'cusLabel'}
             key={i.value}
             onClick={() => this.formChange(keyName,i.value)} >{i.key}</div>))
      }
      </div>
    )
  }

  // 搜索处理
  search = () =>{
    const { formValues } = this.state;
    const temp = {...formValues};
    // 判断系是否为空
    if(formValues.institutionIds.length !== 0){
      temp.institutionIds = formValues.institutionIds.join(',');
    }
    else {
      delete temp.institutionIds;
    }

    // 判断专业是否为空
    if(formValues.majorIds.length !== 0){
      temp.majorIds = formValues.majorIds.join(',');
    }
    else {
      delete temp.majorIds;
    }

    // 判断班级是否为空
    if(formValues.clazzIds.length !== 0){
      temp.clazzIds = formValues.clazzIds.join(',');
    }
    else {
      delete temp.clazzIds;
    }
    this.props.getPage({...temp});
    this.props.Toggle && this.props.Toggle();
  }

  // 重置搜索条件
  reset =() => {
    this.setState({
      inputValue: '',
      formValues: {
        institutionIds: [],
        majorIds:[],
        clazzIds: [],
      }
    })
  }

  // 生成选择
  createSelect = () => {
    const { gradeList, institutionList, majorList, clazzList } = this.state.options;
    const { gradeId, institutionIds , majorIds } = this.state.formValues;
    const { role } = this.state;
    if(role === 0 || role === 1){
       return (
        <>
          <p style={{color: '#666666'}}>年级选择</p>
          {this.generateItem('gradeId',gradeList)}
          { gradeId ? (<><p style={{color: '#666666'}}>学院选择</p>
          {this.generateItem('institutionIds',institutionList)}</>) : null}
          { institutionIds.length ? (<><p style={{color: '#666666'}}>专业选择</p>
          {this.generateItem('majorIds',majorList)}</>) : null}
          { majorIds.length ? <><p style={{color: '#666666'}}>班级选择</p>
          {this.generateItem('clazzIds',clazzList)}</> : null }
        </>
      )
    }
    return null;
  }

  render(){
    return (
      <div className='siderBar'>
        <div className='searchBox'>
          <input type='text' 
                 ref={node => this.input = node} 
                 id='searchInput' 
                 placeholder='请输入姓名/学号' 
                 value={this.state.inputValue} 
                 onChange={this.inputChange} />
        
          <div id="searchButton" onClick={this.search}><Icon type='search' size='sm'/></div>
        </div>
        <div className='mainContent'>
        <WhiteSpace size='lg'/>
        <WingBlank size='lg'>
          {this.createSelect()}
        </WingBlank>
        </div>
        <div className='buttonBox'>
            <div onClick={this.reset}>重置</div>
            <div onClick={this.search}>确定</div>
        </div>
      </div>
    )
  }
}

Filter.propTypes = {
  getPage: PropTypes.func.isRequired, // 页面刷新方法
  toggle: PropTypes.func, // 收回侧边方法
}
Filter.defaultProps = {
  getPage: () => {}
}