<script>
    // var current_editor = new $.fn.dataTable.Editor();
    var current_editor =  null;

    var globalBtnCreate = {
        extend: "create",
        className: 'btn-success',
        text : '<i class="fa fa-plus"></i>',
        formTitle : "{{__("New record")}}",
        action: function (e, dt, button, config) {},
    };

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

        // 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 = new $.fn.dataTable.Editor();
            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: '{{__("Mappage des champs")}}',
                buttons: {
                    className: "btn-success",
                    text:'{{__("Importer ")}}'+csv.length+' {{__("enregistrement(s)")}}',
                    action: function () {
                        this.submit();
                    },

                },
                // message: 'Select the CSV column you want to use the data from for each field.',
                message: '{{__("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: '{{__("Importation CSV")}}',
                    buttons: {
                        className: "btn-success",
                        text:'{{__('Importer')}}',
                        action: function () {
                            this.submit(
                                function () {
                                    //toast('success',this.title, csv.length+' {{__("donnée(s) enregistrée(s)")}}');
                                    let config = {
                                        title:csv.length+' {{__("donnée(s) enregistrée(s)")}}',
                                        timer: 10000,
                                        ok_button: true,
                                    };
                                    toast(config);
                                },
                                function (error) {
                                    //toast('error',this.title,'' ,false,"center");

                                    let config = {
                                        title:"{{__("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: "{!! __("Cliquez sur le boutton <b>Importer</b> pour confirmer l'importation de") !!} "+csv.length+" {{__("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 = new $.fn.dataTable.Editor( {
            fields: [ {
                label: '{{__("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('{{__("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]);
                        }
                    });
                }
            } ]
        } );

        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 = () => {
            var visible_columns = [];
            $.each(DataTable.settings[0].aoColumns, function (key, col) {
                if (col.bVisible) {
                    visible_columns.push(col.name);
                }
            });

            return visible_columns;
        };

        var _downloadFromUrl = (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);
        };

        DataTable.ext.buttons.postExcel = {
            className: 'buttons-excel',
            text: function (dt) {
                return '<i class="fa fa-file-excel"></i> ' + dt.i18n('buttons.excel', 'Excel');
            },

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

                _downloadFromUrl(url, params);
            }
        };

        DataTable.ext.buttons.postExcelVisibleColumns = {
            className: 'buttons-excel',
            text: function (dt) {
                return '<i class="fa fa-file-excel"></i> ' + dt.i18n('buttons.excel', 'Excel (only visible columns)');
            },

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

                _downloadFromUrl(url, params);
            }
        };

        DataTable.ext.buttons.export = {
            extend: 'collection',
            className: 'btn-light',
            attr : {title: '{{__("Export")}}' , icon:'<i class="fa fa-download"></i> '},
            text: function (dt,button,config) {
                //  var label = config.attr.title;
                return config.attr.icon + dt.i18n('buttons.export',"") + '&nbsp;<span class="caret"/>';
            },
            buttons: ['csv', 'excel','pdf']
        };

        DataTable.ext.buttons.postCsv = {
            //className: 'btn-light',
            attr : {title: '{{__("CSV")}}',icon:'<i class="fa fa-file-excel"></i> '},
            text: function (dt,button,config) {
                var label = config.attr.title;
                return config.attr.icon + dt.i18n('buttons.csv', label);
            },

            action: function (e, dt, button, config) {
                var url = dt.ajax.url() || window.location.href;
                var params = _buildParams(dt, 'csv');

                _downloadFromUrl(url, params);
            }
        };

        DataTable.ext.buttons.postCsvVisibleColumns = {
            className: 'btn-light',
            attr : {title: '{{__("CSV (Only visible columns)")}}'},
            text: function (dt,button,config) {
                var label = config.attr.title;
                return '<i class="fa fa-file-excel-o"></i> ' + dt.i18n('buttons.csv', label);
            },

            action: function (e, dt, button, config) {
                var url = dt.ajax.url() || window.location.href;
                var params = _buildParams(dt, 'csv', true);

                _downloadFromUrl(url, params);
            }
        };

        DataTable.ext.buttons.postPdf = {
                //className: 'btn-light',
                attr : {title: '{{__("PDF")}}'},
                text: function (dt,button,config) {
                    var label = config.attr.title;
                    return '<i class="fa fa-file-pdf"></i> ' + dt.i18n('buttons.pdf', label);
                },
                action: function (e, dt, button, config) {
                    let url = dt.ajax.url() || window.location.href;
                    let params = _buildParams(dt, 'pdf');

                    _downloadFromUrl(url, params);
                }
        };

        DataTable.ext.buttons.print = {
            className: 'btn-warning',
            attr : {title: '{{__("Print")}}'},
            text: function (dt,button,config) {
                let label = config.attr.title;
                return  '<i class="fa fa-print"></i> ' + dt.i18n('buttons.print', '');
            },

            action: function (e, dt, button, config) {
                window.location = _buildUrl(dt, 'print');
            }
        };

        $.extend(DataTable.ext.buttons.reset,{
            className: 'btn-default',
            attr : {title: '{{__("Reset")}}', icon:'<i class="fa fa-undo"></i> '},
            text: function (dt,button,config) {
                var 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();
            }
        });

        DataTable.ext.buttons.reload = {
            className: 'btn-dark',
            attr : {title: '{{__("Refresh")}}' , icon:'<i class="fa fa-sync-alt"></i> '},
            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);
                // dt.search('');
                // dt.columns().search('');
                // dt.draw(false);
            }
        }
        // $.extend(DataTable.ext.buttons.reload,{
        //
        // });

        $.extend(DataTable.ext.buttons.searchPanes,{
            className: 'btn-app',
            attr : {title: '{{__("Searh 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.create,{
            className: 'btn-success',
            attr : {title: '{{__("Add")}}',icon: ' <i class="fa fa-plus"></i> '},
            text: function (dt,button,config) {
                //var label = config.attr.title;
                return config.attr.icon + dt.i18n('buttons.create', "");
            },
            formButtons : {
                className: 'btn-success',
                text: '{{__("Add")}}'+' <i class="fa fa-plus"></i> ',
                action: function (e, dt, button, config) {
                    console.log("[editor.create] -> submitted");
                    this.submit(
                        function (response) {
                            if(typeof response === 'object'
                                && ( ('fieldErrors' in response) && $.isEmptyObject(response.fieldErrors))){
                               // dt.editor().create();
                                toast({ title:'{{action_message("create")}}'});
                            }
                        },
                        null,
                        null,
                       true // close
                    );
                },

            },


        });

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

            },

        });

        $.extend(DataTable.ext.buttons.remove,{
             className: 'btn-danger',
              attr : {title: '{{__("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: '{{__("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:'{{action_message("delete")}}'});
                            }
                        },
                        null,
                        null,
                        true // close
                    );
                },

            },
        });


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

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

        $.extend(DataTable.ext.buttons.import,{
            extend: 'collection',
            className: 'btn-success',
            attr : {title: '{{__("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']
        });


        DataTable.ext.buttons.exportData = {
            columns : [0,1],
        };

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

        if (typeof DataTable.ext.buttons.colvis !== 'undefined') {
            $.extend(DataTable.ext.buttons.colvis, {
                attr : {title: '{{__("Colonnes visibles")}}',icon: '<i class="fa fa-eye"></i> '},
                text: function (dt,button,config) {
                    var label = config.attr.title;
                    return config.attr.icon + dt.i18n('buttons.colvis', label);
                }
            });
        }


        $.fn.dataTable.ext.errMode = (settings,helpage,message) => {
            let debug = '{{env('APP_DEBUG',false)}}';
            console.log(message);
            let msg = '<strong>{{general_error()}}<strong>';

            if(debug){
                msg += ' <br><span class="fs-10 text-danger">'+message+'</span>';
            }
            //   console.log(settings);
            let config = {
                title:msg,
                html:msg,
                icon:'error',
                timer: 10000,
                ok_button:true
            };
            toast(config);
        };
        // $.extend( $.fn.dataTable.Editor.display.envelope.conf, {
        //     windowPadding: 50,
        //     attach:        "head"
        // } );


        $.extend( $.fn.dataTable.Editor.defaults, {
            events : {
                open : function (e,type) {
                    // alert( 'Editor '+type+' form shown' );
                    init_bsMultiselect();
                    init_datepicker();
                },
                 opened : function () {
                     $('div.modal[role=dialog]')
                         .closest('.show')
                         .find('.modal-dialog')
                         .removeClass("modal-dialog-scrollable");
                 },
                 //preOpen : function () {},
                 //preBlur : function () {},
                // close : function () {},
            },
        } );

        $.extend( $.fn.dataTable.Editor.DateTime.defaults, {
            format : "DD-MM-YYYY",
            buttons: {
                today: false,
                clear: false
            },
            i18n: {
                previous: '{{__("Previous")}}',
                next:     '{{__("First")}}',
                // months:   [ 'Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre' ],
                // weekdays: [ 'Dim', 'Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam' ]
            },

        } );


        $.extend($.fn.dataTable.defaults, {
            {{--language: {--}}
            {{--    "decimal":        " ",--}}
            {{--    "emptyTable":     "{{__("Aucun résultat pour le moment.")}}",--}}
            {{--    "info":           "{{__('Affichage _START_ à _END_ sur _TOTAL_ ligne(s)')}}",--}}
            {{--    "infoEmpty":      "{{__('Affichage 0 à 0 sur 0 ligne(s)')}}",--}}
            {{--    "infoFiltered":   "({{__("filtré à partir de _MAX_ ligne(s) totales.")}})",--}}
            {{--    "infoPostFix":    "",--}}
            {{--    "thousands":      " ",--}}
            {{--    "lengthMenu":     "{{__('Afficher _MENU_ ligne(s)')}}",--}}
            {{--    "loadingRecords": "{{__("Affichage des données...")}}",--}}
            {{--    "processing":     "{{__('Chargement...')}}",--}}
            {{--    "search":         "{{__('Rechercher:')}}",--}}
            {{--    "zeroRecords":    "{{__('Aucun donnée à afficher pour le moment')}}",--}}
            {{--    "paginate": {--}}
            {{--        "first":      "{{__("Premier")}}",--}}
            {{--        "last":       "{{__('Dernier')}}",--}}
            {{--        "next":       "{{__('Suivant')}}",--}}
            {{--        "previous":   "{{__("Précédent")}}"--}}
            {{--    },--}}
            {{--    "aria": {--}}
            {{--        "sortAscending":  "{{__(": activer pour trier les colonnes par ordre croissant")}}",--}}
            {{--        "sortDescending": "{{__(': activer pour trier les colonnes par ordre déccroissant')}}"--}}
            {{--    }--}}
            {{--},--}}
            lengthMenu : [ [10, 25, 50, -1], [10, 50,100, "All"] ],
        });
    })(jQuery, jQuery.fn.dataTable);
</script>
