Liferay.Loader.define("commerce-frontend-js@3.0.26/components/dataset_display/management_bar/components/filters/AutocompleteFilter", ['module', 'exports', 'require', '@frontend-taglib-clay$clayui/autocomplete', '@frontend-taglib-clay$clayui/button', '@frontend-taglib-clay$clayui/drop-down', '@frontend-taglib-clay$clayui/form', '@frontend-taglib-clay$clayui/label', '@frontend-taglib-clay$clayui/loading-indicator', 'frontend-js-web', 'frontend-js-react-web$prop-types', 'frontend-js-react-web$react', '../../../../../utilities/index', '../../../utilities/filters'], function (module, exports, require) {
  var define = undefined;
  var global = window;
  {
    function _typeof(obj) {
      "@babel/helpers - typeof";
      if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
        _typeof = function _typeof(obj) {
          return typeof obj;
        };
      } else {
        _typeof = function _typeof(obj) {
          return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
        };
      }return _typeof(obj);
    }

    Object.defineProperty(exports, "__esModule", {
      value: true
    });
    exports.default = void 0;

    var _autocomplete = _interopRequireDefault(require("@frontend-taglib-clay$clayui/autocomplete"));

    var _button = _interopRequireDefault(require("@frontend-taglib-clay$clayui/button"));

    var _dropDown = _interopRequireDefault(require("@frontend-taglib-clay$clayui/drop-down"));

    var _form = require("@frontend-taglib-clay$clayui/form");

    var _label = _interopRequireDefault(require("@frontend-taglib-clay$clayui/label"));

    var _loadingIndicator = _interopRequireDefault(require("@frontend-taglib-clay$clayui/loading-indicator"));

    var _frontendJsWeb = require("frontend-js-web");

    var _propTypes = _interopRequireDefault(require("frontend-js-react-web$prop-types"));

    var _react = _interopRequireWildcard(require("frontend-js-react-web$react"));

    var _index = require("../../../../../utilities/index");

    var _filters = require("../../../utilities/filters");

    function _getRequireWildcardCache() {
      if (typeof WeakMap !== "function") return null;var cache = new WeakMap();_getRequireWildcardCache = function _getRequireWildcardCache() {
        return cache;
      };return cache;
    }

    function _interopRequireWildcard(obj) {
      if (obj && obj.__esModule) {
        return obj;
      }if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") {
        return { default: obj };
      }var cache = _getRequireWildcardCache();if (cache && cache.has(obj)) {
        return cache.get(obj);
      }var newObj = {};var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;for (var key in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, key)) {
          var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;if (desc && (desc.get || desc.set)) {
            Object.defineProperty(newObj, key, desc);
          } else {
            newObj[key] = obj[key];
          }
        }
      }newObj.default = obj;if (cache) {
        cache.set(obj, newObj);
      }return newObj;
    }

    function _interopRequireDefault(obj) {
      return obj && obj.__esModule ? obj : { default: obj };
    }

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

    function _nonIterableSpread() {
      throw new TypeError("Invalid attempt to spread non-iterable instance");
    }

    function _iterableToArray(iter) {
      if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
    }

    function _arrayWithoutHoles(arr) {
      if (Array.isArray(arr)) {
        for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) {
          arr2[i] = arr[i];
        }return arr2;
      }
    }

    function _slicedToArray(arr, i) {
      return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest();
    }

    function _nonIterableRest() {
      throw new TypeError("Invalid attempt to destructure non-iterable instance");
    }

    function _iterableToArrayLimit(arr, i) {
      if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) {
        return;
      }var _arr = [];var _n = true;var _d = false;var _e = undefined;try {
        for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
          _arr.push(_s.value);if (i && _arr.length === i) break;
        }
      } catch (err) {
        _d = true;_e = err;
      } finally {
        try {
          if (!_n && _i["return"] != null) _i["return"]();
        } finally {
          if (_d) throw _e;
        }
      }return _arr;
    }

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

    var DEFAULT_PAGE_SIZE = 10;

    function fetchData(apiUrl, searchParam) {
      var currentPage = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;
      return (0, _frontendJsWeb.fetch)("".concat(apiUrl).concat(apiUrl.includes('?') ? '&' : '?', "page=").concat(currentPage, "&pageSize=").concat(DEFAULT_PAGE_SIZE).concat(searchParam ? "&search=".concat(encodeURIComponent(searchParam)) : '')).then(function (response) {
        return response.json();
      });
    }

    function Item(props) {
      var Input = props.selectionType === 'single' ? _form.ClayRadio : _form.ClayCheckbox;
      return (/*#__PURE__*/_react.default.createElement("li", null, /*#__PURE__*/_react.default.createElement(Input, {
          checked: props.selected,
          label: props.label,
          onChange: props.onChange,
          value: props.value
        }))
      );
    }

    var formatValue = function formatValue(value, exclude) {
      return (exclude ? "(".concat(Liferay.Language.get('exclude'), ") ") : '') + value.map(function (el) {
        return el.label;
      }).join(', ');
    };

    function getOdataString(value, key, selectionType, exclude) {
      if (!value || !value.length) {
        return null;
      }

      return selectionType === 'multiple' ? "".concat(key, "/any(x:").concat(value.map(function (v) {
        return "(x ".concat(exclude ? 'ne' : 'eq', " ").concat(typeof v.value === 'string' ? "'".concat(v.value, "'") : v.value, ")");
      }).join(exclude ? ' and ' : ' or '), ")") : "".concat(key, " ").concat(exclude ? 'ne' : 'eq', " ").concat(typeof value[0].value === 'string' ? "'".concat(value[0].value, "'") : value[0].value);
    }

    function AutocompleteFilter(props) {
      var _useState = (0, _react.useState)(''),
          _useState2 = _slicedToArray(_useState, 2),
          query = _useState2[0],
          setQuery = _useState2[1];

      var _useState3 = (0, _react.useState)(''),
          _useState4 = _slicedToArray(_useState3, 2),
          search = _useState4[0],
          setSearch = _useState4[1];

      var _useState5 = (0, _react.useState)(props.value && props.value.items || []),
          _useState6 = _slicedToArray(_useState5, 2),
          selectedItems = _useState6[0],
          setSelectedItems = _useState6[1];

      var _useState7 = (0, _react.useState)(null),
          _useState8 = _slicedToArray(_useState7, 2),
          items = _useState8[0],
          updateItems = _useState8[1];

      var _useState9 = (0, _react.useState)(false),
          _useState10 = _slicedToArray(_useState9, 2),
          loading = _useState10[0],
          setLoading = _useState10[1];

      var _useState11 = (0, _react.useState)(1),
          _useState12 = _slicedToArray(_useState11, 2),
          currentPage = _useState12[0],
          setCurrentPage = _useState12[1];

      var _useState13 = (0, _react.useState)(0),
          _useState14 = _slicedToArray(_useState13, 2),
          totalItems = _useState14[0],
          updateTotalItems = _useState14[1];

      var scrollingArea = (0, _react.useRef)(null);

      var _useState15 = (0, _react.useState)(false),
          _useState16 = _slicedToArray(_useState15, 2),
          scrollingAreaRendered = _useState16[0],
          setScrollingAreaRendered = _useState16[1];

      var infiniteLoader = (0, _react.useRef)(null);

      var _useState17 = (0, _react.useState)(false),
          _useState18 = _slicedToArray(_useState17, 2),
          infiniteLoaderRendered = _useState18[0],
          setInfiniteLoaderRendered = _useState18[1];

      var _useState19 = (0, _react.useState)(props.value && props.value.exclude || false),
          _useState20 = _slicedToArray(_useState19, 2),
          exclude = _useState20[0],
          setExclude = _useState20[1];

      var loaderVisible = items && items.length < totalItems;
      (0, _react.useEffect)(function () {
        setSelectedItems(props.value && props.value.items || []);
      }, [props.value]);
      (0, _react.useEffect)(function () {
        if (query === search) {
          return;
        }

        setCurrentPage(1);
        setSearch(query);
      }, [query, search]);
      (0, _react.useEffect)(function () {
        setLoading(true);
        fetchData(props.apiUrl, search, currentPage).then(function (data) {
          setLoading(false);

          if (currentPage === 1) {
            updateItems(data.items);
          } else {
            updateItems(function (items) {
              return [].concat(_toConsumableArray(items), _toConsumableArray(data.items));
            });
          }

          updateTotalItems(data.totalCount);
        }).catch(function (e) {
          console.error(e);
          setLoading(false);
        });
      }, [currentPage, props.apiUrl, search]);
      var setScrollingArea = (0, _react.useCallback)(function (node) {
        scrollingArea.current = node;
        setScrollingAreaRendered(true);
      }, []);
      var setInfiniteLoader = (0, _react.useCallback)(function (node) {
        infiniteLoader.current = node;
        setInfiniteLoaderRendered(true);
      }, []);
      var setObserver = (0, _react.useCallback)(function () {
        if (!scrollingArea.current || !infiniteLoader.current || !IntersectionObserver) {
          return;
        }

        var options = {
          root: scrollingArea.current,
          rootMargin: '0px',
          threshold: 1.0
        };
        var observer = new IntersectionObserver(function (entries) {
          if (entries[0].intersectionRatio <= 0) {
            return;
          }

          setCurrentPage(function (page) {
            return page + 1;
          });
        }, options);
        observer.observe(infiniteLoader.current);
      }, []);
      (0, _react.useEffect)(function () {
        if (scrollingAreaRendered && infiniteLoaderRendered && loaderVisible) {
          setObserver();
        }
      }, [scrollingAreaRendered, infiniteLoaderRendered, loaderVisible, setObserver]);
      var actionType = 'edit';

      if (props.value && props.value.items && !selectedItems.length) {
        actionType = 'delete';
      }

      if (!props.value) {
        actionType = 'add';
      }

      var submitDisabled = true;

      if (actionType === 'delete' || !props.value && selectedItems.length || props.value && (0, _filters.isValuesArrayChanged)(props.value.items, selectedItems) || props.value && selectedItems.length && props.value.exclude !== exclude) {
        submitDisabled = false;
      }

      return (/*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_dropDown.default.Caption, null, /*#__PURE__*/_react.default.createElement(_autocomplete.default, null, /*#__PURE__*/_react.default.createElement(_autocomplete.default.Input, {
          onChange: function onChange(event) {
            return setQuery(event.target.value);
          },
          placeholder: props.inputPlaceholder
        }), loading && /*#__PURE__*/_react.default.createElement(_autocomplete.default.LoadingIndicator, null)), selectedItems.length ? /*#__PURE__*/_react.default.createElement("div", {
          className: "mt-2 selected-elements-wrapper"
        }, selectedItems.map(function (selectedItem) {
          return (/*#__PURE__*/_react.default.createElement(_label.default, {
              closeButtonProps: {
                onClick: function onClick() {
                  return setSelectedItems(function (items) {
                    return items.filter(function (item) {
                      return item.value !== selectedItem.value;
                    });
                  });
                }
              },
              key: selectedItem.value
            }, selectedItem.label)
          );
        })) : null), /*#__PURE__*/_react.default.createElement(_dropDown.default.Divider, null), /*#__PURE__*/_react.default.createElement(_dropDown.default.Caption, {
          className: "py-0"
        }, /*#__PURE__*/_react.default.createElement("div", {
          className: "row"
        }, /*#__PURE__*/_react.default.createElement("div", {
          className: "col"
        }, /*#__PURE__*/_react.default.createElement("label", {
          htmlFor: "autocomplete-exclude-".concat(props.id)
        }, Liferay.Language.get('exclude'))), /*#__PURE__*/_react.default.createElement("div", {
          className: "col-auto"
        }, /*#__PURE__*/_react.default.createElement(_form.ClayToggle, {
          id: "autocomplete-exclude-".concat(props.id),
          onToggle: function onToggle() {
            return setExclude(!exclude);
          },
          toggled: exclude
        })))), /*#__PURE__*/_react.default.createElement(_dropDown.default.Divider, null), /*#__PURE__*/_react.default.createElement(_dropDown.default.Caption, null, /*#__PURE__*/_react.default.createElement("div", {
          className: "form-group"
        }, items && items.length ? /*#__PURE__*/_react.default.createElement("ul", {
          className: "inline-scroller mb-n2 mx-n2 px-2",
          ref: setScrollingArea
        }, items.map(function (item) {
          var itemValue = item[props.itemKey];
          var itemLabel = (0, _index.getValueFromItem)(item, props.itemLabel);
          var newValue = {
            label: itemLabel,
            value: itemValue
          };
          return (/*#__PURE__*/_react.default.createElement(Item, {
              key: itemValue,
              label: itemLabel,
              onChange: function onChange() {
                setSelectedItems(selectedItems.find(function (el) {
                  return el.value === itemValue;
                }) ? selectedItems.filter(function (el) {
                  return el.value !== itemValue;
                }) : props.selectionType === 'multiple' ? [].concat(_toConsumableArray(selectedItems), [newValue]) : [newValue]);
              },
              selected: Boolean(selectedItems.find(function (el) {
                return el.value === itemValue;
              })),
              selectionType: props.selectionType,
              value: itemValue
            })
          );
        }), loaderVisible && /*#__PURE__*/_react.default.createElement(_loadingIndicator.default, {
          ref: setInfiniteLoader,
          small: true
        })) : /*#__PURE__*/_react.default.createElement("div", {
          className: "mt-2 p-2 text-muted"
        }, Liferay.Language.get('no-items-were-found')))), /*#__PURE__*/_react.default.createElement(_dropDown.default.Divider, null), /*#__PURE__*/_react.default.createElement(_dropDown.default.Caption, null, /*#__PURE__*/_react.default.createElement(_button.default, {
          disabled: submitDisabled,
          onClick: function onClick() {
            return actionType !== 'delete' ? props.actions.updateFilterState(props.id, {
              exclude: exclude,
              items: selectedItems
            }, formatValue(selectedItems, exclude), getOdataString(selectedItems, props.id, props.selectionType, exclude)) : props.actions.updateFilterState(props.id);
          },
          small: true
        }, actionType === 'add' && Liferay.Language.get('add-filter'), actionType === 'edit' && Liferay.Language.get('edit-filter'), actionType === 'delete' && Liferay.Language.get('delete-filter'))))
      );
    }

    AutocompleteFilter.defaultProps = {
      selectionType: 'multiple'
    };
    var _default = AutocompleteFilter;
    exports.default = _default;
    //# sourceMappingURL=AutocompleteFilter.js.map
  }
});
//# sourceMappingURL=AutocompleteFilter.js.map