/**
 * Created by baoyinghai on 1/11/17.
 */
import React from 'react';
import moment from 'moment';
import { autobind } from 'core-decorators';
import { SearchSummary, AdvancedSearch } from '../../../components';
import { Table, Button, Row, Col, Tooltip, Icon, Tag } from '../../../components/mxa';
import SearchInput from '../../../components/search/SearchInput';
import FilterBarContainer from './filterBarContainer';
import { isEmpty } from '../../utils/EmptyUtils';
import { BUTTON_BINDPARAMETERTYPE } from '../../constant/dictCodes';
import DropMenu from './dropMenu';
import { iconWrapper } from '../../utils/IconHelper';
import SearchBar from '../../../components/search/SearchBar';


export default class ToolBar extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      advancedSearch: false,
      requestFilterFields: [],
      isFocus: false,
      showBtns: true,
      showOtherBtns: false,
      toolBarType: this.props.toolBarType
    };
  }

  _deleteNull = ary => {
    return ary.filter(item => !isEmpty(item.value));
  };

  _onChange = value => {
    const isExist = this.state.requestFilterFields && this.state.requestFilterFields.some((item, index) => {
      if (item.fieldName === value.fieldName) {
        this.state.requestFilterFields[index] = value;
        return true;
      }
      return false;
    });
    if (!isExist) {
      this.state.requestFilterFields.push(value);
    }

    this.setState({ requestFilterFields: this._deleteNull(this.state.requestFilterFields) }, () =>
    console.log(this.state.requestFilterFields));
  }


  _onSearch = () => {
    this.setState({ advancedSearch: false }, () => this.props.onSearch && this.props.onSearch(this.state.requestFilterFields, true));
  }

  _clear = () => {
    this.setState({ requestFilterFields: [] });
  }

  _getDefaultValue = code => {
    const tag = this.state.requestFilterFields.filter(item => item.fieldName === code);
    return tag[0] && tag[0].value;
  }

  @autobind
  renderAdvancedDetail() {
    const prefixCls = 'mx-advance-search';
    return (
      <FilterBarContainer {...this.props} advancedSearch={!!this.state.advancedSearch && !this.state.toolBarType} switchHandler={this.updateAdvancedSearch} querySelector="scroll-bar-container">
        <div>
          <div className={`${prefixCls}-advanced-search-form`}>
            {
              this.props.filters && this.props.filters.map((item, index) => (
                <div key={index}>
                  <SearchInput
                    prefixCls={prefixCls + '-input'}
                    key={item.name}
                    type={item.type}
                    operatorType={item.operatorType}
                    code={item.name}
                    title={item.displayValue}
                    extra={item.extra}
                    onChange={this._onChange}
                    value={this._getDefaultValue(item.name)}
                  />
                </div>
              ))
            }
          </div>
        </div>
      </FilterBarContainer>
    );
  }

  @autobind
  updateAdvancedSearch() {
    this.setState({
      advancedSearch: !this.state.advancedSearch
    });
  }


  @autobind
  _switchOtherBtns(e) {
    this.setState({
      showOtherBtns: !this.state.showOtherBtns
    });
  }

  _closeMenu = () => {
    if (this.state.showOtherBtns) {
      this.setState({ showOtherBtns: false });
    }
    console.log('b', this.state.showOtherBtns);
  };


  @autobind
  _moreBtnBlur(e) {
    if (this.state.showOtherBtns === true) {
      this.setState({
        showOtherBtns: false
      });
    }
  }

  @autobind
  _renderFilterButtons() {
    if (this.state.advancedSearch) {
      const prefixCls = 'mx-advance-search';
      return (
        <div className={`${prefixCls}-advanced-button-bar`}>
          <a
            className={`${prefixCls}-advanced-button-clear`}
            onClick={this._clear}
          >清空</a>
          <a
            className={`${prefixCls}-advanced-button`}
            onClick={this._onSearch}
          >检索</a>
        </div>
      );
    }
    const btns = this.props.renderTopButtons(item => item.relatedData === BUTTON_BINDPARAMETERTYPE.NONE || item.relatedData === BUTTON_BINDPARAMETERTYPE.ALL);
    if (btns && btns.length > 0) {
      return (
        <div className="create-entity-toolbar" >
          <div className="create-entity-btn dinline-block lfloat" onClick={this._moreBtnBlur}>
            {btns[0]}
          </div>
          <a
            className={'create-entity-more dinline-block lfloat' + (this.state.showOtherBtns ? ' create-entity-more-down' : '')}
            onClick={this._switchOtherBtns}
          >
            <i className="dblock" />
          </a>
        </div>
      );
    }
    return null;
  }

  _removeFilterItem = id => {
    this.setState({
      requestFilterFields: this.state.requestFilterFields.filter(item => item.fieldName !== id)
    }, () => this.props.onSearch && this.props.onSearch(this.state.requestFilterFields, true));
  };

  _getValueByType = item => {
    const renderHelper = this.props.filters.filter(f => f.name === item.fieldName)[0];
    if (renderHelper.type === 'DATEPICKER') {
      const left = item.value[0] && moment(item.value[0]);
      const right = item.value[1] && moment(item.value[1]);
      return [left, right].join(', ');
    } else if (renderHelper.type === 'INPUT' && renderHelper.operatorType === 'BETWEEN') {
      return item.value;
    } else if (renderHelper.type === 'SELECT') {
      const tag = renderHelper.extra.filter(i => i.code === item.value);
      return tag[0] && tag[0].value;
    }
    return item.value;
  };

  _searchFunc = value => {
    const filters = this.props.filters || [];
    const v = filters.map(item => {
      return {
        [item.name]: value
      };
    });
    this.props.onSearch(v, false);
  };

  _renderTags = () => {
    if (this.state.advancedSearch) return null;
    const filterObj = this.props.filters.reduce((obj, filter) => ({ ...obj, [filter.name]: filter.displayValue }), {});
    return this.state.requestFilterFields.map(item => {
      // TODO: 数据字典
      const value = this._getValueByType(item);
      return (<Tag id={item.fieldName} callback={this._removeFilterItem}>{filterObj[item.fieldName] + ':' + value}</Tag>);
    });
  };

  @autobind
  _renderFilter() {
    const { prefixCls } = this.props;
    const toolbarClass = `${prefixCls}-toolbar`;
    return (
      <div>
        <div className={toolbarClass}>
          <div className={'advanced-search-advanced'}>
            <AdvancedSearch dataSource={this.props.filters} advancedSearch={this.state.advancedSearch} requestFilterFields={this.state.requestFilterFields} onSearch={value => this.props.onSearch(value, true)} updateAdvancedSearch={this.updateAdvancedSearch} />
            <div className="tag-list">{this._renderTags()}</div>
          </div>
          <div className={'toolbar-buttons grid_tool'} >
            {this._renderFilterButtons()}
          </div>
          <SearchBar searchFunc={this._searchFunc} />
        </div>
      </div>
    );
  }

  @autobind
  _renderOperates(isAll) {
    const btns = this.props.renderTopButtons(isAll ? null : item => item.relatedData !== BUTTON_BINDPARAMETERTYPE.NONE && item.relatedData !== BUTTON_BINDPARAMETERTYPE.NONE);
    return btns
      && (
        <ul>
          {btns.map((btn, index) => {
            if (btn.props.showSelectRowsNum) {
              if (this.props.selectRows) {
                btn.props.buttonDescriptionSupper = btn.props.buttonDescription + '(' + this.props.selectRows + ')';
              }
            }
            return (
              <li key={index}>{btn}</li>
            );
          })}
        </ul>
      );
  }

  @autobind
  _switchToolBar() {
    if (this.state.toolBarType) {
      this.props.closeCallback && this.props.closeCallback();
    }
    this.setState({
      toolBarType: !this.state.toolBarType
    });
  }

  @autobind
  _renderOperation() {
    /* eslint-disable */
    return (
      <div className={this.props.prefixCls + '-grid-operate'} >
        <a className="close" onClick={this._switchToolBar}></a>
        {this._renderOperates()}
      </div>
    );
  }

  _renderSimpleOperates = () => {
    const btns = this.props.renderTopButtons();
    return btns
      && (
        <ul>
          {btns.map((btn, index) => {
            let buttonDescriptionSupper = btn.props.buttonDescription;
            if (this.props.selectRows) {
              buttonDescriptionSupper = btn.props.buttonDescription + '(' + this.props.selectRows + ')';
            }
            return (
              <li key={index}>{btn}</li>
            );
          })}
        </ul>
      );
  }

  _renderSimpleOperation = () => {
    /* eslint-disable */
    return (
      <div className={this.props.prefixCls + '-grid-simple-operate'} >
        {this._renderSimpleOperates()}
        {this._renderRightPart()}
      </div>
    );
  };

  componentWillReceiveProps(nextProps) {
    if (nextProps.toolBarType !== this.state.toolBarType) {
      this.setState({
        toolBarType: !this.state.toolBarType
      });
    }
  }

  _renderRightPart = () => {
    return (
      <div className="more-button">
        {this.props.filters.length > 0 && <SearchSummary dataSource={this.props.filters} onSearch={this.props.onSearch} />}
        <div>
          {iconWrapper('icon-raxicongengduo63')}
        </div>
      </div>
    );
  };

  _renderModalBar = () => {
    return (
      <div>
        {this._renderSimpleOperation(true)}
      </div>
    );
  }

  render() {
    let top = '45px';
    if (this.props.isInfo) {
      top = '56px';
    } else if (this.props.isModal) {
      top = '45px';
    } else if (this.props.isProcess) {
      top = '45px';
    }
    if (this.props.isModal) {
      return (
        <div className="scroll-bar-container">
          {this._renderModalBar()}
        </div>
      );
    }
    return (
      <div className="scroll-bar-container">
        <div className="scroll-bar" style={{ overflow: 'hidden', height: '60px' }}>
          <div style={{ marginTop: (this.state.toolBarType ? '-60px' : '0px')}}>
            {this._renderFilter()}
            {this._renderOperation()}
          </div>
        </div>
        {this.renderAdvancedDetail()}
        <DropMenu
          querySelector="scroll-bar-container"
          showOtherBtns={this.state.showOtherBtns}
          style={{ display: this.state.showOtherBtns ? '' : 'none', top: top}}
          renderTopButtons={this.props.renderTopButtons(item => item.relatedData === BUTTON_BINDPARAMETERTYPE.NONE)}
          moreBtnBlur={this._moreBtnBlur}
        />
      </div>
    );
  }
}
