text: import { Type, Loc, Cache, addCustomEvent, onCustomEvent, removeCustomEvent } from 'main.core'
  import { BitrixVue } from 'ui.vue'
  import { Popup } from 'main.popup'
  import { GermesCatalogComponent } from 'germes.multibasket.components.catalog'
  import { userStore as s1 } from 'germes.multibasket'
  // import { GermesCartTableComponent as c1, GermesCartDetailComponent as c2 } from 'germes.multibasket.app'
  import { GermesCartDetailComponent } from 'germes.multibasket.app.cart-detail'
  import { GermesCartTableComponent } from 'germes.multibasket.app.cart-table'
  import hs from 'germes.multibasket.plugins.highslide'
  import './event'
  import './style.css'
  
  (function () {
      'use strict';
  
      BX.namespace('BX.Sale.BasketComponent');
  
      BX.Sale.BasketComponent = {
          maxItemsShowCount: 30,
          precisionFactor: Math.pow(10, 6),
          stickyHeaderOffset: 0,
          instance: false,
  
          duration: {
              priceAnimation: 600,
              filterTimer: 300
          },
  
          ids: {
              item: 'basket-item-',
              quantity: 'basket-item-quantity-',
              progress: 'basket-item-progress-',
              progressbar: 'basket-item-progress-bar-',
              settings: 'basket-item-settings-',
              analog: 'basket-item-analog-',
              wait: 'basket-item-wait-',
              alert: 'basket-item-alert-',
              done: 'basket-item-done-',
              info: 'basket-item-info-',
              price: 'basket-item-price-',
              sumPrice: 'basket-item-sum-price-',
              sumPriceOld: 'basket-item-sum-price-old-',
              sumPriceDiff: 'basket-item-sum-price-difference-',
              itemHeightAligner: 'basket-item-height-aligner-',
              total: 'basket-total-price',
              totalInfo: 'basket-total-info',
              totalInfoLogin: 'basket-total-info-login',
              totalCount: 'basket-total-count',
              totalPrice: 'basket-total-price',
              totalPriceAvailable: 'basket-total-price-available',
              checkoutButton: 'basket-checkout-button',
              removeButton: 'basket-clear-button',
              totalWeight: 'basket-total-weight',
              totalButtons: 'basket-total-buttons',
              totalComments: 'basket-comments-input',
              basketRoot: 'basket-root',
              itemListWrapper: 'basket-items-list-wrapper',
              itemListContainer: 'basket-items-list-container',
              itemList: 'basket-item-list',
              itemListTable: 'basket-item-table',
              itemListEmptyResult: 'basket-item-list-empty-result',
              itemListOverlay: 'basket-items-list-overlay',
              warning: 'basket-warning'
          },
  
          initializePrimaryFields: function () {
              this.templates = {};
              this.nodes = {};
  
              /** Object of all basket items (itemId => itemArray) */
              this.items = {};
  
              /** Array of all basket items to show sorted by field SORT */
              this.sortedItems = [];
  
              /** Array of basket items showed on screen */
              this.shownItems = [];
  
              /** Array of basket items changed since last request */
              this.changedItems = [];
  
              /** Array of basket items postponed by pool to edit */
              this.postponedItems = [];
  
              /** Array of basket items with warnings */
              this.warningItems = [];
  
              this.isMobile = BX.browser.IsMobile();
              this.isTouch = BX.hasClass(document.documentElement, 'bx-touch');
  
              this.lastAction = 'initialLoad';
              this.coupons = null;
  
              this.imagePopup = null;
              this.loadingScreen = null;
  
              this.quantityDelay = null;
              this.quantityTimer = null;
          },
  
          init: function (parameters) {
              if (this.instance) {
                  return false;
              }
              this.initializePrimaryFields();
  
              this.params = parameters.params || {};
              this.template = parameters.template || '';
              this.signedParamsString = parameters.signedParamsString || '';
              this.siteId = parameters.siteId || '';
              this.siteTemplateId = parameters.siteTemplateId || '';
              this.ajaxUrl = this.params.AJAX_PATH || '';
              this.templateFolder = parameters.templateFolder || '';
              this.maxQuantityAdd = this.params.MAX_QUANTITY_ADD || 1000000;
              this.maxPriceAdd = this.params.MAX_PRICE_ADD || 1000000;
  
              this.useDynamicScroll = this.params.USE_DYNAMIC_SCROLL === 'Y';
              this.useItemsFilter = this.params.SHOW_FILTER === 'Y' && !this.isMobile;
  
              // this.applyBasketResult(parameters.result);
              // this.initializeActionPool();
  
              // if (this.useItemsFilter) {
              //     this.checkHeaderDisplay();
              //     this.bindHeaderEvents();
              // }
  
              // this.initializeBasketItems();
              // this.editTotal();
              // this.editWarnings();
  
              // this.adjustBasketWrapperHeight();
              // this.getCacheNode(this.ids.basketRoot).style.opacity = 1;
  
              this.bindInitialEvents();
              this.instance = true;
  
          },
          showDetail: function (id) {
              debugger
              // window.open('" . ($defrow["PATH_TO_DETAIL"] ?: ' / catalog /? q = ' . $defrow["XML_ID"]) . "', '_blank');
          },
          showAnalog: function (id) {
              debugger
  
          },
          showHistory: function () {
              debugger
  
          },
          delete: function () {
              debugger
  
          },
          clearParams: function () {
              debugger
          },
          getTemplate: function (templateName) {
              if (!this.templates.hasOwnProperty(templateName)) {
                  var template = BX(templateName);
                  this.templates[templateName] = BX.type.isDomNode(template) ? template.innerHTML : '';
              }
  
              return this.templates[templateName];
          },
  
          getCacheNode: function (id) {
              if (!this.nodes.hasOwnProperty(id)) {
                  this.nodes[id] = BX(id);
              }
              return this.nodes[id];
          },
  
          getEntity: function (parent, entity, additionalFilter) {
              if (!parent || !entity) {
                  return null;
              }
              additionalFilter = additionalFilter || '';
              return parent.querySelector(additionalFilter + '[data-entity="' + entity + '"]');
          },
  
          getEntities: function (parent, entity, additionalFilter) {
              if (!parent || !entity) {
                  return {
                      length: 0
                  };
              }
              additionalFilter = additionalFilter || '';
  
              return parent.querySelectorAll(additionalFilter + '[data-entity="' + entity + '"]');
          },
  
          bindInitialEvents: function () {
              this.bindWarningEvents();
  
              BX.bind(window, 'scroll', BX.proxy(this.checkStickyHeaders, this));
              BX.bind(window, 'scroll', BX.proxy(this.lazyLoad, this));
  
              BX.bind(window, 'resize', BX.throttle(this.checkStickyHeaders, 20, this));
              BX.bind(window, 'resize', BX.throttle(this.adjustBasketWrapperHeight, 20, this));
  
              BX.addCustomEvent('OnOrderConfirmed', BX.delegate(function () {
                  BX.closeWait(button, checkOutAction);
                  BX.onCustomEvent('OnSwitchBasket');
                  if (result && result.error == undefined) {
                      this.lastResult = result;
                      if (result.order != undefined) {
                          result.order.order_basket = this.items;
                          this.setCheckoutAnalytics(result.order);
                      }
                      if (this.lastResult.message) {
                          BX.SidePanel.Instance.open(
                              // TODO вынести в настройки компонента
                              "/personal/orders/?ID=" + this.lastResult.account_number, {
                              requestMethod: 'post',
                              requestParams: {
                                  ORDER_ID: this.lastResult.account_number,
                                  ACCOUNT_NUMBER: this.lastResult.account_number
                              },
                              Title: this.lastResult.message,
                              width: '500',
                              label: {
                                  contentClassName: "light",
                                  class: 'light',
                                  bgColor: "#ebf1f4", //цвет фона
                                  text: 'Закрыть',
                                  color: "#000000", //цвет текста
                                  opacity: 100 //прозрачность фона
                              }
                          });
                          BX.UI.Notification.Center.notify({
                              content: this.lastResult.message,
                              position: "bottom-right",
                              autoHide: true,
                              autoHideDelay: 86400000,
                              closeButton: true,
                              category: "order-created-" + this.lastResult.account_number,
                              actions: [{
                                  title: "Подробнее",
                                  events: {
                                      click: BX.delegate(function (event, balloon, action) {
                                          balloon.close();
                                          BX.SidePanel.Instance.open(
                                              // TODO вынести в настройки компонента
                                              "/personal/orders/?ID=" + this.lastResult.account_number, {
                                              requestMethod: 'post',
                                              requestParams: {
                                                  ORDER_ID: this.lastResult.account_number,
                                                  ACCOUNT_NUMBER: this.lastResult.account_number
                                              },
                                              Title: this.lastResult.message,
                                              width: '500',
                                              label: {
                                                  text: 'Закрыть',
                                                  color: "#000000", //цвет текста
                                                  bgColor: "#64ba4e", //цвет фона
                                                  opacity: 100 //прозрачность фона
                                              }
                                          });
                                      }, this)
                                  }
                              }]
                          });
                      }
                      if (this.lastResult.new_basket_id) {
                          try {
                              if (this.lastResult.new_basket) {
                                  userStore.commit("addBasket", this.lastResult.new_basket);
                              }
                              userStore.commit("changeData", {
                                  'basket_id': this.lastResult.new_basket_id
                              });
                              BX.UI.Notification.Center.notify({
                                  content: "Корзина переключена.",
                                  position: "bottom-right",
                                  autoHideDelay: 5000,
                                  closeButton: true,
                                  category: "order-basket-change",
                                  actions: []
                              });
                          } catch (error) {
                              console.log(error);
                          }
                      } else {
                          setTimeout(() => {
                              location.reload();
                          }, 1000);
                      }
                      debugger;
                      if (this.lastResult.new_tab_link && this.lastResult.new_tab_link != "") {
                          var creditPopup = window.open(window.location.href, '_blank');
                          window.location.href = this.lastResult.new_tab_link;
                          /*if (creditPopup == null || typeof (creditPopup) == 'undefined') {
                              BX.UI.Notification.Center.notify({
                                  content: 'Пожалуйста, отключите блокировщик всплывающих окон и снова нажмите на ссылку "<a href="#" onclick=" window.open(this.lastResult.new_tab_link, \'creditPopup\'); return false;">Подтвердить кредит</a>".',
                                  position: "bottom-right",
                                  //autoHide: false,
                                  autoHideDelay: 5000,
                                  closeButton: true,
                                  category: "order-basket-credit",
                                  actions: [],
                                  render: function () {
                                      var content = this.getContent();
                                      return BX.create("div", {
                                          props: {
                                              className: "ui-notification-balloon-content ui-notification-balloon-content-dark sber-balloon"
                                          },
                                          html: BX.type.isDomNode(content) ? null : content,
                                          children: (BX.type.isDomNode(content) ? [content] : [
                                              BX.create("div", {
                                                  props: {
                                                      className: "ui-notification-balloon-message pr-5"
                                                  },
                                                  style: {
                                                      color: '#000'
                                                  },
                                                  html: content
                                              }),
                                              BX.create("div", {
                                                  props: {
                                                      className: "ui-notification-balloon-close-btn"
                                                  },
                                                  events: {
                                                      click: BX.proxy(function () {
                                                          this.close();
                                                      }, this)
                                                  }
                                              })
                                          ])
                                      });
                                  }
                              });
                          } else {
                              creditPopup.focus();
                          }*/
                      }
                  } else {
                      var my_error = "Произошла неизвестаня ошибка, пожалуйста, попробуйте обновить страницу или обратитесь к оператору.";
                      if (result != undefined && result.error != undefined) {
                          my_error = result.error;
                      }
                      BX.UI.Notification.Center.notify({
                          content: "Error: " + my_error,
                          position: "bottom-right",
                          autoHide: false,
                          autoHideDelay: 10000,
                          closeButton: true,
                          category: "order-error",
                          actions: [{
                              title: "Обновить страницу",
                              events: {
                                  click: function () {
                                      window.location.reload();
                                  }
                              }
                          }]
                      });
                  }
              }, this));
              BX.SidePanel.Instance
          },
  
          commentsChangeAction: function (event) {
              var target = BX.getEventTarget(event);
              if (target && target.value != undefined) {
                  this.actionPool.setPoolData("COMMENTS", target.value);
              }
          },
          bindWarningEvents: function () {
              var showItemsNode = this.getEntity(BX(this.ids.warning), 'basket-items-warning-count');
  
              if (BX.type.isDomNode(showItemsNode)) {
                  showItemsNode.style.display = '';
                  BX.bind(showItemsNode, 'click', BX.delegate(function () {
                      this.toggleFilter('warning');
                  }, this));
              }
  
              BX.bind(
                  this.getEntity(BX(this.ids.warning), 'basket-items-warning-notification-close'),
                  'click',
                  BX.proxy(this.removeAllWarnings, this)
              );
          },
  
          toggleFilter: function (event) {
              var target = BX.type.isNotEmptyString(event) ?
                  this.getEntity(
                      this.getCacheNode(this.ids.itemListWrapper),
                      'basket-items-count',
                      '[data-filter="' + event + '"]'
                  ) :
                  BX.getEventTarget(event);
  
              if (!BX.type.isDomNode(target) || BX.hasClass(target, 'active')) {
                  return;
              }
  
              var entityName = target.getAttribute('data-filter');
              var entities = target.parentNode.querySelectorAll('[data-filter]');
  
              for (var i = 0; i < entities.length; i++) {
                  if (entities[i].getAttribute('data-filter') === entityName) {
                      BX.addClass(entities[i], 'active');
                  } else if (BX.hasClass(entities[i], 'active')) {
                      BX.removeClass(entities[i], 'active');
                  }
              }
  
              this.filter.showFilterByName(entityName);
          },
  
          scrollToFirstItem: function () {
              var headerNode = this.getEntity(this.getCacheNode(this.ids.itemListWrapper), 'basket-items-list-header');
  
              if (BX.type.isDomNode(headerNode)) {
                  var itemListTopPosition = BX.pos(this.getCacheNode(this.ids.itemListContainer)).top;
                  var headerBottomPosition = BX.pos(headerNode).bottom;
  
                  if (itemListTopPosition < headerBottomPosition) {
                      window.scrollTo(0, itemListTopPosition - this.stickyHeaderOffset);
                  }
              }
          },
  
          showItemsOverlay: function () {
              var overlay = this.getCacheNode(this.ids.itemListOverlay);
  
              if (BX.type.isDomNode(overlay)) {
                  overlay.style.display = '';
              }
          },
  
          hideItemsOverlay: function () {
              var overlay = this.getCacheNode(this.ids.itemListOverlay);
  
              if (BX.type.isDomNode(overlay)) {
                  overlay.style.display = 'none';
              }
          },
  
          checkHeaderDisplay: function () {
              var header = this.getCacheNode(this.ids.itemListWrapper);
  
              if (BX.type.isDomNode(header)) {
                  BX.removeClass(header, 'basket-items-list-wrapper-light');
              }
          },
  
          bindHeaderEvents: function () {
              var entities = this.getEntities(this.getCacheNode(this.ids.itemListWrapper), 'basket-items-count');
  
              for (var i = 0; i < entities.length; i++) {
                  BX.bind(entities[i], 'click', BX.proxy(this.toggleFilter, this));
              }
          },
  
          checkStickyHeaders: function () {
              if (this.isMobile)
                  return;
  
              var position;
              var border = 2,
                  offset = 0;
              var scrollTop = this.getDocumentScrollTop();
              var basketPosition = BX.pos(this.getCacheNode(this.ids.basketRoot));
              var totalBlockNode = this.getEntity(this.getCacheNode(this.ids.basketRoot), 'basket-total-block');
              var node = this.getEntity(totalBlockNode, 'basket-checkout-aligner');
              var totalBlockNodeHeight = node.clientHeight || 400;
              var fixedHeader = BX('header').className.indexOf('fixed') !== false ? BX('fixed-header').clientHeight : 0;
              var basketScrolledToEnd = scrollTop + fixedHeader + totalBlockNodeHeight >= basketPosition.bottom;
  
              if (BX.util.in_array('top', this.params.TOTAL_BLOCK_DISPLAY)) {
                  if (BX.type.isDomNode(totalBlockNode)) {
                      if (BX.type.isDomNode(node)) {
                          position = BX.pos(totalBlockNode);
  
                          if (scrollTop >= position.top) {
                              offset += node.clientHeight;
  
                              if (!BX.hasClass(node, 'basket-checkout-container-fixed') && this.elementInViewport(node)) {
                                  totalBlockNode.style.height = position.height + 'px';
  
                                  node.style.top = fixedHeader + 'px';
                                  // node.style.right = (window.innerWidth - node.getBoundingClientRect().right) + border + 'px';
                                  node.style.right = 0 + 'px';
                                  node.style.width = node.clientWidth + border + 'px';
                                  BX.addClass(node, 'basket-checkout-container-fixed');
                              }
                          } else if (BX.hasClass(node, 'basket-checkout-container-fixed')) {
                              totalBlockNode.style.height = '';
  
                              node.style.width = '';
                              BX.removeClass(node, 'basket-checkout-container-fixed');
                          }
  
                          if (0 && this.elementInViewport(node) && !BX.Browser.isMobile()) {
                              if (basketScrolledToEnd) {
                                  if (!BX.hasClass(node, 'basket-checkout-container-fixed-hide')) {
                                      BX.addClass(node, 'basket-checkout-container-fixed-hide');
                                  } else {
                                      BX.removeClass(node, 'basket-checkout-container-fixed-hide');
                                  }
                              } else if (BX.hasClass(node, 'basket-checkout-container-fixed-hide')) {
                                  BX.removeClass(node, 'basket-checkout-container-fixed-hide');
                              }
                          }
                      }
                  }
              }
  
              if (this.useItemsFilter) {
                  var itemWrapperNode = this.getCacheNode(this.ids.itemListWrapper);
  
                  node = this.getEntity(itemWrapperNode, 'basket-items-list-header');
                  if (BX.type.isDomNode(node)) {
                      position = BX.pos(itemWrapperNode);
  
                      if ((scrollTop + offset >= position.top) && !basketScrolledToEnd) {
                          if (!BX.hasClass(node, 'basket-items-list-header-fixed')) {
                              node.style.width = node.clientWidth + border + 'px';
  
                              itemWrapperNode.style.paddingTop = node.clientHeight + 'px';
  
                              BX.addClass(node, 'basket-items-list-header-fixed');
                          }
  
                          if (offset) {
                              node.style.top = offset + 'px';
                          }
  
                          offset += node.clientHeight;
                      } else if (BX.hasClass(node, 'basket-items-list-header-fixed')) {
                          itemWrapperNode.style.paddingTop = '';
  
                          node.style.width = '';
                          node.style.top = '';
  
                          BX.removeClass(node, 'basket-items-list-header-fixed');
                      }
                  }
              }
  
              var offsetChanged = this.stickyHeaderOffset === offset;
  
              this.stickyHeaderOffset = offset;
  
              if (offsetChanged && !basketScrolledToEnd) {
                  this.adjustBasketWrapperHeight();
              }
          },
          elementInViewport: function (el) {
              var top = el.offsetTop;
              var left = el.offsetLeft;
              var width = el.offsetWidth;
              var height = el.offsetHeight;
  
              while (el.offsetParent) {
                  el = el.offsetParent;
                  top += el.offsetTop;
                  left += el.offsetLeft;
              }
  
              return (
                  top < (window.pageYOffset + window.innerHeight) &&
                  left < (window.pageXOffset + window.innerWidth) &&
                  (top + height) > window.pageYOffset &&
                  (left + width) > window.pageXOffset &&
                  window.getComputedStyle(el).visibility != 'hidden' &&
                  window.getComputedStyle(el).display != 'hidden' &&
                  window.getComputedStyle(el).opacity > 0
              );
          },
          getDocumentScrollTop: function () {
              return window.scrollY ||
                  window.pageYOffset ||
                  document.body.scrollTop + (document.documentElement && document.documentElement.scrollTop || 0);
          },
  
          lazyLoad: function () {
              var itemsNodePosition = BX.pos(this.getCacheNode(this.ids.itemListContainer));
  
              if (this.getDocumentScrollTop() + window.innerHeight >= itemsNodePosition.bottom - 400) {
                  var itemIds = this.getItemsAfter();
                  if (itemIds.length) {
                      this.editBasketItems(itemIds);
                  }
              }
          },
  
          fireCustomEvents: function () {
              if (this.result.EVENT_ONCHANGE_ON_START === 'Y') {
                  BX.onCustomEvent('OnBasketChange');
              }
  
              if (this.params.HIDE_COUPON !== 'Y') {
                  if (this.coupons !== null && this.coupons !== this.result.COUPON_LIST) {
                      BX.onCustomEvent('OnCouponApply');
                  }
  
                  this.coupons = this.result.COUPON_LIST;
              }
          },
  
          adjustBasketWrapperHeight: function () {
              var itemListContainer = this.getCacheNode(this.ids.itemListContainer),
                  itemList = this.getCacheNode(this.ids.itemList);
  
              if (BX.type.isDomNode(itemListContainer) && BX.type.isDomNode(itemList)) {
                  if (itemListContainer.clientHeight + this.stickyHeaderOffset > window.innerHeight) {
                      itemListContainer.style.minHeight = 'calc(100vh - 15px - ' + this.stickyHeaderOffset + 'px)';
                      itemList.style.minHeight = 'calc(100vh - 15px - ' + this.stickyHeaderOffset + 'px)';
                  } else {
                      itemListContainer.style.minHeight = itemListContainer.clientHeight + 'px';
                      itemList.style.minHeight = itemListContainer.clientHeight + 'px';
                  }
              }
          },
  
          fillTotalBlocks: function () {
              var totalNodes = this.getEntities(this.getCacheNode(this.ids.basketRoot), 'basket-total-block');
              if (totalNodes && totalNodes.length) {
                  var totalTemplate = this.getTemplate('basket-total-template');
                  if (totalTemplate) {
                      var totalRender = this.render(totalTemplate, this.result.TOTAL_RENDER_DATA);
  
                      for (var i in totalNodes) {
                          if (totalNodes.hasOwnProperty(i) && BX.type.isDomNode(totalNodes[i])) {
                              totalNodes[i].innerHTML = totalRender;
  
                              this.bindTotalEvents(totalNodes[i]);
                          }
                      }
                  } else {
                      this.bindTotalEvents(totalNodes[0]);
                      var totalBlockNode = this.getEntity(this.getCacheNode(this.ids.basketRoot), 'basket-total-block');
                      // TODO добавить настройку липкой шапки корзины
                      if (BX.type.isDomNode(totalBlockNode)) {
                          let totalPrice = this.getEntity(this.getCacheNode(this.ids.basketRoot), this.ids.totalPrice);
                          if (BX.type.isElementNode(totalPrice)) {
                              totalPrice.innerHTML = this.result.TOTAL_RENDER_DATA.PRICE_FORMATED_NEW || this.result.TOTAL_RENDER_DATA.PRICE_FORMATED;
                          }
                          let totalPriceAvailable = this.getEntity(this.getCacheNode(this.ids.basketRoot), this.ids.totalPriceAvailable);
                          if (BX.type.isElementNode(totalPriceAvailable) && this.result.TOTAL_RENDER_DATA.PRICE_AVAILABLE_FORMATED != undefined) {
                              totalPriceAvailable.innerHTML = this.result.TOTAL_RENDER_DATA.PRICE_AVAILABLE_FORMATED;
                          }
                          let totalCount = this.getEntity(this.getCacheNode(this.ids.basketRoot), this.ids.totalCount);
                          if (BX.type.isElementNode(totalCount)) {
                              // totalCount.innerHTML = this.result.BASKET_ITEMS_COUNT;
                              totalCount.innerHTML = this.getGoodsMessage(this.result.BASKET_ITEMS_COUNT, 'BASKET_TOTAL_COUNT_PRICE').replace(/#COUNT#/i, Object.keys(this.result.TOTAL_RENDER_DATA.BASKET.ITEMS).length);
                          }
                          let totalWeight = this.getEntity(this.getCacheNode(this.ids.basketRoot), this.ids.totalWeight);
                          if (BX.type.isElementNode(totalWeight)) {
                              totalWeight.innerHTML = this.result.TOTAL_RENDER_DATA.WEIGHT_FORMATED || 0;
                          }
                          let totalInfo = this.getEntity(this.getCacheNode(this.ids.basketRoot), this.ids.totalInfo);
                          if (BX.type.isElementNode(totalInfo)) {
                              let info = this.result.TOTAL_RENDER_DATA.BASKET.ACCOUNT_NUMBER;
                              // this.result.TOTAL_RENDER_DATA.BASKET.USER.LAST_NAME;
                              // this.result.TOTAL_RENDER_DATA.BASKET.USER.LOGIN;
                              totalInfo.innerHTML = info;
                          }
                          let totalInfoLogin = this.getEntity(this.getCacheNode(this.ids.basketRoot), this.ids.totalInfoLogin);
                          if (BX.type.isElementNode(totalInfoLogin)) {
                              totalInfoLogin.innerHTML = BX.message('BASKET_USER_' + this.result.TOTAL_RENDER_DATA.BASKET.USER_TYPE).replace(/#LOGIN#/i, this.result.TOTAL_RENDER_DATA.BASKET.USER.LOGIN);
                          }
                          let totalComments = this.getEntity(this.getCacheNode(this.ids.basketRoot), this.ids.totalComments);
                          if (BX.type.isElementNode(totalComments)) {
                              totalComments.value = this.result.TOTAL_RENDER_DATA.BASKET.DESCRIPTION || '';
                          }
                          let checkoutButton = this.getEntity(this.getCacheNode(this.ids.basketRoot), this.ids.checkoutButton);
                          let removeButton = this.getEntity(this.getCacheNode(this.ids.basketRoot), this.ids.removeButton);
                          if (BX.type.isElementNode(checkoutButton)) {
                              if (!this.result.BASKET_ITEMS_COUNT) this.result.TOTAL_RENDER_DATA.DISABLE_CHECKOUT = true;
                              checkoutButton.disabled = this.result.TOTAL_RENDER_DATA.DISABLE_CHECKOUT ? 'disabled' : '';
                              removeButton.disabled = this.result.TOTAL_RENDER_DATA.DISABLE_CHECKOUT ? 'disabled' : '';
                          }
                      }
                  }
              }
  
              this.checkStickyHeaders();
          },
  
          showItemsCount: function () {
              var itemCountNode = this.getEntity(
                  this.getCacheNode(this.ids.itemListWrapper),
                  'basket-items-count',
                  '[data-filter="all"]'
              );
  
              if (BX.type.isDomNode(itemCountNode)) {
                  itemCountNode.innerHTML = BX.message('SBB_IN_BASKET') + ' ' + this.result.BASKET_ITEMS_COUNT + ' ' + this.getGoodsMessage(this.result.BASKET_ITEMS_COUNT);
                  itemCountNode.style.display = '';
              }
          },
  
          showSimilarCount: function (state) {
              var itemCountNode = this.getEntity(
                  this.getCacheNode(this.ids.itemListWrapper),
                  'basket-items-count',
                  '[data-filter="similar"]'
              );
  
              if (BX.type.isDomNode(itemCountNode)) {
                  if (state) {
                      itemCountNode.innerHTML = this.sortedItems.length + ' ' +
                          this.getGoodsMessage(this.result.BASKET_ITEMS_COUNT, 'SBB_SIMILAR_ITEM');
                      itemCountNode.style.display = '';
                  } else {
                      itemCountNode.style.display = 'none';
                  }
              }
          },
  
          showWarningItemsCount: function () {
              var itemCountNode = this.getEntity(
                  this.getCacheNode(this.ids.itemListWrapper),
                  'basket-items-count',
                  '[data-filter="warning"]'
              );
  
              if (BX.type.isDomNode(itemCountNode)) {
                  if (this.warningItems.length) {
                      itemCountNode.innerHTML = this.warningItems.length + ' ' + BX.message('SBB_BASKET_ITEMS_WARNING');
                      itemCountNode.style.display = '';
                  } else {
                      itemCountNode.style.display = 'none';
                  }
              }
          },
  
          showNotAvailableItemsCount: function () {
              var itemCountNode = this.getEntity(
                  this.getCacheNode(this.ids.itemListWrapper),
                  'basket-items-count',
                  '[data-filter="not-available"]'
              );
  
              if (BX.type.isDomNode(itemCountNode)) {
                  if (parseInt(this.result.NOT_AVAILABLE_BASKET_ITEMS_COUNT)) {
                      itemCountNode.innerHTML = this.result.NOT_AVAILABLE_BASKET_ITEMS_COUNT + ' ' +
                          this.getGoodsMessage(this.result.NOT_AVAILABLE_BASKET_ITEMS_COUNT, 'SBB_NOT_AVAILABLE_ITEM');
                      itemCountNode.style.display = '';
                  } else {
                      itemCountNode.style.display = 'none';
                  }
              }
          },
  
          showDelayedItemsCount: function () {
              var itemCountNode = this.getEntity(
                  this.getCacheNode(this.ids.itemListWrapper),
                  'basket-items-count',
                  '[data-filter="delayed"]'
              );
  
              if (BX.type.isDomNode(itemCountNode)) {
                  if (parseInt(this.result.DELAYED_BASKET_ITEMS_COUNT)) {
                      itemCountNode.innerHTML = this.result.DELAYED_BASKET_ITEMS_COUNT + ' ' +
                          this.getGoodsMessage(this.result.DELAYED_BASKET_ITEMS_COUNT, 'SBB_DELAYED_ITEM');
                      itemCountNode.style.display = '';
                  } else {
                      itemCountNode.style.display = 'none';
                  }
              }
          },
  
          getGoodsMessage: function (count, customMessage) {
              var mesCode;
              var countReminder = (count > 10 && count < 20) ? 0 : count % 10;
  
              if (countReminder === 1) {
                  mesCode = customMessage || 'SBB_GOOD';
              } else if (countReminder >= 2 && countReminder <= 4) {
                  mesCode = customMessage ? customMessage + '_2' : 'SBB_GOOD_2';
              } else {
                  mesCode = customMessage ? customMessage + 'S' : 'SBB_GOODS';
              }
  
              return BX.message(mesCode);
          },
  
          bindTotalEvents: function (node) {
              if (this.grid != undefined
                  && typeof this.grid == 'object'
                  && this.grid.containerId == 'baskets_list'
                  && this.grid.arParams["SHOW_ACTION_PANEL"]
              ) {
                  // const buttons = this.grid.getActionsPanel().getButtons();
                  // for (let i = 0; i < buttons.length; i++) {
                  //     const button = buttons[i];
                  //     this.grid.getActionsPanel().deactivateControl(button.id);
                  //     BX.adjust(BX(button.id), {
                  //         prop: {
                  //             'disabled': true
                  //         }
                  //     })
                  // }
              }
              if (!this.result.TOTAL_RENDER_DATA.DISABLE_CHECKOUT) {
                  BX.bind(this.getEntity(node, this.ids.checkoutButton), 'click', BX.proxy(this.checkOutAction, this));
              }
  
              BX.bind(this.getEntity(node, 'basket-clear-button'), 'click', BX.proxy(this.clearAction, this));
              BX.bind(this.getEntity(node, 'basket-coupon-input'), 'change', BX.proxy(this.addCouponAction, this));
              BX.bind(this.getEntity(node, 'basket-coupon-input'), 'paste', BX.proxy(this.pasteCouponAction, this));
  
              BX.bind(this.getEntity(node, 'basket-comments-input'), 'keyup', BX.proxy(this.commentsChangeAction, this));
              BX.bind(this.getEntity(node, 'basket-comments-input'), 'change', BX.proxy(function () {
                  BX.onCustomEvent("OnCommentsChange");
              }, this));
  
              var couponNodes = this.getEntities(node, 'basket-coupon-delete');
              for (var i = 0, l = couponNodes.length; i < l; i++) {
                  BX.bind(couponNodes[i], 'click', BX.proxy(this.removeCouponAction, this));
              }
  
          },
  
          clearAction: function () {
              if (confirm("Удалить все позиции из корзины?")) {
                  // var clearAction = BX.showWait('clearAction');
                  var data = {};
                  if (typeof userStore == 'object') {
                      data.basket_id = userStore.getters['basket/getBasketId'];
                  }
                  // TODO убрать в Store!
                  this.sendRequest('clearBasket', data);
              }
          },
  
          // makeOrderAction: function () {
          //     if (confirm("Оформить заказ?")) {
          //         // var clearAction = BX.showWait('clearAction');
          //         let data = {};
          //         if (BX.type.isDomNode(BX('ORDER_PROP_PAYED_FROM_ACCOUNT'))) {
          //             data.ORDER_PROP_PAYED_FROM_ACCOUNT = BX('ORDER_PROP_PAYED_FROM_ACCOUNT').checked ? 'Y' : false;
          //         }
          //         if (typeof userStore == 'object') {
          //             data.user_id = userStore.getters.user.ID;
          //             data.user_login = userStore.getters.user.LOGIN;
          //             data.basket_id = userStore.getters['basket/getBasketId'];
          //             data.contragent_id = userStore.getters['basket/getContragentId'];
          //             data.contragent = userStore.getters['basket/getContragent'];
          //             data.address_id = userStore.getters['basket/getAddressId'];
          //             data.address = userStore.getters['basket/getAddress'];
          //         }
          //         let totalNodes = this.getEntities(this.getCacheNode(this.ids.basketRoot), 'basket-total-block');
          //         if (totalNodes[0]) {
          //             data.comments = this.getEntity(totalNodes[0], 'basket-comments-input').value;
          //         }
          //         let errors = [];
          //         if (!data.user_login) {
          //             errors.push(BX.message("ERROR_SUBMIT_LOGIN_FIELD"));
          //         } else {
          //             for (const porp_code in data) {
          //                 if (data.hasOwnProperty(porp_code)) {
          //                     const prop_val = data[porp_code];
          //                     if (prop_val == null || prop_val == undefined)
          //                         errors.push(BX.message("ERROR_SUBMIT_" + (porp_code.toUpperCase()) + "_FIELD"));
          //                 }
          //             }
          //         }
          //         if (errors.length > 0) {
          //             BX.UI.Notification.Center.notify({
          //                 content: "<b>" + BX.message("ERROR_SUBMIT_BASKET") + "</b> <br/><ol class='px-0'><li>" + errors.join('</li><li>') + "</li></ol>",
          //                 position: "bottom-right",
          //                 autoHide: false,
          //                 autoHideDelay: 10000,
          //                 closeButton: true,
          //                 category: "order-submit-error",
          //                 /*
          //                     actions: [{
          //                         title: "Подробнее",
          //                         events: {
          //                             click: BX.delegate(function (event, balloon, action) {
          //                                 balloon.close();
          //                                 BX.SidePanel.Instance.open(
          //                                     // TODO вынести в настройки компонента
          //                                     // this.params.PATH_TO_ORDER
          //                                     "/personal/orders/?ID=" + this.result.account_number, {
          //                                         requestMethod: 'post',
          //                                         requestParams: {
          //                                             ORDER_ID: this.result.account_number,
          //                                             ACCOUNT_NUMBER: this.result.account_number
          //                                         },
          //                                         Title: this.result.message,
          //                                         width: '500',
          //                                         label: {
          //                                             text: ('Заказ ' + this.result.account_number),
          //                                             color: "#000000", //цвет текста
          //                                             bgColor: "#64ba4e", //цвет фона
          //                                             opacity: 100 //прозрачность фона
          //                                         }
          //                                     });
          //                             }, this),
          //                         }
          //                     }]
          //                 */
          //             });
          //         } else {
          //             this.sendRequest('makeOrder', data);
          //         }
          //     }
          // },
  
          checkOutAction: function () {
              let formNode = BX('basket-checkout'),
                  data = this.getData({ 'basketAction': 'ORDER' }),
                  orderForm = (typeof FormData === 'function' ? new FormData(formNode) : null),
                  errors = [];
  
              if (!userStore.getters['getUser'].LOGIN) {
                  errors.push(BX.message("ERROR_SUBMIT_LOGIN_FIELD"));
              } else {
                  try {
                      if (!orderForm) throw "No FormData in your browser!";
                      for (const porp_code in data) {
                          if (data.hasOwnProperty(porp_code)) {
                              orderForm.set(porp_code, data[porp_code]);
                          }
                      }
                  } catch (error) {
                      console.error(error);
                      if (BX.type.isDomNode(formNode)) {
                          orderForm = {};
                          for (var i in formNode.elements) {
                              if (formNode[i] && typeof formNode[i] != 'function' && formNode[i].name) {
                                  orderForm[formNode[i].name] = formNode[i].value;
                              }
                          }
                          for (const porp_code in data) {
                              if (data.hasOwnProperty(porp_code)) {
                                  orderForm[porp_code] = data[porp_code]
                              }
                          }
                      }
                  }
                  // TODO переделать проверку полей
                  for (const porp_code in orderForm) {
                      if (orderForm.hasOwnProperty(porp_code)) {
                          const prop_val = orderForm[porp_code];
                          if ((prop_val == null || prop_val == undefined)
                              && porp_code != "comments"
                          ) {
                              errors.push(BX.message("ERROR_SUBMIT_" + (porp_code.toUpperCase()) + "_FIELD"));
                          }
                      }
                  }
              }
              //
              if (formNode != undefined && BX.SidePanel != undefined) {
                  if (errors.length > 0) {
                      BX.UI.Notification.Center.notify({
                          content: "<b>" + BX.message("ERROR_SUBMIT_BASKET") + "</b> <br/><ol class='px-0'><li>" + errors.join('</li><li>') + "</li></ol>",
                          position: "bottom-right",
                          autoHide: false,
                          autoHideDelay: 10000,
                          closeButton: true,
                          category: "order-submit-error",
                          /* actions: [{
                              title: "Подробнее",
                              events: {
                                  click: BX.delegate(function (event, balloon, action) {
                                      balloon.close();
                                      BX.SidePanel.Instance.open(
                                          // TODO вынести в настройки компонента
                                          // this.params.PATH_TO_ORDER
                                          "/personal/orders/?ID=" + this.result.account_number, {
                                          requestMethod: 'post',
                                          requestParams: {
                                              ORDER_ID: this.result.account_number,
                                              ACCOUNT_NUMBER: this.result.account_number
                                          },
                                          Title: this.result.message,
                                          width: '500',
                                          label: {
                                              text: ('Заказ ' + this.result.account_number),
                                              color: "#000000", //цвет текста
                                              bgColor: "#64ba4e", //цвет фона
                                              opacity: 100 //прозрачность фона
                                          }
                                      });
                                  }, this),
                              }
                          }] */
                      });
                  } else {
                      this.lastAction = 'ORDER';
                      var button = this.getEntity(BX(this.ids.basketRoot), this.ids.checkoutButton),
                          checkOutAction = BX.showWait(button);
                      // BX.show(button);
                      BX.ajax({
                          url: this.ajaxUrl,
                          data: orderForm,
                          method: 'POST',
                          dataType: 'json',
                          processData: (orderForm instanceof FormData ? true : true),     //
                          preparePost: (orderForm instanceof FormData ? false : true),     //предобработка передаваемых данных
                          timeout: 600,
                          onsuccess: BX.delegate(function (result) {
                              BX.closeWait(button, checkOutAction);
                              if (location.search.search('debug=log') > 0) {
                                  console.log(result);
                              }
                              if (result.order != undefined && result.error == undefined) {
                                  // BX.onCustomEvent('OnSwitchBasket');
                                  this.lastResult = result;
                                  if (result.order != undefined) {
                                      result.order.order_basket = this.items;
                                      this.setCheckoutAnalytics(result.order);
                                  }
                                  if (this.lastResult.message) {
                                      BX.SidePanel.Instance.open(
                                          // TODO вынести в настройки компонента
                                          "/personal/orders/?ID=" + this.lastResult.account_number, {
                                          requestMethod: 'post',
                                          requestParams: {
                                              ORDER_ID: this.lastResult.account_number,
                                              ACCOUNT_NUMBER: this.lastResult.account_number
                                          },
                                          Title: this.lastResult.message,
                                          width: '500',
                                          label: {
                                              contentClassName: "light",
                                              class: 'light',
                                              bgColor: "#ebf1f4", //цвет фона
                                              text: 'Закрыть',
                                              color: "#000000", //цвет текста
                                              opacity: 100 //прозрачность фона
                                          }
                                      });
                                      BX.UI.Notification.Center.notify({
                                          content: this.lastResult.message,
                                          position: "bottom-right",
                                          autoHide: true,
                                          autoHideDelay: 86400000,
                                          closeButton: true,
                                          category: "order-created-" + this.lastResult.account_number,
                                          actions: [{
                                              title: "Подробнее",
                                              events: {
                                                  click: BX.delegate(function (event, balloon, action) {
                                                      balloon.close();
                                                      BX.SidePanel.Instance.open(
                                                          // TODO вынести в настройки компонента
                                                          "/personal/orders/?ID=" + this.lastResult.account_number, {
                                                          requestMethod: 'post',
                                                          requestParams: {
                                                              ORDER_ID: this.lastResult.account_number,
                                                              ACCOUNT_NUMBER: this.lastResult.account_number
                                                          },
                                                          Title: this.lastResult.message,
                                                          width: '500',
                                                          label: {
                                                              text: 'Закрыть',
                                                              color: "#000000", //цвет текста
                                                              bgColor: "#64ba4e", //цвет фона
                                                              opacity: 100 //прозрачность фона
                                                          }
                                                      });
                                                  }, this),
                                              }
                                          }]
                                      });
                                  }
                                  if (this.lastResult.new_basket) {
                                      if (this.lastResult.new_basket) {
                                          userStore.commit("basket/setBasket", this.lastResult.new_basket);
                                      }
                                  } else {
                                      setTimeout(() => {
                                          location.reload();
                                      }, 5000);
                                  }
                                  if (this.lastResult.new_tab_link && this.lastResult.new_tab_link != "") {
                                      BX.onCustomEvent('OnCreateCreditPopup', this.lastResult);
                                      /*let creditPopup = window.open(this.lastResult.new_tab_link, 'creditPopup');
                                      if (creditPopup == null || typeof (creditPopup) == 'undefined') {
                                          BX.UI.Notification.Center.notify({
                                              content: 'Пожалуйста, отключите блокировщик всплывающих окон и снова нажмите на ссылку "<a href="#" onclick=" window.open(this.lastResult.new_tab_link, \'creditPopup\'); return false;">Подтвердить кредит</a>".',
                                              position: "bottom-right",
                                              //autoHide: false,
                                              autoHideDelay: 5000,
                                              closeButton: true,
                                              category: "order-basket-credit",
                                              actions: [],
                                              render: function () {
                                                  var content = this.getContent();
                                                  return BX.create("div", {
                                                      props: {
                                                          className: "ui-notification-balloon-content ui-notification-balloon-content-dark sber-balloon"
                                                      },
                                                      html: BX.type.isDomNode(content) ? null : content,
                                                      children: (BX.type.isDomNode(content) ? [content] : [
                                                          BX.create("div", {
                                                              props: {
                                                                  className: "ui-notification-balloon-message pr-5"
                                                              },
                                                              style: {
                                                                  color: '#000'
                                                              },
                                                              html: content,
                                                          }),
                                                          BX.create("div", {
                                                              props: {
                                                                  className: "ui-notification-balloon-close-btn"
                                                              },
                                                              events: {
                                                                  click: BX.proxy(function () {
                                                                      this.close();
                                                                  }, this)
                                                              },
                                                          })
                                                      ]),
                                                  })
                                              }
                                          });
                                      } else {
                                          creditPopup.focus();
                                      }*/
                                  }
                              } else {
                                  let error = "Произошла неизвестаня ошибка, пожалуйста, попробуйте обновить страницу или обратитесь к оператору.";
                                  if (result != undefined && result.error != undefined) {
                                      error = result.error;
                                  }
                                  BX.UI.Notification.Center.notify({
                                      content: "Error: " + error,
                                      position: "bottom-right",
                                      autoHide: false,
                                      autoHideDelay: 10000,
                                      closeButton: true,
                                      category: "order-error",
                                      actions: [{
                                          title: "Обновить страницу",
                                          events: {
                                              click: function () {
                                                  window.location.reload();
                                              }
                                          }
                                      }]
                                  });
                              }
                          }, this),
                          onfailure: BX.delegate(function (error) {
                              BX.closeWait(button, checkOutAction);
                              if (BX.message(error)) error = BX.message(error);
                              BX.UI.Notification.Center.notify({
                                  content: "Error: " + error,
                                  position: "bottom-right",
                                  autoHide: false,
                                  autoHideDelay: 5000,
                                  closeButton: true,
                                  category: "order-error",
                                  actions: []
                              });
                              console.log("error");
                              console.log(error);
                          }, this)
                      });
                  }
              } else {
                  document.location.href = this.params.PATH_TO_ORDER;
              }
          },
  
          printBakset: function () {
              var data = {
                  IFRAME: 'Y',
                  print: 'Y'
              };
              debugger
              if (typeof userStore == 'object') {
                  data.basket_number = userStore.getters['basket/getBasketNumber'];
                  data.basket_id = userStore.getters['basket/getBasketId'];
              } else {
                  data.basket_id = BX.Sale.BasketComponent.result.TOTAL_RENDER_DATA.BASKET.ID;
                  data.basket_number = BX.Sale.BasketComponent.result.TOTAL_RENDER_DATA.BASKET.ACCOUNT_NUMBER;
              }
              if (data.basket_id) {
                  this.lastAction = 'basketShowDetail';
                  this.showRequest(this.ajaxUrl, {
                      printable: true,
                      requestMethod: 'post',
                      requestParams: this.getData(data),
                      contentClassName: "light-sidepanel",
                      data: data,
                      width: '500',
                      allowChangeHistory: false,
                      cacheable: true,
                      label: {
                          class: 'dark',
                          text: "Корзина ",
                          color: "#000000", //цвет текста
                          bgColor: "#ebf1f4", //цвет фона
                          opacity: 100 //прозрачность фона
                      },
                      events: {
                          onOpenStart: BX.proxy(this.SidePanelOpenStart, this),
                          onLoad: BX.proxy(this.SidePanelLoad, this),
                      }
                  });
              }
          },
          exportBakset: function () {
              var data = {};
              if (typeof userStore == 'object') {
                  data.basket_number = userStore.getters['basket/getBasketNumber'];
                  data.basket_id = userStore.getters['basket/getBasketId'];
              } else {
                  data.basket_id = BX.Sale.BasketComponent.result.TOTAL_RENDER_DATA.BASKET.ID;
                  data.basket_number = BX.Sale.BasketComponent.result.TOTAL_RENDER_DATA.BASKET.ACCOUNT_NUMBER;
              }
              if (data.basket_id) {
                  data.action = 'EXPORT';
                  this.lastAction = 'basketExport';
                  // Просто скачиваем
                  var data = {};
                  if (typeof userStore == 'object') {
                      data.basket_number = userStore.getters['basket/getBasketNumber'];
                      data.basket_id = userStore.getters['basket/getBasketId'];
                  } else {
                      data.basket_id = BX.Sale.BasketComponent.result.TOTAL_RENDER_DATA.BASKET.ID;
                      data.basket_number = BX.Sale.BasketComponent.result.TOTAL_RENDER_DATA.BASKET.ACCOUNT_NUMBER;
                  }
  
                  data.action = 'EXPORT';
                  this.lastAction = 'basketExport';
                  // Просто скачиваем
                  var url_params = new URLSearchParams(this.getData(data)).toString();
                  var request = new XMLHttpRequest();
                  request.open('POST', this.ajaxUrl, true);
                  request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
                  request.responseType = 'blob';
                  request.onload = function () {
                      // Only handle status code 200
                      if (request.readyState === request.DONE) {
                          if (request.status === 200) {
                              // Try to find out the filename from the content disposition `filename` value
                              var matches = /filename=(.*)/.exec(request.getResponseHeader('content-disposition'));
                              var filename = (matches != null && matches[1] ? matches[1] : 'file.pdf');
                              // The actual download
                              var type = request.getResponseHeader('content-type');
                              var blob = new Blob([request.response], { type: type });
                              var link = document.createElement('a');
                              link.href = window.URL.createObjectURL(blob);
                              link.download = filename;
                              document.body.appendChild(link);
                              link.click();
                              document.body.removeChild(link);
                          } else {
                              BX.UI.Notification.Center.notify({
                                  content: request.responseText,
                                  position: "bottom-right",
                                  autoHideDelay: 5000,
                                  closeButton: true,
                                  category: "basket-" + this.lastAction,
                                  // actions: []
                              });
                          }
                      }
  
                  };
                  request.send('content=' + url_params);
                  /* this.showRequest(this.ajaxUrl, {
                      printable: true,
                      requestMethod: 'post',
                      requestParams: this.getData(data),
                      contentClassName: "light-sidepanel",
                      data: data,
                      width: '500',
                      allowChangeHistory: false,
                      cacheable: true,
                      label: {
                          class: 'dark',
                          text: "Экспорт корзины ",
                          color: "#000000", //цвет текста
                          bgColor: "#ebf1f4", //цвет фона
                          opacity: 100 //прозрачность фона
                      },
                      events: {
                          onOpenStart: BX.proxy(this.SidePanelOpenStart, this),
                          onLoad: BX.proxy(this.SidePanelLoad, this),
                      }
                  }); */
              }
          },
  
          SidePanelOpenStart: function (event) {
              let slider = event.getSlider(),
                  basket_id,
                  basket_number;
              if (slider.url.search(/.+ID=([a-z_0-9]+).*/i) >= 0) {
                  basket_id = slider.url.replace(/.+ID=([a-z_0-9]+).*/i, '$1');
              } else if (slider.getData().data.basket_id) {
                  basket_id = slider.getData().data.basket_id;
              }
              if (slider.url.search(/.+BASKET_NUMBER=([a-z_0-9]+).*/i) >= 0) {
                  basket_number = slider.url.replace(/.+BASKET_NUMBER=([a-z_0-9]+).*/i, '$1');
              } else if (slider.getData().data.basket_number) {
                  basket_number = slider.getData().data.basket_number;
              }
              if (slider.options.label.text && (basket_number || basket_id)) {
                  slider.getLabel().setText(slider.options.label.text + ' ' + (basket_number || basket_id));
              }
              if (slider.options.label.class && slider.getLabel().layout != undefined) {
                  slider.getLabel().layout.closeBtn.classList.add(slider.options.label.class)
              }
          },
  
          SidePanelLoad: function (event) {
              // Если запрос с принт - печатаем!
              if (event.slider != undefined &&
                  event.slider.isLoaded() &&
                  event.slider.getData().data.print == 'Y'
              ) {
                  event.slider.handlePrintBtnClick();
              }
              // найти способ прочие ссылки открывать в родительском окне
              BX.findChildren(document, {
                  tag: "a"
              }, true).forEach(tag_a => {
                  BX.adjust(tag_a, {
                      attrs: {
                          target: "_top"
                      }
                  });
              });
              var slider = event.getSlider();
              if (slider && slider.getWindow().$body != undefined) slider.getWindow().$body.find('form[target]').attr('target', slider.getFrameId());
          },
  
          showRequest: function (path, params) {
              let def_params = {
                  width: '500',
                  allowChangeHistory: false,
                  cacheable: true,
                  label: {
                      color: "#000000", //цвет текста
                      bgColor: "#64ba4e", //цвет фона
                      opacity: 100 //прозрачность фона
                  }
              };
              params = Object.assign(def_params, this.getData(), params);
              BX.SidePanel.Instance.open(path, params);
          },
  
          addCouponAction: function (event) {
              var target = BX.getEventTarget(event);
              if (target && target.value) {
                  this.actionPool.addCoupon(target.value);
                  target.disabled = true;
              }
          },
  
          pasteCouponAction: function (event) {
              setTimeout(BX.delegate(function () {
                  this.addCouponAction(event);
              }, this), 10);
          },
  
          removeCouponAction: function () {
              var value = BX.proxy_context && BX.util.trim(BX.proxy_context.getAttribute('data-coupon'));
              if (value) {
                  this.actionPool.removeCoupon(value);
              }
          },
  
          initializeActionPool: function () {
              this.actionPool = new BX.Sale.BasketActionPool(this);
          },
  
          initializeFilter: function () {
              this.filter = new BX.Sale.BasketFilter(this);
          },
  
          /**
           * Send ajax request with basket data and executes callback by action
           */
          sendRequest: function (action, data) {
              this.lastAction = action;
              if (!data.basket_id) {
                  data.basket_id = userStore.getters['basket/getBasketId'];
              }
  
              if (this.lastAction === 'recalculateAjax') {
                  // we use it to reload all items if applied discounts changed
                  data.lastAppliedDiscounts = BX.util.array_keys(this.result.FULL_DISCOUNT_LIST).join(',');
                  if (this.params.USE_ENHANCED_ECOMMERCE === 'Y') {
                      this.checkAnalytics(data);
                  }
              }
              this.loaderNodeId = this.ids.basketRoot;
              if (data.fullRecalculation != undefined && data.fullRecalculation == 'Y') { } else if (0) {
                  for (let i in data.basket) {
                      if (data.basket[i]) {
                          this.loaderNodeId = "basket-item-" + i.replace(/\D*/, '');
                      }
                  }
              }
              this.load = true;
              this.sendRequestLoader = BX.showWait(this.loaderNodeId);
              BX.ajax({
                  method: 'POST',
                  timeout: 6000,
                  dataType: 'json',
                  url: this.ajaxUrl,
                  data: this.getData(data),
                  onsuccess: BX.delegate(function (result) {
                      if (location.search.search('debug=log') > 0) {
                          console.log(result);
                      }
                      BX.closeWait(this.loaderNodeId, this.sendRequestLoader);
                      this.load = false;
                      // this.actionPool.doProcessing(false);
  
                      if (!BX.type.isPlainObject(result)) {
                          this.lastActionErrorEvent();
                          return;
                      }
                      this.lastActionSuccessEvent();
  
                      // if (result.BASKET_REFRESHED && result.BASKET_DATA == undefined)
                      //     return;
  
                      // this.applyBasketResult(result.BASKET_DATA);
                      // this.editBasketItems(this.getItemsToEdit());
                      // this.editTotal();
  
                      // this.adjustBasketWrapperHeight();
                      // this.applyPriceAnimation();
                      // this.editWarnings();
  
                      // this.actionPool.switchTimer();
                      // this.actionPool.isBasketRefreshed = false;
  
                      // if (this.isBasketIntegrated() && this.isBasketChanged()) {
                      //     BX.Sale.OrderAjaxComponent.sendRequest();
                      // }
  
                      BX.closeWait();
                      $(function () {
                          $('[data-toggle="tooltip"]').tooltip();
                      });
                  }, this),
                  onfailure: BX.delegate(function (error) {
                      this.load = false;
                      BX.closeWait(this.loaderNodeId, this.sendRequestLoader);
                      // this.actionPool.doProcessing(false);
                      this.lastActionErrorEvent();
  
                      BX.closeWait();
                      $(function () {
                          $('[data-toggle="tooltip"]').tooltip();
                      })
                  }, this)
              });
          },
  
          lastActionSuccessEvent: function () {
              var content = '';
  
              switch (this.lastAction) {
                  case 'clearBasket':
                      content = BX.message('SUCCESS_EVENT_CLEAR_BASKET');
                      BX.onCustomEvent('OnBasketClear');
                      BX.onCustomEvent('OnBasketChange');
                      if (typeof userStore != 'undefined') {
                          userStore.commit("basket/clearBasket", userStore.getters['basket/getBasket']);
                      }
                      break;
                  case 'makeOrder':
                      content = BX.message('SUCCESS_EVENT_MAKE_ORDER');
                      BX.onCustomEvent('OnOrderConfirmed', this.lastResult);
                      break;
                  default:
                      break;
              }
              if (content) {
                  BX.UI.Notification.Center.notify({
                      content: content,
                      position: "bottom-right",
                      autoHideDelay: 5000,
                      closeButton: true,
                      category: "basket-" + this.lastAction,
                      // actions: []
                  });
              }
          },
  
          lastActionErrorEvent: function () {
              var content = '';
  
              switch (this.lastAction) {
                  case 'clearBasket':
                      content = BX.message('ERROR_EVENT_CLEAR_BASKET');
                      break;
                  case 'makeOrder':
                      content = BX.message('ERROR_EVENT_MAKE_ORDER');
                      break;
                  default:
                      break;
              }
              if (content) {
                  BX.UI.Notification.Center.notify({
                      content: content,
                      position: "bottom-right",
                      autoHideDelay: 5000,
                      closeButton: true,
                      category: "basket-" + this.lastAction,
                      // actions: []
                  });
              }
          },
  
          array_column: function (input, ColumnKey = null, IndexKey = null) { // eslint-disable-line camelcase
              //   discuss at: https://locutus.io/php/array_column/
              //   original by: Enzo Dañobeytía
              //   example 1: array_column([{name: 'Alex', value: 1}, {name: 'Elvis', value: 2}, {name: 'Michael', value: 3}], 'name')
              //   returns 1: {0: "Alex", 1: "Elvis", 2: "Michael"}
              //   example 2: array_column({0: {name: 'Alex', value: 1}, 1: {name: 'Elvis', value: 2}, 2: {name: 'Michael', value: 3}}, 'name')
              //   returns 2: {0: "Alex", 1: "Elvis", 2: "Michael"}
              //   example 3: array_column([{name: 'Alex', value: 1}, {name: 'Elvis', value: 2}, {name: 'Michael', value: 3}], 'name', 'value')
              //   returns 3: {1: "Alex", 2: "Elvis", 3: "Michael"}
              //   example 4: array_column([{name: 'Alex', value: 1}, {name: 'Elvis', value: 2}, {name: 'Michael', value: 3}], null, 'value')
              //   returns 4: {1: {name: 'Alex', value: 1}, 2: {name: 'Elvis', value: 2}, 3: {name: 'Michael', value: 3}}
  
              if (input !== null && (typeof input === 'object' || Array.isArray(input))) {
                  var newarray = []
                  if (typeof input === 'object') {
                      let temparray = []
                      for (let key of Object.keys(input)) {
                          temparray.push(input[key])
                      }
                      input = temparray
                  }
                  if (Array.isArray(input)) {
                      for (let key of input.keys()) {
                          if (IndexKey && input[key][IndexKey]) {
                              if (ColumnKey) {
                                  newarray[input[key][IndexKey]] = input[key][ColumnKey]
                              } else {
                                  newarray[input[key][IndexKey]] = input[key]
                              }
                          } else {
                              if (ColumnKey) {
                                  newarray.push(input[key][ColumnKey])
                              } else {
                                  newarray.push(input[key])
                              }
                          }
                      }
                  }
                  return Object.assign({}, newarray)
              }
          },
  
          isBasketIntegrated: function () {
              return this.params.BASKET_WITH_ORDER_INTEGRATION === 'Y';
          },
  
          isBasketChanged: function () {
              return this.changedItems.length;
          },
  
          addPriceAnimationData: function (nodeId, start, finish, currency) {
              if (!BX.type.isPlainObject(this.priceAnimationData)) {
                  this.clearPriceAnimationData();
              }
  
              this.priceAnimationData.start[nodeId] = parseFloat(start);
              this.priceAnimationData.finish[nodeId] = parseFloat(finish);
              this.priceAnimationData.currency[nodeId] = currency;
              this.priceAnimationData.int[nodeId] = (parseFloat(start) === parseInt(start)) && (parseFloat(finish) === parseInt(finish));
          },
  
          clearPriceAnimationData: function () {
              this.priceAnimationData = {
                  start: {},
                  finish: {},
                  currency: {},
                  int: {}
              };
          },
  
          applyBasketResult: function (result) {
              this.changedItems = [];
              if (this.result != undefined && result != undefined && result.TOTAL_RENDER_DATA.BASKET.ID != this.result.TOTAL_RENDER_DATA.BASKET.ID) // сменилась корзина - обнулим товары
                  this.items = {};
              this.clearPriceAnimationData();
  
              if (!BX.type.isPlainObject(result)) {
                  BX.onCustomEvent('OnBasketUpdated');
                  return;
              }
  
              // Обновим данные по товарам в компоненте BX.Sale.BasketComponent
              if (result.SELECT_RESULT_ALL) {
                  var i, newData;
                  for (i in result.SELECT_RESULT_ALL) {
                      if (result.SELECT_RESULT_ALL.hasOwnProperty(i)) {
                          newData = result.SELECT_RESULT_ALL[i];
                          // newData.WARNINGS = this.checkBasketItemWarnings(newData, result.WARNING_MESSAGE_WITH_CODE);
  
                          if (this.items[newData.ID]) {
                              // Если товар уже есть в корзине - проверяем изменения
                              if (JSON.stringify(this.items[newData.ID]) === JSON.stringify(newData)) {
                                  continue;
                              }
                              if (
                                  this.items[newData.ID].PRICE != newData.PRICE ||
                                  this.items[newData.ID].CURRENCY != newData.CURRENCY
                              ) {
                                  this.changedItems.push(newData.ID);
                              }
                              // newData.ID = this.items[newData.ID].ID;
                              // this.items[newData.ID] = Object.assign(this.items[newData.ID],newData);
                              // this.items[newData.ID].PRICE = newData.PRICE;
                              // this.items[newData.ID].QUANTITY = newData.QUANTITY;
                              // this.items[newData.ID].CAN_BUY_IN_PERCENT = newData.CAN_BUY_IN_PERCENT;
                          } else {
                              // если товара нет просто добавляем отметку о его обновлении
                              let find = false;
                              for (let i in this.items) {
                                  if (this.items[i].PRODUCT_ID == newData.PRODUCT_ID) {
                                      find = true;
                                      if (
                                          this.items[i].PRICE != newData.PRICE ||
                                          this.items[i].CURRENCY != newData.CURRENCY ||
                                          this.items[i].QUANTITY != newData.QUANTITY ||
                                          this.items[i].WEIGHT != newData.WEIGHT
                                      ) {
                                          this.changedItems.push(this.items[i].ID);
                                      }
                                      // newData.ID = this.items[i].ID;
                                      // this.items[i] = Object.assign(this.items[i],newData);
                                      // this.items[i].PRICE = newData.PRICE;
                                      // this.items[i].QUANTITY = newData.QUANTITY;
                                      // this.items[i].CAN_BUY_IN_PERCENT = newData.CAN_BUY_IN_PERCENT;
                                  }
                              }
                              if (!find) {
                                  this.changedItems.push(newData.PRODUCT_ID);
                              }
                              // this.changedItems.push(newData.ID);
                              // this.items[newData.ID];
                              // this.addSortedItem(newData.ID, true);
                          }
  
                          newData = this.checkBasketItemsAnimation(newData);
                          this.items[newData.ID] = newData;
                      }
                  }
                  if (this.isBasketChanged()) {
                      // this.items = result.SELECT_RESULT_ALL;
                  }
              }
              if (
                  (result != undefined && result.BASKET_ITEMS_COUNT === 0) ||
                  (this.result != undefined && result != undefined && result.TOTAL_RENDER_DATA.BASKET.ID != this.result.TOTAL_RENDER_DATA.BASKET.ID) // сменилась корзина
                  ||
                  (this.result != undefined && result != undefined && result.TOTAL_RENDER_DATA.BASKET.CONTRAGENT != this.result.TOTAL_RENDER_DATA.BASKET.CONTRAGENT.ID) // сменился контрагент
                  ||
                  (this.result != undefined && result != undefined && result.BASKET_ITEMS_COUNT != this.result.BASKET_ITEMS_COUNT) // сменилось количество товаров в корзине
                  // || (this.result != undefined && result != undefined && result.TOTAL_RENDER_DATA.BASKET.ITEMS != this.result.TOTAL_RENDER_DATA.BASKET.CONTRAGENT.ID)
                  ||
                  (this.result != undefined && result != undefined && result.CURRENCY != this.result.CURRENCY) // сменилась валюта корзины
                  ||
                  this.isBasketChanged() >= 2 // сменился состав корзины
              ) {
                  // TODO перебрать этот старый, но рабочий код!
                  if (result.GRID_ID == undefined &&
                      result.GRID.ID != undefined
                  ) {
                      result.GRID_ID = result.GRID.ID;
                  }
                  if (!this.grid && result.GRID_ID) {
                      this.grid = BX.Main.gridManager.getInstanceById(result.GRID_ID);
                  }
                  if (this.grid != undefined) {
                      debugger
                      var curPage = null;
                      var page_active_node = BX.findChild(this.grid.getPagination().getContainer(), {
                          class: "main-ui-pagination-active"
                      }, true);
                      if (page_active_node != undefined) {
                          curPage = parseInt(page_active_node.innerText);
                      }
                      if (curPage == undefined) {
                          curPage = 1;
                      } else {
                          if (this.grid.rows.rows.reduce(function (sum, row) {
                              sum = parseInt(sum) || 0;
                              var is_node = document.body.contains(row.node);
                              return sum + (is_node ? 1 : 0);
                          }) < 2) { // в верстке остаётся заголовок таблицы
                              curPage -= 1;
                          }
                      }
                      if (!curPage) {
                          curPage = 1
                      }
                      // this.grid.settings.defaultSettings.classTableFade = '';
                      // var classTableFade = this.grid.settings.get('classTableFade');
                      this.grid.reloadTable('POST', null, BX.proxy(function () {
                          $(function () {
                              $('[data-toggle="tooltip"]').tooltip();
                          })
                          // this.grid.settings.defaultSettings.classTableFade = classTableFade;
                          BX.onCustomEvent('OnBasketUpdated');
                      }, this), window.location.pathname + '?basket_list=page-' + curPage);
                  }
              }
              // Обновим глобальные данные о товарах в корзине
              if (result != null && result.TOTAL_RENDER_DATA != null && result.BASKET_ITEM_RENDER_DATA != undefined) {
                  if (typeof userStore != 'undefined' && result.TOTAL_RENDER_DATA.BASKET != undefined) {
                      userStore.commit("basket/updateBasket", Object.assign({}, result.TOTAL_RENDER_DATA.BASKET));
                  }
              }
  
              if (result.TOTAL_RENDER_DATA) {
                  result.TOTAL_RENDER_DATA = this.checkTotalAnimation(result.TOTAL_RENDER_DATA);
              }
              this.checkMarks();
              this.result = result;
          },
  
          itemSortFunction: function (a, b) {
              if (!this.items.hasOwnProperty(a) || !this.items.hasOwnProperty(b)) {
                  return 0;
              }
  
              return parseFloat(this.items[a].SORT) - parseFloat(this.items[b].SORT);
          },
  
          getChangedSimilarOffers: function () {
              var changedSimilarOffers = [];
  
              var otherSimilarItemsQuantity, totalSimilarItemsQuantity;
              var hashMap = this.getHashMap();
  
              for (var hash in hashMap) {
                  if (hashMap.hasOwnProperty(hash)) {
                      if (hashMap[hash].length > 1) {
                          for (var i = 0; i < hashMap[hash].length; i++) {
                              otherSimilarItemsQuantity = 0;
                              totalSimilarItemsQuantity = 0;
  
                              for (var k = 0; k < hashMap[hash].length; k++) {
                                  if (hashMap[hash][k] != hashMap[hash][i]) {
                                      otherSimilarItemsQuantity += parseFloat(this.items[hashMap[hash][k]].QUANTITY);
                                  }
  
                                  totalSimilarItemsQuantity += parseFloat(this.items[hashMap[hash][k]].QUANTITY);
                              }
  
                              if (
                                  !this.items[hashMap[hash][i]].HAS_SIMILAR_ITEMS ||
                                  this.items[hashMap[hash][i]].SIMILAR_ITEMS_QUANTITY != otherSimilarItemsQuantity ||
                                  this.items[hashMap[hash][i]].TOTAL_SIMILAR_ITEMS_QUANTITY != totalSimilarItemsQuantity
                              ) {
                                  changedSimilarOffers.push(hashMap[hash][i]);
  
                                  this.items[hashMap[hash][i]].HAS_SIMILAR_ITEMS = true;
                                  this.items[hashMap[hash][i]].SIMILAR_ITEMS_QUANTITY = otherSimilarItemsQuantity;
                                  this.items[hashMap[hash][i]].TOTAL_SIMILAR_ITEMS_QUANTITY = totalSimilarItemsQuantity;
  
                                  this.items[hashMap[hash][i]].ALL_AVAILABLE_QUANTITY = this.items[hashMap[hash][i]].AVAILABLE_QUANTITY;
                                  this.items[hashMap[hash][i]].AVAILABLE_QUANTITY = this.items[hashMap[hash][i]].ALL_AVAILABLE_QUANTITY - otherSimilarItemsQuantity;
                              }
                          }
                      } else if (hashMap[hash][0] && this.items[hashMap[hash][0]].HAS_SIMILAR_ITEMS) {
                          changedSimilarOffers.push(hashMap[hash][0]);
  
                          delete this.items[hashMap[hash][0]].HAS_SIMILAR_ITEMS;
                          delete this.items[hashMap[hash][0]].SIMILAR_ITEMS_QUANTITY;
                          delete this.items[hashMap[hash][0]].TOTAL_SIMILAR_ITEMS_QUANTITY;
  
                          this.items[hashMap[hash][0]].AVAILABLE_QUANTITY = this.items[hashMap[hash][0]].ALL_AVAILABLE_QUANTITY;
                          delete this.items[hashMap[hash][0]].ALL_AVAILABLE_QUANTITY;
                      }
                  }
              }
  
              return changedSimilarOffers;
          },
  
          getHashMap: function () {
              var hashMap = {};
  
              for (var id in this.items) {
                  if (this.items.hasOwnProperty(id) && this.isItemAvailable(id)) {
                      if (!hashMap.hasOwnProperty(this.items[id].HASH)) {
                          hashMap[this.items[id].HASH] = [];
                      }
  
                      hashMap[this.items[id].HASH].push(id);
                  }
              }
  
              return hashMap;
          },
  
          isItemAvailable: function (itemId) {
              // var sortedItems = this.filter.isActive() ? this.filter.realSortedItems : this.sortedItems;
              // TODO придумать как проталкивать все товары в компонент.
              if (this.items[itemId])
                  return this.items[itemId] &&
                      !this.items[itemId].NOT_AVAILABLE &&
                      !this.items[itemId].SHOW_RESTORE
                      // && BX.util.in_array(itemId, sortedItems)
                      ;
              return true;
          },
  
          checkTotalAnimation: function (totalData) {
              if (this.result && this.result.TOTAL_RENDER_DATA && parseFloat(this.result.TOTAL_RENDER_DATA.PRICE) > parseFloat(totalData.PRICE)) {
                  totalData.PRICE_NEW = totalData.PRICE;
                  totalData.PRICE = this.result.TOTAL_RENDER_DATA.PRICE;
  
                  totalData.PRICE_FORMATED_NEW = totalData.PRICE_FORMATED;
                  totalData.PRICE_FORMATED = this.result.TOTAL_RENDER_DATA.PRICE_FORMATED;
              }
  
              return totalData;
          },
  
          checkBasketItemsAnimation: function (itemData) {
              var itemId = itemData.ID;
  
              if (this.items[itemId]) {
                  var quantityNode = BX(this.ids.quantity + itemId);
                  if (
                      BX.type.isDomNode(quantityNode) &&
                      !this.actionPool.isItemInPool(itemId) &&
                      parseFloat(quantityNode.value) !== parseFloat(itemData.QUANTITY)
                  ) {
                      itemData.QUANTITY_ANIMATION = true;
                      this.actionPool.clearLastActualQuantityPool(itemId);
                  }
  
                  if (
                      BX.util.in_array('PRICE', this.params.COLUMNS_LIST)
                      // && parseFloat(this.items[itemId].PRICE) != parseFloat(itemData.PRICE)
                      &&
                      parseFloat(itemData.PRICE)
                  ) {
                      itemData.PRICE_NEW = itemData.PRICE;
                      itemData.PRICE = this.items[itemId].PRICE;
  
                      itemData.PRICE_FORMATED_NEW = itemData.PRICE_FORMATED;
                      itemData.PRICE_FORMATED = this.items[itemId].PRICE_FORMATED;
  
                      this.addPriceAnimationData(this.ids.price + itemId, itemData.PRICE, itemData.PRICE_NEW, itemData.CURRENCY);
                  }
  
                  if (
                      BX.util.in_array('SUM', this.params.COLUMNS_LIST) &&
                      parseFloat(this.items[itemId].SUM_PRICE) != parseFloat(itemData.SUM_PRICE)
                      // && parseFloat(this.items[itemId].QUANTITY) === parseFloat(itemData.QUANTITY)
                  ) {
                      itemData.SUM_PRICE_NEW = itemData.PRICE * itemData.QUANTITY;
                      itemData.SUM_PRICE = this.items[itemId].SUM_PRICE;
  
                      itemData.SUM_PRICE_FORMATED_NEW = itemData.SUM_PRICE_FORMATED;
                      itemData.SUM_PRICE_FORMATED = this.items[itemId].SUM_PRICE_FORMATED;
  
                      this.addPriceAnimationData(this.ids.sumPrice + itemId, itemData.SUM_PRICE, itemData.SUM_PRICE_NEW, itemData.CURRENCY);
                  }
              }
  
              return itemData;
          },
  
          getData: function (data) {
              data = data || {};
  
              if (data[this.params.ACTION_VARIABLE] == null || data[this.params.ACTION_VARIABLE] == undefined || !data[this.params.ACTION_VARIABLE]) {
                  data[this.params.ACTION_VARIABLE] = this.lastAction;
              }
              data.site_template_id = this.siteTemplateId;
              data.via_ajax = 'Y';
              data.site_id = this.siteId;
              data.sessid = BX.bitrix_sessid();
              data.template = this.template;
              data.signedParamsString = this.signedParamsString;
              return data;
          },
  
          startLoader: function () {
              /* if (!this.loadingScreen)
              {
                  this.loadingScreen = new BX.PopupWindow('loading_screen', null, {
                      events: {
                          onAfterPopupShow: BX.delegate(function() {
                              BX.cleanNode(this.loadingScreen.popupContainer);
                              BX.removeClass(this.loadingScreen.popupContainer, 'popup-window');
                              this.loadingScreen.popupContainer.appendChild(
                                  BX.create('IMG', {props: {src: this.templateFolder + '/images/loader.gif'}})
                              );
                              this.loadingScreen.popupContainer.removeAttribute('style');
                              this.loadingScreen.popupContainer.style.display = 'block';
                          }, this)
                      }
                  });
                  BX.addClass(this.loadingScreen.popupContainer, 'bx-step-opacity');
              }
  
              this.loadingScreen.show(); */
          },
  
          /**
           * Hiding loader image with overlay.
           */
          endLoader: function () {
              /* if (this.loadingScreen && this.loadingScreen.isShown())
              {
                  this.loadingScreen.close();
              } */
          },
  
          editWarnings: function () {
              this.editGeneralWarnings();
              this.editBasketItemWarnings();
              this.toggleWarningBlock();
              this.showWarningItemsCount();
          },
  
          editGeneralWarnings: function () {
              var warningsNode = this.getEntity(this.getCacheNode(this.ids.warning), 'basket-general-warnings');
  
              if (BX.type.isDomNode(warningsNode)) {
                  var generalWarningText = warningsNode.innerHTML;
  
                  if (this.result.WARNING_MESSAGE_WITH_CODE) {
                      for (var code in this.result.WARNING_MESSAGE_WITH_CODE) {
                          if (this.result.WARNING_MESSAGE_WITH_CODE.hasOwnProperty(code)) {
                              if (
                                  !this.items[code] &&
                                  generalWarningText.indexOf(this.result.WARNING_MESSAGE_WITH_CODE[code]) === -1
                              ) {
                                  generalWarningText += this.result.WARNING_MESSAGE_WITH_CODE[code] + '<br/>';
                              }
                          }
                      }
                  }
  
                  if (generalWarningText) {
                      warningsNode.innerHTML = generalWarningText;
                      warningsNode.style.display = '';
                  } else {
                      warningsNode.style.display = 'none';
                      warningsNode.innerHTML = '';
                  }
              }
          },
  
          editBasketItemWarnings: function () {
              var itemsWarningsNode = this.getEntity(this.getCacheNode(this.ids.warning), 'basket-item-warnings');
  
              if (BX.type.isDomNode(itemsWarningsNode)) {
                  if (this.warningItems.length) {
                      var warningCount = this.getEntity(itemsWarningsNode, 'basket-items-warning-count');
                      if (BX.type.isDomNode(warningCount)) {
                          warningCount.innerHTML = this.warningItems.length + ' ' + this.getGoodsMessage(this.warningItems.length);
                      }
  
                      itemsWarningsNode.style.display = '';
                  } else if (itemsWarningsNode.style.display !== 'none') {
                      itemsWarningsNode.style.display = 'none';
  
                      if (this.filter.isActive()) {
                          this.toggleFilter('all');
                      }
                  }
              }
          },
  
          toggleWarningBlock: function () {
              var warningNode = this.getCacheNode(this.ids.warning);
  
              if (BX.type.isDomNode(warningNode)) {
                  var generalWarningNode = this.getEntity(warningNode, 'basket-general-warnings');
                  var itemsWarningsNode = this.getEntity(warningNode, 'basket-item-warnings');
  
                  if (
                      (!BX.type.isDomNode(generalWarningNode) || generalWarningNode.style.display === 'none') &&
                      (!BX.type.isDomNode(itemsWarningsNode) || itemsWarningsNode.style.display === 'none')
                  ) {
                      warningNode.style.display = 'none';
                  } else {
                      warningNode.style.display = '';
                  }
              }
          },
  
          checkBasketItemWarnings: function (itemData, warnings) {
              if (!itemData)
                  return;
  
              var itemWarnings;
  
              if (this.items[itemData.ID] && this.lastAction === 'refreshAjax') {
                  itemWarnings = this.items[itemData.ID].WARNINGS;
              } else {
                  itemWarnings = [];
              }
  
              if (BX.type.isArray(warnings[itemData.ID]) && warnings[itemData.ID].length) {
                  for (var i in warnings[itemData.ID]) {
                      if (warnings[itemData.ID].hasOwnProperty(i) && !BX.util.in_array(warnings[itemData.ID][i], itemWarnings)) {
                          itemWarnings.push(warnings[itemData.ID][i]);
                      }
                  }
              }
  
              if (itemWarnings != undefined && itemWarnings.length) {
                  if (!BX.util.in_array(itemData.ID, this.warningItems)) {
                      this.warningItems.push(itemData.ID);
                  }
              } else if (BX.util.in_array(itemData.ID, this.warningItems)) {
                  this.warningItems.splice(BX.util.array_search(itemData.ID, this.warningItems), 1);
              }
  
              return itemWarnings;
          },
  
          removeAllWarnings: function (event) {
              this.clearGeneralWarnings();
              this.clearBasketItemsWarnings();
  
              this.editWarnings();
  
              event && event.preventDefault();
          },
  
          clearGeneralWarnings: function () {
              this.result.WARNING_MESSAGE_WITH_CODE = {};
  
              var generalWarningNode = this.getEntity(this.getCacheNode(this.ids.warning), 'basket-general-warnings');
  
              if (BX.type.isDomNode(generalWarningNode)) {
                  generalWarningNode.innerHTML = '';
              }
          },
  
          clearBasketItemsWarnings: function () {
              var itemsToEdit = [];
  
              for (var i in this.warningItems) {
                  if (this.warningItems.hasOwnProperty(i)) {
                      this.items[this.warningItems[i]].WARNINGS = [];
  
                      if (this.isItemShown(this.warningItems[i])) {
                          itemsToEdit.push(this.warningItems[i]);
                      }
                  }
              }
  
              this.warningItems = [];
              this.editBasketItems(itemsToEdit);
          },
  
          isItemShown: function (itemId) {
              return BX.util.in_array(itemId, this.shownItems);
          },
  
          initializeBasketItems: function () {
              if (Object.keys(this.items).length === 0)
                  return;
  
              if (this.sortedItems.length > 0) {
                  for (var i = 0; i < this.sortedItems.length; i++) {
                      if (this.useDynamicScroll && this.shownItems.length >= this.maxItemsShowCount) {
                          break;
                      }
  
                      this.createBasketItem(this.sortedItems[i]);
                  }
              } else {
                  let items = Object.keys(this.items);
                  for (var i = 0; i < items.length; i++) {
                      this.createBasketItem(items[i]);
                  }
              }
          },
  
          createBasketItem: function (itemId) {
              if (!this.items[itemId]) {
                  return;
              }
  
              var basketItemTemplate = this.getTemplate('basket-item-template');
              if (basketItemTemplate) {
                  var basketItemHtml = this.renderBasketItem(basketItemTemplate, this.items[itemId]);
                  var sortIndex = BX.util.array_search(itemId, this.sortedItems);
  
                  if (this.shownItems.length && sortIndex >= 0) {
                      if (sortIndex < BX.util.array_search(this.shownItems[0], this.sortedItems)) {
                          // insert before
                          BX(this.ids.item + this.shownItems[0]).insertAdjacentHTML('beforebegin', basketItemHtml);
                          this.shownItems.unshift(itemId);
                      } else if (sortIndex > BX.util.array_search(this.shownItems[this.shownItems.length - 1], this.sortedItems)) {
                          // insert after
                          BX(this.ids.item + this.shownItems[this.shownItems.length - 1]).insertAdjacentHTML('afterend', basketItemHtml);
                          this.shownItems.push(itemId);
                      } else {
                          // insert between
                          BX(this.ids.item + this.sortedItems[sortIndex + 1]).insertAdjacentHTML('beforebegin', basketItemHtml);
                          this.shownItems.splice(sortIndex + 1, 0, itemId);
                      }
                  } else {
                      this.getCacheNode(this.ids.itemListTable).insertAdjacentHTML('beforeend', basketItemHtml);
                      this.shownItems.push(itemId);
                  }
  
                  this.bindBasketItemEvents(this.items[itemId]);
  
                  if (this.filter.isActive()) {
                      this.filter.highlightSearchMatch(this.items[itemId]);
                  }
              } else {
                  this.bindBasketItemEvents(this.items[itemId]);
                  this.checkMark(this.items[itemId]);
              }
          },
  
          getItemsToEdit: function () {
              var itemIds = [];
  
              if (this.isBasketChanged()) {
                  for (var i in this.changedItems) {
                      if (this.changedItems.hasOwnProperty(i) && this.isItemShown(this.changedItems[i])) {
                          itemIds.push(this.changedItems[i]);
                      }
                  }
              }
  
              return itemIds;
          },
  
          getItemsAfter: function () {
              var itemIdsAfter = [];
  
              if (this.useDynamicScroll) {
                  var lastShownItemId = this.shownItems[this.shownItems.length - 1] || false;
  
                  if (lastShownItemId) {
                      var i = 0;
                      var index = BX.util.array_search(lastShownItemId, this.sortedItems);
  
                      while (this.sortedItems[++index] && i++ < this.maxItemsShowCount) {
                          itemIdsAfter.push(this.sortedItems[index]);
                      }
                  }
              }
  
              return itemIdsAfter;
          },
  
          editBasketItems: function (itemIds) {
              if (!itemIds || itemIds.length === 0) {
                  return;
              }
  
              var i, item;
  
              for (i in itemIds) {
                  if (!itemIds.hasOwnProperty(i) || !BX.type.isPlainObject(this.items[itemIds[i]])) {
                      continue;
                  }
  
                  item = this.items[itemIds[i]];
  
                  if (this.actionPool.isItemInPool(item.ID)) {
                      if (!BX.util.in_array(item.ID, this.postponedItems)) {
                          this.postponedItems.push(item.ID);
                      }
  
                      continue;
                  }
  
                  if (BX.type.isDomNode(BX(this.ids.item + item.ID))) {
                      this.redrawBasketItemNode(item.ID);
                      this.checkMark(item);
                      this.applyQuantityAnimation(item.ID);
                  } else {
                      this.createBasketItem(item.ID);
                  }
              }
          },
          checkMarks: function () {
              if (typeof window.user_basket == 'undefined')
                  window.user_basket = {};
              let items = Object.keys(window.user_basket);
              if (items.length) {
                  for (var i = 0; i < items.length; i++) {
                      let item = window.user_basket[items[i]];
                      let itemId = this.ids.item + item.ID;
                      let row = BX(itemId);
                      if (!row || row == undefined) {
                          row = BX.findChild(this.getCacheNode(this.ids.basketRoot), {
                              attribute: {
                                  'data-grid-item_id': item.PRODUCT_ID
                              }
                          }, true);
                          if (row && row.id) {
                              item.ID = parseInt(row.id.replace('basket-item-', ''));
                          }
                      }
                      if (!row || row == undefined) {
                          //
                      } else {
                          if (item != undefined && this.items[item.ID] != undefined) {
                              Object.assign(this.items[item.ID], item);
                          }
                          this.checkMark(item);
                          this.bindBasketItemEvents(item);
                      }
                  }
              } else {
                  items = Object.keys(this.items);
                  if (items) {
                      for (var i = 0; i < items.length; i++) {
                          this.checkMark(this.items[items[i]]);
                      }
                  }
              }
          },
          checkMark: function (item) {
              /* let row = BX(this.ids.item + item.ID);
              if (!row || row == undefined) return;
              let analog = BX(this.ids.analog + item.ID);
              let alert = BX(this.ids.alert + item.ID);
              let wait = BX(this.ids.wait + item.ID);
              let done = BX(this.ids.done + item.ID);
              let quantity = BX(this.ids.quantity + item.ID);
              let progress = BX(this.ids.progress + item.ID);
              let progress_bar = BX(this.ids.progressbar + item.ID);
              row.setAttribute('data-grid-analog', "");
              row.setAttribute('data-grid-whait', "");
              BX.removeClass(analog, "d-inline");
              BX.removeClass(alert, "d-inline");
              BX.removeClass(wait, "d-inline");
              BX.removeClass(done, "d-inline");
              if ((BX.getCookie('FIT24_LOGIN') != undefined || (typeof userStore != 'undefined' &&
                  userStore.getters.user != undefined &&
                  userStore.getters.user.ID > 0))) {
                  if (item.CAN_BUY_IN_PERCENT < 100) {
                      if (item.ANALOGS !== undefined && item.ANALOGS.length && !this.chouseAnalog) {
                          BX.addClass(analog, "d-inline");
                          row.setAttribute('data-grid-analog', "analog");
                          BX.unbind(analog, 'click');
                          BX.bind(analog, 'click', BX.proxy(this.checkAnalog, item));
                      }
                      if (item.PROPS != undefined &&
                          item.PROPS.WHAIT_FROM_RC !== undefined &&
                          item.PROPS.WHAIT_FROM_RC.VALUE != undefined
                      ) {
                          let wait_from_rc = BX.findChildren(BX(this.ids.wait + item.ID), {
                              "tagName": "i"
                          }, true);
                          if (BX.type.isElementNode(wait_from_rc) || BX.type.isDomNode(wait_from_rc) || wait_from_rc.length) {
                              BX.removeClass(wait_from_rc[0], "far");
                              BX.addClass(wait_from_rc[0], "fas");
                          }
                      }
                      if (item.QUANTITY_RC != undefined) {
                          if (parseInt(item.QUANTITY_RC) + parseInt(item.QUANTITY_OPT) >= item.QUANTITY) {
                              BX.addClass(wait, "d-inline");
                              row.setAttribute('data-grid-whait', "whait");
                              BX.unbind(wait, 'click');
                              BX.bind(wait, 'click', BX.proxy(this.setWhait, item));
                          } else {
                              BX.removeClass(this.ids.wait + item.ID, "d-inline");
                          }
                      }
                  } else if (item.CAN_BUY_IN_PERCENT != undefined) {
                      BX.addClass(done, "d-inline");
                  }
                  if (BX(this.ids.progressbar + item.ID) && item.CAN_BUY_IN_PERCENT != undefined) {
                      if (progress_bar) {
                          if (!!!item.CAN_BUY_IN_PERCENT || item.CAN_BUY_IN_PERCENT == undefined) item.CAN_BUY_IN_PERCENT = 0;
                          BX.removeClass(progress_bar, 'd-none');
                          progress_bar.setAttribute("style", "width: " + item.CAN_BUY_IN_PERCENT + "%");
                          progress_bar.setAttribute("aria-valuenow", item.CAN_BUY_IN_PERCENT);
                          // BX(this.ids.progress+item.ID).setAttribute("title","Доступность выполнения "+item.CAN_BUY_IN_PERCENT+"%");
                          BX(this.ids.progress + item.ID).setAttribute("data-original-title", "Доступность выполнения " + item.CAN_BUY_IN_PERCENT + "%");
                      }
                  } else {
                      if (progress_bar) {
                          BX.addClass(progress_bar, 'd-none');
                      }
                  }
              } else {
                  BX.addClass(done, "d-inline");
                  if (progress) {
                      BX.addClass(progress, 'd-none');
                      BX.addClass(progress_bar, 'd-none');
                  }
              }
              // TODO временно, почему не обновляет Grid?
              if (quantity != undefined && parseInt(item.QUANTITY_ADD) && quantity.value != parseInt(item.QUANTITY_ADD)) {
                  quantity.value = parseInt(item.QUANTITY_ADD);
              } */
          },
          checkAnalog: function (item = null) {
              let window_width = (isMobile.any()) ? window.outerWidth : (window.outerWidth / 2);
              if (typeof window.PopupWindowManagerAnalogs == 'undefined') {
                  window.PopupWindowManagerAnalogs = {};
              }
              if (typeof item != 'object' && item != undefined) {
                  item = this.items[item];
              }
              if (item.PRODUCT_ID == undefined && this.PRODUCT_ID != undefined) {
                  item = this;
              }
              if (item.PRODUCT_ID == undefined) {
                  window.PopupWindowManagerAnalogs['analogs-error'] = BX.PopupWindowManager.create(null, null, {
                      width: window_width, // ширина окна
                      content: '',
                      closeIcon: {
                          right: "20px",
                          top: "10px",
                          opacity: "0"
                      },
                      titleBar: {
                          content: BX.create("span", {
                              html: '<h1 class="h4 py-2 text-center">Ошибка подбора аналога!</h1>',
                              'props': {
                                  'className': 'basketConfirmer-title-bar'
                              }
                          })
                      },
                      zIndex: 0,
                      offsetLeft: 0,
                      offsetTop: -(window.outerHeight / 4),
                      closeByEsc: true, // закрытие окна по esc
                      darkMode: false, // окно будет светлым или темным
                      lightShadow: false, // использовать светлую тень у окна
                      autoHide: true, // закрытие при клике вне окна
                      draggable: {
                          restrict: false
                      }, // можно двигать или нет
                      resizable: true, // можно ресайзить
                      min_height: 100, // минимальная высота окна
                      min_width: 100, // минимальная ширина окна
                      // angle: true, // появится уголок
                      overlay: {
                          backgroundColor: '#333',
                          opacity: 500
                      },
                      buttons: [
                          new BX.PopupWindowButton({
                              text: "Закрыть",
                              className: "popup-window-button-accept",
                              events: {
                                  click: function () {
                                      BX.onCustomEvent("OnAnalogWindowClose");
                                      this.popupWindow.close();
                                  }
                              }
                          }),
                      ],
                      events: {
                          onPopupClose: function () {
                              BX.onCustomEvent("OnAnalogWindowClose");
                          }
                      }
                  });
                  window.PopupWindowManagerAnalogs['analogs-error'].show();
              } else {
                  let uniq_id = "basketAnalogs-message-" + item.ID,
                      arResult = {
                          "ID": item.PRODUCT_ID,
                          "ANALOGS": item.ANALOGS
                      };
                  if (typeof window.PopupWindowManagerAnalogs[uniq_id] == 'undefined') {
                      window.PopupWindowManagerAnalogs[uniq_id] = BX.PopupWindowManager.create(uniq_id, null, {
                          width: window_width, // ширина окна
                          content: '<div class="d-flex justify-content-center"><div class="spinner-border" role="status"><span class="sr-only">Loading...</span></div></div>',
                          closeIcon: {
                              right: "20px",
                              top: "10px",
                              opacity: "1"
                          },
                          titleBar: {
                              content: BX.create("span", {
                                  html: '<h1 class="h4 py-2 text-center">Заказываемого товара не достаточно на складе, подбираем аналог... "' /*+ (item.XML_ID.replace(/.*#/, '') || item.NAME)*/ + '"</h1>',
                                  'props': {
                                      'className': 'basketConfirmer-title-bar'
                                  }
                              })
                          },
                          zIndex: 0,
                          offsetLeft: 0,
                          offsetTop: -(window.outerHeight / 4),
                          closeByEsc: true, // закрытие окна по esc
                          darkMode: false, // окно будет светлым или темным
                          autoHide: true, // закрытие при клике вне окна
                          draggable: {
                              restrict: false
                          }, // можно двигать или нет
                          resizable: true, // можно ресайзить
                          min_height: 100, // минимальная высота окна
                          min_width: 100, // минимальная ширина окна
                          lightShadow: true, // использовать светлую тень у окна
                          // angle: true, // появится уголок
                          overlay: {
                              backgroundColor: '#333',
                              opacity: 500
                          },
                          buttons: [
                              /* new BX.PopupWindowButton({
                                  text: "Распределить",
                                  className: "popup-window-button-link",
                                  events: {click: function(){
                                      console.log(this);
                                      console.log(window.PopupWindowManagerAnalogs[uniq_id]);
                                      // $(window.PopupWindowManagerAnalogs[uniq_id].contentContainer).find("#item-analogs").find("input[name='quantity']");
                                      // this.popupWindow.close();
                                  }}
                              }), */
                              new BX.PopupWindowButton({
                                  text: "Применить",
                                  className: "popup-window-button-accept",
                                  events: {
                                      click: function () {
                                          BX.onCustomEvent("OnAnalogWindowAccept");
                                          let fields = BX.findChild(BX(uniq_id), {
                                              tag: 'input',
                                              attribute: {
                                                  "name": "quantity"
                                              }
                                          }, true, true);
                                          fields.forEach(function (field, i) {
                                              if (BX(field).getAttribute("data-addtobasket-action") == "N") BX(field).setAttribute("data-addtobasket-action", "Y");
                                              if (BX(field).value != "") BX.fireEvent(BX(field), "change");
                                          });
                                          // hide-analog-optionstoggle
                                          let hideBasketCheckAnalog = BX.findChild(BX(uniq_id), {
                                              tag: 'input',
                                              attribute: {
                                                  "name": "hidebasketcheckanalog"
                                              },
                                              property: "checked"
                                          }, true);
                                          if (hideBasketCheckAnalog != null) {
                                              BX.userOptions.save("bitrix_catalog", "check_analogs", "hide_visual_analog_" + userStore.getters['basket/getBasketId'], "1");
                                          }
                                          // BX.Sale.BasketComponent.sendRequest('refreshAjax', {
                                          //     basket: BX.Sale.BasketComponent.actionPool.getPoolData()
                                          // });
                                          // $(window.PopupWindowManagerAnalogs[uniq_id].contentContainer).find("#item-analogs").find("input[name='quantity']");
                                          this.popupWindow.close();
                                      }
                                  }
                              }),
                              new BX.PopupWindowButton({
                                  text: "Отменить",
                                  className: "popup-button-link-cancel",
                                  events: {
                                      click: function () {
                                          BX.onCustomEvent("OnAnalogWindowClose");
                                          this.popupWindow.close();
                                      }
                                  }
                              }) /**/
                          ],
                          events: {
                              onPopupClose: function () {
                                  BX.onCustomEvent("OnAnalogWindowClose");
                              }
                          }
                      });
                      window.PopupWindowManagerAnalogs[uniq_id].show();
                      BX.ajax({
                          url: '/ajax/analogs.php?SKU_PRODUCT_ID=' + item.PRODUCT_ID,
                          data: arResult,
                          method: 'POST',
                          dataType: 'html',
                          timeout: 30,
                          async: true,
                          processData: true,
                          scriptsRunFirst: false,
                          emulateOnload: true,
                          start: true,
                          cache: false,
                          onsuccess: function (data) {
                              window.PopupWindowManagerAnalogs[uniq_id].contentContainer.innerHTML = data;
                              $(window).lazyLoadXT(); // ленивая загрузка фото
                          },
                          onfailure: function (data) {
                              window.PopupWindowManagerAnalogs[uniq_id].contentContainer.innerHTML = data;
                              $(window).lazyLoadXT(); // ленивая загрузка фото
                          }
                      });
                  } else {
                      window.PopupWindowManagerAnalogs[uniq_id].show();
                  }
              }
          },
          checkAnalogs: function () {
              let items = Object.keys(this.items);
              if (items) {
                  for (var i = 0; i < items.length; i++) {
                      this.checkAnalog(this.items[items[i]]);
                  }
              }
          },
          setWhait: function () {
              let item = this;
              //
              if (item.ID) {
                  var wait_from_rc = BX(event.target);
                  let data = {
                      "ITEM_ID": item.ID,
                      "CODE": 'WHAIT_FROM_RC',
                      // "VALUE": BX(this.ids.quantity+item.ID).value,
                      "ACTION": BX.hasClass(wait_from_rc, 'far') ? "ADD" : "DEL",
                  }
                  // this.loaderNodeId = this.ids.basketRoot;
                  // this.sendRequestLoader = BX.showWait(this.loaderNodeId);
                  BX.ajax({
                      method: 'POST',
                      dataType: 'json',
                      timeout: 30,
                      async: true,
                      processData: true,
                      scriptsRunFirst: false,
                      emulateOnload: true,
                      start: true,
                      url: BX.Sale.BasketComponent.ajaxUrl,
                      data: BX.Sale.BasketComponent.getData(data),
                      onsuccess: BX.delegate(function (result) {
                          if (result == 'success') {
                              if (BX.type.isDomNode(wait_from_rc)) {
                                  if (BX.hasClass(wait_from_rc, 'far')) {
                                      // добавили свойство WAIT_FROM_RC
                                      BX.removeClass(wait_from_rc, 'far');
                                      BX.addClass(wait_from_rc, 'fas');
                                  } else {
                                      // удалили свойство WAIT_FROM_RC
                                      BX.removeClass(wait_from_rc, 'fas');
                                      BX.addClass(wait_from_rc, 'far');
                                  }
                              }
                          }
                          // BX.closeWait(this.loaderNodeId, this.sendRequestLoader);
                          // this.actionPool.doProcessing(false);
  
                          if (!BX.type.isPlainObject(result))
                              return;
  
                          /* this.sendRequest('refreshAjax', {
                              fullRecalculation: 'Y',
                              basket: this.actionPool.getPoolData()
                          }); */
                      }, this),
                      onfailure: BX.delegate(function (error) {
                          console.log(error);
                          // BX.closeWait(this.loaderNodeId, this.sendRequestLoader);
                          BX.Sale.BasketComponent.actionPool.doProcessing(false);
                      }, this)
                  });
              }
          },
          editPostponedBasketItems: function () {
              if (!this.postponedItems.length)
                  return;
  
              var itemsToEdit = [];
  
              for (var i in this.postponedItems) {
                  if (this.postponedItems.hasOwnProperty(i) && this.isItemShown(this.postponedItems[i])) {
                      itemsToEdit.push(this.postponedItems[i]);
                  }
              }
  
              this.postponedItems = [];
              this.editBasketItems(itemsToEdit);
          },
  
          applyQuantityAnimation: function (itemId) {
              var basketItemNode = BX(this.ids.item + itemId);
  
              if (BX.type.isDomNode(basketItemNode) && this.items[itemId]) {
                  if (this.items[itemId].QUANTITY_ANIMATION) {
                      BX.addClass(BX(this.ids.quantity + itemId), 'basket-updated');
                  }
              }
          },
  
          applyPriceAnimation: function () {
              if (!this.priceAnimationData || Object.keys(this.priceAnimationData.start).length === 0)
                  return;
  
              var animationData = this.priceAnimationData,
                  nodeCache = {};
  
              new BX.easing({
                  duration: this.params.USE_PRICE_ANIMATION === 'Y' ? this.duration.priceAnimation : 1,
                  start: animationData.start,
                  finish: animationData.finish,
                  transition: BX.easing.makeEaseOut(BX.easing.transitions.quad),
                  step: BX.delegate(function (state) {
                      for (var nodeId in animationData.start) {
                          if (animationData.start.hasOwnProperty(nodeId)) {
                              if (!nodeCache[nodeId]) {
                                  if (nodeId === this.ids.total) {
                                      nodeCache[nodeId] = this.getEntities(this.getCacheNode(this.ids.basketRoot), this.ids.total);
                                  } else {
                                      var node = BX(nodeId);
                                      nodeCache[nodeId] = node ? [node] : [];
                                  }
                              }
  
                              if (!animationData.int[nodeId]) {
                                  // fix price blinking
                                  state[nodeId] = (state[nodeId] + (state[nodeId] % 1000) / 1000).toFixed(5);
                              }
  
                              for (var i = 0; i < nodeCache[nodeId].length; i++) {
                                  nodeCache[nodeId][i].innerHTML = this.getFormatPrice(state[nodeId], animationData.currency[nodeId]).replace(/\s?\W+\.?$/, "");
                              }
                          }
                      }
                  }, this),
                  complete: BX.delegate(function () {
                      var nodeId, formattedPrice, itemId, type;
  
                      for (nodeId in animationData.start) {
                          if (animationData.start.hasOwnProperty(nodeId)) {
                              formattedPrice = this.getFormatPrice(animationData.finish[nodeId], animationData.currency[nodeId]).replace(/\s?\W+\.?$/, "");
  
                              for (var i = 0; i < nodeCache[nodeId].length; i++) {
                                  nodeCache[nodeId][i].innerHTML = formattedPrice;
                              }
  
                              if (nodeId.indexOf(this.ids.sumPrice) !== -1) {
                                  type = 'SUM_PRICE';
                                  itemId = nodeId.substr(this.ids.sumPrice.length);
                              } else if (nodeId.indexOf(this.ids.price) !== -1) {
                                  type = 'PRICE';
                                  itemId = nodeId.substr(this.ids.price.length);
                              } else if (nodeId.indexOf(this.ids.total) !== -1) {
                                  type = 'TOTAL';
                                  itemId = '';
                              } else {
                                  itemId = '';
                                  type = '';
                              }
  
                              if (BX.type.isNotEmptyString(type)) {
                                  if (itemId) {
                                      this.items[itemId][type] = animationData.finish[nodeId];
                                      delete this.items[itemId][type + '_NEW'];
                                      this.items[itemId][type + '_FORMATED'] = formattedPrice;
                                      delete this.items[itemId][type + '_FORMATED_NEW'];
                                  } else if (type === 'TOTAL') {
                                      this.result.TOTAL_RENDER_DATA.PRICE = animationData.finish[nodeId];
                                      delete this.result.TOTAL_RENDER_DATA.PRICE_NEW;
                                      this.result.TOTAL_RENDER_DATA.PRICE_FORMATED = formattedPrice;
                                      delete this.result.TOTAL_RENDER_DATA.PRICE_FORMATED_NEW;
                                  }
                              }
                          }
                      }
  
                      // this.filter.highlightFoundItems();
                  }, this)
              }).animate();
          },
  
          getFormatPrice: function (price, currency) {
              return BX.Currency.currencyFormat(price, currency, true);
          },
  
          deleteBasketItems: function (items, restore, final) {
              if (!items || !items.length) {
                  return;
              }
              if (typeof userStore == 'object') {
                  for (var i in items) {
                      if (items.hasOwnProperty(i)) {
                          userStore.commit("basket/deleteProduct", { ID: items[i] });
                          let row = BX(this.ids.item + items[i]);
                          if (BX.type.isDomNode(row)) {
                              BX.addClass(row, 'removed');
                              setTimeout(() => { BX.remove(row); }, 100);
                          }
                      }
                  }
              } else {
                  for (var i in items) {
                      if (items.hasOwnProperty(i)) {
                          this.deleteBasketItem(items[i], restore, final);
                      }
                  }
              }
          },
          deleteBasketItem: function (itemId, restore, final) {
              // TODO добавить возможность восстановить товар без удаления
              let itemData = this.items[itemId];
              if (itemData == undefined && this.params.GRID_ID) {
                  let item_product_id = BX.findChild(BX(this.params.GRID_ID), {
                      "attribute": {
                          'data-id': itemId
                      }
                  }, true).getAttribute('data-grid-item_id');
                  for (let i in this.items) {
                      if (this.items[i].PRODUCT_ID == item_product_id) {
                          itemData = this.items[i];
                      }
                  }
              }
              if (itemData == undefined) {
                  if (BX('support-chat-link') != undefined) {
                      BX.UI.Notification.Center.notify({
                          content: "Ошибка удаления, пожалуйста, сообщите в поддержку.",
                          position: "bottom-right",
                          autoHideDelay: 5000,
                          closeButton: true,
                          category: "basket-clear-one",
                          actions: [{
                              title: "Сообщить",
                              events: {
                                  click: function (event, balloon, action) {
                                      window.open(BX('support-chat-link').href);
                                  }
                              }
                          },
                          {
                              title: "Закрыть",
                              events: {
                                  click: function (event, balloon, action) {
                                      balloon.close();
                                  }
                              }
                          }
                          ]
                      });
                  } else {
                      BX.UI.Notification.Center.notify({
                          content: "Ошибка удаления, пожалуйста, сообщите в поддержку.",
                          position: "bottom-right",
                          autoHideDelay: 3000,
                          closeButton: true,
                          category: "basket-clear-one",
                          actions: [{
                              title: "Закрыть",
                              events: {
                                  click: function (event, balloon, action) {
                                      balloon.close();
                                  }
                              }
                          }]
                      });
                  }
              }
              // delete not available item with no chance to restore
              if (itemData.NOT_AVAILABLE && restore) {
                  restore = false;
                  final = true;
              }
  
              if (restore) {
                  itemData.SHOW_RESTORE = true;
                  itemData.SHOW_LOADING = false;
                  this.redrawBasketItemNode(itemId);
              } else {
                  this.changeShownItem(itemId);
                  BX.remove(BX(this.ids.item + itemId));
                  if (final == undefined) {
                      final = true;
                  }
              }
  
              if (final) {
                  this.actionPool.deleteItem(itemData.ID);
                  // BX.onCustomEvent('OnBasketChange');
                  // this.changeSortedItem(itemId, false, true);
                  // this.changeShownItem(itemId, false, true);
              }
          },
  
          addSortedItem: function (itemId, all) {
              this.sortedItems.push(itemId.toString());
  
              if (all && this.filter.isActive()) {
                  this.filter.realSortedItems.push(itemId.toString());
              }
          },
  
          changeSortedItem: function (itemId, newItemId, all) {
              var index = BX.util.array_search(itemId, this.sortedItems);
  
              if (index >= 0) {
                  if (newItemId) {
                      this.sortedItems.splice(index, 1, newItemId.toString());
                  } else {
                      this.sortedItems.splice(index, 1);
                  }
              }
  
              if (all && this.filter.isActive()) {
                  index = BX.util.array_search(itemId, this.filter.realSortedItems);
  
                  if (index >= 0) {
                      if (newItemId) {
                          this.filter.realSortedItems.splice(index, 1, newItemId.toString());
                      } else {
                          this.filter.realSortedItems.splice(index, 1);
                      }
                  }
              }
          },
  
          sortSortedItems: function (all) {
              this.sortedItems.sort(BX.proxy(this.itemSortFunction, this));
  
              if (all && this.filter.isActive()) {
                  this.filter.realSortedItems.sort(BX.proxy(this.itemSortFunction, this));
              }
          },
  
          changeShownItem: function (itemId, newItemId, all) {
              var index = BX.util.array_search(itemId, this.shownItems);
  
              if (index >= 0) {
                  if (newItemId) {
                      this.shownItems.splice(index, 1, newItemId.toString());
                  } else {
                      this.shownItems.splice(index, 1);
                  }
              }
  
              if (all && this.filter.isActive()) {
                  index = BX.util.array_search(itemId, this.filter.realShownItems);
  
                  if (index >= 0) {
                      if (newItemId) {
                          this.filter.realShownItems.splice(index, 1, newItemId.toString());
                      } else {
                          this.filter.realShownItems.splice(index, 1);
                      }
                  }
              }
          },
  
          redrawBasketItemNode: function (itemId) {
              var basketItemNode = BX(this.ids.item + itemId);
  
              if (!this.items[itemId] || !BX.type.isDomNode(basketItemNode))
                  return;
  
              var basketItemTemplate = this.getTemplate('basket-item-template');
              if (basketItemTemplate) {
                  var nodeAligner = BX(this.ids.itemHeightAligner + itemId),
                      oldHeight;
  
                  if (BX.type.isDomNode(nodeAligner)) {
                      oldHeight = nodeAligner.clientHeight;
                  }
  
                  var basketItemHtml = this.renderBasketItem(basketItemTemplate, this.items[itemId]);
                  basketItemNode.insertAdjacentHTML('beforebegin', basketItemHtml);
                  BX.remove(basketItemNode);
  
                  if (oldHeight) {
                      nodeAligner = BX(this.ids.itemHeightAligner + itemId);
  
                      if (BX.type.isDomNode(nodeAligner) && nodeAligner.clientHeight < oldHeight) {
                          nodeAligner.style.minHeight = oldHeight + 'px';
                          setTimeout(function () {
                              nodeAligner.style.minHeight = '0px';
                          }, 1);
                      }
                  }
  
                  this.bindBasketItemEvents(this.items[itemId]);
  
                  if (this.filter.isActive()) {
                      this.filter.highlightSearchMatch(this.items[itemId]);
                  }
              } else {
                  var itemRow = BX(this.ids.item + itemId);
  
                  if (BX.type.isDomNode(itemRow)) {
                      // itemRow;
                  }
              }
          },
          newBasketItems: function (items) {
              if (!items || Object.keys(items).length === 0) {
                  return;
              }
  
              var newItem,
                  basketItemListNode = BX.findChild(BX(this.ids.itemListTable), {
                      "tag": "tbody"
                  });
              for (const i in items) {
                  if (items.hasOwnProperty(i)) {
                      newItem = items[i];
                      // TODO добавляем элемент в список
                      var basketItemTemplate = this.getTemplate('basket-item-template');
                      if (basketItemTemplate) {
                          newItem.WARNINGS = [];
                          newItem.SHOW_RESTORE = false;
                          this.sortedItems.push(newItem.ID);
                          this.shownItems.push(newItem.ID);
                          var basketItemHtml = this.renderBasketItem(basketItemTemplate, newItem);
                          basketItemListNode.insertAdjacentHTML('beforeend', basketItemHtml);
                          this.items[newItem.ID] = newItem;
                          this.bindBasketItemEvents(newItem);
                          this.checkMark(newItem);
                          if (this.filter.isActive()) {
                              this.filter.highlightSearchMatch(newItem);
                          }
                      }
                  }
              }
          },
          restoreBasketItems: function (items) {
              if (!items || Object.keys(items).length === 0) {
                  return;
              }
  
              var oldItemId, newItemId, basketItemNode;
  
              for (oldItemId in items) {
                  if (items.hasOwnProperty(oldItemId)) {
                      newItemId = items[oldItemId];
  
                      if (this.isItemShown(oldItemId)) {
                          this.changeShownItem(oldItemId, newItemId, true);
  
                          basketItemNode = BX(this.ids.item + oldItemId);
                          if (BX.type.isDomNode(basketItemNode)) {
                              basketItemNode.id = this.ids.item + newItemId;
                              basketItemNode.setAttribute('data-id', newItemId);
                          }
                      }
  
                      this.changeSortedItem(oldItemId, false, true);
                  }
              }
          },
  
          bindBasketItemEvents: function (itemData) {
              if (!itemData)
                  return;
  
              // var itemNode = BX(this.ids.item + itemData.ID);
              // if (BX.type.isDomNode(itemNode)) {
              //     this.bindQuantityEvents(itemNode, itemData);
              //     this.bindSkuEvents(itemNode, itemData);
              //     this.bindImageEvents(itemNode, itemData);
              //     this.bindActionEvents(itemNode, itemData);
              //     this.bindRestoreAction(itemNode, itemData);
              //     this.bindItemWarningEvents(itemNode, itemData);
              // }
          },
  
          bindQuantityEvents: function (node, data) {
              if (!node || !data || !this.isItemAvailable(data.ID))
                  return;
  
              var entity;
  
              var block = this.getEntity(node, 'basket-item-quantity-block');
              if (block) {
                  var startEventName = this.isTouch ? 'touchstart' : 'mousedown';
                  var endEventName = this.isTouch ? 'touchend' : 'mouseup';
  
                  entity = this.getEntity(block, 'basket-item-quantity-minus');
                  BX.bind(entity, startEventName, BX.proxy(this.startQuantityInterval, this));
                  BX.bind(entity, endEventName, BX.proxy(this.clearQuantityInterval, this));
                  BX.bind(entity, 'mouseout', BX.proxy(this.clearQuantityInterval, this));
                  BX.bind(entity, 'click', BX.proxy(this.quantityMinus, this));
  
                  entity = this.getEntity(block, 'basket-item-quantity-plus');
                  BX.bind(entity, startEventName, BX.proxy(this.startQuantityInterval, this));
                  BX.bind(entity, endEventName, BX.proxy(this.clearQuantityInterval, this));
                  BX.bind(entity, 'mouseout', BX.proxy(this.clearQuantityInterval, this));
                  BX.bind(entity, 'click', BX.proxy(this.quantityPlus, this));
  
                  entity = this.getEntity(block, 'basket-item-quantity-field');
                  BX.bind(entity, 'keypress', BX.proxy(this.quantityChangeStop, this));
                  BX.bind(entity, 'change', BX.proxy(this.quantityChange, this));
                  BX.bind(entity, 'keyup', BX.proxy(this.nextQuantityItem, this));
              }
          },
  
          startQuantityInterval: function () {
              var target = BX.proxy_context;
              var func = target.getAttribute('data-entity') === 'basket-item-quantity-minus' ?
                  BX.proxy(this.quantityMinus, this) :
                  BX.proxy(this.quantityPlus, this);
  
              this.quantityDelay = setTimeout(
                  BX.delegate(function () {
                      this.quantityTimer = setInterval(function () {
                          func(target);
                      }, 150);
                  }, this),
                  300
              );
          },
  
          clearQuantityInterval: function () {
              clearTimeout(this.quantityDelay);
              clearInterval(this.quantityTimer);
          },
  
          quantityPlus: function (target) {
              if (!BX.type.isDomNode(target)) {
                  target = BX.proxy_context;
                  this.clearQuantityInterval();
              }
  
              var itemData = this.getItemDataByTarget(target);
              if (itemData) {
                  var quantityField = BX(this.ids.quantity + itemData.ID);
                  var isQuantityFloat = this.isQuantityFloat(itemData);
  
                  var currentQuantity = isQuantityFloat ? parseFloat(quantityField.value) : Math.round(quantityField.value);
                  var measureRatio = isQuantityFloat ? parseFloat(itemData.MEASURE_RATIO) : parseInt(itemData.MEASURE_RATIO);
                  if (!measureRatio) measureRatio = 1;
  
                  var quantity = parseFloat((currentQuantity + measureRatio).toFixed(5));
                  quantity = this.getCorrectQuantity(itemData, quantity);
  
                  this.setQuantity(itemData, quantity);
              }
          },
  
          quantityMinus: function (target) {
              target = BX.type.isDomNode(target) ? target : BX.proxy_context;
  
              var itemData = this.getItemDataByTarget(target);
              if (itemData) {
                  var quantityField = BX(this.ids.quantity + itemData.ID);
                  var isQuantityFloat = this.isQuantityFloat(itemData);
  
                  var currentQuantity = isQuantityFloat ? parseFloat(quantityField.value) : Math.round(quantityField.value);
                  var measureRatio = isQuantityFloat ? parseFloat(itemData.MEASURE_RATIO) : parseInt(itemData.MEASURE_RATIO);
                  if (!measureRatio) measureRatio = 1;
  
                  var quantity = parseFloat((currentQuantity - measureRatio).toFixed(5));
                  quantity = this.getCorrectQuantity(itemData, quantity);
  
                  this.setQuantity(itemData, quantity);
              }
          },
  
          quantityChangeStop: function () {
              if (event.keyCode == 13) {
                  event.preventDefault();
                  event.stopPropagation();
                  this.quantityChange();
              }
          },
  
          quantityChange: function () {
              var itemData = this.getItemDataByTarget(BX.proxy_context);
              if (itemData) {
                  var quantityField, quantity;
  
                  quantityField = BX(this.ids.quantity + itemData.ID);
                  quantity = this.getCorrectQuantity(itemData, quantityField.value);
                  if (quantity >= this.maxQuantityAdd ||
                      (itemData.PRICE * quantity) >= this.maxPriceAdd
                  ) {
                      quantity = this.requestQuantityConfirmation(itemData, quantity);
                  }
                  this.setQuantity(itemData, quantity);
              }
          },
  
          requestQuantityConfirmation: function (itemData, quantity) {
              let product = '';
              let confirmed = null;
              if (itemData.NAME) {
                  var parser = new DOMParser;
                  var dom = parser.parseFromString('<!doctype html><body>' + itemData.NAME, 'text/html');
                  var decodedString = dom.body.textContent.replace(/<[^>]+>/g, '');
                  product = ' товара `' + decodedString + ' ' + (itemData.PREVIEW_TEXT || '') + '`';
              }
              // TODO вынести фразу в параметры компонентов
              if (userStore != undefined &&
                  userStore.getters['basket/getContragent'].UF_VALYUTAOTGRUZKI != undefined &&
                  userStore.getters['basket/getContragent'].UF_VALYUTAOTGRUZKI.CURRENCY_NAME
              ) {
                  confirmed = confirm("Уверены что хотите добавить " + quantity + "шт" + product + " на сумму " + BX.Currency.currencyFormat(parseFloat(itemData.PRICE) * quantity, userStore.getters['basket/getContragent'].UF_VALYUTAOTGRUZKI.CURRENCY_NAME, true).replace(/&nbsp;/gi, ' ') + "?");
              } else {
                  confirmed = confirm("Уверены что хотите добавить " + quantity + "шт" + product + " на сумму " + (parseFloat(itemData.PRICE) * quantity) + "?");
              }
              parser = null;
              product = null;
              dom = null;
              decodedString = null;
              if (!confirmed) {
                  return itemData.QUANTITY;
              }
              return quantity;
          },
  
          nextQuantityItem: function () {
              // след поле ввода
              var code = event.keyCode || event.which;
              // if (code === 13) {
              //     var itemData = this.getItemDataByTarget(BX.proxy_context);
              //     if (itemData)
              //     {
              //         let keys = Object.keys(this.items);
              //         let nextIndex = keys.indexOf(itemData.ID) +1;
              //         let nextItem_ID = keys[nextIndex];
              //         let block = BX(this.ids.item + nextItem_ID);
              //         let entity = this.getEntity(block, 'basket-item-quantity-field');
              //         entity.focus();
              //     }
              // }
          },
  
          isQuantityFloat: function (item) {
              return this.params.QUANTITY_FLOAT === 'Y' || (item.MEASURE_RATIO && parseInt(item.MEASURE_RATIO) !== parseFloat(item.MEASURE_RATIO));
          },
  
          getCorrectQuantity: function (itemData, quantity) {
              var isQuantityFloat = this.isQuantityFloat(itemData),
                  measureRatio = isQuantityFloat ? parseFloat(itemData.MEASURE_RATIO) : parseInt(itemData.MEASURE_RATIO),
                  availableQuantity = 0;
  
              quantity = (isQuantityFloat ? parseFloat(quantity) : parseInt(quantity, 10)) || 0;
              if (quantity < 0) {
                  quantity = 0;
              }
  
              if (measureRatio > 0 && quantity < measureRatio) {
                  quantity = measureRatio;
              }
  
              if (itemData.CHECK_MAX_QUANTITY === 'Y') {
                  availableQuantity = isQuantityFloat ? parseFloat(itemData.AVAILABLE_QUANTITY) : parseInt(itemData.AVAILABLE_QUANTITY);
                  if (availableQuantity > 0 && quantity > availableQuantity) {
                      quantity = availableQuantity;
                  }
              }
  
              var reminder = (quantity / measureRatio - ((quantity / measureRatio).toFixed(0))).toFixed(5),
                  remain;
  
              if (parseFloat(reminder) === 0) {
                  return quantity;
              }
  
              if (measureRatio !== 0 && measureRatio !== 1) {
                  remain = (quantity * this.precisionFactor) % (measureRatio * this.precisionFactor) / this.precisionFactor;
  
                  if (measureRatio > 0 && remain > 0) {
                      if (
                          remain >= measureRatio / 2 &&
                          (
                              availableQuantity === 0 ||
                              (quantity + measureRatio - remain) <= availableQuantity
                          )
                      ) {
                          quantity += (measureRatio - remain);
                      } else {
                          quantity -= remain;
                      }
                  }
              }
  
              quantity = isQuantityFloat ? parseFloat(quantity) : parseInt(quantity, 10);
  
              return quantity;
          },
  
          setQuantity: function (itemData, quantity) {
              var quantityField = BX(this.ids.quantity + itemData.ID),
                  currentQuantity;
  
              if (quantityField) {
                  quantity = parseFloat(quantity);
                  currentQuantity = parseFloat(quantityField.getAttribute('data-value'));
  
                  quantityField.value = quantity;
  
                  if (parseFloat(itemData.QUANTITY) !== parseFloat(quantity)) {
                      this.animatePriceByQuantity(itemData, quantity);
                      this.actionPool.changeQuantity(itemData.ID, quantity, currentQuantity);
                  }
              }
              event && event.stopPropagation() && event.preventDefault();
          },
  
          animatePriceByQuantity: function (itemData, quantity) {
              var priceNode = BX(this.ids.sumPrice + itemData.ID);
              if (!BX.type.isDomNode(priceNode))
                  return;
  
              if (!itemData.MEASURE_RATIO) itemData.MEASURE_RATIO = 1;
  
              var quantityMultiplier = quantity / parseFloat(itemData.MEASURE_RATIO);
  
              var startPrice = parseFloat(itemData.SUM_PRICE) || parseFloat(priceNode.textContent),
                  finalPrice = (parseFloat(itemData.PRICE) * quantityMultiplier).toFixed(2),
                  isInt = parseInt(startPrice) === parseFloat(startPrice) &&
                      parseInt(finalPrice) === parseFloat(finalPrice);
  
              if (startPrice !== finalPrice) {
                  this.items[itemData.ID].QUANTITY = quantity;
                  this.items[itemData.ID].SUM_PRICE = finalPrice;
  
                  new BX.easing({
                      duration: this.params.USE_PRICE_ANIMATION === 'Y' ? this.duration.priceAnimation : 1,
                      start: {
                          price: startPrice
                      },
                      finish: {
                          price: finalPrice
                      },
                      transition: BX.easing.makeEaseOut(BX.easing.transitions.quad),
                      step: BX.delegate(function (state) {
                          if (!isInt) {
                              // fix price blinking
                              state.price = (state.price + (state.price % 1000) / 1000).toFixed(5);
                          }
                          priceNode.innerHTML = (this.getFormatPrice(state.price, itemData.CURRENCY)).replace(/\s?\W+\.?$/, "");
                      }, this),
                      complete: BX.delegate(function () {
                          var node, price;
  
                          priceNode.innerHTML = (this.getFormatPrice(finalPrice, itemData.CURRENCY)).replace(/\s?\W+\.?$/, "");
  
                          node = BX(this.ids.sumPriceOld + itemData.ID);
                          if (BX.type.isDomNode(node)) {
                              price = parseFloat(itemData.FULL_PRICE) * quantityMultiplier;
                              node.innerHTML = (this.getFormatPrice(price, itemData.CURRENCY)).replace(/\s?\W+\.?$/, "");
                          }
  
                          node = BX(this.ids.sumPriceDiff + itemData.ID);
                          if (BX.type.isDomNode(node)) {
                              price = parseFloat(itemData.DISCOUNT_PRICE) * quantityMultiplier;
                              node.innerHTML = (this.getFormatPrice(price, itemData.CURRENCY)).replace(/\s?\W+\.?$/, "");
                          }
                      }, this)
                  }).animate();
              }
          },
  
          getItemDataByTarget: function (target) {
              var data = false;
              var id;
  
              var itemNode = BX.findParent(target, {
                  attrs: {
                      'data-entity': 'basket-item'
                  }
              });
              if (itemNode) {
                  id = itemNode.getAttribute('data-id');
                  data = this.items[id];
              } else {
                  itemNode = BX.findParent(target, {
                      "tag": "tr",
                      "class": 'main-grid-row'
                  });
                  if (itemNode) {
                      id = itemNode.getAttribute('data-id');
                      data = this.items[id];
                      if (!data) {
                          data = this.result.SELECT_RESULT_ALL[id];
                      }
                      this.items[data.ID] = data;
                  }
              }
  
              return data;
          },
  
          bindSkuEvents: function (node, data) {
              if (!node || !data)
                  return;
  
              var blocks = this.getEntities(node, 'basket-item-sku-block');
              var blockEntities, i, l, ii, ll;
  
              for (i = 0, l = blocks.length; i < l; i++) {
                  blockEntities = this.getEntities(blocks[i], 'basket-item-sku-field');
  
                  for (ii = 0, ll = blockEntities.length; ii < ll; ii++) {
                      BX.bind(blockEntities[ii], 'click', BX.proxy(this.changeSku, this));
                  }
              }
          },
  
          changeSku: function () {
              var i, l;
  
              var target = BX.proxy_context;
  
              if (BX.hasClass(target, 'selected'))
                  return;
  
              var itemData = this.getItemDataByTarget(target);
              if (itemData) {
                  var basketItemNode = BX(this.ids.item + itemData.ID);
                  if (basketItemNode) {
                      var currentSkuListNodes = this.getEntities(target.parentNode, 'basket-item-sku-field');
                      for (i = 0, l = currentSkuListNodes.length; i < l; i++) {
                          if (currentSkuListNodes[i].isEqualNode(target)) {
                              BX.addClass(currentSkuListNodes[i], 'selected');
                          } else {
                              BX.removeClass(currentSkuListNodes[i], 'selected');
                          }
                      }
  
                      this.actionPool.changeSku(
                          itemData.ID,
                          this.getSkuPropertyValues(basketItemNode),
                          this.getInitialSkuPropertyValues(basketItemNode)
                      );
                  }
              }
          },
  
          getSkuPropertyValues: function (basketItemNode) {
              var propertyValues = {};
  
              var propNodes = this.getEntities(basketItemNode, 'basket-item-sku-field', '.selected');
              for (var i = 0, l = propNodes.length; i < l; i++) {
                  propertyValues[propNodes[i].getAttribute('data-property')] = BX.util.htmlspecialcharsback(propNodes[i].getAttribute('data-value-id'));
              }
  
              return propertyValues;
          },
  
          getInitialSkuPropertyValues: function (basketItemNode) {
              var propertyValues = {};
  
              var propNodes = this.getEntities(basketItemNode, 'basket-item-sku-field', '[data-initial="true"]');
              for (var i = 0, l = propNodes.length; i < l; i++) {
                  propertyValues[propNodes[i].getAttribute('data-property')] = BX.util.htmlspecialcharsback(propNodes[i].getAttribute('data-value-id'));
              }
  
              return propertyValues;
          },
  
          bindImageEvents: function (node, data) {
              if (!node || !data)
                  return;
  
              var images = node.querySelectorAll('.basket-item-custom-block-photo-item');
              for (var i = 0, l = images.length; i < l; i++) {
                  BX.bind(images[i], 'click', BX.proxy(this.showPropertyImagePopup, this));
              }
          },
  
          showPropertyImagePopup: function () {
              var target, propertyCode, imageIndex, item, imageSrc, i;
  
              target = BX.proxy_context;
              item = this.getItemDataByTarget(target);
  
              propertyCode = target.getAttribute('data-column-property-code');
              imageIndex = target.getAttribute('data-image-index');
  
              if (item && item.COLUMN_LIST) {
                  for (i in item.COLUMN_LIST) {
                      if (
                          item.COLUMN_LIST.hasOwnProperty(i) &&
                          item.COLUMN_LIST[i].CODE === propertyCode &&
                          item.COLUMN_LIST[i].VALUE[imageIndex]
                      ) {
                          imageSrc = item.COLUMN_LIST[i].VALUE[imageIndex].IMAGE_SRC_ORIGINAL;
                          break;
                      }
                  }
              }
  
              if (!imageSrc) {
                  return;
              }
  
              if (this.imagePopup) {
                  this.imagePopup.destroy();
              }
  
              var imageId = 'bx-soa-image-popup-content';
              var that = this;
  
              this.imagePopup = new BX.PopupWindow('bx-soa-image-popup', null, {
                  lightShadow: true,
                  offsetTop: 0,
                  offsetLeft: 0,
                  closeIcon: {
                      top: '3px',
                      right: '10px'
                  },
                  autoHide: true,
                  bindOptions: {
                      position: 'bottom'
                  },
                  closeByEsc: true,
                  zIndex: 100,
                  events: {
                      onPopupShow: function () {
                          BX.create('IMG', {
                              props: {
                                  src: imageSrc
                              },
                              events: {
                                  load: function () {
                                      var content = BX(imageId);
                                      if (content) {
                                          var windowSize = BX.GetWindowInnerSize(),
                                              ratio = that.isMobile ? 0.5 : 0.9,
                                              contentHeight, contentWidth;
  
                                          BX.cleanNode(content);
                                          content.appendChild(this);
  
                                          contentHeight = content.offsetHeight;
                                          contentWidth = content.offsetWidth;
  
                                          if (contentHeight > windowSize.innerHeight * ratio) {
                                              content.style.height = windowSize.innerHeight * ratio + 'px';
                                              content.style.width = contentWidth * (windowSize.innerHeight * ratio / contentHeight) + 'px';
                                              contentHeight = content.offsetHeight;
                                              contentWidth = content.offsetWidth;
                                          }
  
                                          if (contentWidth > windowSize.innerWidth * ratio) {
                                              content.style.width = windowSize.innerWidth * ratio + 'px';
                                              content.style.height = contentHeight * (windowSize.innerWidth * ratio / contentWidth) + 'px';
                                          }
  
                                          content.style.height = content.offsetHeight + 'px';
                                          content.style.width = content.offsetWidth + 'px';
  
                                          that.imagePopup.adjustPosition();
                                      }
                                  }
                              }
                          });
                      },
                      onPopupClose: function () {
                          this.destroy();
                      }
                  },
                  content: BX.create('DIV', {
                      props: {
                          id: imageId
                      }
                  })
              });
              this.imagePopup.show();
          },
  
          bindActionEvents: function (node, data) {
              if (!node || !data)
                  return;
  
              var entity;
              if (BX.util.in_array('DELETE', this.params.COLUMNS_LIST)) {
                  entity = this.getEntities(node, 'basket-item-delete');
                  for (var i = 0, l = entity.length; i < l; i++) {
                      BX.bind(entity[i], 'click', BX.proxy(this.deleteAction, this));
                  }
              }
  
              if (BX.util.in_array('DELAY', this.params.COLUMNS_LIST)) {
                  entity = this.getEntity(node, 'basket-item-add-delayed');
                  BX.bind(entity, 'click', BX.proxy(this.addDelayedAction, this));
              }
  
              entity = this.getEntity(node, 'basket-item-remove-delayed');
              BX.bind(entity, 'click', BX.proxy(this.removeDelayedAction, this));
  
              entity = this.getEntity(node, 'basket-item-merge-sku-link');
              BX.bind(entity, 'click', BX.proxy(this.mergeAction, this));
  
              entity = this.getEntity(node, 'basket-item-show-similar-link');
              BX.bind(entity, 'click', BX.delegate(function () {
                  this.toggleFilter('similar');
              }, this));
          },
  
          addAction: function (itemData) {
              var itemData = this.getItemDataByTarget(BX.proxy_context);
              if (itemData) {
                  this.actionPool.addItem(itemData.ID);
                  this.items[itemData.ID].SHOW_LOADING = false;
                  this.redrawBasketItemNode(itemData.ID);
              }
          },
  
          deleteAction: function () {
              var itemData = this.getItemDataByTarget(BX.proxy_context);
              if (itemData) {
                  this.actionPool.deleteItem(itemData.ID);
  
                  this.items[itemData.ID].SHOW_LOADING = true;
  
                  if (this.params.SHOW_RESTORE === 'Y' && this.isItemAvailable(itemData.ID)) {
                      this.items[itemData.ID].SHOW_RESTORE = true;
                  }
  
                  this.redrawBasketItemNode(itemData.ID);
              }
          },
  
          addDelayedAction: function () {
              var itemData = this.getItemDataByTarget(BX.proxy_context);
              if (itemData) {
                  this.actionPool.addDelayed(itemData.ID);
  
                  this.items[itemData.ID].SHOW_LOADING = true;
                  this.redrawBasketItemNode(itemData.ID);
              }
          },
  
          removeDelayedAction: function () {
              var itemData = this.getItemDataByTarget(BX.proxy_context);
              if (itemData) {
                  this.actionPool.removeDelayed(itemData.ID);
  
                  this.items[itemData.ID].SHOW_LOADING = true;
                  this.redrawBasketItemNode(itemData.ID);
              }
          },
  
          mergeAction: function () {
              var itemData = this.getItemDataByTarget(BX.proxy_context);
              if (itemData) {
                  this.actionPool.mergeSku(itemData.ID);
              }
          },
  
          bindRestoreAction: function (node, itemData) {
              if (!node || !itemData || this.params.SHOW_RESTORE !== 'Y')
                  return;
  
              BX.bind(
                  this.getEntity(node, 'basket-item-restore-button'),
                  'click',
                  BX.delegate(function () {
                      this.actionPool.restoreItem(itemData.ID, {
                          PRODUCT_ID: itemData.PRODUCT_ID,
                          QUANTITY: itemData.QUANTITY,
                          PROPS: itemData.PROPS_ALL,
                          SORT: itemData.SORT,
                          MODULE: itemData.MODULE,
                          PRODUCT_PROVIDER_CLASS: itemData.PRODUCT_PROVIDER_CLASS
                      });
  
                      this.items[itemData.ID].SHOW_RESTORE = false;
                      this.items[itemData.ID].SHOW_LOADING = true;
                      this.redrawBasketItemNode(itemData.ID);
                  }, this)
              );
              BX.bind(
                  this.getEntity(node, 'basket-item-close-restore-button'),
                  'click',
                  BX.delegate(function () {
                      this.deleteBasketItem(itemData.ID, false, true);
                  }, this)
              );
          },
  
          bindItemWarningEvents: function (node, data) {
              if (!node || !data)
                  return;
  
              BX.bind(
                  this.getEntity(BX(this.ids.item + data.ID), 'basket-item-warning-close'),
                  'click',
                  BX.proxy(this.closeItemWarnings, this)
              );
          },
  
          closeItemWarnings: function () {
              var target = BX.proxy_context;
  
              if (BX.type.isDomNode(target)) {
                  var itemData = this.getItemDataByTarget(target);
  
                  this.items[itemData.ID].WARNINGS = [];
                  this.warningItems.splice(BX.util.array_search(itemData.ID, this.warningItems), 1);
  
                  this.redrawBasketItemNode(itemData.ID);
                  this.editWarnings();
              }
          },
  
          renderBasketItem: function (template, data) {
              var clonedData = BX.clone(data);
  
              if (BX.type.isPlainObject(clonedData)) {
                  clonedData.USE_FILTER = this.useItemsFilter &&
                      !this.filter.currentFilter.similarHash.length;
              }
  
              return Mustache.render(template, clonedData);
          },
  
          render: function (template, data) {
              return Mustache.render(template, data);
          },
  
          checkAnalytics: function (data) {
              if (!data || !data.basket)
                  return;
  
              var itemId, itemsDiff = {};
  
              for (var i in data.basket) {
                  if (data.basket.hasOwnProperty(i)) {
                      if (i.indexOf('QUANTITY_') >= 0) {
                          itemId = i.substr(9);
  
                          if (this.items[itemId] && BX(this.ids.quantity + itemId)) {
                              itemsDiff[itemId] = parseFloat(data.basket[i]) - parseFloat(BX(this.ids.quantity + itemId).getAttribute('data-value'));
                          }
                      } else if (i.indexOf('DELETE_') >= 0) {
                          itemId = i.substr(7);
  
                          if (this.items[itemId]) {
                              itemsDiff[itemId] = -parseFloat(this.items[itemId].QUANTITY);
                          }
                      } else if (i.indexOf('RESTORE_') >= 0) {
                          itemId = i.substr(8);
  
                          if (this.items[itemId]) {
                              itemsDiff[itemId] = parseFloat(this.items[itemId].QUANTITY);
                          }
                      }
                  }
              }
  
              this.setAnalyticsDataLayer(itemsDiff);
          },
  
          setAnalyticsDataLayer: function (itemsDiff) {
              if (!itemsDiff || Object.keys(itemsDiff).length === 0)
                  return;
  
              window[this.params.DATA_LAYER_NAME] = window[this.params.DATA_LAYER_NAME] || [];
  
              var plus = [],
                  minus = [];
  
              for (var itemId in itemsDiff) {
                  if (itemsDiff.hasOwnProperty(itemId)) {
                      if (itemsDiff[itemId] > 0) {
                          plus.push(this.getItemAnalyticsInfo(itemId, itemsDiff[itemId]));
                      } else if (itemsDiff[itemId] < 0) {
                          minus.push(this.getItemAnalyticsInfo(itemId, itemsDiff[itemId]));
                      }
                  }
              }
  
              if (plus.length) {
                  window[this.params.DATA_LAYER_NAME].push({
                      event: 'addToCart',
                      ecommerce: {
                          currencyCode: this.items[itemId].CURRENCY || '',
                          add: {
                              products: plus
                          }
                      }
                  });
              }
  
              if (minus.length) {
                  window[this.params.DATA_LAYER_NAME].push({
                      event: 'removeFromCart',
                      ecommerce: {
                          currencyCode: this.items[itemId].CURRENCY || '',
                          remove: {
                              products: minus
                          }
                      }
                  });
              }
          },
          setCheckoutAnalytics: function (order) {
              if (order &&
                  order.order_basket &&
                  Object.keys(order.order_basket).length
              ) {
                  let products = [];
                  for (const key in order.order_basket) {
                      if (order.order_basket.hasOwnProperty(key)) {
                          const product = order.order_basket[key];
                          products.push({ // List of productFieldObjects.
                              name: product.NAME, // Name or ID is required.
                              id: product.PRODUCT_ID,
                              price: product.PRICE,
                              brand: product.BRAND,
                              category: product.TYPE,
                              quantity: product.QUANTITY,
                              variant: '',
                              coupon: '', // Optional fields may be omitted or set to empty string.
                              position: product.SORT_NUMBER,
                          });
                      }
                  }
                  window[this.params.DATA_LAYER_NAME].push({
                      event: 'checkout',
                      ecommerce: {
                          purchase: {
                              'actionField': {
                                  'id': order.order_account_number, // Transaction ID. Required for purchases and refunds.
                                  'affiliation': 'FIT24 ' + order.order_store,
                                  'revenue': order.order_price, // Total transaction value (incl. tax and shipping)
                                  'tax': order.order_tax_price,
                                  'shipping': order.order_shipping,
                                  'coupon': order.order_cupon
                              },
                              'products': products
                          }
                      }
                  });
              }
          },
          getItemAnalyticsInfo: function (itemId, diff) {
              if (!this.items[itemId])
                  return {};
  
              var brand = (this.items[itemId].BRAND || '').split(',  ').join('/');
              var variants = [];
  
              var selectedSku = this.getEntities(BX(this.ids.item + itemId), 'basket-item-sku-field', '.selected');
              for (var i = 0, l = selectedSku.length; i < l; i++) {
                  variants.push(selectedSku[i].getAttribute('data-sku-name'));
              }
  
              return {
                  'name': this.items[itemId].NAME || '',
                  'id': this.items[itemId].PRODUCT_ID || '',
                  'price': this.items[itemId].PRICE || 0,
                  'brand': brand,
                  'variant': variants.join('/'),
                  'quantity': Math.abs(diff)
              };
          }
      };
  })();
  