import React , { Component } from 'react';
import { Dropdown , Icon , Input } from 'antd';

import "./branch.css"
const $ = window.$;
class SelectBranch extends Component{
  constructor(props){
    super(props);
    this.state={
      visible:false,
      value:undefined
    }
  }
  componentDidMount() { 
    document.body.addEventListener('click', e => { 
      if (e.target && (e.target.matches('#m-btn') || e.target.matches("#input-btn")|| e.target.matches("#ul-btn"))) { 
        return; 
      }   
      if($(e.target)[0].className === "task-hide ulALink")return;
      this.setState({
        visible:false,
        value:undefined
      })
    });             
  } 

  ChangeVisible=(visible)=>{
    this.setState({
      visible:!visible
    })
  }

  InputClick=(e)=>{
    this.stopPropagations(e);
  }

  stopPropagations=(e)=>{
    e.stopPropagation();
  }

  // 输入搜索内容
  changeValue=(e)=>{
    this.setState({
      value:e.target.value
    })
  }

  // 选择分支
  changeBranchs=(e,value)=>{
    e.stopPropagation();
    this.setState({
      visible:false,
      value
    })
    const { changeBranch } = this.props;
    changeBranch && changeBranch(value);
  }

  render(){
    const { visible , value } = this.state;
    const { branchs , branch } = this.props;

    let branchsFilter = value ? (branchs && branchs.length>0 && branchs.filter(item=>item.name.indexOf(value)>-1)):branchs;
    const menu = (
      <div className="branchOptions" id="m-btn" onClick={this.stopPropagations}>
        <Input placeholder="请输入分支名称进行搜索" autocomplete="off" id="input-btn" value={value} className="OptionsInput" onChange={this.changeValue} onClick={this.InputClick}/>
        <ul className="OptionsUl" id="ul-btn">
          {
            branchsFilter && branchsFilter.map((item,key)=>{
              return(
                <li key={key}><a className="task-hide ulALink" onClick={(e)=>this.changeBranchs(e,`${item.name}`)}>{item.name}</a></li>
              )
            })
          }
        </ul>
      </div>
    );
    return(
      <div className="branchDropdown f-wrap-alignCenter" onClick={()=>this.ChangeVisible(visible)}>
        <Dropdown overlay={menu} trigger={['click']} placement="bottomLeft" visible={visible}>
          <span>
            <span className="color-grey-9 mr3"><i className="iconfont icon-fenzhi font-20 color-grey-6 mr3"></i>分支:</span>
            <a className="ant-dropdown-link">
              {branch} <Icon type="down" />
            </a>
          </span>
        </Dropdown>
      </div>
    )
  }
}
export default SelectBranch;