window.PriceListProfitCenterAdmin=function (options) {
    /*
     * Variables accessible
     * in the class
     */
    let Opts = {
        token: null,
        containerCssSelector: '.containerPriceListProfitCenter',
        testMode: false,
        URL: {
            getDataTableContent: '',
            getProductGroupHTML: '',
            index: '',
            show: '',
            edit: '',
            create: '',
            store: '',
            update: '',
            destroy: '',
        },
        dataTable: {
            orderDirective: [1, 'asc']
        },
        onAfterInitViewDetails: function () {
        }
    };
    let root = this;
    /*
     * Constructor
     */
    this.construct = function (options, SupplierItem) {
        console.log('PriceListProfitCenterAdmin constructor called');
        $.extend(Opts, options);
    };
    this.getOpts = function () {
        return Opts;
    }
    let changeParameter={
        supplier:'',
        profitCenter:'',
        deliveryDate:'',
        /*
        supplier:26,
        profitCenter:49,
        deliveryDate:'2023-09-10',
        */

    }

    this.checkRefreshPossible=function (){
        console.log('check need parameter');
        let needRefresh=true;
        $.each(changeParameter,function (name,data){
            if(data===''){
                needRefresh=false;
            }
        });
        if(needRefresh){
            root.refreshDatatable()
            root.refreshProductGroup();
            root.setDatatableHeaderText('');
        }
    }
    this.setDatatableHeaderText=function(text){
        $('.tableHeaderText').text(text);
    }

    this.getTreePathName=function (node){
        let res='';
        let items=$(node).parents('li').toArray();
        items.shift();
        items.reverse();
        for (const item in items) {
            if($(items[item]).children('a.categoryItem').length>0){
                res+=$(items[item]).children('a.categoryItem').text()+'/'
            }
        }
        res+=$(node).text();
        return res;
    }

    this.bindProductGroupItem=function(){
        $('.sidebar-menu .sidebar-dropdown .sidebar-submenu li a.categoryItem.clickable').off('click');
        $('.sidebar-menu .sidebar-dropdown .sidebar-submenu li a.categoryItem.clickable').on('click',
            function () {
                let groupId=$(this).data('id');
                selectedProductGroup=groupId;
                root.setDatatableHeaderText(root.getTreePathName(this));
                /*
                console.log(groupId);
                console.log(root.getTreePathName(this));
                */
                root.refreshDatatable();
            });


    }
    this.refreshProductGroup=function (){
        let ajaxData={
            'supplierId':changeParameter.supplier,
            'deliveryDate':changeParameter.deliveryDate
        }
        let ajaxUrl=Opts.URL.getProductGroupHTML;
        $.ajax({
            url:ajaxUrl,
            data:ajaxData,
            type:'GET',
            contentType:false,
            processData: true,
            beforeSend: function() {

            },
            success: function(data) {
                $('.sidebar-menu .productGroup').find('ul').html(data);
                root.bindProductGroupItem();
            },
            error: function(data) {
                ajaxErrorFieldHandler(data.responseJSON.error);
            }
        })

    }
    this.refreshDatatable=function (){
        $('.dataTableOrderProductSelect').DataTable().ajax.reload();
    }


    this.changePriceListProfitCenterParameter=function(e,obj){
        if(typeof obj =='undefined'){
            obj=$(this);
        }
        let objName=obj.attr("name");
        if(objName=='supplier'){
            selectedProductGroup=null;
        }
        let data='';
        if(obj.get(0).nodeName=='SELECT'){
            if(obj.select2('data').length>0){
                data=obj.select2('data')[0].id;
            };
        }else{
            data=obj.val()
        }
        if(changeParameter[objName]!=data){
            changeParameter[objName]=data;
            root.checkRefreshPossible();
        }
    }

    this.init=function (options){
        $.extend(Opts, options);
        let CSSSelectorForm=Opts.containerCssSelector;
        $(CSSSelectorForm+' .datePickerClick').click(function(){
            $(CSSSelectorForm+' .datePicker').datepicker('show');
        });

        $('.supplierSelect').on('change',root.changePriceListProfitCenterParameter);
        $('.profitCenterSelect').on('change',root.changePriceListProfitCenterParameter);

        //$('input[name="deliveryDate"]').on('change',changePriceListProfitCenterParameter);


        $(".supplierSelect").select2({
            maximumSelectionLength: 1,
        });
        /*
        */
        $(".profitCenterSelect").select2({
            maximumSelectionLength: 1,
        });

        $(CSSSelectorForm + ' .datePicker').datepicker({
            dateFormat: 'yy-mm-dd',
            minDate: new Date(),
            onSelect: function (dateText,obj) {
                $(CSSSelectorForm + ' .selectedDateText').text(dateText);
                $('.deliveryDatePlace').text(dateText.replaceAll('-', '.') + '.');
                $(CSSSelectorForm + ' input[name="deliveryDate"]').val(dateText);
                root.changePriceListProfitCenterParameter(null,$(obj.input));
            },
        });
        //root.initViewList();
        let table = root.getDatatables('');
        $('.dataTableOrderProductSelect').on( 'draw.dt',root.productSelectDataTableDrawDT).dataTable();
        /*
          /!*
          ----------------------------------------------------------
           Add event listener for opening and closing details
           *!/

          $('.dataTableOrderProductSelect tbody').on('click', 'td.details-control', function () {
              let tr = $(this).closest('tr');
              let row = table.row( tr );

              if ( row.child.isShown() ) {
                  // This row is already open - close it
                  row.child.hide();
                  tr.removeClass('shown');
              }
              else {
                  // Open this row
                  row.child( root.productSelectDatatablesRowFormatter(row.data()) ).show();
                  tr.addClass('shown');
                  root.bindProductDetailsAction();
              }
          } );*/
    }
    this.productSelectDataTableDrawDT=function (e) {
        //debug( 'Table draw complete: '+new Date().getTime() );

        $('td:contains("*")').html('<i class="bi bi-check-circle-fill"></i>');
        $('td.details-control').removeClass('details-control');



    }
    let selectedProductGroup=null;

    this.getDatatables=function (orderType){
        let table = $('.dataTableOrderProductSelect').DataTable( {
            language: {
                url: '//cdn.datatables.net/plug-ins/1.10.24/i18n/Hungarian.json'
            },

            //"ajax": "{{asset('exapmle2.json')}}",
            "ajax": {
                url:Opts.URL.getDataTableContent,
                data:function (data) {
                    /*
                                            data.searchStr=dataTableSearchStr;
                                            data.krel=dataTableSearchKrel;
                                            data.groupId=selectedProductGroup;
                    */
                    data.supplierId=changeParameter.supplier;
                    data.profitCenterId=changeParameter.profitCenter;
                    data.deliveryDate=changeParameter.deliveryDate;
                    data.groupId=selectedProductGroup;
                }
            },
            buttons: {
                buttons: []
            },
            "columnDefs": APP.OrderModule.productSelectDataTableColumnDefs(),
            "columns": APP.OrderModule.productSelectDataTableColumn(),
            "order": [[1, 'asc']],
        } );
        return table;
    }


}
