import React,{Component} from 'react';
import classNames from 'classnames';
import ReactDom from "react-dom";

import style from "./index.less";
/****
 * 搜索结果下拉
 * 接收参数：
 * data: json数组
 * show:true/false
 * textKey: 选项文字字段名
 * idKey: 选项id字段名
 * type: text选项为纯文本,label选项为标签
 * onSelect: 选中事件
 * showType：1-本体，2-同义词，3-子项，同义词展示在括号内
 * retrievalName：同义词
 * name：本体
 **/

class SearchDrop extends Component{
  constructor(props){
    super(props);
    this.handleSelect = this.handleSelect.bind(this);
    this.state={
      data:props.data||[]
    }
  }
  getClass(){
    let name = style['text-list'];
    let isHide = this.props.show?'':style['hide'];
    switch (this.props.type){
      case 'text':
        name = style['text-list'];
        break;
      case 'label':
        name = style['label-list'];
        break;
      default:
        name = style['text-list'];
    }
    return classNames(style['list'],name,isHide);
  }

  getStyle(){
    const {left,top} = this.props;
    return {
      left:left?left+'px':'',
      top:top?top+'px':''
    }
  }

  handleSelect(e,item){
    // onClick事件换成onmouseup--点击清除后谷歌下搜索结果点击不上去的情况
    e.stopPropagation();
    const {onSelect,onShow} = this.props;
    onSelect&&onSelect(item);
    // onShow&&onShow(e,false);
  }
  render(){
    const {mainEmpty} = this.props;
    let litext = '';
    if(mainEmpty){
      return <div className={this.getClass()} contenteditable="false" id="searchBox" style={this.getStyle()}>
          <ul>
            {this.props.data&&this.props.data.map((it)=>{
              litext = it.showType==1?it.name:it.name+'（'+it.retrievalName+'）';
              return <li onClick={(e)=>this.handleSelect(e,it)} title={litext}>{litext}</li>
            })}
          </ul>
        </div>
    }else{
      
      const domNode = document.getElementById('root');
      return ReactDom.createPortal(
        <div className={this.getClass()} contenteditable="false" id="searchBox" style={this.getStyle()}>
          <ul>
            {this.props.data&&this.props.data.map((it)=>{
              litext = it.showType==1?it.name:it.name+'（'+it.retrievalName+'）';
              return <li onClick={(e)=>this.handleSelect(e,it)} title={litext}>{litext}</li>
            })}
          </ul>
        </div>
      ,domNode)
    }
    
  }
}

export default SearchDrop;