import _defineProperty from "@babel/runtime/helpers/defineProperty";
import _classCallCheck from "@babel/runtime/helpers/classCallCheck";
import _createClass from "@babel/runtime/helpers/createClass";
import _assertThisInitialized from "@babel/runtime/helpers/assertThisInitialized";
import _inherits from "@babel/runtime/helpers/inherits";
import _createSuper from "@babel/runtime/helpers/createSuper";
import React, { Component } from 'react';
import { findDOMNode } from 'react-dom';
import Icon from '../icon';
import Select from '../select';
import { filterByInputValue, getColumnKey } from './util';
import Checkbox from '../checkbox/Checkbox';
import { SelectMode } from '../select/enum';
import ConfigContext from '../config-provider/ConfigContext';
var Option = Select.Option,
    OptGroup = Select.OptGroup;
var PAIR_SPLIT = ':';
var VALUE_SPLIT = '、';
var OPTION_OR = 'option-or';
export var VALUE_OR = 'OR';

function pairValue(column) {
  var value = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
  var filters = column.filters;
  var found = filters && filters.find(function (filter) {
    return String(filter.value) === value;
  });
  return {
    key: "".concat(getColumnKey(column)).concat(PAIR_SPLIT).concat(value),
    label: [column.filterTitle || column.title, PAIR_SPLIT, ' ', found ? found.text : value]
  };
}

function barPair(value, index) {
  return {
    key: "".concat(value).concat(PAIR_SPLIT).concat(index),
    label: [value]
  };
}

function removeDoubleOr(filters) {
  return filters.filter(function (_ref, index) {
    var label = _ref.label;
    return label !== VALUE_OR || label !== filters[index + 1];
  });
}

var FilterSelect = /*#__PURE__*/function (_Component) {
  _inherits(FilterSelect, _Component);

  var _super = _createSuper(FilterSelect);

  function FilterSelect(props) {
    var _this;

    _classCallCheck(this, FilterSelect);

    _this = _super.call(this, props);
    _this.columnRefs = {};

    _this.handleDropdownMouseDown = function (e) {
      e.preventDefault();

      _this.rcSelect.focus();
    };

    _this.saveRef = function (node) {
      if (node) {
        _this.rcSelect = node.rcSelect;
      }
    };

    _this.saveColumnRef = function (key, node) {
      if (node) {
        _this.columnRefs[key] = node;
      }
    };

    _this.handleInputKeyDown = function (e) {
      var value = e.target.value;
      var _this$state = _this.state,
          filters = _this$state.filters,
          columnFilters = _this$state.columnFilters,
          selectColumn = _this$state.selectColumn;
      var filterText = value;

      if (selectColumn && value) {
        filterText = value.split(_this.getColumnTitle(selectColumn)).slice(1);
      }

      if (e.keyCode === 13 && filterText[0]) {
        if (selectColumn) {
          var key = getColumnKey(selectColumn);

          if (key) {
            var columFilters = selectColumn.filters;
            columnFilters[key] = filterText;
            var found = columFilters && columFilters.find(function (filter) {
              return filter.text === filterText[0];
            });
            var filterValue = found ? String(found.value) : filterText[0];

            _this.fireColumnFilterChange(key, [filterValue]);
          }
        } else {
          filters.push(value);

          _this.fireChange(filters);
        }

        _this.setState({
          inputValue: '',
          filters: filters,
          columnFilters: columnFilters,
          selectColumn: undefined
        });

        _this.rcSelect.setState({
          inputValue: ''
        });
      }
    };

    _this.handleInput = function (value) {
      var selectColumn = _this.state.selectColumn;

      if (selectColumn) {
        if (value.indexOf(_this.getColumnTitle(selectColumn)) === -1) {
          selectColumn = undefined;
        }
      }

      _this.setState({
        selectColumn: selectColumn,
        inputValue: value
      });
    };

    _this.handleChoiceItemClick = function (_ref2) {
      var key = _ref2.key;
      var pair = key.split(PAIR_SPLIT);

      if (pair.length > 1) {
        var columnKey = pair.shift();

        var selectColumn = _this.findColumn(columnKey);

        if (selectColumn && selectColumn.filterMultiple) {
          var filters = selectColumn.filters;
          var checked = pair.join(PAIR_SPLIT).split(VALUE_SPLIT).map(function (text) {
            var found = filters && filters.find(function (filter) {
              return filter.text === text;
            });
            return found ? found.value : text;
          });

          _this.setState({
            selectColumn: selectColumn,
            checked: checked
          });
        }
      }
    };

    _this.handleSelect = function (_ref3) {
      var key = _ref3.key;
      var _this$state2 = _this.state,
          checked = _this$state2.checked,
          selectColumn = _this$state2.selectColumn;

      if (key === '__ok__') {
        _this.handleMultiCheckConfirm();
      } else if (key !== "".concat(selectColumn && selectColumn.title, ":")) {
        var index = checked.indexOf(key);

        if (index === -1) {
          checked.push(key);
        } else {
          checked.splice(index, 1);
        }

        _this.setState({
          checked: checked
        }, function () {
          if (selectColumn) {
            var columnFilters = _this.state.columnFilters;
            var columnKey = getColumnKey(selectColumn);

            if (columnKey) {
              var filters = columnFilters[columnKey];

              if (!filters || !filters.length) {
                _this.rcSelect.setState({
                  inputValue: _this.getColumnTitle(selectColumn)
                });
              }
            }
          }
        });
      }

      return false;
    };

    _this.handleMultiCheckConfirm = function () {
      var _this$state3 = _this.state,
          selectColumn = _this$state3.selectColumn,
          checked = _this$state3.checked;

      if (selectColumn) {
        var columnKey = getColumnKey(selectColumn);

        if (columnKey) {
          _this.fireColumnFilterChange(columnKey, checked);

          _this.setState({
            selectColumn: undefined,
            checked: []
          });

          _this.rcSelect.setState({
            inputValue: ''
          });
        }
      }
    };

    _this.handleClear = function () {
      _this.setState({
        selectColumn: undefined
      });
    };

    _this.handleChange = function (changedValue) {
      var _assertThisInitialize = _assertThisInitialized(_this),
          state = _assertThisInitialize.state,
          rcSelect = _assertThisInitialize.rcSelect;

      var selectColumn = state.selectColumn,
          inputValue = state.inputValue,
          columnFilters = state.columnFilters;
      var filters = state.filters;

      var all = _this.getValue();

      var change = false;

      if (changedValue.length > all.length) {
        var value = changedValue.pop();

        if (inputValue && value && value.key === inputValue) {
          change = true;

          if (selectColumn && !selectColumn.filterMultiple && value) {
            var columnKey = getColumnKey(selectColumn);

            var columnTitle = _this.getColumnTitle(selectColumn);

            var val = rcSelect.state.inputValue || value.key;

            if (columnKey) {
              _this.fireColumnFilterChange(columnKey, [val.split("".concat(columnTitle))[1]]);
            }
          } else {
            filters.push(value.label);
          }

          _this.setState({
            selectColumn: undefined,
            inputValue: '',
            filters: filters
          });
        } else if (value && value.label === OPTION_OR) {
          filters.push(VALUE_OR);
          change = true;

          _this.setState({
            filters: filters
          });
        } else if (selectColumn) {
          if (!selectColumn.filterMultiple) {
            var _columnKey = getColumnKey(selectColumn);

            if (rcSelect.state.inputValue && value && _columnKey) {
              _this.fireColumnFilterChange(_columnKey, selectColumn.filters && !selectColumn.filters.length && !inputValue ? [] : [value.key]);
            }

            _this.setState({
              selectColumn: undefined
            });
          } else {
            _this.setState({
              selectColumn: undefined,
              checked: []
            });

            rcSelect.setState({
              inputValue: ''
            });
          }
        } else if (value) {
          var column = _this.findColumn(value.key);

          var columnFilter = columnFilters[value.key];

          if (column && (!columnFilter || !columnFilter.length)) {
            rcSelect.setState({
              inputValue: _this.getColumnTitle(column)
            });
          }

          _this.setState({
            selectColumn: column
          });
        }
      } else {
        filters = _this.changeValue(changedValue, rcSelect.state.value);

        if (state.filters.length !== filters.length) {
          change = true;
        }

        _this.setState({
          inputValue: '',
          filters: filters
        });
      }

      if (change) {
        _this.fireChange(filters);
      }
    };

    _this.toValueString = function (item) {
      var key = Object.keys(item)[0];

      var col = _this.findColumn(key);

      if (col) {
        return pairValue(col, item[key]);
      }

      return '';
    };

    _this.getRootDomNode = function () {
      var getPrefixCls = _this.context.getPrefixCls;
      return findDOMNode(_assertThisInitialized(_this)).querySelector(".".concat(getPrefixCls('select'), "-search__field"));
    };

    _this.state = {
      columns: _this.getColumnsWidthFilters(),
      filters: props.filters || [],
      columnFilters: props.columnFilters || {},
      inputValue: '',
      selectColumn: undefined,
      checked: []
    };
    return _this;
  }

  _createClass(FilterSelect, [{
    key: "componentWillReceiveProps",
    value: function componentWillReceiveProps(nextProps) {
      this.setState({
        columns: this.getColumnsWidthFilters(nextProps)
      });

      if (nextProps.filters) {
        this.setState({
          filters: nextProps.filters
        });
      }

      if (nextProps.columnFilters) {
        this.setState({
          columnFilters: nextProps.columnFilters
        });
      }
    }
  }, {
    key: "getPrefixCls",
    value: function getPrefixCls() {
      var prefixCls = this.props.prefixCls;
      return "".concat(prefixCls, "-filter-select");
    }
  }, {
    key: "render",
    value: function render() {
      var _this$props = this.props,
          placeholder = _this$props.placeholder,
          getPopupContainer = _this$props.getPopupContainer;
      var inputValue = this.state.inputValue;
      var prefixCls = this.getPrefixCls();
      var multiple = this.isMultiple();
      return /*#__PURE__*/React.createElement("div", {
        className: prefixCls
      }, /*#__PURE__*/React.createElement("div", {
        className: "".concat(prefixCls, "-icon")
      }, /*#__PURE__*/React.createElement(Icon, {
        type: "filter_list"
      })), /*#__PURE__*/React.createElement(Select, {
        ref: this.saveRef,
        mode: SelectMode.tags,
        filterOption: false,
        onChange: this.handleChange,
        onSelect: multiple ? this.handleSelect : undefined,
        onInput: this.handleInput,
        onInputKeyDown: this.handleInputKeyDown,
        onClear: this.handleClear,
        value: this.getValue(),
        placeholder: placeholder,
        notFoundContent: false,
        showNotFindInputItem: false,
        showNotFindSelectedItem: false,
        dropdownMatchSelectWidth: false,
        defaultActiveFirstOption: !inputValue,
        dropdownStyle: {
          minWidth: 256
        },
        onDropdownMouseDown: this.handleDropdownMouseDown,
        dropdownClassName: "".concat(prefixCls, "-dropdown"),
        getRootDomNode: this.getRootDomNode,
        showCheckAll: false,
        onChoiceItemClick: this.handleChoiceItemClick,
        getPopupContainer: getPopupContainer,
        allowClear: true,
        labelInValue: true,
        blurChange: true,
        border: false
      }, this.getOptions()), /*#__PURE__*/React.createElement("div", {
        className: "".concat(prefixCls, "-columns")
      }, this.renderColumnsTitle()));
    }
  }, {
    key: "renderColumnsTitle",
    value: function renderColumnsTitle() {
      var _this2 = this;

      var columns = this.state.columns;
      this.columnRefs = {};
      return columns.map(function (col) {
        var key = getColumnKey(col);
        return /*#__PURE__*/React.createElement("span", {
          ref: _this2.saveColumnRef.bind(_this2, key),
          key: key
        }, col.filterTitle || col.title);
      });
    }
  }, {
    key: "isMultiple",
    value: function isMultiple() {
      var selectColumn = this.state.selectColumn;

      if (selectColumn) {
        return selectColumn.filterMultiple;
      }

      return false;
    }
  }, {
    key: "fireChange",
    value: function fireChange(filters) {
      var onChange = this.props.onChange;

      if (typeof onChange === 'function') {
        onChange(filters);
      }
    }
  }, {
    key: "fireColumnFilterChange",
    value: function fireColumnFilterChange(columnKey, value) {
      var col = this.findColumn(columnKey);
      var onFilter = this.props.onFilter;

      if (col && onFilter) {
        onFilter(col, value || null);
      }
    }
  }, {
    key: "changeValue",
    value: function changeValue(changedValue, oldValue) {
      var _this3 = this;

      var state = this.state;
      var changedColumnKeys = [];
      var changedColumnFilters = state.columnFilters;
      var columnFiltersValues = this.getColumnFiltersValues();

      if (changedValue.length) {
        var len = columnFiltersValues.length;

        if (len > 0) {
          var index = oldValue.findIndex(function (item, i) {
            return item !== (changedValue[i] && changedValue[i].key);
          });

          if (index < columnFiltersValues.length) {
            var deleted = changedValue.splice(0, len - 1);

            if (deleted.length < 2 && changedValue[0] && changedValue[0].label === VALUE_OR) {
              changedValue.shift();
            }

            var value = columnFiltersValues[index];

            if (value === VALUE_OR) {
              value = columnFiltersValues[index + 1];
            }

            var columnKey = Object.keys(value)[0];
            var columnFilters = changedColumnFilters[columnKey].slice();
            var column = this.findColumn(columnKey);

            if (column) {
              var filters = column.filters;
              value[columnKey].split(VALUE_SPLIT).forEach(function (text) {
                var found = filters && filters.find(function (filter) {
                  return filter.text === text;
                });
                var filterIndex = columnFilters.indexOf(found ? found.value : text);

                if (filterIndex !== -1) {
                  columnFilters.splice(filterIndex, 1);
                  changedColumnFilters[columnKey] = columnFilters;

                  if (changedColumnKeys.indexOf(columnKey) === -1) {
                    changedColumnKeys.push(columnKey);
                  }
                }
              });
            }
          } else {
            changedValue.splice(0, len);
          }
        }

        changedColumnKeys.forEach(function (key) {
          _this3.fireColumnFilterChange(key, changedColumnFilters[key]);
        });
      } else {
        var onClear = this.props.onClear;

        if (onClear) {
          onClear();
        }
      }

      return removeDoubleOr(changedValue).map(function (item) {
        var label = item.label;

        if (label.constructor === Array) {
          return label && label[0];
        }

        return label;
      });
    }
  }, {
    key: "getColumnFiltersValues",
    value: function getColumnFiltersValues() {
      var _this4 = this;

      var values = [];
      var columnFilters = this.state.columnFilters;
      Object.keys(columnFilters).forEach(function (c) {
        var filteredValue = columnFilters[c];

        var column = _this4.findColumn(c);

        if (filteredValue && filteredValue.length && column) {
          var filters = column.filters;
          values.push(_defineProperty({}, c, filteredValue.map(function (value) {
            var found = filters && filters.find(function (filter) {
              return String(filter.value) === String(value);
            });
            return found ? found.text : value;
          }).join(VALUE_SPLIT)));
        }
      });
      return values;
    }
  }, {
    key: "getValue",
    value: function getValue() {
      var filters = this.state.filters;
      return this.getColumnFiltersValues().map(this.toValueString).concat(filters.map(barPair));
    }
  }, {
    key: "getInputFilterOptions",
    value: function getInputFilterOptions(inputValue) {
      var _this$props2 = this.props,
          columns = _this$props2.columns,
          dataSource = _this$props2.dataSource;
      var options = [];

      if (dataSource && columns) {
        var values = {};
        filterByInputValue(dataSource, columns, inputValue, function (record, column) {
          var dataIndex = column.dataIndex;

          if (dataIndex) {
            var value = record[dataIndex].toString();

            if (!values[value]) {
              values[value] = true;
              options.push( /*#__PURE__*/React.createElement(Option, {
                key: value,
                value: value
              }, value));
            }
          }
        });
      }

      return options;
    }
  }, {
    key: "getOptions",
    value: function getOptions() {
      var state = this.state;
      var selectColumn = state.selectColumn,
          inputValue = state.inputValue,
          columns = state.columns,
          checked = state.checked,
          columnFilters = state.columnFilters;

      if (selectColumn) {
        if (inputValue && inputValue.split(PAIR_SPLIT)[1]) {
          return null;
        }

        var filters = selectColumn.filters,
            filterMultiple = selectColumn.filterMultiple;
        var columnKey = getColumnKey(selectColumn);

        if (filters) {
          return filters.filter(function (filter) {
            return !filter.children;
          }).map(function (filter, i) {
            var value = String(filter.value);
            var text = filter.text;

            if (filterMultiple && columnKey) {
              var _checked = columnFilters[columnKey];

              if (_checked && !checked.length) {
                state.checked = _checked.slice();
              } else {
                _checked = checked;
              }

              text = [/*#__PURE__*/React.createElement(Checkbox, {
                key: "ck",
                className: "multiple",
                checked: _checked.indexOf(value) !== -1
              }), text];
            }

            return /*#__PURE__*/React.createElement(Option, {
              key: "filter-".concat(String(i)),
              value: value
            }, text);
          }).concat(filterMultiple ? /*#__PURE__*/React.createElement(OptGroup, {
            key: "ok"
          }, /*#__PURE__*/React.createElement(Option, {
            value: "__ok__",
            className: "".concat(this.getPrefixCls(), "-ok-btn")
          }, "\u786E\u8BA4")) : []);
        }
      } else if (inputValue) {
        return this.getInputFilterOptions(inputValue);
      } else {
        var _filters = this.state.filters;
        var multiple = this.props.multiple;
        var length = _filters.length;
        var value = this.getColumnFiltersValues();
        var keys = value.map(function (item) {
          return Object.keys(item)[0];
        });
        var options = columns.reduce(function (opts, column, i) {
          var key = getColumnKey(column, i);

          if (keys.indexOf(key) === -1 || column.filterMultiple) {
            opts.push( /*#__PURE__*/React.createElement(Option, {
              key: "column-".concat(key),
              value: key
            }, /*#__PURE__*/React.createElement("span", null, column.filterTitle || column.title)));
          }

          return opts;
        }, []);

        if (multiple && (length ? _filters[length - 1] !== VALUE_OR : value.length)) {
          return [/*#__PURE__*/React.createElement(OptGroup, {
            key: "or"
          }, /*#__PURE__*/React.createElement(Option, {
            value: OPTION_OR
          }, "OR")), /*#__PURE__*/React.createElement(OptGroup, {
            key: "all"
          }, options)];
        }

        return options;
      }
    }
  }, {
    key: "getColumnsWidthFilters",
    value: function getColumnsWidthFilters() {
      var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.props;
      return (props.columns || []).filter(function (column) {
        return column.filters instanceof Array;
      });
    }
  }, {
    key: "findColumn",
    value: function findColumn(myKey) {
      var columns = this.state.columns;
      return columns.find(function (c) {
        return getColumnKey(c) === myKey;
      });
    }
  }, {
    key: "getColumnTitle",
    value: function getColumnTitle(column) {
      var columnKey = getColumnKey(column);

      if (columnKey) {
        return "".concat(this.columnRefs[columnKey].textContent).concat(PAIR_SPLIT);
      }

      return '';
    }
  }], [{
    key: "contextType",
    get: function get() {
      return ConfigContext;
    }
  }]);

  return FilterSelect;
}(Component);

export { FilterSelect as default };
FilterSelect.displayName = 'FilterSelect';
//# sourceMappingURL=FilterSelect.js.map
