
<script>

    (function ($, DataTable) {
        "use strict";

        var _buildParams = function (dt, action, onlyVisibles) {
            var params = dt.ajax.params();
            params.action = action;
            params._token = $('meta[name="csrf-token"]').attr('content');

            if (onlyVisibles) {
                params.visible_columns = _getVisibleColumns();
            } else {
                params.visible_columns = null;
            }

            return params;
        };

        var _getVisibleColumns = function () {

            var visible_columns = [];
            $.each(DataTable.settings[0].aoColumns, function (key, col) {
                if (col.bVisible) {
                    visible_columns.push(col.name);
                }
            });

            return visible_columns;
        };

        var _downloadFromUrl = function (url, params) {
            var postUrl = url + '/export';
            var xhr = new XMLHttpRequest();
            xhr.open('POST', postUrl, true);
            xhr.responseType = 'arraybuffer';
            xhr.onload = function () {
                if (this.status === 200) {
                    var filename = "";
                    var disposition = xhr.getResponseHeader('Content-Disposition');
                    if (disposition && disposition.indexOf('attachment') !== -1) {
                        var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
                        var matches = filenameRegex.exec(disposition);
                        if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
                    }
                    var type = xhr.getResponseHeader('Content-Type');

                    var blob = new Blob([this.response], {type: type});
                    if (typeof window.navigator.msSaveBlob !== 'undefined') {
                        // IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created. These URLs will no longer resolve as the data backing the URL has been freed."
                        window.navigator.msSaveBlob(blob, filename);
                    } else {
                        var URL = window.URL || window.webkitURL;
                        var downloadUrl = URL.createObjectURL(blob);

                        if (filename) {
                            // use HTML5 a[download] attribute to specify filename
                            var a = document.createElement("a");
                            // safari doesn't support this yet
                            if (typeof a.download === 'undefined') {
                                window.location = downloadUrl;
                            } else {
                                a.href = downloadUrl;
                                a.download = filename;
                                document.body.appendChild(a);
                                a.click();
                            }
                        } else {
                            window.location = downloadUrl;
                        }

                        setTimeout(function () {
                            URL.revokeObjectURL(downloadUrl);
                        }, 100); // cleanup
                    }
                }
            };
            xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
            xhr.send($.param(params));
        };

        var _buildUrl = function(dt, action) {
            var url = dt.ajax.url() || '';
            var params = dt.ajax.params();
            params.action = action;

            if (url.indexOf('?') > -1) {
                return url + '&' + $.param(params);
            }

            return url + '?' + $.param(params);
        };

        // Display an Editor form that allows the user to pick the CSV data to apply to each column
        function selectColumns ( editor, csv, header ) {
            var selectEditor = DataTableEditor();
            var fields = editor.order();

            //header.push([])
            //console.log(header);
            //console.log();

            for ( var i=0 ; i<fields.length ; i++ ) {
                var field = editor.field( fields[i] );

                //console.log( fields[i] );
                //console.log(header[i]);
                selectEditor.add( {
                    label: field.label(),
                    name: field.name(),
                    type: 'select',
                    options: header,
                    //def: header[i],
                    //placeholder:'Valeur'
                } );
            }

            selectEditor.create({
                title: '<?php echo e(__("Mappage des champs")); ?>',
                buttons: {
                    className: "btn-success",
                    text:'<?php echo e(__("Importer ")); ?>'+csv.length+' <?php echo e(__("enregistrement(s)")); ?>',
                    action: function () {
                        this.submit();
                    },

                },
                // message: 'Select the CSV column you want to use the data from for each field.',
                message: '<?php echo e(__("Selectionnez les champs que vous souhaitez remplir.")); ?>',
                onComplete: 'none'
            });

            selectEditor.on('submitComplete', function (e, json, data, action) {
                // Use the host Editor instance to show a multi-row create form allowing the user to submit the data.
                //editor.create(csv.length,false, null);

                editor.create( csv.length, {
                    title: '<?php echo e(__("Importation CSV")); ?>',
                    buttons: {
                        className: "btn-success",
                        text:'<?php echo e(__('Importer')); ?>',
                        action: function () {
                            this.submit( () => {
                                    //toast('success',this.title, csv.length+' <?php echo e(__("donnée(s) enregistrée(s)")); ?>');
                                    let config = {
                                        title:csv.length+' <?php echo e(__("donnée(s) enregistrée(s)")); ?>',
                                        timer: 10000,
                                        ok_button: true,
                                    };
                                    toast(config);
                                },
                                function (error) {
                                    //toast('error',this.title,'' ,false,"center");

                                    let config = {
                                        title:"<?php echo e(__("Des erreurs sont survenues lors de l'importation")); ?>",
                                        icon:'error',
                                        position:'center',
                                        timer: false,
                                        ok_button: true,
                                    };
                                    toast(config);
                                },
                                null,
                                false
                            );
                        },

                    },
                    //message: 'Click the <i>Submit</i> button to confirm the import of '+csv.length+' rows of data. Optionally, override the value for a field to set a common value by clicking on the field below.'
                    message: "<?php echo __("Cliquez sur le boutton <b>Importer</b> pour confirmer l'importation de"); ?> "+csv.length+" <?php echo e(__("enregistrement(s)")); ?>."
                } );

                for ( var i=0 ; i<fields.length ; i++ ) {
                    var field = editor.field( fields[i] );
                    var mapped = data[ field.name() ];

                    for ( var j=0 ; j<csv.length ; j++ ) {
                        field.multiSet( j, csv[j][mapped] );
                    }
                }
                // editor.
            } );
        }

        // Upload Editor - triggered from the import button. Used only for uploading a file to the browser
        var uploadEditor = DataTableEditor( {
            fields: [ {
                label: '<?php echo e(__("Fichier CSV")); ?> :',
                name: 'csv',
                type: 'upload',
                ajax: function ( files, done ) {
                    // Ajax override of the upload so we can handle the file locally. Here we use Papa
                    // to parse the CSV.
                    Papa.parse(files[0], {
                        header: true,
                        skipEmptyLines: true,
                        complete: function (results) {
                            if ( results.errors.length ) {
                                // console.log( results );
                                uploadEditor.field('csv').error('<?php echo e(__("Erreur lors de l\'importation")); ?> : '+ results.errors[0].message );
                            }
                            else {
                                selectColumns( current_editor, results.data, results.meta.fields );
                            }

                            // Tell Editor the upload is complete - the array is a list of file
                            // id's, which the value of doesn't matter in this case.
                            done([0]);
                        }
                    });
                }
            } ]
        } );


        //CUSTOM FIELDS
        var Editor = DataTable.Editor;
        var _fieldTypes = DataTable.ext.editorFields;

        _fieldTypes.state = {
            create: function (conf) {
                conf._enabled = true;

                // Create the elements to use for the input
                conf._input = document.createElement('div');
                conf._input.id = Editor.safeId(conf.id);

                // Build button 1 (To do) and its event listener
                let button1 = document.createElement('button');
                button1.type = 'button';
                button1.value = 0;
                button1.classList.add('inputButton');
                button1.textContent = 'To do';
                conf._input.appendChild(button1);

                button1.addEventListener('click', () => {
                    if (conf._enabled) {
                        this.set(conf.name, button1.value);
                    }
                });

                // Build button 2 (Done) and its event listener
                let button2 = document.createElement('button');
                button2.type = 'button';
                button2.value = 1;
                button2.classList.add('inputButton');
                button2.textContent = 'Done';
                conf._input.appendChild(button2);

                button2.addEventListener('click', () => {
                    if (conf._enabled) {
                        this.set(conf.name, button2.value);
                    }
                });

                return conf._input;
            },

            get: function (conf) {
                return conf._input.querySelector('button.selected').value;
            },

            set: function (conf, val) {
                let current = conf._input.querySelector('button.selected');

                if (current) {
                    current.classList.remove('selected');
                }

                conf._input
                    .querySelector('button.inputButton[value="' + val + '"]')
                    .classList.add('selected');
            },

            enable: function (conf) {
                conf._enabled = true;
                conf._input.classList.remove('disabled');
            },

            disable: function (conf) {
                conf._enabled = false;
                conf._input.classList.remove('add');
            }
        };


        //BUTTTONS INITIALISATIONS

        DataTable.ext.buttons.excels = {
            className: 'buttons-excel',

            text: function (dt) {
                return '<i class="fa fa-file-excel"></i> ' + dt.i18n('buttons.excel', 'Excel');
            },
            customize: function( xlsx ) {
                // setSheetName(xlsx, 'Calls');
                // addSheet(xlsx, '#example2', 'My Sheet2', 'Summary2', '2');
            },

            action: function (e, dt, button, config) {
                //let url = _buildUrl(dt, 'excel');
              //  window.location = _buildUrl(dt, 'excel');
              //   let url = dt.ajax.url() || window.location.href;
              //   let params = _buildParams(dt, 'excel', true);
              //
              //   _downloadFromUrl(url, params);

                // console.log(e);
                // console.log(dt);
                // console.log(button);
                // console.log(config);

                let info = dt.buttons.exportInfo();

                console.log(info)
            },

        };

        //Initialisation du bouton ""
        DataTable.ext.buttons.export = {
            extend: 'collection',
            className: 'btn-info text-white',
            attr : {
                title: '<?php echo e(__("Export")); ?>' ,
                icon:'<i class="fa fa-download"></i> ',
                btns : {
                    csv : {
                        attr : { title: '<?php echo e(__("CSV")); ?>' , icon:'<i class="fa fa-file-csv"></i> '},
                        text:  (dt,button,config) => config.attr.icon + config.attr.title,
                        exportOptions: {
                            columns: [ ':visible' ]
                        },

                    }
                }
            },
            text: function (dt,button,config) {
                //  var label = config.attr.title;
                return config.attr.icon + dt.i18n('buttons.export',"") + '&nbsp;<span class="caret"/>';
            },
            fade: true,
            buttons: ["csv", 'excel', 'pdf'],
        };

        //Initialisation d'un bouton "Print"
        $.extend(DataTable.ext.buttons.print,{
            className: 'btn-warning',
            attr : {title: '<?php echo e(__("Print")); ?>'},
            text: function (dt,button,config) {
                let label = config.attr.title;
                return  '<i class="fa fa-print"></i> ' + dt.i18n('buttons.print', '');
            },
            //title: ()=> '', //Titre du rapport
            //messageTop: ()=> '',
            //messageBottom: ()=> '<small style="color: darkred"> SS sdsd</small>',
            actionss: function (e, dt, button, config) {
                window.location = _buildUrl(dt, 'print');
            },
            exportOptions: {
                //columns: [ 0, ':visible' ]
                columns: [ ':visible' ]
            },
            exportInfo : {
                messageTop : "Title",
            },
            customize: function ( win,dt ) {
                let $body  = $(win.document.body);
                $body.css('font-size', '10pt')
                     .append("<link rel='stylesheet' type='text/css' media='screen' href='<?php echo e(url('vendors/general/bootstrap/dist/css/bootstrap.min.css')); ?>'>")

                // .prepend('<img src="http://datatables.net/media/images/logo-fade.png" style="position:absolute; top:0; left:0;" />');

               let $table = $body.find('table')

                $table.addClass('compact')
                      .css('font-size','inherit')
                      .css('border-collapse','collapse')
                      .find('tr th,tr td')
                      .css('border','1px solid #eee')
                      .css('padding-top','0.75em 10px 0.75em 10px')

            },
        })

        //Initialisation d'un bouton "Reload"
        DataTable.ext.buttons.reload = {
            className: 'btn-dark dt-btn-refresh',
            attr : {
                title: '<?php echo e(__("Refresh data")); ?>' ,
                icon:'<i class="fa fa-sync-alt"></i> ',
                "data-skin":"dark",
                "data-toggle":"tooltip",
                "data-original-title" : '<?php echo e(__("Refresh data")); ?>',
            },
            text: function (dt,button,config) {
            //    let label = config.attr.title;
                return config.attr.icon  + dt.i18n('buttons.reload', "");
            },

            action: function (e, dt, button, config) {
                dt.draw(false).clear();
            }
        }

        //Initialisation d'un bouton "Refresh" (semblable au reload mais reset les filtres)
        DataTable.ext.buttons.reset = {
            className: 'btn-default',
            attr : {title: '<?php echo e(__("Reset")); ?>', icon:'<i class="fa fa-undo"></i> '},
            text: function (dt,button,config) {
                let label = config.attr.title;
                return config.attr.icon + dt.i18n('buttons.reset', "");
            },

            action: function (e, dt, button, config) {
                dt.search('');
                dt.columns().search('');
                dt.draw();
            }
        }

        $.extend(DataTable.ext.buttons.searchPanes,{
            className: 'btn-app',
            attr : {title: '<?php echo e(__("Search Pane")); ?>' , icon:'<i class="fa fa-users"></i> '},
            text: function (dt,button,config) {
                let label = config.attr.title;
                return config.attr.icon  + dt.i18n('buttons.searchPanes', "");
            },

            config: {
                cascadePanes: true,
                controls: false,
            }
        });

        $.extend(DataTable.ext.buttons.import_csv,{
            //className: 'btn-success',
            attr : {title: '<?php echo e(__("CSV")); ?>' , icon: '<i class="fa fa-file-alt"></i> '},
            text: function (dt,button,config) {
                let label = config.attr.title;
                return config.attr.icon+ dt.i18n('buttons.import_csv', label);
            },

            action: function (e, dt, button, config) {
                uploadEditor.create( {
                    title: '<?php echo e(__('Importer un fichier CSV')); ?>'
                } );
            }
        });

        $.extend(DataTable.ext.buttons.import,{
            extend: 'collection',
            className: 'btn-success',
            attr : {title: '<?php echo e(__("Importer")); ?>' , icon:'<i class="fa fa-upload"></i> '},
            text: function (dt,button,config) {
                current_editor = config.editor ?? null;
                //console.log(config)
                return config.attr.icon + dt.i18n('buttons.import',"") + '&nbsp;<span class="caret"/>';
            },

            buttons: ['import_csv']
        });

        $.extend(DataTable.ext.buttons.remove,{
            className: 'btn-danger',
            attr : {title: '<?php echo e(__("Delete")); ?>',icon: ' <i class="fa fa-trash"></i> '},
            text: function (dt,button,config) {
                return config.attr.icon + dt.i18n('buttons.remove', "");
            },
            formButtons : {
                className: 'btn-danger',
                text: '<?php echo e(__("Delete")); ?>'+' <i class="fa fa-trash"></i> ',
                action: function () {
                    console.log("[editor.remove] -> submitted");
                    this.submit(
                        function (response) {
                            if(typeof response === 'object'
                                && ( ('data' in response) && !$.isEmptyObject(response.data))){
                                toast({ title:'<?php echo e(action_message("delete")); ?>'});
                            }
                        },
                        null,
                        null,
                        true // close
                    );
                },

            },
        });

        DataTable.ext.buttons.create = {
            className: 'btn-success',
            attr : {
                title: '<?php echo e(__("Add")); ?>',
                icon: '<i class="fa fa-plus"></i> ',
                "data-skin":"dark",
                "data-toggle":"tooltip",
                "data-original-title" : '<?php echo e(__("Add new record")); ?>',
            },
            text: function (dt,button,config) {
                //var label = config.attr.title;
                return dt.i18n('buttons.create', "") +  config.attr.icon;
            },
            action: function (e, dt, button, config) {
                //console.log(dt.editor);
                //console.log(button.editor);

                config.editor.create({
                    title: '<?php echo e(__("Add record")); ?>',
                    buttons: {
                        className: config.className,
                        text: config.attr.icon+config.attr.title,
                        action: function () {
                            this.submit(
                                (response) => {
                                    if(typeof response === 'object'
                                        && ( ('fieldErrors' in response) && $.isEmptyObject(response.fieldErrors))){
                                        config.editor.create();
                                        toast({ title:'<?php echo e(__("Successful Created.")); ?>'});

                                    }
                                },
                                null,
                                null,
                                true
                            );
                        },

                    }
                })
            }

        };

        $.extend(DataTable.ext.buttons.exportData,{
            columns: ':visible',
            format: {
                header: function ( data, columnIdx ) {
                    return columnIdx +': '+ data;
                }
            }
        });
        $.extend(DataTable.ext.buttons.exportOptions,{
            columns: ':visible',
            title: "<center style='text-decoration: underline'><?php echo e(__('Liste des virements à valider du :date',['date' => date('d-m-Y')])); ?></center>",
            // exportOptions: {
            //     columns: [ 1,2,3,4,5,8 ]
            // },
            format: {
                header: function ( data, columnIdx ) {
                    return columnIdx +': '+ data;
                }
            }
        });

        if (typeof DataTable.ext.buttons.copyHtml5 !== 'undefined') {
            $.extend(DataTable.ext.buttons.copyHtml5, {
                attr : {title: '<?php echo e(__("Copier")); ?>',icon: '<i class="fa fa-copy"></i> '},
                text: function (dt,button,config) {
                    let label = config.attr.title;
                    return config.attr.icon + dt.i18n('buttons.copy', "");
                }
            });
        }


        if (typeof DataTable.ext.buttons.colvis !== 'undefined') {
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            $.extend(DataTable.ext.buttons.colvis, {
                text: function (dt) {
                    return '<i class="fa fa-eye"></i> ' + dt.i18n('buttons.colvis', 'Column visibilityss');
                }
            });
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
        }

        //Initialisation d'un bouton "Filters"
        DataTable.ext.buttons.filters = {
            className: 'btn-primary btn-show-filters',
            attr : {
                title: '<?php echo e(__("Appliquer des filtres sur le tableau")); ?>' ,
                icon:'<i class="fa fa-sync-alt"></i> ',
                "data-skin":"dark",
                "data-toggle":"tooltip",
                "data-original-title" : '<?php echo e(__("Appliquer des filtres sur le tableau")); ?>',
                offcanvas: {
                    targetId: 'offcanvas-modal-filters'
                },
            },
            text: function (dt,button,config) {
                // let label = config.attr.title;
                // return config.attr.icon  + dt.i18n('buttons.filters', "");
                return '<i class="fa fa-filter"></i> ' ;
            },

            action: function (e, dt, button, config) {
                let offcanvas = config.attr.offcanvas ;
                let targetId = offcanvas.targetId ?? "offcanvas-modal-filters";
                showOffcanvas(targetId,true);

            }
        }

    })(jQuery, jQuery.fn.dataTable);
</script>

<?php /**PATH /home/lekruu/public_html/resources/views/shared/datatable-buttons-init-js.blade.php ENDPATH**/ ?>