import { rpx2vw4style as __rpx2vw__ } from "babel-runtime-jsx-style-transform";

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }

function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }

function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

import React, { createElement, useContext } from "react";
import List from '../../list';
import Menu from '../../menu';
import Button from '../../button';
import TagSelect from '../../tag-select';
import { findInArray, isFunction, isNil, isValidArray, mergeDataSource, replaceMessage } from '../../utils';
import View from '../../view';
import SelectContext from '../context';
import Typography from '../../typography';
import Option from '../option';
import { defaultLocalFilter, isSelected, removeItemFromArray } from '../util';
var Text = Typography.Text;

var sort = function sort(arr, value) {
  var selectedArr = [];
  var unSelectedArr = [];
  arr.forEach(function (item) {
    if (isSelected(value, item.value)) {
      selectedArr.push(item);
    } else {
      unSelectedArr.push(item);
    }
  });
  return [].concat(selectedArr, unSelectedArr);
};

var SelectBody = function SelectBody(props) {
  var _useContext = useContext(SelectContext),
      prefix = _useContext.prefix,
      size = _useContext.size,
      displayType = _useContext.displayType,
      disabled = _useContext.disabled,
      mode = _useContext.mode,
      dataSource = _useContext.dataSource,
      _useContext$filterLoc = _useContext.filterLocal,
      filterLocal = _useContext$filterLoc === void 0 ? true : _useContext$filterLoc,
      _useContext$stickyOnT = _useContext.stickyOnTop,
      stickyOnTop = _useContext$stickyOnT === void 0 ? true : _useContext$stickyOnT,
      _useContext$filter = _useContext.filter,
      filter = _useContext$filter === void 0 ? defaultLocalFilter : _useContext$filter,
      searchValue = _useContext.searchValue,
      innerValue = _useContext.innerValue,
      value = _useContext.value,
      transferSearchToOption = _useContext.transferSearchToOption,
      _onChange = _useContext.onChange,
      onSearchAdd = _useContext.onSearchAdd;

  var _props$searchToOption = props.searchToOptionBtnText,
      searchToOptionBtnText = _props$searchToOption === void 0 ? '' : _props$searchToOption,
      _props$emptySearchTex = props.emptySearchText,
      emptySearchText = _props$emptySearchTex === void 0 ? '' : _props$emptySearchTex;
  var renderWithTag = displayType === 'tag';
  var renderWithMenu = !renderWithTag && mode === 'single';
  var clsPrefix = "".concat(prefix, "select");
  var filteredDataSource = filterLocal ? mergeDataSource(dataSource, [].concat(_toConsumableArray(value), _toConsumableArray(innerValue))).filter(function (item) {
    return filter(searchValue, item);
  }) : dataSource;

  if (mode === 'multiple' && stickyOnTop) {
    filteredDataSource = sort(filteredDataSource, value);
  }

  if (renderWithMenu) {
    return /*#__PURE__*/React.createElement(Menu, {
      prefix: prefix,
      size: size,
      selectMode: "single",
      dataSource: filteredDataSource,
      selectedKeys: innerValue.map(function (it) {
        return it.value;
      }),
      onItemClick: function onItemClick(_, item) {
        var onClick = item.onClick;

        if (isFunction(onClick)) {
          onClick(item.value);
        }

        _onChange([{
          label: item.label,
          value: item.value
        }]);
      }
    });
  }

  if (renderWithTag) {
    return /*#__PURE__*/React.createElement(View, {
      className: "".concat(prefix, "select--tag-").concat(size)
    }, /*#__PURE__*/React.createElement(TagSelect, {
      prefix: prefix,
      mode: mode,
      size: size,
      value: innerValue.map(function (it) {
        return it.value;
      }),
      dataSource: filteredDataSource,
      onChange: function onChange(v) {
        if (isNil(v)) {
          _onChange([]);

          return;
        }

        var newValue = Array.isArray(v) ? v : [v];
        var newItems = newValue.map(function (x) {
          return findInArray(filteredDataSource, function (item) {
            return item.value === x;
          });
        });

        _onChange(newItems);
      }
    }));
  }

  var options = filteredDataSource.map(function (it) {
    return /*#__PURE__*/React.createElement(Option, _extends({
      key: it.value,
      selected: isSelected(innerValue, it.value),
      disabled: disabled || it.disabled,
      onClick: function onClick() {
        var selectedItem = findInArray(innerValue, function (item) {
          return item.value === it.value;
        });

        if (selectedItem) {
          _onChange(removeItemFromArray(innerValue, selectedItem.value));
        } else {
          _onChange([].concat(_toConsumableArray(innerValue), [{
            label: it.label,
            value: it.value
          }]));
        }
      }
    }, it), it.label);
  });
  return transferSearchToOption ? /*#__PURE__*/React.createElement(List, null, searchValue && !findInArray(filteredDataSource, function (it) {
    return "".concat(it.label) === "".concat(searchValue);
  }) && /*#__PURE__*/React.createElement(Option, {
    isNew: true,
    onClick: function onClick() {
      if (onSearchAdd) {
        onSearchAdd(searchValue, innerValue);
      }

      _onChange([].concat(_toConsumableArray(innerValue), [{
        label: searchValue,
        value: searchValue,
        userAdd: true
      }]));
    }
  }, /*#__PURE__*/React.createElement(View, {
    style: __rpx2vw__({
      display: 'flex',
      flexDirection: 'row',
      alignItems: 'center',
      justifyContent: 'space-between'
    })
  }, /*#__PURE__*/React.createElement("span", null, searchValue), /*#__PURE__*/React.createElement(Button, {
    size: "small",
    type: "primary",
    model: "outline"
  }, searchToOptionBtnText))), options) : isValidArray(filteredDataSource) ? /*#__PURE__*/React.createElement(List, null, options) : /*#__PURE__*/React.createElement(View, {
    className: "".concat(clsPrefix, "-search-empty")
  }, /*#__PURE__*/React.createElement(Text, {
    className: "".concat(clsPrefix, "-search-empty-tip"),
    type: "body-2"
  }, replaceMessage(emptySearchText, {
    searchVal: searchValue
  })));
};

export default SelectBody;