

if(typeof window.DataModelOrderArchive ==="undefined"){
    window.OrderArchiveModulDefault={
        actionFunction: function () {},
    }
    class DataModelOrderArchive extends DataModel{

        /*
         * Constructor
         */
        constructor (data,options) {
            super(data,options)
            if(typeof this.items ==="undefined"){
                this.items={};
            }
            console.log(this.constructor.name+' constructor called');
        };
    };
    window.DataModelOrderArchive=DataModelOrderArchive;
}


if(typeof window.OrderArchiveModule ==="undefined") {
    class OrderArchiveModule extends ModuleBase{
        constructor (options,data) {
            super(options,data)
            if(data!=="undefined" || data!=null){
            }else{
                this.data=new DataModelOrderArchive();
            }
            this.dataTable=null;
            this.Opts.dataTable.advanceSearchParameter={
                deliveryDateFrom:null,
                deliveryDateTo:null,
                profitCenterId:null,
                supplierId:null,
            }

        }

        datatableRowActionAttachment(rowData,node) {
            debug('call datatableRowActionAttachment');
            super.datatableRowActionAttachment(rowData,node,{defaultFileName:"order"});
        }

        datatableRowActionView(rowData,node) {
            debug('call datatableRowActionView');
            super.datatableRowActionView(rowData,node,APP.OrderArchiveModule)
            console.log('datatableRowActionEdit End');
        }

        datatableRowActionButtonClick(event) {
            debug('datatableRowActionButtonClick');
            super.datatableRowActionButtonClick(event,APP.OrderArchiveModule);
        }
        /*
        datatableRowActionButtonClick (event){
            debug('datatableRowActionButtonClick');
            let node=$(event[0].currentTarget);
            let row=$(dataTableCSSSelector).DataTable().row(node.parents('tr'));
            let rowData=row.data();
            let actionName='datatableRowAction'+node.data('buttontype').capitalize();
            if (typeof root[actionName] === "function") {
                return root[actionName](rowData,node)
            }
        }
        */
        datatableRowActionEdit(rowData,node) {
            console.log('datatableRowActionEdit Called');
            //Opts.onAfterInitViewDetails=root.autofillDetails;
            let ajaxUrl=this.Opts.URL.edit.replace('%id%',rowData.id);
                    console.log(this.Opts.URL);
                    console.log(ajaxUrl);
            /*
            */
            APP.loadMainContent(ajaxUrl);
            console.log('datatableRowActionEdit End');
        }

        initViewShow(){
            debug('call initViewShow');
            let root=APP.OrderArchiveModule;
            let styleStr='<link rel="stylesheet" href="'+root.Opts.URL.root+'/css/invoice.css">';
            $('table.invoice button.printButton').off('click');
            $('table.invoice button.printButton').on('click',function () {
                window.print();
                return;
                let newWin= window.open("");
                newWin.document.write(styleStr);
                let print=$('table.invoice').clone();
                print.find('button.printButton').remove();
//            newWin.document.write($('table.invoice').prop('outerHTML'));
                newWin.document.write(print.prop('outerHTML'));
                newWin.print();
//                newWin.close();
            });
        }

        datatableCustomHeadButtonClickCallBack(){
            console.info('hello itt vagyok');
            $('.advanceSearchModal').modal('show');
        }

        initAdvancedSearch(){
            console.log('initAdvancedSearch');
            window.datePickerTarget='';
            $('.deliveryDateFrom,.deliveryDateTo').datepicker({
                dateFormat: 'yy-mm-dd',
                //minDate:new Date(),
                onSelect:function (dateText){
                    debug('target:'+window.datePickerTarget);
                    $('.'+window.datePickerTarget+'SelectedDateText').text(dateText);
                    debug($(' input[name="'+window.datePickerTarget+'"]'));
                    $(' input[name="'+window.datePickerTarget+'"]').val(dateText);
                },
            });



            $('.datePickerClick').click(function(){
                debug($(this).data('target'));
                datePickerTarget=$(this).data('target');
                //$('.datePicker .'+datePickerTarget).datepicker('show');
                $('.'+datePickerTarget).datepicker('show');
            });
            $(".selectProfitCenter,.selectSupplier").select2({
                maximumSelectionLength: 1,
            });
            /*
            stored advanceSearchParameter restoring
            */
            let advanceFiltered=false;
           $.each(this.Opts.dataTable.advanceSearchParameter,function (k,v) {
                if(v!=null){
                    advanceFiltered=true;
                    console.log(k+' > '+v);
                    $('.advanceSearchModal input[name='+k+'],.advanceSearchModal select[name='+k+']').val(v).trigger('change');
                    $('.'+k+'SelectedDateText').text(v);
                }

            });
           if(advanceFiltered){
               $('.dt-button.btn-advanceSearchParameter').addClass('btn-success');
           }
            /*
            clearing advanceSearchParameter
            */
            $('.advanceSearchModal .buttonClear').off('click');
            $('.advanceSearchModal .buttonClear').on('click',function () {
                $('.advanceSearchModal input,.advanceSearchModal select').val('').trigger('change');
                $('.SelectedDateText').text('\xa0');
                let root=APP.OrderArchiveModule;
                $.each(root.Opts.dataTable.advanceSearchParameter,function (k,v) {
                    root.Opts.dataTable.advanceSearchParameter[k]=null;
                });
                $('.dt-button.btn-advanceSearchParameter').removeClass('btn-success');
                let dataTableCSSSelector=root.Opts.CSSSelectorContainer+' .dataTable';
                $(dataTableCSSSelector).DataTable().ajax.reload();
                $('.advanceSearchModal').modal('hide');

            });

            /*
            process advanceSearchParameter
            */
            $('.advanceSearchModal .buttonSave').off('click');
            $('.advanceSearchModal .buttonSave').on('click',function (){
                console.log('clicked advanced search ');
                let root=APP.OrderArchiveModule;
                let dataSearch=$('.advanceSearchModalForm').find('input,select').serializeArray();
                console.log(dataSearch);
                console.log(root.Opts);
                console.log(root.Opts.dataTable.advanceSearchParameter);
                $.each(root.Opts.dataTable.advanceSearchParameter,function (k,v) {
                    root.Opts.dataTable.advanceSearchParameter[k]=null;
                });
                $.each(dataSearch,function (k,item) {
                    console.log(item['name']);
                    console.log(item['value']);
                    if( typeof root.Opts.dataTable.advanceSearchParameter[item['name']]!= 'undefined'
                        && item['value'].length>0
                    ){
                        root.Opts.dataTable.advanceSearchParameter[item['name']]=item['value'];
                    }
                })
                console.log(root.Opts.dataTable.advanceSearchParameter);
                let dataTableCSSSelector=root.Opts.CSSSelectorContainer+' .dataTable';
                $(dataTableCSSSelector).DataTable().ajax.reload();
                $('.dt-button.btn-advanceSearchParameter').addClass('btn-success');
                $('.advanceSearchModal').modal('hide');
            });

        }

        initViewList(options={}) {
            debug('listview inicialization');

            if(APP.IsUserAdmin){
                this.DtColumns=[
                    { "data": "supplier_name" },
                    { "data": "deliveryDate" },
                    { "data": "profit_center.name" },
                    { "data": "deliveryAddressName" },
                    { "data": "sentTime" },
                    { "data": "humanId" },
                    { "data": "confirmed" },
                    null,
                ];
            }else{
                this.DtColumns=[
                    { "data": "supplier_name" },
                    { "data": "deliveryDate" },
                    { "data": "deliveryAddressName" },
                    { "data": "sentTime" },
                    { "data": "humanId" },
                    { "data": "confirmed" },
                    null,
                ];
            }

            let dataTableCSSSelector=this.Opts.CSSSelectorContainer+' .dataTable'; //
            let colNum=$(dataTableCSSSelector+' thead th').length; //buttons insert position need
            APP.setOpts({
                //datatableRowActionButtonClickCallBack:this.datatableRowActionButtonClick,
                datatableRowActionButtonClickCallBack:this.datatableRowActionButtonClick,
                datatableCustomHeadButtonClickCallBack:this.datatableCustomHeadButtonClickCallBack,
            })
            let orderDirective=this.Opts.dataTable.orderDirective;
            let advanceSearchParameter=this.Opts.dataTable.advanceSearchParameter;

            if(typeof options['orderDirective']!='undefined'){
                orderDirective=options['orderDirective'];
            }
            //let ajaxUrl=this.Opts.URL.getDataTableContent;
            this.dataTable=$(dataTableCSSSelector).DataTable( {
                language: {
                    url: '//cdn.datatables.net/plug-ins/1.10.24/i18n/Hungarian.json'
                },

                //"ajax": "{{asset('exapmle2.json')}}",
                "ajax": {
                    url:this.Opts.URL.getDataTableContent,
                    data:function (data) {
                        data.advanceSearchParameter=advanceSearchParameter;
/*
data.searchParam=this.Opts.dataTable.advanceSearchParameter
                        data.searchStr=dataTableSearchStr;
                        data.groupId=selectedProductGroup;
                        data.supplierId=Order.supplierId;
                        data.deliveryDate=Order.deliveryDate;
*/
                    }
                },
                "columnDefs": [
                    {
                        "targets": colNum-1,
                        "render": function ( data, type, row ) {
                            let buttons=APP.datatableAddRowViewButton(0,arguments);
                            buttons+=APP.datatableAddRowAttachmentButton(0,arguments);
                            //buttons+=APP.datatableAddRowEditButton(0, arguments);
                            if(row.canEditable){
                                buttons+=APP.datatableAddRowEditButton(0, {title:"módosítás"});
                            }
                            return buttons;
                        },
                    },
                    {
                        "targets": colNum-2,
                        "render": function ( data, type, row ) {
                            if(row.confirmed==null){
                                return '<span class="badge badge-pill badge-danger"><i class="fas fa-handshake-slash"></i></span>';
                            }else{
                                return row.confirmed;
                            }

                        },
                    },
                    {
                        "targets": 1,
                        "render": function ( data, type, row ) {
                            row=null;
                            return type === "sort" ? data.latinise() : data;
                        },
                    },
                    //{ "visible": false,  "targets": [ 0 ] }
                ],
                buttons:{
                    buttons: [
                        'excel','pdf',
                        {
                            extend: 'print',
                            //text: 'Print current page',
                            'title': 'title custom text',
                            'messageTop': 'Message On Top',
                            autoPrint: true
                        },
                        {
                            text: 'Szürők',
                            action: function ( e, dt, node, config ) {
                                APP.datatableCustomHeadButtonClickCallBack();
                            },
                            className: 'btn-advanceSearchParameter'
                        }
                        /**/
                    ]
                },
                "columns": this.DtColumns,
                "order": orderDirective,
                "stateSave": true,
                "drawCallback": function( settings ) {
                    settings=null;
                    APP.datatableAddRowAction(dataTableCSSSelector);
                }
            } );

            this.initAdvancedSearch();
            debug('listview end');
        }
    }
    window.OrderArchiveModule=OrderArchiveModule;
}
