/*
 * @Author: sunbingqing
 * @Date: 2019-07-24 17:21:00
 * @Last Modified by: 吴文洁
 * @Last Modified time: 2020-02-25 10:23:49
 */

import React, { useState, useEffect } from 'react';
import { Input } from 'antd';
import _ from 'underscore';
import './SearchBar.less';
import Bus from '../core/tbus';

interface SearchBarProps {
  value?: string;
  type?: string;
  className?: string;
  label?: string;
  id?: string;
  placeholder?: string;
  options?: any;
  style?: any,
  onChangeText?: (value: any) => void;
  onSearch?: (value: any) => void;
}

const SearchBar = (props: SearchBarProps) => {
  const { type, className, label, id, placeholder, options, onChangeText, onSearch, style } = props;
  const cls = `xm-search-bar xm-search-bar-${type || ""} ${className || ""}`;
  const plh = placeholder || `请输入${_.values(options).join('/')}`;
  const defprops = {
    id: ''
  };
  if (id) { defprops.id = id; }
  const [ value, setValue] = useState(props.value);
  
  useEffect(() => {
    Bus.bind('resetSearchBar', () => {
      setValue('');
    });
  }, []);

  function _handleOnChangeText(e: any): any {
    setValue(e.target.value);
    onChangeText && onChangeText(e.target.value);
  }

  function _onPressEnter() {
    onSearch && onSearch(value);
  }

  function _renderAddonAfter() {
    return (
      <span className="icon iconfont" onClick={_onPressEnter}>&#xe6ba;</span>
    );
  }

  return (
    <div className={cls} style={style}>
      {
        !!label && <div className='label'> {label}:</div>
      }

      <Input
        {...defprops}
        name="value"
        placeholder={plh}
        value={value}
        onChange={_handleOnChangeText}
        addonAfter={_renderAddonAfter()}
        onPressEnter={_onPressEnter}
      />
    </div>
  );
};

export default SearchBar;
