@if($edit)
    <div class="mceNonEditable component-container" data-component-key="productGrid" data-banner-title="{{ $bannerTitle }}">
        <a href="#" class="btn btn-danger pull-right delete-component">X</a>
        <h4>@lang('hilco::app.product_grid')</h4>
        <p>@lang('hilco::app.display_a_ribbon_of_product_hierarchy_elements')</p>
        <div data-banner-id="{{ $bannerId }}" class="pgrid-container">
            <div class="row pgrid-products-container">
                @foreach ($products as $index => $product)
                    <div data-product-index="{{$index}}"
                         data-product-webasset-url="{{ Arr::get($product, 'productWebAssetUrl') }}"
                         data-product-webasset-id="{{ Arr::get($product, 'productWebAssetId') }}"
                         data-product-type="{{ Arr::get($product, 'productType') }}"
                         data-product-id="{{ Arr::get($product, 'productId') }}"
                         data-product-title="{{ Arr::get($product, 'productTitle') }}"
                         data-product-discount="{{ Arr::get($product, 'productDiscount') }}"
                         class="col-md-3 pgrid-product-container">
                        <div style="margin: 5px; padding: 5px; border: 1px solid black;">
                            <img class="center-block img-responsive pgrid-product-thumbnail" style="min-height: 50px;"
                                 src="{{ Arr::get($product, 'productWebAssetUrl', webAssetUrl([])) }}" alt="">
                            <div class="product-title"> {{ Arr::get($product, 'productTitle') }}</div>
                            <div class="product-discount"><a href="#" class="pgrid-discount-product-link">Discount Badge: "{{ Arr::get($product, 'productDiscount', 0) }}"</a></div>
                            <div class="row">
                                <div class="col-sm-4"><a class="pgrid-move-left-product-button btn btn-info" href="#">&lt;</a></div>
                                <div class="col-sm-4"><a class="pgrid-delete-product-button btn btn-danger btn-block" href="#">@lang('hilco::app.delete')</a></div>
                                <div class="col-sm-4"><a class="pgrid-move-right-product-button btn btn-info" href="#">&gt;</a></div>
                            </div>
                        </div>
                    </div>
                @endforeach
            </div>
            <div class="row">
                <div class="col-md-4 col-md-offset-4">
                    <div>
                        @lang('hilco::app.banner_title_colon')
                        <div style="display: inline;" class="banner-title">{{ $bannerTitle }}</div>
                    </div>
                    <a href="#" class="btn btn-primary pgrid-add-product-button">@lang('hilco::app.add_product')</a>
                    <a href="#" class="btn btn-primary pgrid-set-title-button">@lang('hilco::app.set_banner_title')</a>
                </div>
            </div>

        </div>
    </div>
@endif

@if($script)
    <script type="text/javascript">
        registerComponent('productGrid', {
            menuText: '@lang('hilco::app.product_grid')',
            bladeTemplate: 'hilco::components.productGrid',
            init: function (body) {
                $(body).on('click', 'a.pgrid-add-product-button', function () {
                    var grid = $(this).closest('.pgrid-container');
                    var lastProduct = $(grid).find('div.pgrid-product-container').last();
                    var newProductIndex = lastProduct.data('product-index') + 1;
                    var newProduct = lastProduct.clone().attr('data-product-index', newProductIndex);
                    newProduct.find('[data-product-index]').each(function () {
                        $(this).attr('data-product-index', newProductIndex);
                    }).find('img').attr('src', '');
                    $(grid).find('.pgrid-products-container').append(newProduct);
                });
                $(body).on('click', 'a.pgrid-delete-product-button', function () {
                    var product = $(this).closest('.pgrid-product-container');
                    var productCount = $(this).closest('.pgrid-container').find('.pgrid-product-container').length;
                    if (productCount == 1) {
                        alert('@lang('hilco::app.you_cannot_delete_the_last_product')');
                        return;
                    }

                    $(product).remove();
                }).on('click', 'a.pgrid-move-left-product-button', function () {
                    var product = $(this).closest('.pgrid-product-container');
                    var prev = product.prev();
                    product.insertBefore(prev);
                }).on('click', 'a.pgrid-move-right-product-button', function () {
                    var product = $(this).closest('.pgrid-product-container');
                    var next = product.next();
                    product.insertAfter(next);
                }).on('click', 'a.pgrid-discount-product-link', function () {
                    var product = $(this).closest('.pgrid-product-container');
                    var data = {
                        discount: $(product).data('product-discount'),
                    };

                    win = tinymce.activeEditor.windowManager.open({
                        title: 'Set Discount Badge',
                        data: data,
                        body: [
                            {
                                name: 'discount',
                                type: 'textbox',
                                label: 'Discount Badge',
                            },
                        ],
                        onSubmit: function (e) {
                            data = tinymce.extend(data, e.data);
                            product
                                .data('product-discount', data.discount)
                                .attr('data-product-discount', data.discount)
                            ;
                            product.find('a.pgrid-discount-product-link').text('Discount: "' + data.discount + '"');
                        },
                    });
                });
                $(body).on('click', '.pgrid-set-title-button', function () {
                    var component = $(this).closest('.component-container');
                    var data = {
                        title: $(component).data('banner-title'),
                    };

                    win = tinymce.activeEditor.windowManager.open({
                        title: 'Set Banner Title',
                        data: data,
                        body: [
                            {
                                name: 'title',
                                type: 'textbox',
                                label: 'Title',
                            },
                        ],
                        onSubmit: function (e) {
                            data = tinymce.extend(data, e.data);
                            component
                                .data('banner-title', data.title)
                                .attr('data-banner-title', data.title)
                            ;
                            component.find('.banner-title').text(data.title);
                        },
                    });
                }).on('click', '.pgrid-product-thumbnail', function () {
                    var product = $(this).closest('.pgrid-product-container');
                    var data = {
                        product_type: $(product).data('product-type'),
                        product_id: $(product).data('product-id'),
                    };

                    win = tinymce.activeEditor.windowManager.open({
                        title: '@lang('hilco::app.configure_product')',
                        data: data,
                        body: [
                            {
                                name: 'product_search',
                                type: 'textbox',
                                label: '@lang('hilco::app.product')',
                                id: 'product_search',
                            },
                            {
                                name: 'product_type',
                                type: 'textbox',
                                visible: false,
                                id: 'product_type',
                            },
                            {
                                name: 'product_id',
                                type: 'textbox',
                                visible: false,
                                id: 'product_id',
                            },
                            {
                                name: 'product_title',
                                type: 'textbox',
                                visible: false,
                                id: 'product_title',
                            },
                        ],
                        onSubmit: function (e) {
                            data = tinymce.extend(data, e.data);
                            product
                                .data('product-type', data.product_type)
                                .data('product-id', data.product_id)
                                .data('product-title', data.product_title)
                                .attr('data-product-type', data.product_type)
                                .attr('data-product-id', data.product_id)
                                .attr('data-product-title', data.product_title)
                            ;
                            product.find('.product-title').text(data.product_title);
                            $.getJSON(
                                '{{ route('webAsset.search') }}',
                                {
                                    type: data.product_type,
                                    id: data.product_id
                                },
                                function (webAssetInfo) {
                                    product
                                        .data('product-webasset-url', webAssetInfo.url)
                                        .data('product-webasset-id', webAssetInfo.id)
                                        .attr('data-product-webasset-url', webAssetInfo.url)
                                        .attr('data-product-webasset-id', webAssetInfo.id)
                                    ;
                                    product.find('.pgrid-product-thumbnail').attr('src', webAssetInfo.url);
                                }
                            );
                        },
                        onPostRender: function () {
                            _win = this;
                            $('#product_search').autocomplete({
                                hint: false,
                                debug: true,
                                appendTo: $('body'),
                                minLength: 2,
                                autoselect: true,
                            }, [
                                {
                                    name: 'products',
                                    source: function (query, callback) {
                                        $.getJSON('/search/productUrl', {
                                            search: query,
                                            familyAndParts: 'yes',
                                        }, function (data) {
                                            callback(data);
                                        });
                                    },
                                    displayKey: function (suggestion) {
                                        return suggestion.name;
                                    },
                                    templates: {
                                        suggestion: function (suggestion) {
                                            return suggestion.name + ' - ' + suggestion.styled_type;
                                        }
                                    }
                                }
                            ]).on('autocomplete:selected', function (event, suggestion, dataset) {
                                // $('#customerAlias').val(suggestion.id).closest('form').submit();
                                _win.find('#product_type').value(suggestion.type);
                                _win.find('#product_id').value(suggestion.id);
                                _win.find('#product_title').value(suggestion.name);
                            });
                        }
                    });
                });
            },
            serialize: function (componentNode) {
                var data = {
                    bannerTitle: $(componentNode).data('banner-title'),
                    products: [],
                };
                $(componentNode).find('.pgrid-product-container').each(function () {
                    data.products.push({
                        productType: $(this).data('product-type'),
                        productId: $(this).data('product-id'),
                        productTitle: $(this).data('product-title'),
                        productWebAssetUrl: $(this).data('product-webasset-url'),
                        productWebAssetId: $(this).data('product-webasset-id'),
                        productDiscount: $(this).data('product-discount'),
                    });
                });
                return data;
            },
        });
    </script>
@endif
@if($view)
@set('productsGridId', str_random(8))
<div class="row container center-block">
    <div class="col-md-12">
        <div class="panel panel-primary">
            <div class="panel-heading">
                <h3 class="panel-title text-center">{{ $bannerTitle ?? ''}}</h3>
            </div>
            <div class="panel-body" style="">
                <div id="products-grid-{{ $productsGridId }}" class="">

                    @foreach(b2b()->retrieveProductModels($products) as $productModel)
                        <div class="col-tn-12 col-xs-6 col-sm-4 col-md-3">
                            {{--@if($result->resultType == 'webCollection')--}}
                            {{--<a href="{{$result->slugUrl()}}" class="thumbnail" style="border: 0;">--}}
                            {{--<div class="image" style="min-height: 100px; padding-top: 30px">--}}
                            {{--<img src="{{ $result->featuredImage(325, 125) }}" class="img img-responsive center-block" alt="{{$result->name}}" style="max-height: 150px">--}}
                            {{--</div>--}}
                            {{--<div class="caption text-center">--}}
                            {{--<h4>{{ $result->name }}</h4>--}}
                            {{--</div>--}}
                            {{--</a>--}}
                            {{--@else--}}

                            @if($productModel->getTable() == 'WebParts')
                                @php $firstFamily = $productModel->webFamilies->first(); @endphp
                                @php $firstCollection = $firstFamily->webCollections->first(); @endphp
                                @php $firstCategory = (isset($firstCollection)) ? $firstCollection->webCategories->first() : null; @endphp
                                @php $firstGroup = (isset($firstCategory)) ? $firstCategory->webGroups->first() : null; @endphp
                                @php $brandName = (isset($firstGroup)) ? $firstGroup->name : ""; @endphp
                                @include('partials.part-block', ['containerStyle' => 'margin: 0 10px', 'family' => $firstFamily, 'position' => $loop->index, 'visibleWebPart' => $productModel, 'brandName' => $brandName, 'list' => 'product-grid-component', 'discountBadge' => Arr::get(Arr::first($products, function ($value, $key) use ($productModel) { return (Arr::get($value, 'productId') == $productModel['id']); }), 'productDiscount'),])
                            @else
                                @php $firstCollection = $productModel->webCollections->first(); @endphp
                                @php $firstCategory = (isset($firstCollection)) ? $firstCollection->webCategories->first() : null; @endphp
                                @php $firstGroup = (isset($firstCategory)) ? $firstCategory->webGroups->first() : null; @endphp
                                @php $brandName = (isset($firstGroup)) ? $firstGroup->name : ""; @endphp
                                @include('partials.family-block', ['containerStyle' => 'margin: 0 10px', 'family' => $productModel, 'position' => $loop->index, 'visibleWebPart' => $productModel->visibleWebParts->first(), 'brandName' => $brandName, 'list' => 'product-grid-component', 'discountBadge' => Arr::get(Arr::first($products, function ($value, $key) use ($productModel) { return (Arr::get($value, 'productId') == $productModel['id']); }), 'productDiscount'),])
                            @endif
                        </div>
                        <div class="col-xs-12 visible-tn-block"><hr></div>
                        @if ($loop->iteration % 2 == 0)
                            <div class="clearfix visible-xs-block"><hr></div><div class="col-xs-12 visible-xs-block"><hr></div>
                        @endif
                        @if ($loop->iteration % 3 == 0)
                            <div class="clearfix visible-sm-block"><hr></div><div class="col-xs-12 visible-sm-block"><hr></div>
                        @endif
                        @if ($loop->iteration % 4 == 0)
                            <div class="clearfix visible-md-block visible-lg-block"><hr></div><div class="col-xs-12 visible-md-block visible-lg-block"><hr></div>
                        @endif
                        {{--@if ($loop->iteration % 6 == 0)--}}
                            {{--<div class="clearfix visible-lg-block"><hr></div><div class="col-xs-12 visible-lg-block"><hr></div>--}}
                        {{--@endif--}}
                    @endforeach
                </div>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript">
    $(document).ready(function() {
        fetchAllPrices{{ $productsGridId }}();
    });

    function fetchAllPrices{{ $productsGridId }}(){
        var pricingData = {};
        var pricingResponse = null;

        $.ajax({
            type: 'POST',
            url: '{{route('families.prices')}}',
            data: {
                _token: _csrf_token,
                pricingData: {!! json_encode(b2b()->formatFamilyPricingData(b2b()->retrieveProductModels($products, true, false))) !!}
            },
            success: function(data){
                pricingResponse = data;
            },
            error: function(){
                $.each(pricingData, function(familyId, data){
                    if($('.price-loader-' + familyId).is(":visible")) {
                        $('.item-price-' + familyId).append('<strong class="price-unavailable" style="color: red">{!! trans('messages.temporarily_unavailable') !!}</strong>');
                        $('.price-loader-' + familyId).hide();
                    }

                    let $familyBlockDiv = $('.item-price-' + familyId).parents('div[class^="family-block-item"]').eq(0);
                    if($familyBlockDiv.find('.quantity-add-to-cart-button').length) {
                        $familyBlockDiv.find('.quantity-add-to-cart-button').prop('disabled', true);
                        $familyBlockDiv.find('.quantity-select-box').prop('disabled', true);
                        $familyBlockDiv.find('.quantity-select-box').val(0);
                        $familyBlockDiv.find('.select-item-link').data('family-price', '');
                    }
                });
            },
            complete: function(){
                let impressions = [];
                $.each(pricingResponse, function(familyId, prices){
                    if($('.price-loader-' + familyId).is(":visible")) {
                        let $familyBlockDiv = $('.item-price-' + familyId).parents('div[class^="family-block-item"]').eq(0);
                        if (prices === '{!! trans('messages.temporarily_unavailable') !!}') {
                            if($familyBlockDiv.find('.quantity-add-to-cart-button').length) {
                                $familyBlockDiv.find('.quantity-add-to-cart-button').prop('disabled', true);
                                $familyBlockDiv.find('.quantity-select-box').prop('disabled', true);
                                $familyBlockDiv.find('.quantity-select-box').val(0);
                                $familyBlockDiv.find('.select-item-link').data('family-price', '');
                            }
                            $('.item-price-' + familyId).append('<strong class="price-unavailable" style="color: red">{!! trans('messages.temporarily_unavailable') !!}</strong>');
                        }
                        else {
                            $familyBlockDiv.find('.select-item-link').data('family-price', prices['minPrice']);
                            if(prices['minPrice'] != prices['maxPrice']){
                                $('.item-price-' + familyId).append(prices['minPriceFormatted'] + ' - ' + prices['maxPriceFormatted']);
                            }else{
                                $('.item-price-' + familyId).append(prices['minPriceFormatted']);
                            }
                        }
                        $('.price-loader-' + familyId).hide();
                        impressions.push({
                            'id': $familyBlockDiv.data('part-number'),
                            'name': $familyBlockDiv.data('part-name'),
                            'price': $familyBlockDiv.find('.select-item-link').data('family-price'),
                            'brand': $familyBlockDiv.data('brand'),
                            'category': $familyBlockDiv.data('category'),
                            'position': $familyBlockDiv.data('position'),
                            'list': 'product-grid-component',
                        });
                    }
                });

                @if($consentedCookies != null && in_array('marketingConsent', $consentedCookies) && !empty(b2b()->activeWebSilo()->google_tracking))
                dataLayer.push({
                    'event': 'view_item_list',
                    'ecommerce': {
                        'currencyCode': '{{b2b()->activeCurrency()}}',
                        'impressions': impressions
                    }
                });
                @endif
            }
        });


        $.ajax({
            type: 'POST',
            url: '{{route('parts.prices')}}',
            data: {
                _token: _csrf_token,
                pricingData: {!! json_encode(b2b()->formatPartPricingData(b2b()->retrieveProductModels($products, false, true))) !!}
            },
            success: function(data){
                pricingResponse = data;
            },
            error: function(){
                $.each(pricingData, function(partNumber, data){
                    if($('.part-price-loader-' + partNumber).is(":visible")) {
                        $('.part-item-price-' + partNumber).append('<strong class="price-unavailable" style="color: red">{!! trans('messages.temporarily_unavailable') !!}</strong>');
                        $('.part-price-loader-' + partNumber).hide();
                    }
                    let $partBlockDiv = $('.part-item-price-' + partNumber).parents('div[class^="part-block-item"]').eq(0);
                    if($partBlockDiv.find('.quantity-add-to-cart-button').length) {
                        $partBlockDiv.find('.quantity-add-to-cart-button').prop('disabled', true);
                        $partBlockDiv.find('.quantity-select-box').prop('disabled', true);
                        $partBlockDiv.find('.quantity-select-box').val(0);
                        $partBlockDiv.find('.select-item-link').data('part-price', '');
                    }
                });
            },
            complete: function(){
                let impressions = [];
                $.each(pricingResponse, function(partNumber, prices){
                    if($('.part-price-loader-' + partNumber).is(":visible")) {
                        let $partBlockDiv = $('.part-item-price-' + partNumber).parents('div[class^="part-block-item"]').eq(0);
                        if (prices === '{!! trans('messages.temporarily_unavailable') !!}') {
                            if($partBlockDiv.find('.quantity-add-to-cart-button').length) {
                                $partBlockDiv.find('.quantity-add-to-cart-button').prop('disabled', true);
                                $partBlockDiv.find('.quantity-select-box').prop('disabled', true);
                                $partBlockDiv.find('.quantity-select-box').val(0);
                                $partBlockDiv.find('.select-item-link').data('part-price', '');
                            }
                            $('.part-item-price-' + partNumber).append('<strong class="price-unavailable" style="color: red">{!! trans('messages.temporarily_unavailable') !!}</strong>');
                        }
                        else {
                            $('.part-item-price-' + partNumber).append(prices['priceFormatted']);
                            $partBlockDiv.find('.select-item-link').data('part-price', prices['price']);
                        }
                        $('.part-price-loader-' + partNumber).hide();
                        impressions.push({
                            'id': $partBlockDiv.data('part-number'),
                            'name': $partBlockDiv.data('part-name'),
                            'price': $partBlockDiv.find('.select-item-link').data('part-price'),
                            'brand': $partBlockDiv.data('brand'),
                            'category': $partBlockDiv.data('category'),
                            'position': $partBlockDiv.data('position'),
                            'list': 'product-grid-component',
                        });
                    }
                });

                @if($consentedCookies != null && in_array('marketingConsent', $consentedCookies) && !empty(b2b()->activeWebSilo()->google_tracking))
                dataLayer.push({
                    'event': 'view_item_list',
                    'ecommerce': {
                        'currencyCode': '{{b2b()->activeCurrency()}}',
                        'impressions': impressions
                    }
                });
                @endif
            }
        });
    }
</script>
@endif