Advertisement
svenpro

Untitled

Jul 21st, 2017
508
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * Nobel script quickSearch widget extend
  3.  *
  4.  * @category  Nobel
  5.  * @package   Nobel\Search
  6.  * @author    Andrii Ravskyi <anrav@smile.fr>
  7.  * @copyright 2017 Smile
  8.  */
  9.  
  10. /*jshint browser:true jquery:true*/
  11. /*global alert*/
  12.  
  13. define([
  14.     'ko',
  15.     'jquery',
  16.     'mage/template',
  17.     'Magento_Customer/js/customer-data',
  18.     'Magento_Catalog/js/price-utils',
  19.     'jquery/ui',
  20.     'mageQuickSearch',
  21.     'Smile_ElasticsuiteCore/js/form-mini',
  22.     'Nobel_CustomerPrice/js/view/custom-customer-prices',
  23.     'underscore',
  24.     "mage/cookies",
  25.     'mage/translate'
  26. ], function (ko, $, mageTemplate, customerData, utils, _) {
  27.     'use strict';
  28.  
  29.     $.widget('nobel.quickSearchUpdate', $.smileEs.quickSearch, {
  30.         options: {
  31.             enableToggleSearch: true,
  32.             ajaxLoader: false,
  33.             elementsSelector: '[data-role=price-amount-element]'
  34.         },
  35.  
  36.         priceTemplate: mageTemplate('<span class="price update-price"><%- priceFormatted %></span>'),
  37.         productAmong: mageTemplate('<span class="product-among">(<%- data.size %>)</span>'),
  38.  
  39.         _create: function () {
  40.             this._switchBetweenTabs();
  41.             if(this.options.enableToggleSearch) {
  42.                 this._toggleSearchField();
  43.             }
  44.             this._super();
  45.             this.element.off('blur');
  46.             this.element.off('mouseleave');
  47.  
  48.         },
  49.  
  50.         /**
  51.          *  Toggle search field after click on icon
  52.          */
  53.         _toggleSearchField: function() {
  54.             $('.toggle-search-icon').on('click', function () {
  55.                 var overlay = $('.search-overlay');
  56.                 if($('.search-autocomplete').is(':hidden')) {
  57.                     overlay.show();
  58.                 } else {
  59.                     overlay.hide();
  60.                 }
  61.                 $('.block-search').toggle();
  62.  
  63.             });
  64.         },
  65.  
  66.  
  67.         /**
  68.          *  Switch between search tabs
  69.          */
  70.         _switchBetweenTabs: function () {
  71.             var self = this;
  72.             $(document).on('click', '.search-toggle .item', function(){
  73.                 self.paramScope = $(this).attr('data-role');
  74.                 $('.search-toggle .item').removeClass('active');
  75.                 $(this).addClass('active');
  76.                 self._onPropertyChange();
  77.             });
  78.         },
  79.  
  80.         /**
  81.          *  Form add to cart 'submit' ajax request
  82.          */
  83.         ajaxSubmit: function(form) {
  84.             $.ajax({
  85.                 url: form.attr('action'),
  86.                 data: form.serialize(),
  87.                 type: 'post',
  88.                 dataType: 'json',
  89.                 showLoader: true
  90.             });
  91.         },
  92.  
  93.         /**
  94.          *  Override to add specific type
  95.          */
  96.         _getSectionHeader: function(type, data) {
  97.             var title = '';
  98.             var header = $('<dl role="listbox" class="autocomplete-list-' + type + '"></dl>');
  99.  
  100.             if (type !== undefined) {
  101.                 title = this._getSectionTitle(type, data);
  102.                 header.append(title);
  103.             }
  104.  
  105.             return header;
  106.         },
  107.  
  108.         /**
  109.          * Add submit event on show all button
  110.          */
  111.         _showAllAction: function(){
  112.             $('.search.autocomplete').on('click', function() {
  113.                 document.getElementById('search_mini_form').submit();
  114.             });
  115.         },
  116.  
  117.         /**
  118.          * Call search search tabs template
  119.          */
  120.         _callSearchTabs: function () {
  121.             var searchToggleTemplate =  mageTemplate('#search-tabs-template');
  122.             $('.smile-elasticsuite-autocomplete-result').prepend(searchToggleTemplate);
  123.         },
  124.  
  125.         /**
  126.          * Call show all button template
  127.          */
  128.         _callShowAll: function () {
  129.             var searchShowAllTemplate =  mageTemplate('#search-show-all');
  130.  
  131.             $('.autocomplete-list-product').append(searchShowAllTemplate);
  132.         },
  133.  
  134.         /**
  135.          * Get search overlay
  136.          */
  137.         getOverlay: function() {
  138.             var body = $('body'),
  139.                 overlay = $('<div></div>').addClass('search-overlay');
  140.  
  141.             body.find('.search-overlay').remove();
  142.             body.append(overlay);
  143.  
  144.             overlay.on('click', function(){
  145.                 setTimeout(function() {
  146.                     overlay.hide();
  147.                     $('.block-search').toggle();
  148.                 }, 500);
  149.             });
  150.  
  151.         },
  152.  
  153.         updateDefaultPrice: function (message) {
  154.             if (message) {
  155.                 console.log('2');
  156.                 $('.price-wrapper').html(this.priceTemplate({ priceFormatted: message }));
  157.             } else {
  158.                 var priceAmount = $('.price-wrapper').data('priceAmount');
  159.  
  160.                 this._updatePriceValue('.price-wrapper', priceAmount);
  161.                 console.log(priceAmount);
  162.             }
  163.         },
  164.  
  165.         _updatePriceValue: function (element, priceAmount) {
  166.             var priceFormatted = utils.formatPrice(priceAmount, this.priceFormat);
  167.             console.log('3');
  168.  
  169.             $('.price-wrapper').html(this.priceTemplate({ priceFormatted: priceFormatted}));
  170.             console.log($('.price-wrapper'));
  171.         },
  172.  
  173.         updateCustomerPrice: function(data) {
  174.             var itemId = $('.price-wrapper').data('itemId');
  175.  
  176.  
  177.             if ((_.isUndefined(data.status) || data.status == 0) && !this.timerId) {
  178.                 this.timerId = setTimeout(this.reloadPriceData.bind(this), 10000);
  179.             }
  180.             console.log('4');
  181.             this.elements.each(function (index, element) {
  182.                 var itemId = $(element).data('itemId');
  183.                 if (!_.isEmpty(data.items[itemId])) {
  184.                     var priceType = $(element).data('priceType');
  185.                     if (!_.isEmpty(data.items[itemId][priceType])) {
  186.                         var priceAmount = data.items[itemId][priceType]['amount'];
  187.                         this._updatePriceValue(element, priceAmount);
  188.                     }
  189.                 }
  190.             }.bind(this));
  191.  
  192.         },
  193.  
  194.         reloadPriceData: function () {
  195.             this.timerId = null;
  196.             customerData.reload(['custom-customer-prices']);
  197.         },
  198.  
  199.         /**
  200.          * Set special url for discover tab
  201.          */
  202.         getRequestUrl: function() {
  203.             if(this.paramScope == 'discover' && this.options.urlDiscover !== ''){
  204.                 return this.options.urlDiscover
  205.             } else {
  206.                 return this.options.url
  207.             }
  208.         },
  209.  
  210.         /**
  211.          * Override to :
  212.          *  - Add toggle buttons to search popup
  213.          *  - Add additional elements to popup
  214.          *  - Add elements filter depends of search category
  215.          *  - Extend current functionality
  216.          */
  217.         _onPropertyChange: function () {
  218.             var value = this.element.val(),
  219.                 searchWrapper =  $('.search-autocomplete'),
  220.                 preloader = $('<div></div>').addClass('search-loader');
  221.  
  222.             this.submitBtn.disabled = this._isEmpty(value);
  223.  
  224.             if (value.length >= parseInt(this.options.minSearchLength, 10)) {
  225.  
  226.                 this.currentRequest = $.ajax({
  227.                     method: "GET",
  228.                         url: this.getRequestUrl(),
  229.                         data:{
  230.                         product_type: this.paramScope,
  231.                         q: value
  232.                     },
  233.  
  234.                     // This function will ensure proper killing of the last Ajax call.
  235.                     // In order to prevent requests of an old request to pop up later and replace results.
  236.                     beforeSend: function() {
  237.                         if (this.currentRequest !== null)
  238.                             this.currentRequest.abort();
  239.                         searchWrapper.find('.search-loader').remove();
  240.                         searchWrapper.prepend(preloader);
  241.                     }.bind(this),
  242.  
  243.                     success: $.proxy(function (data) {
  244.                         var self = this,
  245.                             tabsParam = self.paramScope,
  246.                             lastElement = false,
  247.                             content = this._getResultWrapper(),
  248.                             sectionDropdown = this._getSectionHeader(),
  249.                             productItem = '.product-item',
  250.                             productElement = '.product-item-wrapper',
  251.                             groupId = parseInt($.mage.cookies.get('mage-customer-group-id'));
  252.                             self.firstProduct = 0;
  253.                             var priceValue = [];
  254.  
  255.                         if (tabsParam == 'simple' || tabsParam == undefined) {
  256.  
  257.                             $.each(data, function (index, element) {
  258.                                 if (!lastElement || (lastElement && lastElement.type !== element.type)) {
  259.                                     sectionDropdown = this._getSectionHeader(element.type, data);
  260.                                 }
  261.  
  262.                                 var elementHtml = this._renderItem(element, index);
  263.  
  264.                                 sectionDropdown.append(elementHtml);
  265.  
  266.                                 if (!lastElement || (lastElement && lastElement.type !== element.type)) {
  267.                                     content.append(sectionDropdown);
  268.                                 }
  269.                                 lastElement = element;
  270.  
  271.                                 if (element.type == "product") {
  272.                                     self.firstProduct = element
  273.                                 }
  274.  
  275.                                 if(element.price !== undefined) {
  276.                                     priceValue.push(element.price)
  277.                                 }
  278.  
  279.                             }.bind(this));
  280.  
  281.  
  282.                         } else {
  283.                             $.each(data, function (index, element) {
  284.                                 if (element.type !== "product") {
  285.                                     return;
  286.                                 } else {
  287.                                     self.firstProduct = element
  288.                                 }
  289.  
  290.                                 if (!lastElement || (lastElement && lastElement.type !== element.type)) {
  291.                                     sectionDropdown = this._getSectionHeader(element.type, data);
  292.                                 }
  293.  
  294.                                 var elementHtml = this._renderItem(element, index);
  295.  
  296.                                 sectionDropdown.append(elementHtml);
  297.  
  298.                                 if (!lastElement || (lastElement && lastElement.type !== element.type)) {
  299.                                     content.append(sectionDropdown);
  300.                                 }
  301.  
  302.                                 lastElement = element;
  303.                             }.bind(this));
  304.  
  305.                         }
  306.  
  307.                         this.responseList.indexList = this.autoComplete.html(content)
  308.                             .show()
  309.                             .find(this.options.responseFieldElements + ':visible');
  310.                         this._resetResponseList(false);
  311.                         this.element.removeAttr('aria-activedescendant');
  312.  
  313.                         if (this.responseList.indexList.length) {
  314.                             this._updateAriaHasPopup(true);
  315.                         } else {
  316.                             this._updateAriaHasPopup(false);
  317.                         }
  318.  
  319.                         $(productElement).on('click', function (e) {
  320.                             self.responseList.selected = $(this).closest(productItem);
  321.  
  322.                             if (self.responseList.selected.attr("href")) {
  323.                                 window.location.href = self.responseList.selected.attr("href");
  324.                                 e.stopPropagation();
  325.                                 return false;
  326.                             }
  327.                             $(this).closest(productItem).searchForm.trigger('submit');
  328.                         });
  329.  
  330.                         this.responseList.indexList.on('mouseenter mouseleave', function (e) {
  331.                             self.responseList.indexList.removeClass(self.options.selectClass);
  332.                             $(this).addClass(self.options.selectClass);
  333.                             self.responseList.selected = $(e.target);
  334.                             self.element.attr('aria-activedescendant', $(e.target).attr('id'));
  335.                         })
  336.                         .on('mouseout', function () {
  337.                             if (!self._getLastElement() && self._getLastElement().hasClass(self.options.selectClass)) {
  338.                                 $(this).removeClass(self.options.selectClass);
  339.                                 self._resetResponseList(false);
  340.                             }
  341.                         });
  342.  
  343.                         $('form.action-wrapper').on('submit', function(e) {
  344.                                 var form = $(this);
  345.                                 e.preventDefault();
  346.                                 self.ajaxSubmit(form);
  347.                         });
  348.  
  349.                         this._callShowAll();
  350.                         this._callSearchTabs();
  351.                         this.getOverlay();
  352.                         this._showAllAction();
  353.                         console.log(priceValue);
  354.  
  355.                         $('.product-secondary').each(function (index) {
  356.                             $(this).append(priceValue[index]);
  357.                             console.log(priceValue[index]);
  358.  
  359.                         });
  360.  
  361.                         this.myElements = $(self.options.elementsSelector);
  362.  
  363.                         if (groupId) {
  364.                             console.log('10');
  365.                             this.updateDefaultPrice();
  366.                             this.customerPrices = customerData.get('custom-customer-prices');
  367.                             this.customerPrices.subscribe(this.updateCustomerPrice.bind(this));
  368.                            // this.updateCustomerPrice(this.customerPrices());
  369.                         } else {
  370.                             console.log('20');
  371.                             this.updateDefaultPrice(this.options.pricePlaceholder);
  372.                         }
  373.  
  374.                         if(this.paramScope === undefined) {
  375.                             $('.item.shop').addClass('active');
  376.                             $('#show-all-param').val('simple');
  377.                         } else {
  378.                             $('.smile-elasticsuite-autocomplete-result')
  379.                                 .find("[data-role ='" + this.paramScope +  "']")
  380.                                 .addClass('active');
  381.                             $('#show-all-param').val(self.paramScope);
  382.                         }
  383.  
  384.                         var findeElem = 0;
  385.  
  386.                         if(this.firstProduct.size != undefined)
  387.                             findeElem = this.firstProduct.size;
  388.  
  389.                         $('.search-toggle .active').append(this.productAmong({ data: { size: findeElem }}));
  390.                         $(preloader).remove();
  391.  
  392.                     },this)
  393.                 });
  394.  
  395.             } else {
  396.                 this._resetResponseList(true);
  397.                 this.autoComplete.hide();
  398.                 this._updateAriaHasPopup(false);
  399.                 this.element.removeAttr('aria-activedescendant');
  400.             }
  401.         }
  402.  
  403.     });
  404.  
  405.     return $.nobel.quickSearchUpdate;
  406. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement