import React from 'react';
import styles from './index.less';
import clear from './imgs/clear.png';
import search from './imgs/search.png';
import config from '@config/index';
import classNames from 'classnames';
import LiItem from '@common/components/LiItem';
import ScrollArea from 'react-scrollbar';
/**
 * 主诉“添加症状”下拉中的：搜索框（含结果下拉）
 * 接收参数：
 * show:上级下拉是否隐藏，用于componentWillReceiveProps中
 */
class SearchBox extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
          showBox:false, //显示搜索结果
          border:'',
          showClear:false, //显示清空icon
          timer:null
        }
        this.textInput = React.createRef();
        this.handleClearVal = this.handleClearVal.bind(this);
        this.handleFocus = this.handleFocus.bind(this);
        this.handleBlur = this.handleBlur.bind(this);
        this.clickIcon = this.clickIcon.bind(this);
        //this.handleSearchSelect = this.handleSearchSelect.bind(this);
        this.reset = this.reset.bind(this);
    }
    handleClearVal(){
        const { clearSearch } = this.props;
        this.textInput.current.value = '';
        this.textInput.current.focus();
        this.setState({
          showClear:false
        });
        clearSearch&&clearSearch();
    }
    handleSearchSelect(item,e){
      e.stopPropagation();
      e.preventDefault();
      const {clearSearch,onSelect} = this.props;
      onSelect(item);//上一级的“确定”事件
      clearSearch&&clearSearch();
      this.textInput.current.value = "";
    }
    handleInput(e){
      e.stopPropagation();
      e.preventDefault();
      const { getSearchData ,mainIds,clearSearch,pushIds} = this.props;
      const ids = [...mainIds,...pushIds];
        clearTimeout(this.state.timer);
        let timer = setTimeout(()=>{
            clearTimeout(this.state.timer);
            if(e.target.value.trim() == ''){
              this.setState({
                showClear:false
              });
              clearSearch();
              return
            }
            this.setState({
              showClear:true
            })
            getSearchData && getSearchData({inpStr:e.target.value.replace('<br>',''),boxMark:1,itemType:0,mainIds:ids});
        },config.delayTime);
        this.setState({
          timer
        });
    }
    handleFocus(e){//聚焦时边框变蓝色
      //e.stopPropagation();
      e.preventDefault();
      this.setState({border:true})
    }
    handleBlur(e){
      e.stopPropagation();
      e.preventDefault();
      this.setState({border:false})
    }
    clickIcon(){
      this.setState({showBox:true})
      setTimeout(()=>{
        this.textInput.current.focus();
      },0)
    }
    // 重置事件
    reset(){
      const { clearSearch } = this.props;
      clearSearch();
      this.textInput.current.value = "";
      this.setState({
        showBox:false,
        border:false,
        showClear:false
      })
    }
    componentDidMount(){
      this.props.onRef(this);
    }
    componentWillReceiveProps(next){
      // 隐藏时，清空搜索框内文字，清空搜索结果，隐藏搜索框
      if(!next.show && next.show != this.props.show){
        this.reset();
      }
    }
    render() {
        const { mainSearchData } = this.props;
        const { showClear ,border, showBox} = this.state;
        const showBd = showBox?styles['borderNone']:'';//显示边框
        const borderCor = border?styles['border']:''; //蓝色边框
        const isShow = showBox?styles['show']:styles['hide']; //是否显示输入框
        let litext = '';
        const contStyle={
          opacity:'0.4',
          right:'0',
          top:'1px',
          zIndex:'15',
          width:'14px',
          background:'#f1f1f1'};
        const barStyle={background:'#777',width:'100%'};
        return (
            <div className={classNames(styles['search'])} onClick={this.clickIcon} onBlur={(e)=>{e.stopPropagation();}}>
                <img className={styles.searchVal} src={search} alt="搜索"/>
                <img style={{display:showClear?'block':'none'}} className={styles.clearVal} src={clear} onClick={this.handleClearVal} alt="清空" />
                <input
                    className={classNames(isShow,borderCor,showBd)}
                    type="text"
                    maxLength="30"
                    ref={this.textInput}
                    onFocus={this.handleFocus}
                    onBlur={this.handleBlur}
                    onInput={(e) => { 
                      this.handleInput(e)
                    }}
                    onPropertyChange={(e) => {  // 兼容ie
                      this.handleInput(e)
                    }}
                />
                {mainSearchData&&mainSearchData.length>0 ? <div className={styles.autoList}>
                    <ScrollArea speed={0.8}
                      horizontal={false}
                      stopScrollPropagation={mainSearchData.length>6?true:false}
                      style={{maxHeight:'180px'}}
                      verticalContainerStyle={contStyle}
                      verticalScrollbarStyle={barStyle}
                      contentClassName="content">
                      <ul>
                        {mainSearchData&&mainSearchData.map((it)=>{
                          litext = it.showType==1?it.name:it.name+'（'+it.retrievalName+'）';
                          return <LiItem key={it.conceptId}
                                         handleClick={this.handleSearchSelect.bind(this,it)}
                                         title={litext}>{litext}</LiItem>
                        })}
                      </ul>
                    </ScrollArea>
                  </div>:''}
            </div>
        )
    }
}
export default SearchBox;