Skip to content

Instantly share code, notes, and snippets.

@EscApp2
Last active July 23, 2024 10:21
Show Gist options
  • Save EscApp2/ec0b6c06560f889a13830d37827c7eb2 to your computer and use it in GitHub Desktop.
Save EscApp2/ec0b6c06560f889a13830d37827c7eb2 to your computer and use it in GitHub Desktop.
Create custom sku tree selecter v3
.js_custom_sku_error_text{
font-size: 16px;
line-height: 20px;
font-weight: 400;
letter-spacing: 0.3px;
color: red;
margin-bottom:10px;
display:none;
}
.js_custom_sku_error_text.show{
display:inherit;
}
.product-data-sizes__name_wrapp{
isplay: flex;
flex-direction: row;
justify-content: space-between;
}
.property_sku_single_block .links,
.property_sku_single_block .name{
font-size: 16px;
line-height: 20px;
font-weight: 400;
letter-spacing: 0.3px;
text-align: left;
text-decoration: none;
}
.product-data__radio-sizes{
display: grid;
grid-template-columns: repeat(6, 1fr);
gap: 1rem 0.5rem;
width: 100%;
padding: 1rem 0px;
}
.radio-size_detail.disable,
.radio-size_detail.missing{
opacity:0.5;
}
.css_radio-sizes__label{
display:block;
padding:5px 0;
cursor: pointer;
text-align: center;
background: transparent;
border: 1px solid #404040;
color: #000;
border-radius:5px;
}
.css_radio-sizes__label:hover,
.css_radio-sizes__label.active{
background: #404040;
color: rgb(255, 255, 255);
}
.css_radio-sizes__label input{
display:none;
}
.property_sku_single_block{
width: 100%;
display: flex;
flex-direction: column;
padding: 0px 0px 1rem;
}
.radio-size__text{
font-size: 16px;
line-height: 20px;
}
<?
$arData = $arResult;
$ComponentID = "bx_custom_sku_".$arResult['ID']."_".randString(10);
$arJsParams = array(
"ID" => $ComponentID,
"CONTAINER" => "#".$ComponentID, // container selector
"DEFAULT_OFFER_ID"=>array_values($arResult['OFFERS'])[0]['ID'],
"ORIGIN_OBJ_CATALOG_ELEMENT_NAME"=>$arItemIDs["strObName"],
"HIDE_IF_OFFER_NOT_FIND" => ".offer_buy_block, .main_item_wrapper .flex_custom_btns, .element_detail.offer_quantity_block, .subscribe",
//"ALWAYS_SHOW_OFFER"=>"Y",
);
?>
<div id="<?=$ComponentID?>">
<input class="js_custom_sku_offer_id" type="hidden" value="" >
<div class="js_custom_sku_error_text no-choose" >
Выберите товар
</div>
<?php
$i =0;
foreach($arResult['AR_CUSTOM_SKU']['ROWS'] as $oneSelect){
$i++;
?>
<? $intCountSizes = count($oneSelect['OPTIONS']);
$NAME = GetMessage('JNS__SEPARATE_SKU_TREE__PROPERTY_'.$i);
if(empty($NAME)){
$NAME = $oneSelect['NAME'];
}
?>
<div class="property_sku_single_block">
<div class="product-data-sizes__name_wrapp ">
<div class="name"><?=$NAME?></div>
<?/*?>
<div class="links">Размер</div>
<?*/?>
</div>
<div class="product-data-sizes__wrapp _flex ">
<div class="product_sizes">
<div class="p-0 js_custom_sku_tree " data-prop-id="<?=$oneSelect['ID']?>" >
<div class="sizes-swiper_<?=$i?>">
<div id="sizesSlider_<?=$i?>" class="radio-sizes product-data__radio-sizes">
<?
foreach ($oneSelect['OPTIONS'] as $key => $arOption) {
$size_orig = $arOption['VALUE'];
$size_orig = mb_strtoupper($size_orig);
$size_orig_strlower = mb_strtolower($size_orig);?>
<div class="swiper-slide radio-size radio-size_detail
js_custom_sku_tree_option
js-popup-separate-size__show
" >
<label class="css_radio-sizes__label js_radio-sizes__label">
<input type="radio" name="product-data-size_<?=$oneSelect['ID']?>" value="<?= $arOption['ID'] ?>">
<span class="radio-size__text">
<span class="orig"> <?= $size_orig ?></span>
</span>
</label>
</div>
<?}?>
</div>
</div>
<? /*if ($intCountSizes >= 8) { ?>
<div class="offer-select-slider-button-prev slider-button-prev_sizes_<?=$i?> swiper-button-disabled"></div>
<div class="offer-select-slider-button-next slider-button-next_sizes_<?=$i?> "></div>
<? } */?>
</div>
</div>
</div>
</div>
<?
}
?>
</div>
<?
foreach($arData['OFFERS'] as &$arOffer){
unset($arOffer['PROPERTIES']);
}
?>
<script>
$(document).ready(function(){
if($.isEmptyObject(window.ObjNAVcustomSKUTree)){
window.ObjNAVcustomSKUTree = {};
}
var obj = window.NAVcustomSKUTree.Init(
<?=CUtil::PhpToJSObject($arJsParams);?>,
<?=CUtil::PhpToJSObject($arData['AR_CUSTOM_SKU']);?>,
<?=CUtil::PhpToJSObject(array_column($arData['OFFERS'], null, 'ID'));?>);
obj.Exec();
window.ObjNAVcustomSKUTree.obj_<?=$ComponentID;?> = obj;
});
</script>
<?
if(!function_exists('createCustomSkuTree')){
function createCustomSkuTree(&$arResult,$arParams,$arOption = array()){
$arPropCodesOrIds = $arParams['OFFER_TREE_PROPS'];
$is_detail = false;
if(isset($arResult['ITEMS'])){
$arResultList = $arResult['ITEMS'];
}else{
$is_detail = true;
$arResultList = array($arResult);
}
foreach($arResultList as $itemKey=>$arItem){
$OFFERS_PROPS = array();
$arAvailable = array();
$arEnumOrigList = $arEnumList = $arPropList = array();
foreach($arItem['OFFERS'] as $arOffer){
$arAvailable[$arOffer['ID']] = (bool)("Y" == $arOffer['PRODUCT']['AVAILABLE']);
if($arOption['AVAILABLE_OFFERS'] && count($arOption['AVAILABLE_OFFERS'])>0){
if(!in_array($arOffer['ID'],$arOption['AVAILABLE_OFFERS'])){
continue;
}
}
if("Y" != $arOption['SHOW_NOT_AVAILABLE']){
if("N" == $arOffer['PRODUCT']['AVAILABLE']){
continue;
}
}
//TODO resort
foreach($arPropCodesOrIds as $arPropCodeOrId){
foreach($arOffer['PROPERTIES'] as $arProp){
if($arProp['CODE'] == $arPropCodeOrId
|| $arProp['ID'] == $arPropCodeOrId
){
$arPropList[$arProp['ID']] = $arProp;
if($arProp['VALUE_XML_ID']){
$arEnumList[$arProp['ID']][$arOffer['ID']] = $arProp['VALUE_XML_ID'];
}
if($arProp['VALUE_ENUM_ID']){
$arEnumOrigList[$arProp['ID']][$arOffer['ID']] = $arProp['VALUE_ENUM_ID'];
}else{
//CHECK
$arEnumOrigList[$arProp['ID']][$arOffer['ID']] = $arProp['VALUE'];
}
if(!empty($arProp['VALUE'])){
$OFFERS_PROPS[$arProp['ID']][$arOffer['ID']] = $arProp['VALUE'];
}
break;
}
}
}
}
$arValToEnumOrigList = $arValToEnumList = $arList = $arOfferList = $arOffersProp = $arNewArray = array();
foreach($OFFERS_PROPS as $prop_id=>$arValues){
asort($arValues);
foreach($arValues as $offer_id=>$val){
$prop_val = abs(crc32($val));
$arNewArray[$prop_id][$prop_val][$offer_id] = $offer_id;
$arOffersProp[$prop_id][$offer_id] = $prop_val;
$arList[$prop_val] = $val;
if($arEnumList[$prop_id][$offer_id]){
$arValToEnumList[$prop_id][$prop_val] = $arEnumList[$prop_id][$offer_id];
}
if($arEnumOrigList[$prop_id][$offer_id]){
$arValToEnumOrigList[$prop_id][$prop_val] = $arEnumOrigList[$prop_id][$offer_id];
}
$arOfferList[$offer_id][$prop_id] = $prop_val;
}
}
if(!$arOption['SORT_AS_CLOTH_SIZES']){
$arOption['SORT_AS_CLOTH_SIZES'] = array();
}
$offersChooser = [];
foreach ($arNewArray as $propId => $property) {
$select = [
'ID' => $propId,
'NAME' => $arPropList[$propId]['NAME'],
'TYPE' => 'BLOCK',
'CLASS' => "PROPERTY_".$propId,
'CODE' => $arPropList[$propId]['CODE'],
'OPTIONS' => [],
];
if(!empty($arOption['SELECT_VIEW'])){
if(in_array($select['CODE'], $arOption['SELECT_VIEW'])){
$select['TYPE'] = "SELECT";
}
}
$arColorList = array();
if(!empty($arOption['COLOR_XML_LINK'])){
if(in_array($select['CODE'], $arOption['COLOR_XML_LINK'])){
$hlblock = \Bitrix\Highloadblock\HighloadBlockTable::getList(
array(
"filter" => array(
'TABLE_NAME' => "eshop_color_reference"
)
)
)->fetch();
if (isset($hlblock['ID'])) {
$entity = \Bitrix\Highloadblock\HighloadBlockTable::compileEntity($hlblock);
$entity_data_class = $entity->getDataClass();
$res = $entity_data_class::getList(array(
'filter' => array(
"UF_XML_ID" => $arEnumList[$propId],
)
));
while ($color = $res->fetch()) {
$arColorList[$color["UF_XML_ID"]] = CFile::GetPath($color["UF_FILE"]);
}
}
}
}
$SORT_VALUE = "VALUE";
if(
in_array($arPropList[$propId]['CODE'],$arOption['SORT_AS_CLOTH_SIZES'])
|| in_array($arPropList[$propId]['ID'],$arOption['SORT_AS_CLOTH_SIZES'])
){
$SORT_VALUE = "CLOTH";
}
foreach ($property as $id => $offer_id) {
$img = NULL;
$xml_id = $arValToEnumList[$propId][$id];
if($xml_id && count($arColorList)>0){
$img = $arColorList[$xml_id];
}
$sort_val = $arList[$id];
if($SORT_VALUE == "CLOTH"){
$sort_val = sortClothSizes($arList[$id]);
}
$select['OPTIONS'][$id] = [
"ID" => $id,
"NAME" => $arList[$id],
"VALUE" => $arList[$id],
'IMG' => $img,
"SORT_VALUE"=>$sort_val,
];
}
uasort($select['OPTIONS'], function($a, $b){
if ($a['SORT_VALUE'] == $b['SORT_VALUE']) {
return 0;
}
return ($a['SORT_VALUE'] < $b['SORT_VALUE']) ? -1 : 1;
});
$offersChooser[$select['ID']] = $select;
}
$AR_CUSTOM_SKU = array(
"ROWS"=>$offersChooser,
"HELP_ARRAYS"=>array(
$arNewArray, $arOffersProp, $arOfferList, $arList, $arValToEnumOrigList
),
"AVAILABLE"=>$arAvailable,
);
$arResultList = array($arResult);
if( $is_detail){
$arResult['AR_CUSTOM_SKU'] = $AR_CUSTOM_SKU;
}else{
$arResult['ITEMS'][$itemKey]['AR_CUSTOM_SKU'] = $AR_CUSTOM_SKU;
}
}
}
}
if(!function_exists('sortClothSizes')){
function sortClothSizes($value){
$arSizeSortDefaults = array(
"XXXXXXXXXXS"=>100000,
"10XS"=>100000,
"XXXXXXXXXS"=>110000,
"9XS"=>110000,
"XXXXXXXXS"=>120000,
"8XS"=>120000,
"XXXXXXXS"=>130000,
"7XS"=>130000,
"XXXXXXS"=>140000,
"6XS"=>140000,
"XXXXXS"=>150000,
"5XS"=>150000,
"XXXXS"=>160000,
"4XS"=>160000,
"XXXS"=>170000,
"3XS"=>170000,
"XXS"=>180000,
"2XS"=>180000,
"XS"=>190000,
"S"=>200000,
"M"=>210000,
"L"=>220000,
"XL"=>230000,
"XXL"=>240000,
"2XL"=>240000,
"XXXL"=>250000,
"3XL"=>250000,
"XXXXL"=>260000,
"4XL"=>260000,
"XXXXXL"=>270000,
"5XL"=>270000,
"XXXXXXL"=>280000,
"6XL"=>280000,
"XXXXXXXL"=>290000,
"7XL"=>290000,
"XXXXXXXXL"=>300000,
"8XL"=>300000,
"XXXXXXXXXL"=>310000,
"9XL"=>310000,
"XXXXXXXXXXL"=>320000,
"10XL"=>320000,
);
$size = ToUpper($value);
// Регулярные выражения для замены
// \x0425 - Unicode для заглавной русской буквы Х
// \x0445 - Unicode для строчной русской буквы х
// \x041C - Unicode для заглавной русской буквы М
// \x043C - Unicode для строчной русской буквы м
$patterns = ['/\x{0425}/u', '/\x{0445}/u', '/\x{041C}/u', '/\x{043C}/u'];
$replacements = ['X', 'x', 'M', 'm'];
$size = preg_replace($patterns, $replacements, $size);
$size = str_replace("-","/",$size);
$arSize = explode("/",$size);
$arSizeSortValue = array();
$add_step = 100;
$add_value = 0;
if(count($arSize)>1){
$add_value = $add_step;
}
foreach($arSize as $one_size){
$one_size = trim($one_size);
if($arSizeSortDefaults[$one_size]){
$arSizeSortValue[] = $arSizeSortDefaults[$one_size];
}
}
$ret = $value;
if(count($arSizeSortValue)>0){
$min = min($arSizeSortValue)+$add_value;
if($min){
$ret = $min+$add_value;
}
}
return $ret;
}
}
<?
if (!defined('B_PROLOG_INCLUDED') || B_PROLOG_INCLUDED!==true) die();
$arData = $arItem;
$ComponentID = "bx_custom_sku_".$arData['ID']."_".randString(10);
$arJsParams = array(
"ID" => $ComponentID,
"CONTAINER" => "#".$ComponentID, // container selector
//"DEFAULT_OFFER_ID"=>array_values($arData['OFFERS'])[0]['ID'],
//"ORIGIN_OBJ_CATALOG_ELEMENT_NAME"=>$arItemIDs["strObName"]."el",
"HIDE_IF_OFFER_NOT_FIND" => "#".$arItemIDs['strMainID']." .offer_btns",
"ON_OFFER_CHANGE_CALLBACK" => "showOfferButtonInCatalog",
);
?>
<div id="<?=$ComponentID?>">
<input class="js_custom_sku_offer_id" type="hidden" value="" >
<div class="js_custom_sku_error_text no-choose" >
Выберите товар
</div>
<?php
$i =0;
foreach($arData['AR_CUSTOM_SKU']['ROWS'] as $oneSelect){
$i++;
?>
<? $intCountSizes = count($oneSelect['OPTIONS']);
$NAME = GetMessage('JNS__SEPARATE_SKU_TREE__PROPERTY_'.$i);
if(empty($NAME)){
$NAME = $oneSelect['NAME'];
}
?>
<div class="property_sku_single_block">
<div class="product-data-sizes__name_wrapp ">
<div class="name"><?=$NAME?></div>
<?/*?>
<div class="links">Размер</div>
<?*/?>
</div>
<div class="product-data-sizes__wrapp _flex ">
<div class="product_sizes">
<div class="sizes-swiper-wrap p-0 js_custom_sku_tree " data-prop-id="<?=$oneSelect['ID']?>" >
<div class="sizes-1swiper_<?=$i?> ">
<div id="sizesSlider_<?=$i?>" class="radio-sizes product-data__radio-sizes">
<?
foreach ($oneSelect['OPTIONS'] as $key => $arOption) {
$size_orig = $arOption['VALUE'];
$size_orig = mb_strtoupper($size_orig);
$size_orig_strlower = mb_strtolower($size_orig);?>
<div class="radio-size radio-size_detail js_custom_sku_tree_option
js-popup-separate-size__show" >
<label class="css_radio-sizes__label js_radio-sizes__label">
<input type="radio" name="product-data-size_<?=$oneSelect['ID']?>"
value="<?= $arOption['ID'] ?>">
<span class="radio-size__text">
<span class="orig"> <?= $size_orig ?></span>
</span>
</label>
</div>
<?}?>
</div>
</div>
<? /*if ($intCountSizes >= 8) { ?>
<div class="offer-select-slider-button-prev slider-button-prev_sizes_<?=$i?> swiper-button-disabled"></div>
<div class="offer-select-slider-button-next slider-button-next_sizes_<?=$i?> "></div>
<? } */?>
</div>
</div>
</div>
</div>
<?
}
?>
</div>
<?php
foreach($arData['OFFERS'] as &$arOffer){
unset($arOffer['PROPERTIES']);
}
?>
<script>
$(document).ready(function(){
if($.isEmptyObject(window.ObjNAVcustomSKUTree)){
window.ObjNAVcustomSKUTree = {};
}
var obj = window.NAVcustomSKUTree.Init(
<?=CUtil::PhpToJSObject($arJsParams);?>,
<?=CUtil::PhpToJSObject($arData['AR_CUSTOM_SKU']);?>,
<?=CUtil::PhpToJSObject(array_column($arData['OFFERS'], null, 'ID'));?>);
obj.Exec();
window.ObjNAVcustomSKUTree.obj_<?=$ComponentID;?> = obj;
});
</script>
<?
$arParamsCustom = $arParams;
$arParamsCustom['OFFER_TREE_PROPS'] = array("ROST",'SIZES');
createCustomSkuTree(
$arResult,
$arParamsCustom,
array(
"SORT_AS_CLOTH_SIZES"=>array('SIZES'),
'SELECT_VIEW'=>array(),
'COLOR_XML_LINK'=>array(),
)
);
//https://gist.github.com/EscApp2/19b1b0ff89aa6770e96a4199b4e4fdc5
(function (window) {
window.NAVcustomSKUTree = {
/**
* Initialization
*/
Init: function (arParams, AR_CUSTOM_SKU, offersJsData) {
var that = this;
that.SEPARATE_SKU_TREE__LAST_CLICK_ELEM = false;
that.SEPARATE_SKU_TREE__OFFER_ID = false;
that.offersJsData = offersJsData;
that.AR_CUSTOM_SKU = AR_CUSTOM_SKU;
that.ID = arParams.ID;
that.params = {};
that.params.alwaysShowOffer = false;
that.params.default_offer_id = false;
that.errorCode = 0;
if(!arParams.CONTAINER){
that.errorCode = "Not set container selector";
}
if($(arParams.CONTAINER).length<=0){
that.errorCode = "Not find container";
}else{
that.container = $(arParams.CONTAINER);
}
if(arParams.DEFAULT_OFFER_ID){
that.params.default_offer_id = arParams.DEFAULT_OFFER_ID;
}
that.ORIGIN_OBJ_CATALOG_ELEMENT_NAME = arParams.ORIGIN_OBJ_CATALOG_ELEMENT_NAME;
if(!!arParams.ORIGIN_OBJ_CATALOG_ELEMENT_NAME && !window[arParams.ORIGIN_OBJ_CATALOG_ELEMENT_NAME]){
that.errorCode = "Not find default obj for catalog element";
}else{
that.origin_object = window[arParams.ORIGIN_OBJ_CATALOG_ELEMENT_NAME];
}
that.params.hideIfOffersNotFind = false;
if(that.errorCode === 0){
if(!!arParams.HIDE_IF_OFFER_NOT_FIND){
that.params.hideIfOffersNotFind = $(arParams.HIDE_IF_OFFER_NOT_FIND);
}
if("Y" == arParams.ALWAYS_SHOW_OFFER){
that.params.alwaysShowOffer = true;
}
if(!!arParams.ON_OFFER_CHANGE_CALLBACK){
that.params.OnOfferChangeCallback = arParams.ON_OFFER_CHANGE_CALLBACK;
}
}
console.log(that.errorCode);
//clone object
return Object.assign({}, that);
},
Exec: function () {
var that = this;
if(that.errorCode === 0){
that.container.on('change, click', '.js_custom_sku_tree input, .js_custom_sku_tree select', function (event, param) {
that.SEPARATE_SKU_TREE__LAST_CLICK_ELEM = $(this);
that.changeHandle($(this), event, param);
});
BX.addCustomEvent('onChangeTree', BX.proxy(that.onChangeTree, that));
BX.addCustomEvent('onChangeTree', BX.proxy(that.hideVariants, that));
BX.addCustomEvent('onChangeTree', BX.proxy(that.hideNotAvailable, that));
BX.addCustomEvent('onChangeOffer', BX.proxy(that.onChangeOffer, that));
BX.addCustomEvent('onChangeOffer', BX.proxy(that.fireChangeOfferInOriginObj, that));
if(that.params.default_offer_id) {
that.setDefaultOfferID(that.params.default_offer_id);
}
}
},
changeHandle: function (elem, event, param) {
var that = this;
let value = $(elem).val();
var arData = $(elem).parents('.js_custom_sku_tree').data();
let stop = false;
if (!!param && !!param.stop_cycle) {
stop = true;
}
let stop_cycle = $(elem).data('stop_cycle');
if (!!stop_cycle) {
$(elem).data({"stop_cycle": false});
stop = true;
}
$(elem).closest('.js_custom_sku_tree').find('label').removeClass('active');
//$(elem).closest('label').addClass('active');
if (!stop) {
let prev_offer_id = that.SEPARATE_SKU_TREE__OFFER_ID;
//console.log(arData.propId, value, prev_offer_id);
that.setHtmlValuesOnChange(arData.propId, value);
BX.onCustomEvent("onChangeTree", [that.ID, that.getSelectedTree()]); // fire events
let offer_id_selected = that.getOffersIdBySelected();
if(that.params.alwaysShowOffer){
offer_id_selected = that.customSkuTreeGetNearestOffer(arData.propId, value, prev_offer_id);
that.setDefaultOfferID(offer_id_selected);
return true;
}
if (!!offer_id_selected) {
that.SEPARATE_SKU_TREE__OFFER_ID = offer_id_selected;
BX.onCustomEvent("onChangeOffer", [that.ID, offer_id_selected, that.offersJsData]); // fire events
} else {
}
}
if ($(elem).get(0).tagName == "SELECT") {
if ($(elem).next().hasClass('nice-select')) {
$(elem).niceSelect('update');
}
}
},
_compareSkuObject: function ($object, $cur_object) {
var $arChanges = {};
$.each($object, function ($key, $val) {
if (typeof $cur_object[$key] !== 'undefined') {
if ($cur_object[$key] == $val) {
//similar
} else {
$arChanges[$key] = $val;
}
} else {
//TODO
}
});
return $arChanges;
},
_compareSkuObject2: function ($object, $cur_object){
var $arChanges = {};
$.each($object, function($key, $val){
if (typeof $cur_object[$key] !== 'undefined') {
if($cur_object[$key] == $val){
//similar
}else{
$arChanges[$key] = $val;
}
}else{
$arChanges[$key] = $val;
}
});
return $arChanges;
},
setHtmlValuesOnChange: function (prop_id, value, not_remove) {
var that = this;
that.container.find('.js_custom_sku_tree[data-prop-id="' + prop_id + '"]')
.find('input, select')
.each(function (ind, val) {
let elem = $(this);
let tag = $(this).get(0).tagName;
if (tag == "INPUT") {
if ($(this).val() == value) {
if (!!$(this).attr('checked')) {
if (!not_remove) {
$(this).attr('checked', false);
$(this).prop('checked', false);
elem.closest('.js_custom_sku_tree_option').find('label').removeClass('active');
}
} else {
$(this).attr('checked', 'checked');
$(this).prop('checked', true);
elem.closest('.js_custom_sku_tree_option').find('label').addClass('active');
}
} else {
$(this).attr('checked', false);
$(this).prop('checked', false);
elem.closest('.js_custom_sku_tree_option').find('label').removeClass('active');
}
} else if (tag == "SELECT") {
$(this).find('option').each(function () {
if ($(this).val() == value) {
$(this).attr('selected', 'selected');
} else {
$(this).removeAttr('selected');
}
});
}
});
},
setDefaultOfferID: function (offer_id, stop_click_event) {
var that = this;
if (!that.AR_CUSTOM_SKU || !that.AR_CUSTOM_SKU['HELP_ARRAYS'] || !that.AR_CUSTOM_SKU['HELP_ARRAYS'][2]) {
return false;
}
var ob_offer_props = that.AR_CUSTOM_SKU['HELP_ARRAYS'][2][offer_id];
if (!!ob_offer_props) {
that.SEPARATE_SKU_TREE__OFFER_ID = offer_id;
$.each(ob_offer_props, function (_prop_id, value) {
that.setHtmlValuesOnChange(_prop_id, value, true);
});
}
BX.onCustomEvent("onChangeTree", [that.ID, that.getSelectedTree()]); // fire events
if (!stop_click_event) {
BX.onCustomEvent("onChangeOffer", [that.ID, offer_id, that.offersJsData]); // fire events
}
},
getSelectedTree: function () {
var that = this;
if (!that.AR_CUSTOM_SKU || !that.AR_CUSTOM_SKU['HELP_ARRAYS']) {
return false;
}
let $arTree = {};
$.each(that.AR_CUSTOM_SKU['HELP_ARRAYS'][1], function (_prop_id, ob_offer) {
$('.js_custom_sku_tree[data-prop-id="' + _prop_id + '"]')
.find('input:checked, select option:selected')
.each(function (ind, val) {
let tag = $(this).get(0).tagName;
if (tag == "INPUT") {
$arTree[_prop_id] = $(this).val();
} else if (tag == "OPTION") {
$arTree[_prop_id] = $(this).val();
}
});
});
return $arTree;
},
getOffersIdBySelected: function () {
var that = this;
let $arTree = that.getSelectedTree();
return that.getOfferIdByTree($arTree);
},
getOfferIdByTree: function ($paramTree) {
var that = this;
if (!that.AR_CUSTOM_SKU || !that.AR_CUSTOM_SKU['HELP_ARRAYS']) {
return false;
}
let $checkedOfferId = false;
let $arTreeList = that.AR_CUSTOM_SKU['HELP_ARRAYS'][2];
$.each($arTreeList, function (offerId, $arTree) {
let $arChanges = that._compareSkuObject2($arTree, $paramTree);
//console.log($arTree, $paramTree, $arChanges);
if (Object.keys($arChanges).length == 0) {
$checkedOfferId = offerId;
return false; //break;
}
});
return $checkedOfferId;
},
onChangeTree: function(ID){
var that = this;
if(that.ID != ID){
return false;
}
if(that.params.hideIfOffersNotFind){
if(that.params.hideIfOffersNotFind.length>0){
that.params.hideIfOffersNotFind.hide();
}
}
},
hideVariants: function (ID, $CUR_TREE) {
// скрыть не существующие варианты
var that = this;
if(that.ID != ID){
return false;
}
let MISSING_CLICKABLE = false;
that.container.find('.js_custom_sku_tree .missing')
.removeClass('missing')
.css({'pointer-events': 'initial'});
if (Object.keys($CUR_TREE).length > 0) {
let arData = {};
//if( that.SEPARATE_SKU_TREE__LAST_CLICK_ELEM.length > 0){
// ищем последний кликнутый
// arData = $(that.SEPARATE_SKU_TREE__LAST_CLICK_ELEM).closest('.js_custom_sku_tree').data();
//}else{
// ищем первый элемент
//arData = that.container.find('.js_custom_sku_tree').first().data();
//}
// ищем первый элемент
arData = that.container.find('.js_custom_sku_tree').first().data();
let $PROP_ID = arData.propId;
let $CUR_VALUE = $CUR_TREE[$PROP_ID];
let $arRes = {};
$.each(that.offersJsData, function ($o_key, $oneOffer) {
let oneTREE = that.AR_CUSTOM_SKU['HELP_ARRAYS'][2][$oneOffer.ID];
if (!!oneTREE && !!oneTREE[$PROP_ID] && oneTREE[$PROP_ID] == $CUR_VALUE) {
$.each(oneTREE, function ($prop, $value) {
let $prop_id = $prop.replace("PROP_", "");
if ($PROP_ID == $prop_id) {
return true; //continue;
}
if (!$arRes[$prop_id]) {
$arRes[$prop_id] = {};
}
$arRes[$prop_id][$value] = $value;
});
}
});
let arKeys = Object.keys($arRes);
$.each(that.AR_CUSTOM_SKU['HELP_ARRAYS'][0], function ($prop_id, arValue) {
if (-1 == $.inArray($prop_id, arKeys)) {
return true; //continue;
}
$.each(arValue, function ($value, _ar) {
if ($arRes[$prop_id] && $arRes[$prop_id][$value] && $arRes[$prop_id][$value] == $value) {
//ok
//}else if(_ar[offerId] && _ar[offerId] == offerId){
// current
} else {
let input = that.container.find('.js_custom_sku_tree[data-prop-id="' + $prop_id + '"] .js_custom_sku_tree_option input[value="' + $value + '"]');
let event = 'initial';
if (!MISSING_CLICKABLE) {
event = 'none';
}
let js_custom_sku_tree_option = input.closest('.js_custom_sku_tree_option');
js_custom_sku_tree_option.addClass('missing').css({'pointer-events': event});
// only for input
input.attr('checked', false);
input.prop('checked', false);
js_custom_sku_tree_option.find('label').removeClass('active');
}
});
});
}
},
hideNotAvailable: function (ID, $CUR_TREE) {
// скрыть варианты не доступных ТП
var that = this;
if(that.ID != ID){
return false;
}
if(!that.AR_CUSTOM_SKU || !that.AR_CUSTOM_SKU['HELP_ARRAYS']
|| !that.AR_CUSTOM_SKU['AVAILABLE']){
return false;
}
that.container.find('.js_custom_sku_tree .disable')
.removeClass('disable')
.css({'pointer-events': 'initial'});
if(Object.keys($CUR_TREE).length > 0){
let offerId = that.getOfferIdByTree($CUR_TREE);
$.each(that.offersJsData, function($o_key, $oneOffer){
let oneOfferId = $oneOffer.ID;
let oneTREE = that.AR_CUSTOM_SKU['HELP_ARRAYS'][2][oneOfferId];
let $arChanges = that._compareSkuObject2(oneTREE, $CUR_TREE);
let $available = that.AR_CUSTOM_SKU['AVAILABLE'][oneOfferId];
let $workTree = false;
if(
// Если ТП выбрано
// !!offerId &&
//Object.keys($CUR_TREE).length == Object.keys(AR_CUSTOM_SKU['HELP_ARRAYS'][0]).length
// Если ТП отличаеться на 1 параметр от текущего ТП, работаем с ними
Object.keys($arChanges).length == 1
){
$workTree = $arChanges;
}
// Если это текуший ТП, то тоже работаем с ним
if(!!offerId){
if(oneOfferId == offerId){
//console.log($workTree);
$workTree = oneTREE;
}
}
if(!!$workTree){
$.each($workTree, function($prop, $value){
let $prop_id = $prop.replace("PROP_", "");
var input = that.container.find('.js_custom_sku_tree[data-prop-id="'+$prop_id+'"] .js_custom_sku_tree_option input[value="'+$value+'"]');
var label = input.closest('.js_radio-sizes__label');
var wrap = input.closest('.radio-size_detail');
if(!$available){
//let event = 'initial';
//if (!MISSING_CLICKABLE) {
let event = 'none';
//}
wrap.addClass('disable')
.css({'pointer-events': event});
}
});
}
});
}
window.AR_CUSTOM_SKU = that.AR_CUSTOM_SKU;
//Если у первого параметра нет ни одного доступного второго параметра
// то добавляем класс disabled к такому первому параметру
$.each(that.AR_CUSTOM_SKU['HELP_ARRAYS'][1], function($prop_id, $ob_offer){
let $arValues = {};
$.each($ob_offer, function($offer, $value){
if(! $arValues[$value]){
$arValues[$value]={};
$arValues[$value]['count'] = 0;
$arValues[$value]['disabled'] = 0;
}
$arValues[$value]['count']++;
let $available = that.AR_CUSTOM_SKU['AVAILABLE'][$offer];
if(!$available){
$arValues[$value]['disabled']++;
}
});
$.each($arValues, function($value, $ob_info){
if($ob_info['count'] == $ob_info['disabled']){
let input = that.container.find('.js_custom_sku_tree[data-prop-id="'+$prop_id+'"] .js_custom_sku_tree_option input[value="'+$value+'"]');
let label = input.closest('.js_radio-sizes__label');
let wrap = input.closest('.radio-size_detail');
//let event = 'initial';
//if (!MISSING_CLICKABLE) {
let event = 'none';
//}
wrap.addClass('disable')
.css({'pointer-events': event});
}
});
});
},
onChangeOffer: function(ID){
var that = this;
if(that.ID != ID){
return false;
}
let offerId = that.getOffersIdBySelected();
if(offerId){
$('.js_custom_sku_offer_id').val(offerId);
}
if(that.params.hideIfOffersNotFind){
if(that.params.hideIfOffersNotFind.length>0){
that.params.hideIfOffersNotFind.show();
}
}
if(!!that.params.OnOfferChangeCallback && window[that.params.OnOfferChangeCallback]){
window[that.params.OnOfferChangeCallback].call(that,offerId);
}
},
fireChangeOfferInOriginObj: function(ID){
var that = this;
if(that.ID != ID){
return false;
}
if(that.origin_object){
let offerId = that.getOffersIdBySelected();
//let $arTree = that.getSelectedTree();
//let originObjSelectedValues = {};
//$.each($arTree, function(ind,val){
// originObjSelectedValues['PROP_'+ind] = that.AR_CUSTOM_SKU['HELP_ARRAYS'][4][ind][val];
//});
//that.origin_object.selectedValues = originObjSelectedValues;
that.origin_object.ChangeInfo(false, offerId);
}
},
customSkuTreeGetNearestOffer: function (prop_id, value, prev_offer_id) {
var that = this;
if (!that.AR_CUSTOM_SKU || !that.AR_CUSTOM_SKU['HELP_ARRAYS'] || !that.AR_CUSTOM_SKU['HELP_ARRAYS'][0]) {
return false;
}
let STOP_SELECT_OFFER_BY_ONE_CLICK = true;
var ob_offer_id = that.AR_CUSTOM_SKU['HELP_ARRAYS'][0][prop_id][value];
if (!!ob_offer_id) {
if (!!prev_offer_id) {
let $obMin = {};
$.each(ob_offer_id, function (each_offer, val) {
if (each_offer != prev_offer_id) {
let $arChanges = that._compareSkuObject(
that.AR_CUSTOM_SKU['HELP_ARRAYS'][2][each_offer],
that.AR_CUSTOM_SKU['HELP_ARRAYS'][2][prev_offer_id]
);
$obMin[Object.keys($arChanges).length] = each_offer;
}
});
let $arMin = Object.keys($obMin);
let $min = Math.min.apply(Math, $arMin);
var offer_id = $obMin[$min];
} else {
if (!STOP_SELECT_OFFER_BY_ONE_CLICK) {
var offer_id = Object.values(ob_offer_id)[0];
} else {
return false;
}
}
return offer_id;
}
return false;
},
getHoverOfferId: function (elem) {
var that = this;
let arData = $(elem).closest('.js_custom_sku_tree').data();
let $HOVER_PROP_ID = arData.propId;
let $HOVER_VALUE = false;
if ($(elem).hasClass('js_custom_sku_tree_option')) {
$HOVER_VALUE = $(elem).find('input').val();
} else {
$HOVER_VALUE = $(elem).find('.js_custom_sku_tree_option input').val();
}
let $curOfferId = that.SEPARATE_SKU_TREE__OFFER_ID;
if ($curOfferId && $HOVER_VALUE && $HOVER_PROP_ID) {
let $curTREE = that.AR_CUSTOM_SKU['HELP_ARRAYS'][2][$curOfferId];
let $hoverTREE = Object.assign({}, $curTREE);
$hoverTREE[$HOVER_PROP_ID] = $HOVER_VALUE;
let $hoverOfferId = that.getOfferIdByTree($hoverTREE);
if (!!$hoverOfferId) {
return $hoverOfferId;
}
}
return false;
},
getOfferSizeValue: function (offerId) {
var that = this;
if (!that.AR_CUSTOM_SKU || !that.AR_CUSTOM_SKU['HELP_ARRAYS']) {
return false;
}
if (offerId) {
let $arTree = that.AR_CUSTOM_SKU['HELP_ARRAYS'][2][offerId];
let arSize = [];
$.each($arTree, function (prop, id) {
let val = that.AR_CUSTOM_SKU['HELP_ARRAYS'][3][id];
if (!!val) {
arSize.push(val);
}
});
return arSize.join('/').toLowerCase();
}
return false;
},
}
})(window);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment