Liferay.Loader.define("commerce-frontend-js@3.0.33/components/mini_cart/CartItem", ['module', 'exports', 'require', '@frontend-taglib-clay$clayui/button', '@frontend-taglib-clay$clayui/icon', 'frontend-js-react-web$classnames', 'frontend-js-react-web$prop-types', 'frontend-js-react-web$react', '../../utilities/eventsDefinitions', '../quantity_selector/QuantitySelector', './CartItemViews/ItemInfoView', './CartItemViews/ItemPriceView', './MiniCartContext', './util/index'], 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 _button = _interopRequireDefault(require("@frontend-taglib-clay$clayui/button"));

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

    var _classnames = _interopRequireDefault(require("frontend-js-react-web$classnames"));

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

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

    var _eventsDefinitions = require("../../utilities/eventsDefinitions");

    var _QuantitySelector = _interopRequireDefault(require("../quantity_selector/QuantitySelector"));

    var _ItemInfoView = _interopRequireDefault(require("./CartItemViews/ItemInfoView"));

    var _ItemPriceView = _interopRequireDefault(require("./CartItemViews/ItemPriceView"));

    var _MiniCartContext = _interopRequireDefault(require("./MiniCartContext"));

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

    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 _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 _objectWithoutProperties(source, excluded) {
      if (source == null) return {};var target = _objectWithoutPropertiesLoose(source, excluded);var key, i;if (Object.getOwnPropertySymbols) {
        var sourceSymbolKeys = Object.getOwnPropertySymbols(source);for (i = 0; i < sourceSymbolKeys.length; i++) {
          key = sourceSymbolKeys[i];if (excluded.indexOf(key) >= 0) continue;if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;target[key] = source[key];
        }
      }return target;
    }

    function _objectWithoutPropertiesLoose(source, excluded) {
      if (source == null) return {};var target = {};var sourceKeys = Object.keys(source);var key, i;for (i = 0; i < sourceKeys.length; i++) {
        key = sourceKeys[i];if (excluded.indexOf(key) >= 0) continue;target[key] = source[key];
      }return target;
    }

    function ownKeys(object, enumerableOnly) {
      var keys = Object.keys(object);if (Object.getOwnPropertySymbols) {
        var symbols = Object.getOwnPropertySymbols(object);if (enumerableOnly) symbols = symbols.filter(function (sym) {
          return Object.getOwnPropertyDescriptor(object, sym).enumerable;
        });keys.push.apply(keys, symbols);
      }return keys;
    }

    function _objectSpread(target) {
      for (var i = 1; i < arguments.length; i++) {
        var source = arguments[i] != null ? arguments[i] : {};if (i % 2) {
          ownKeys(Object(source), true).forEach(function (key) {
            _defineProperty(target, key, source[key]);
          });
        } else if (Object.getOwnPropertyDescriptors) {
          Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
        } else {
          ownKeys(Object(source)).forEach(function (key) {
            Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
          });
        }
      }return target;
    }

    function _defineProperty(obj, key, value) {
      if (key in obj) {
        Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true });
      } else {
        obj[key] = value;
      }return obj;
    }

    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 REMOVAL_TIMEOUT = 2000,
        REMOVAL_CANCELING_TIMEOUT = 700,
        REMOVAL_ERRORS_TIMEOUT = 4000,
        INITIAL_ITEM_STATE = {
      isGettingRemoved: false,
      isRemovalCanceled: false,
      isRemoved: false,
      isShowingErrors: false,
      previousQuantity: null,
      removalTimeoutRef: null
    };

    function CartItem(_ref) {
      var cartItem = _ref.item;
      var childItems = cartItem.cartItems,
          errorMessages = cartItem.errorMessages,
          cartItemId = cartItem.id,
          name = cartItem.name,
          rawOptions = cartItem.options,
          price = cartItem.price,
          quantity = cartItem.quantity,
          settings = cartItem.settings,
          sku = cartItem.sku,
          skuId = cartItem.skuId,
          thumbnail = cartItem.thumbnail;

      var _useContext = (0, _react.useContext)(_MiniCartContext.default),
          CartResource = _useContext.CartResource,
          cartState = _useContext.cartState,
          displayDiscountLevels = _useContext.displayDiscountLevels,
          setIsUpdating = _useContext.setIsUpdating,
          spritemap = _useContext.spritemap,
          updateCartModel = _useContext.updateCartModel;

      var orderId = cartState.id;

      var _useState = (0, _react.useState)(INITIAL_ITEM_STATE),
          _useState2 = _slicedToArray(_useState, 2),
          itemState = _useState2[0],
          setItemState = _useState2[1];

      var _useState3 = (0, _react.useState)(quantity),
          _useState4 = _slicedToArray(_useState3, 2),
          itemQuantity = _useState4[0],
          setItemQuantity = _useState4[1];

      var _useState5 = (0, _react.useState)(price),
          _useState6 = _slicedToArray(_useState5, 2),
          itemPrice = _useState6[0],
          updateItemPrice = _useState6[1];

      var options = (0, _index.parseOptions)(rawOptions); // eslint-disable-next-line react-hooks/exhaustive-deps

      var showErrors = function showErrors() {
        setIsUpdating(false);
        setItemState(_objectSpread(_objectSpread({}, INITIAL_ITEM_STATE), {}, {
          isShowingErrors: true,
          removalTimeoutRef: setTimeout(function () {
            setItemState(INITIAL_ITEM_STATE);
          }, REMOVAL_ERRORS_TIMEOUT)
        }));
        return Promise.resolve();
      };

      var updateItemQuantity = (0, _react.useCallback)(function (quantity) {
        if (quantity !== itemQuantity) {
          setIsUpdating(true);
          CartResource.updateItemById(cartItemId, _objectSpread(_objectSpread({}, cartItem), {}, {
            quantity: quantity
          })).catch(showErrors).then(function (_ref2) {
            var updatedQuantity = _ref2.quantity,
                updatedItem = _objectWithoutProperties(_ref2, ["quantity"]);

            setItemQuantity(updatedQuantity);
            return Promise.resolve(updatedItem);
          }).then(function (_ref3) {
            var updatedPrice = _ref3.price;
            var currentPriceValue = itemPrice.price;
            var updatedPriceValue = updatedPrice.price;
            /**
             * The unit price of an item may change based
             * on the change of its quantity
             * @type {boolean}
             */

            if (!currentPriceValue || currentPriceValue !== updatedPriceValue) {
              return updateItemPrice(updatedPrice);
            }

            return Promise.resolve();
          }).then(function () {
            return updateCartModel({
              orderId: orderId
            });
          }).then(function () {
            return setIsUpdating(false);
          });
        }

        return Promise.resolve();
      }, // eslint-disable-next-line react-hooks/exhaustive-deps
      [CartResource, cartItem, cartItemId, orderId]);
      var isGettingRemoved = itemState.isGettingRemoved,
          isRemovalCanceled = itemState.isRemovalCanceled,
          isRemoved = itemState.isRemoved,
          isShowingErrors = itemState.isShowingErrors;
      return (/*#__PURE__*/_react.default.createElement("div", {
          className: (0, _classnames.default)('mini-cart-item', isRemoved && 'is-removed')
        }, !!thumbnail && /*#__PURE__*/_react.default.createElement("div", {
          className: 'mini-cart-item-thumbnail',
          style: {
            backgroundImage: "url(".concat(thumbnail, ")")
          }
        }), /*#__PURE__*/_react.default.createElement("div", {
          className: (0, _classnames.default)('mini-cart-item-info', !!options && 'has-options')
        }, /*#__PURE__*/_react.default.createElement(_ItemInfoView.default, {
          childItems: childItems,
          name: name,
          options: options,
          sku: sku
        })), /*#__PURE__*/_react.default.createElement("div", {
          className: 'mini-cart-item-quantity'
        }, /*#__PURE__*/_react.default.createElement(_QuantitySelector.default, _extends({
          onUpdate: updateItemQuantity,
          quantity: quantity,
          size: 'small',
          spritemap: spritemap,
          throttleOnUpdate: true
        }, settings))), /*#__PURE__*/_react.default.createElement("div", {
          className: 'mini-cart-item-price'
        }, /*#__PURE__*/_react.default.createElement(_ItemPriceView.default, {
          displayDiscountLevels: displayDiscountLevels,
          price: itemPrice
        })), /*#__PURE__*/_react.default.createElement("div", {
          className: 'mini-cart-item-delete'
        }, /*#__PURE__*/_react.default.createElement("button", {
          className: 'btn btn-unstyled',
          onClick: function removeItem() {
            setItemState(_objectSpread(_objectSpread({}, INITIAL_ITEM_STATE), {}, {
              isGettingRemoved: true,
              removalTimeoutRef: setTimeout(function () {
                setIsUpdating(true);
                setItemState(_objectSpread(_objectSpread({}, INITIAL_ITEM_STATE), {}, {
                  isGettingRemoved: true,
                  isRemoved: true,
                  removalTimeoutRef: setTimeout(function () {
                    CartResource.deleteItemById(cartItemId).then(function () {
                      return updateCartModel({
                        orderId: orderId
                      });
                    }).then(function () {
                      setIsUpdating(false);
                      Liferay.fire(_eventsDefinitions.PRODUCT_REMOVED, {
                        skuId: skuId
                      });
                    }).catch(showErrors);
                  }, REMOVAL_CANCELING_TIMEOUT)
                }));
              }, REMOVAL_TIMEOUT)
            }));
          },
          type: 'button'
        }, /*#__PURE__*/_react.default.createElement(_icon.default, {
          spritemap: spritemap,
          symbol: 'times'
        }))), errorMessages && /*#__PURE__*/_react.default.createElement("div", {
          className: 'mini-cart-item-errors'
        }, /*#__PURE__*/_react.default.createElement(_icon.default, {
          spritemap: spritemap,
          symbol: 'exclamation-circle'
        }), /*#__PURE__*/_react.default.createElement("span", null, errorMessages)), isShowingErrors && /*#__PURE__*/_react.default.createElement("div", {
          className: 'mini-cart-item-errors'
        }, /*#__PURE__*/_react.default.createElement(_icon.default, {
          spritemap: spritemap,
          symbol: 'exclamation-circle'
        }), /*#__PURE__*/_react.default.createElement("span", null, Liferay.Language.get('an-unexpected-error-occurred'))), /*#__PURE__*/_react.default.createElement("div", {
          className: (0, _classnames.default)('mini-cart-item-removing', isGettingRemoved && 'active', isRemovalCanceled && 'canceled')
        }, /*#__PURE__*/_react.default.createElement("span", null, Liferay.Language.get('the-item-has-been-removed')), /*#__PURE__*/_react.default.createElement("span", null, /*#__PURE__*/_react.default.createElement(_button.default, {
          displayType: 'link',
          href: '#',
          onClick: function cancelRemoveItem() {
            clearTimeout(itemState.removalTimeoutRef);
            setItemState(_objectSpread(_objectSpread({}, INITIAL_ITEM_STATE), {}, {
              isRemovalCanceled: true,
              removalTimeoutRef: setTimeout(function () {
                setIsUpdating(false);
                setItemState(INITIAL_ITEM_STATE);
              }, REMOVAL_CANCELING_TIMEOUT)
            }));
          },
          small: true,
          type: 'button'
        }, Liferay.Language.get('undo')))))
      );
    }

    var _default = CartItem;
    exports.default = _default;
    //# sourceMappingURL=CartItem.js.map
  }
});
//# sourceMappingURL=CartItem.js.map