
{{--
<script src="https://cdn.datatables.net/colreorder/2.0.4/js/dataTables.colReorder.js"></script>
<script src="https://cdn.datatables.net/colreorder/2.0.4/js/colReorder.dataTables.js"></script>
--}}

<div class="page-wrapper chiller-theme toggled">

    @include('admin.statistics.navSidebar');

    <main class="page-content">

        <div class="container  containerStatisticsAdmin" style="display: none" >
            <form class="statisticsAdminForm needs-validation" enctype="multipart/form-data">
                @csrf
@include('admin.statistics.filter')
                <input type="hidden" name="type" value="">
                <div class="form-group row">
                    <div class="col-sm-10">
                        <button type="button" class="btn btn-success FormSendButton" inputmode="text" value="">Lekérdezés inditása</button>
                    </div>
                </div>

            </form>
        </div>

        <div class="table-responsive-xl statisticResultContainer" >

        </div>
        <template data-name="statisticLoading">
            <div class="d-flex justify-content-center" >
                <strong>Loading...</strong>
                <div class="spinner-border ml-1" role="status" aria-hidden="true"></div>
            </div>
        </template>

        <template data-name="dataTableOrderFrequency">
        <div class="container-fluid " >
            <table class="dataTable display" style="width:100%">
                <thead>
                <tr>
                    <th>Beszállító</th>
                    <th>Profitcenter név</th>
                    <th>Minimum szállítási érték</th>
                    <th>Átlag szállítási érték</th>
                    <th>Maximum szállítási érték</th>
                    <th>Összes szállítási érték</th>
                    <th>Szállítások darabszáma</th>
                </tr>
                </thead>
                <tfoot>
                <tr>
                    <th>Totál</th>
                    <th colspan="4"></th>
                    <th data-name="footerSumPrice" class="dt-right">12345678</th>
                    <th data-name="footerSumOrderCount" class="dt-right">123</th>
                </tr>
                </tfoot>
            </table>
        </div>
        </template>
        <template data-name="dataTableProductAmount">
            <div class="container-fluid " >
                <table class="dataTable display" style="width:100%">
                    <thead>
                    <tr>
                        <th>Beszállító</th>
                        <th>Profitcenter név</th>
                        <th>Gyártó</th>
                        <th>Termék Főcsoport</th>
                        <th>Termék alcsoport 1</th>
                        <th>Termék alcsoport 2</th>
                        <th>Termék megnevezése</th>
                        <th>Horeyca megnevezés</th>
                        <th>Aktuális Ár</th>
                        <th>Rendelt mennyiség/legkisebb eladási egység</th>
                        <th>Mennyiségi egység/amira a megadott ár vonatkozik</th>
                        <th>Érték</th>
                    </tr>
                    </thead>
                    <tfoot>
                    <tr>
                        <th>Totál</th>
                        <th colspan="8"></th>
                        <th data-name="footerQuantity" class="dt-right">123</th>
                        <th data-name="footerOrderValue" class="dt-right">1234</th>
                        <th data-name="footerSumAmount" class="dt-right">1234</th>
                    </tr>
                    </tfoot>
                </table>
            </div>
        </template>
        <template data-name="dataTablePriceChange">
            <div class="container-fluid " >

                <table class="dataTable display" style="width:100%">
                    <thead>
                    <tr>
                        <th>Beszállító</th>
                        <th>Gyártó</th>
                        <th>Termék Főcsoport</th>
                        <th>Termék alcsoport 1</th>
                        <th>Termék alcsoport 2</th>
                        <th>Termék megnevezése</th>
                   </tr>
                    </thead>
                    <tfoot>
                    <tr>
                        <th>Beszállító</th>
                        <th>Gyártó</th>
                        <th>Termék Főcsoport</th>
                        <th>Termék alcsoport 1</th>
                        <th>Termék alcsoport 2</th>
                        <th>Termék megnevezése</th>
                    </tr>
                    </tfoot>
                </table>
            </div>
        </template>
    </main>
</div>

<style>
    .priceListProfitCenterForm .selectedDateText{
        vertical-align: super;
        padding: 5px;
        display: inline;

    }
    td.details-control {
        background: url('{{asset('images/icons/details_open.png')}}') no-repeat center center;
        cursor: pointer;
    }
    tr.shown td.details-control {
        background: url('{{asset('images/icons/details_close.png')}}') no-repeat center center;
    }

    div.page-wrapper.toggled{
        margin-left: 250px;
    }

</style>




<script>

    $(document).ready(function() {
        //$('.supplierSelect').select2('data').length;

        window.StatisticsAdmin=function (options) {
            /*
             * Variables accessible
             * in the class
             */
            let Opts = {
                token: null,
                containerCssSelector: '.containerStatisticsAdmin',
                container:null,
                resultContainerSelector:'.statisticResultContainer',
                resultContainer:null,
                testMode: false,
                filters:{
                    OrderFrequency:{},
                    PriceChange:{},
                    ProductAmount:{},
                },
                URL: {
                    getDataTableContent: '',
                    getProductSearch:'',
                    getStat:'',
                    index: '',
                    show: '',
                    edit: '',
                    create: '',
                    store: '',
                    update: '',
                    destroy: '',
                },
                type:null,
                dataTable: {
                    orderDirective: [1, 'asc']
                },
                onAfterInit: function () {
                }
            };
            let root = this;
            /*
             * Constructor
             */
            this.construct = function (options, SupplierItem) {
                console.log('StatisticsAdmin constructor called');
                $.extend(Opts, options);
            };
            this.getOpts = function () {
                return Opts;
            }

            this.init=function (options) {
                $.extend(Opts, options);
                let CSSSelectorForm = Opts.containerCssSelector;
                root.initNavBarButton();
                root.initView();
            }

            this.initView=function (){

                $.fn.DataTable.Api.register( 'sum()', function () {
                    var sum = 0;

                    for ( var i=0, ien=this.length ; i<ien ; i++ ) {
                        sum += this[i];
                    }

                    return sum;
                } );

                root.container=$(Opts.containerCssSelector);
                root.container.hide();
                root.resultContainer=$(Opts.resultContainerSelector);
                root.container.find('select.supplierSelect, select.profitCenterSelect, select.productGroupSelect, select.producerSelect, select.hooreycaNamesSelect, select.specialOfferSelect').select2();
                debug(root.container.find('select.product'));
                root.container.find('select.productSelect').select2({
                    placeholder: '...',
                    allowClear: true,
                    ajax: {
                        url: Opts.URL.getProductSearch,
                        dataType: 'json',
                        data: function(params) {
                            return {
                                term: params.term || '',
                                page: params.page || 1,
                                supplierId: root.container.find('select.supplierSelect').val(),
                            }
                        },
                        cache: true
                    }
                });
                root.container.find('.datePickerFrom, .datePickerTo').datepicker({
                    dateFormat: 'yy-mm-dd',

                    onSelect: function (dateText,obj) {
                        debug(this);
                        debug(obj.input);
/*
                        root.container.find('.selectedDateText').text(dateText);
                        $('.deliveryDatePlace').text(dateText.replaceAll('-', '.') + '.');
                        root.container.find(' input[name="deliveryDate"]').val(dateText);
*/
                        //root.changePriceListProfitCenterParameter(null,$(obj.input));
                    },
                });
                root.container.find('.datePickerClick').click(function(){
                    debug($(this).data('action'));
                    root.container.find('input[name="'+$(this).data('action')+'"]').datepicker('show');
                });
                let button=root.container.find('.FormSendButton');
                button.off('click');
                button.on('click',function (){
                    debug ('FormSendButton click');
                    root.loadingResultContainer();
                    root.requestStatistics();

                });


            }

            this.formDataToDataObjectAPICall = function (CSSSelectorForm) {
                let ajaxData = new FormData(root.container.find('form')[0]);
                $.each(ajaxData.getAll('supplier'), function (key, value) {
                    ajaxData.append('suppliers[]', value);
                })
                ajaxData.delete('supplier');
                $.each(ajaxData.getAll('profitCenter'), function (key, value) {
                    ajaxData.append('profitCenters[]', value);
                })
                ajaxData.delete('profitCenter');
                $.each(ajaxData.getAll('productGroup'), function (key, value) {
                    ajaxData.append('productGroups[]', value);
                })
                ajaxData.delete('productGroup');
                $.each(ajaxData.getAll('product'), function (key, value) {

                    ajaxData.append('products[]', value);
                })
                ajaxData.delete('product');
                $.each(ajaxData.getAll('producer'), function (key, value) {
                    ajaxData.append('producers[]', value);
                })
                ajaxData.delete('producer');
                $.each(ajaxData.getAll('hooreycaName'), function (key, value) {
                    ajaxData.append('hooreycaNames[]', value);
                })
                ajaxData.delete('hooreycaName');

                ajaxData.append('_token', root.container.find('input[name=_token]').val());

/*
                $(CSSSelectorForm + ' input[data-inputmask]').each(function () {
                    let indexKey = $(this).attr('name');
                    if (ajaxData.get(indexKey)) {
                        ajaxData.set(indexKey, ajaxData.get(indexKey).replace(/[_ ]+$/g, ""));
                    }
                });
*/
                return ajaxData;

            }

            this.requestStatistics=function () {
                let ajaxUrl=Opts.URL.getStat;
                let ajaxMethod='POST';
                //token formdataba!
                debug(ajaxUrl);

                let ajaxData=root.formDataToDataObjectAPICall();
                console.log('======================');
                for (let pair of ajaxData.entries()) {
                    console.log(pair[0]+ ', ' + pair[1]);
                }
                $.ajax({
                    url:ajaxUrl,
                    data:ajaxData,
                    type:ajaxMethod,
                    contentType:false,
                    processData: false,
                    headers: {
                        'X-CSRF-TOKEN': $('input[name="_token"]').val()
                    },

                    success:function (data){
                        if(data.success==true){
                            root.processStatisticsResponse(data);

                            /*
                            //Opts.onAfterInitViewDetails=root.autofillDetails;
                            Opts.dataTable.orderDirective=[0, 'desc'];
                            Toast.create("Sikeres rögzítés!", ajaxData.get('name')+" nevű beszálllító elmentve", TOAST_STATUS.SUCCESS,5000);
                            APP.loadMainContent(Opts.URL.index+'?init=0',root.initViewList);

                             */
                        }
                    }
                });


            }

            this.clearResultContainer=function (){
                debug('clearResultContainer');
                debug(root.resultContainer);
                root.resultContainer.html('');
            }

            this.loadingResultContainer=function (){
                debug('clearResultContainer');
                debug(root.resultContainer);
                root.clearResultContainer();
                let template=$('template[data-name="statisticLoading"]').html()
                root.resultContainer.html(template);
            }

            this.setVisibleFilters=function (type){
                console.log(Opts.filters[type]);
                $(root.container).find('div[class*="filter"]').hide()
                for (const typeIndex in Opts.filters[type]) {
                    const typeName=Opts.filters[type][typeIndex];
                    debug(typeName);
                    $(root.container).find('.filter_'+typeName).show();
                }
            }
            this.initNavBarButton=function () {
                debug('asdadasd');
                $('nav a.sidebar').off('click');
                $('nav a.sidebar').on('click',function (){

                    //let type=$(this).data('action');

                    root.clearResultContainer();
                    root.type=$(this).data('action');
                    root.container.show();
                    root.setVisibleFilters(root.type);

                    debug(root.type);
                    $('nav a.sidebar').parent().removeClass('menuItemActive');
                    $(this).parent().toggleClass('menuItemActive');

                    root.container.find('input[name="type"').val(root.type);
                    /*
                    $('.containerStatisticsAdmin').load(
                        Opts.URL.show.replace('%id%',type)
                    );
                    */
                });
            }


            this.processStatisticsResponse=function(data){
                debug(data.ret.SQL);
                root.clearResultContainer();
                //root.processOrderFrequencyResponse(data);
                const functionName='process'+root.type+'Response';
                if(typeof root['process'+root.type+'Response'] ==='function' ){
                    root['process'+root.type+'Response'](data);
                }else{
                    alert('Unknown stat function!');
                }
            }
            this.processPriceChangeResponse=function(data){
                root.clearResultContainer();
                //root.resultContainer.html('<img src="{{asset('images/pictures/uc.jpg')}}">');
                root.initDatatablePriceChange(data.ret.data);
            }

            this.processOrderFrequencyResponse=function(data){
                root.initDatatableOrderFrequency(data.ret.data);
            }

            this.processProductAmountResponse=function(data){
                root.initDatatableProductAmount(data.ret.data);
            }

            this.initDatatablePriceChange =function (tableData){
                let template = $($('template[data-name="dataTablePriceChange"]').html())
                //root.resultContainer.html(template);
                let changesDate=tableData.changeDate;

                let DataTableColumns=[
                    { "data": "supplier_name" },
                    { "data": "producer_name" },
                    { "data": "productGroupData.1" },
                    { "data": "productGroupData.2" },
                    { "data": "productGroupData.3" },
                    { "data": "name" },
                ];
                console.log(changesDate);
                $.each(changesDate, function () {
                    let dateStr=this.replaceAll('-','.')+'.';
                    template.find('thead tr').append('<th>'+dateStr+'</th>');
                    template.find('tfoot tr').append('<th>'+dateStr+'</th>');
                    DataTableColumns.push({"data":"changes."+this.replace(/\D/g,'')});
                });
                root.resultContainer.html(template.html());

                let dataTableCSSSelector=Opts.resultContainerSelector+' .dataTable';
                debug(tableData.changedProducts);
                $(dataTableCSSSelector).DataTable( {
                    language: {
                        url: '//cdn.datatables.net/plug-ins/1.10.24/i18n/Hungarian.json'
                    },
                    data:tableData.changedProducts,
                    //"ajax": "{{asset('exapmle2.json')}}",
                    //"ajax": Opts.URL.getDataTableContent,

                    buttons: {
                        buttons: [
                            'excel','pdf',
                            {
                                footer:true,
                                extend: 'print',
                                //text: 'Print current page',
                                'title': 'Árváltozás statisztika',
                                //'messageTop': 'Message On Top',
                                autoPrint: true
                            },
                        ]
                    },
                    columnDefs: [{
                        "defaultContent": "-",
                        "targets": "_all"
                    },
                      /*  {
                            targets: [8,9,10,11],
                            className: 'dt-body-right',
                            render: $.fn.dataTable.render.number(' ', '.', 0, '')
                        }*/


                    ],
                    "columns": DataTableColumns,

                } );

            }



            this.initDatatableProductAmount =function (tableData){
                let template=$('template[data-name="dataTableProductAmount"]').html()

                root.resultContainer.html(template);

                let dataTableCSSSelector=Opts.resultContainerSelector+' .dataTable';
                debug(tableData);
                $(dataTableCSSSelector).DataTable( {
                    language: {
                        url: '//cdn.datatables.net/plug-ins/1.10.24/i18n/Hungarian.json'
                    },
                    data:tableData,
                    //"ajax": "{{asset('exapmle2.json')}}",
                    //"ajax": Opts.URL.getDataTableContent,

                    buttons: {
                        buttons: [
                            'excel','pdf',
                            {
                                footer:true,
                                extend: 'print',
                                //text: 'Print current page',
                                'title': 'Rendelés Gyakoriság statisztika',
                                //'messageTop': 'Message On Top',
                                autoPrint: true
                            },
                        ]
                    },
                    columnDefs: [{
                        "defaultContent": "-",
                        "targets": "_all"
                    },
                        {
                            targets: [8,9,10,11],
                            className: 'dt-body-right',
                            render: $.fn.dataTable.render.number(' ', '.', 0, '')
                        }


                    ],
                    "columns": [
                        { "data": "supplier_name" },
                        { "data": "order_archive.profit_center_name" },
                        { "data": "producer_name" },
                        { "data": "productGroupData.1" },
                        { "data": "productGroupData.2" },
                        { "data": "productGroupData.3" },
                        { "data": "name" },
                        { "data": "buyerProductName" },
                        { "data": "price",
                            render: function (data, type, row) {
                                return type === 'export' ? data.replace(/ /g, '') : data;
                            } },
                        { "data": "quantity",
                            render: function (data, type, row) {
                                return type === 'export' ? data.replace(/ /g, '') : data;
                            } },
                        { "data": "sum_quantity",
                            render: function (data, type, row) {
                                return type === 'export' ? data.replace(/ /g, '') : data;
                            }
                            /*
                            render: function ( data, type, row ) {

                                return row.quantity * row.unitMultiplier;
                            }

                             */
                        },
                        { "data": "amount",
                            render: function (data, type, row) {
                                return type === 'export' ? data.replace(/ /g, '') : data;
                            }
                        },

                    ],
                    //"order": orderDirective,
                    //"stateSave": true,

                    /*
                                        "drawCallback": function( settings ) {
                                            APP.datatableAddRowAction(dataTableCSSSelector);
                                        }
                    */
                    footerCallback: function (row, data, start, end, display) {
                        let api = this.api();
                        console.log(row);
                        console.log(data);
                        console.log(start);
                        console.log(end);
                        console.log(display);


                        let footerQuantity=api.column(9).data().sum();
                        let footerOrderValue=api.column(10).data().sum();
                        let footerSumAmount=api.column(11).data().sum();
                        console.log(footerQuantity);
                        console.log(footerOrderValue);
                        console.log(footerSumAmount);
                        $(row).find('*[data-name="footerQuantity"]').html( $.fn.dataTable.render.number(' ', '.', 0, '').display(footerQuantity));
                        $(row).find('*[data-name="footerOrderValue"]').html($.fn.dataTable.render.number(' ', '.', 0, '').display(footerOrderValue));
                        $(row).find('*[data-name="footerSumAmount"]').html($.fn.dataTable.render.number(' ', '.', 0, '').display(footerSumAmount));
                        /*
    <th data-name="footerQuantity" class="dt-right">123</th>
                        <th data-name="footerOrderValue" class="dt-right">1234</th>
                        <th data-name="footerSumAmount" class="dt-right">1234</th>                         */

                    }
                } );

            }

            this.initDatatableOrderFrequency=function (tableData){
                let template=$('template[data-name="dataTableOrderFrequency"]').html()
                root.resultContainer.html(template);

                let dataTableCSSSelector=Opts.resultContainerSelector+' .dataTable';
                debug(tableData);
                $(dataTableCSSSelector).DataTable( {
                    language: {
                        url: '//cdn.datatables.net/plug-ins/1.10.24/i18n/Hungarian.json'
                    },
                    data:tableData,
                    //"ajax": "{{asset('exapmle2.json')}}",
                    //"ajax": Opts.URL.getDataTableContent,

                    buttons: {
                        buttons: [
                            'excel','pdf',
                            {
                                footer:true,
                                extend: 'print',
                                //text: 'Print current page',
                                'title': 'Rendelés Gyakoriság statisztika',
                                //'messageTop': 'Message On Top',
                                autoPrint: true
                            },
                        ]
                    },
                    columnDefs: [{
                        "defaultContent": "-",
                        "targets": "_all"
                    },
                        {
                            targets: [2,3,4,5,6],
                            className: 'dt-body-right',
                            render: $.fn.dataTable.render.number(' ', '.', 0, '')
                        }


                    ],
                    "columns": [
                        {
                            //footer: 'First footer',
                            //title: 'First header',

                            "data": "supplier_name" },
                        { "data": "profit_center_name" },
                        { "data": "min_price" },
                        { "data": "avg_price" },
                        { "data": "max_price" },
                        { "data": "sum_price" },
                        { "data": "count_transaction" },
                    ],
                    //"order": orderDirective,
                    //"stateSave": true,

/*
                    "drawCallback": function( settings ) {
                        APP.datatableAddRowAction(dataTableCSSSelector);
                    }
*/
                    footerCallback: function (row, data, start, end, display) {
                        let api = this.api();

                        console.log(row);
                        console.log(data);
                        console.log(start);
                        console.log(end);
                        console.log(display);


                        let sumPrice=api.column(5).data().sum();
                        let sumCount=api.column(6).data().sum();
                        console.log(sumPrice);
                        console.log(sumCount);
                        $(row).find('*[data-name="footerSumPrice"]').html( $.fn.dataTable.render.number(' ', '.', 0, '').display(sumPrice));
                        $(row).find('*[data-name="footerSumOrderCount"]').html($.fn.dataTable.render.number(' ', '.', 0, '').display(sumCount));
                        /*
                        <th data-name="footerSumPrice">12345678</th>
                        <th data-name="footerSumOrderCount">123</th>
                         */

                    }
                } );

            }

            this.initDatatablePriceChangeT =function (tableData) {
                let template = $($('template[data-name="dataTablePriceChange"]').html())
                //root.resultContainer.html(template);
                let changesDate=tableData.changeDate;
                let DataTableColumns=[
                    { "data": "supplier_name" },
                    { "data": "producer_name" },
                    { "data": "productGroupData.1" },
                    { "data": "productGroupData.2" },
                    { "data": "productGroupData.3" },
                    { "data": "name" },
                ];
                console.log(changesDate);
                $.each(changesDate, function () {
                    template.find('thead tr').append('<th>'+this.replaceAll('-','.')+'.</th>');
                    template.find('tfoot tr').append('<th>'+this.replaceAll('-','.')+'.</th>');
                    DataTableColumns.push({"data":"changes."+this.replace(/\D/g,'')});
                });

                root.resultContainer.html(template.html());
                return;
            }
            };


        if(!APP.StatisticsAdmin){
            console.log('nincs APP.StatisticsAdmin')
        };
        APP.StatisticsAdmin = new window.StatisticsAdmin();
        APP.StatisticsAdmin.init({
            URL: {
                show:'{{route('admin.statistics.show',"%id%")}}',
                getProductSearch:'{{route('admin.statistics.getProductSearch')}}',
                getStat:'{{route('admin.statistics.getStat')}}',
                //getProductGroupHTML:'{{route('admin.priceListProfitCenter.getProductGroupHTML')}}',

            },
            filters:{!!$availableFilters!!}

        });

    });

</script>
