{{--<script src="{{url('js/server-status.js')}}"></script>--}}

<script>

    var $app_tooltip = $('[data-toggle="tooltip"]');
    var $app_popover = $('[data-toggle="popover"]');

    var currentEditor = null;

    const randomValue = (arr)=>{
        return  arr[Math.floor(Math.random() * arr.length)]
    };

    const showOffcanvas = (id,visible)=>{
        const $elt_offcanvas = document.getElementById(id)
        const bs_offcanvas = new bootstrap.Offcanvas($elt_offcanvas);
        //bs_offcanvas.isShown()
        return (visible) ? bs_offcanvas.show() : bs_offcanvas.hide()
    }
    const isOnline = ()=> navigator.onLine

    const createRandomString = (length,param={})=> {

        const default_params = { letters : true, numbers : true};
        param = {...default_params , ...param};

        const { letters , numbers} = param;
        let chars = "";
        if (letters){
             chars += "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        }
        if (numbers){
             chars += "0123456789";
        }
        let result = "";
        const randomArray = new Uint8Array(length);
        window.crypto.getRandomValues(randomArray);
        randomArray.forEach((number) => {
            result += chars[number % chars.length];
        });
        return result;
    }

    const printHtmlBlock =  (idBlock,titre = '{{__('Impression Document')}}',portrait_mode = true)=> {
        let prtContent = document.getElementById(idBlock);
        let WinPrint = window.open('', '', 'left=100,top=0,width=800,height=900,toolbar=0,scrollbars=0,status=0');

        WinPrint.document.title = titre;

        WinPrint.document.write('<html><head><title>'+titre+'</title>');

        WinPrint.document.write('<link rel="stylesheet" href="{{url('frontend/css/bootstrap.min.css')}}">');
        WinPrint.document.write('<link rel="stylesheet" href="{{url('vendor/print.css')}}">');
        WinPrint.document.write('<link rel="stylesheet" href="{{url('vendor/util.css')}}">');
        WinPrint.document.write('<\/head><body onload="print()">');

        if(!portrait_mode){
            WinPrint.document.write("<style>@media print{@page {size: landscape; } }</style>");
        }

        WinPrint.document.write(prtContent.innerHTML);
        WinPrint.document.write("<\/body><\/html>");

        WinPrint.document.close();
        WinPrint.focus();
    };

    const dispatchBrowserEvent = (eventName,arg = null) => {
        return document.dispatchEvent(new CustomEvent(eventName, { detail : arg}))
    }

    const hideModal = function () {
        $('.modal').removeClass('in').fadeIn().hide();
        $('.modal-backdrop').fadeIn().remove();
        $('body').removeClass("modal-open").css("padding-right",'');
    };

    // 👉 IsEmpty
     const isEmpty = (value) => blank(value);

    // 👉 blank
     const blank = (value) => {
        if (value === null || value === undefined || value === '')  return true;
        if(isObject(value) && Object.keys(value).length === 0) return true;
        return (Array.isArray(value) && value.length === 0);
    };

    // 👉 filled
     const filled = (value) => !blank(value);

    // 👉 IsNullOrUndefined
     const isNullOrUndefined = (value) =>  (value === null || value === undefined);

    // 👉 IsEmptyArray
     const isEmptyArray = (arr) => (Array.isArray(arr) && arr.length === 0);

    // 👉 IsObject
     const isObject = (obj) => obj !== null && !!obj && typeof obj === 'object' && !Array.isArray(obj);

     const isArray = (arr) => arr !== null && !!arr && Array.isArray(arr);

     const removeUndefined = (arr) => filled(arr) ? arr.filter((v) => v !== undefined) : [];

     const confirmAction = (options = {})=>{
        const defaultOptions = {
            title: '{{__("Confirmation")}}',
            text: "Confirm this action ?",
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: '{{__("Yes")}}',
            cancelButtonText: '{{__("No")}}',
            reverseButtons : true,
            allowOutsideClick : false,
        };

        const onConfirm = ('onConfirm' in options) ? options.onConfirm : ()=>{};

        return  swal.fire({...defaultOptions, ...options})
                    .then((result) => {
                        if (result.isConfirmed) {
                          onConfirm();
                        }
                    });
    }

    //   const send =  async function(){
    //         const params = {
    //             method : 'post',
    //             body : {
    //                 full_name : 'Fomath Jospin',
    //                 description : 'Utilise Alpine Js',
    //             },
    //         }
    //         const data = await request("api.ge/v1",params,false)
    //
    //         console.log(data)
    // };

    function disconnection(route) {
        swal.fire({
            title: '{{__("Log out")}}',
            text: "{{__('Are you sure you want to log out')}} ?",
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: '{{__("Yes")}}',
            cancelButtonText: '{{__("No")}}',
        })
        .then( result => {
            if (result.isConfirmed) {
                request(route,{method:'post'})
                .then( data => {
                    if(data.success){
                        var temp = 5000;
                        var sec = 1000;
                        swal.fire({
                            title: '{{__('Loug out')}}',
                            text: data.message,
                            icon: 'success',
                            showConfirmButton: true,
                            confirmButtonText: '{{__("OK")}}!',
                            html: data.message+' {{__("Redirection in")}} <b>'+(temp/sec)+'</b> sec.',
                            timer: temp,
                            timerProgressBar: true,
                            didOpen: () => {
                                //swal.showLoading();
                                const b = Swal.getHtmlContainer().querySelector('b');
                                timerInterval = setInterval(() => {
                                                    let old_time = b.textContent;
                                                    b.textContent = (old_time - 1).toString();
                                                }, sec)
                            },
                            willClose: () => {
                                clearInterval(timerInterval);
                                location.href = data?.redirect ?? "/";
                            }
                        });
                    }
                });

            }
        });
    }

    var request = async function(url, param = {}, swal = true) {
        let csrf_token = $('meta[name="csrf-token"]').attr('content');
        if(!("headers" in param)){
            param.headers =  {
                'X-CSRF-TOKEN': csrf_token,
                //'Accept': 'application/json , text/plain, */*',
                'Content-Type': 'application/json , multipart/form-data',
                'X-Requested-With': 'XMLHttpRequest',
            };
        }else{
            param['headers']['X-CSRF-TOKEN'] = csrf_token;
            param['headers']['X-Requested-With'] = "XMLHttpRequest";
        }

        if(!("method" in param)){
            param.method = 'get';
        }

        if( ("body" in param)){
            if(param.method === 'get'){
                url = url+'?';
                $.each(param.body , function (index, value){
                    let v = index+"="+value+"&";
                    if(typeof value === 'object'){
                        v = "";
                        $.each(value ,function(i, d){
                            v += index+"[]="+d+"&";
                        });
                    }
                    url += v;
                }); // get n'a pas besoin de 'body'
                delete param.body;
            }else{ // post
                param.body = JSON.stringify(param.body);
            }
        }

        return  await  fetch(url,param)
                       .then(response => {
                            let result = response.json();
                            let status = response.status;
                            let msg = result.statusText;
                            if (!response.ok) {
                                if(swal){
                                    result.then(data => {
                                                ajax_error_popup(data,status,msg);
                                            });
                                }
                               // throw new Error(msg);
                            }
                            return result;
                       });
    };

    var ajax_error_popup = function (reponse,status,msg = "") {

        if( ("responseJSON" in reponse)){
            status = reponse.status; // 500
            let jqXHRJSON = reponse.responseJSON;
            console.log(jqXHRJSON);
            if(!$.isEmptyObject(jqXHRJSON)){
                reponse = jqXHRJSON;
            }
        }
        var message =  '{{general_error()}}.'+
                         '<br><center> <marquee class="text-danger">'+msg+'</marquee></center>';
        var config = {
            icon: 'error',
            //allowOutsideClick:false,
            title: '{{__("Oops...")}}',
            html: message,
            footer: "",
        };

       let statuts_errors = [];

        console.log("status error = "+status,reponse);
        console.log("rep url  = "+reponse.url);

        if( $.inArray(status,statuts_errors) !== -1 ){
            let notif = reponse.notification;
            config.html = notif.msg;
            config.title = notif.title;
            config.icon = 'warning';

            if(reponse.url !== ""){
                if( status === parseInt('{{\App\Exceptions\ServerStatus::AUTH_REQUIRED}}') ){
                    config.footer = '<span class="text-danger">' +
                                      '<a style="text-decoration:underline;" class="text-success" href="'+reponse.url+'">'+
                                            '{{__("Click here")}} '+
                                        '</a> '+"{{__('for you connected.')}}"+
                                    ' </span>'
                }
            }
            if(status === parseInt('{{\App\Exceptions\ServerStatus::CSFR_TOKEN_MISMATCH}}')){
                reponse.url = "{{url()->current()}}";
            }
        }
        else{
            reponse.url = "";
        }
        swal.fire(config)
            .then( result => {
                if (result.isConfirmed) {
                    if(reponse.url !== ""){
                        location.href = reponse.url;
                    }
                }
            })

    };

    var redirect_if_ajax_success = function (data) {
        /*si le resultat contient des données html*/
        if(!$.isEmptyObject(data.redirect)){
            location.href = data.redirect;
        }
    };

    var formatNumber = function (number,currency = "", separate = " ") {
        return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, separate)+" "+currency;
    };
    var effacerLigneTableau = function (domObjet,classTable){
        $(domObjet).parents("table."+classTable+" tr").remove();
    };

    var toast = function(config = {}){

        let icon = ("icon" in config) ? config.icon:'success';
        let title = ("title" in config) ? config.title:'';
        let position  = ("position" in config) ? config.position:'top-end';
        let timer  = ("timer" in config) ? config.timer:3000;
        let ok_button  = ("ok_button" in config) ? config.ok_button:false;
        let html  = ("html" in config) ? config.html:false;

        const Toast = swal.mixin({
            toast: true,
            position: position,
            showConfirmButton: ok_button,
            timer: timer,
            timerProgressBar: true,
            didOpen: (toast) => {
                toast.addEventListener('mouseenter', swal.stopTimer);
                toast.addEventListener('mouseleave', swal.resumeTimer);
            }
        });

        Toast.fire({
            icon: icon,
            title: title,
            //html:html,
        });
    };

    var simple_swal = function (message,is_validation = false ,
                                title = "{{__("Oops ...")}}",type = "error",footer = '') {
        let config = {
            icon: type,
            title: title,
            html : message,
            footer : footer,
            showConfirmButton: true,
            showCancelButton: false,
            allowOutsideClick: false,
        };

        if (is_validation){
            delete config.html;
            config.willOpen =  function () {
                swal.showValidationMessage(message)
            }
        }
        return  swal.fire(config);
    };

    var getFormDataObj = function (id) {
        let data = {};
        var formData = new FormData();
        let inputs = $('#'+id).serializeArray();
        $.each(inputs,(i,input) => {
            formData.append(input.name, input.value);
            if((input.name in data)){
                data[input.name] += ","+input.value;
            }else{
                data[input.name] = input.value;
            }

        });
        return data;
    };

    var checkedValues = function(node){
      let val = [];
        $.each(node.children(),function() {
            let $this = $(this);
            if($this.is(":checked") || $this.is(":selected"))
            val.push($(this).val());
        });
        return val;
    };

    var editIcon = function ( data, type, row ) {
        if ( type === 'display' ) {
            return data + ' <small class="fa fa-pencil-alt fa-pencils"></small>';
        }
        return data;
    };

    var get_formated_url = function(base_url,param){
        let url = base_url+'?';
        if(!$.isEmptyObject(param)){
            $.each(param , function (index, value){
                let v = index+"="+value+"&";
                if(typeof value === 'object'){
                    v = "";
                    $.each(value ,function(i, d){
                        v += index+"[]="+d+"&";
                    });
                }
                url += v;
            });
        }
        return url;
    };

    function refresh_select(id,datas,label = ""){
        let $select = $("#"+id);
        $select.html(""); // efface toutes les options
        if(label !==""){
            $select.parent().prev().text(label)
        }
        if (!$.isEmptyObject(datas)){
            $.each(datas, function (index,data) {
                $select.append('<option value="'+data.value+'">'+data.label+'</option>');
            });
        }
    };

    function refresh_multiselect($select,datas,selected = true){
        if (!$.isEmptyObject(datas)){
            $select.find("option").remove();
            $.each(datas , function(i, val) {
                console.log("i = "+i+" val ="+val)
                $select.append('<option value="'+i+'">'+val+'</option>').multiselect('rebuild');
            });
        }
    };


    // Datepicker
    (function(theme, $) {

        theme = theme || {};

        var instanceName = '__datepicker';

        var PluginDatePicker = function($el, opts) {
            return this.initialize($el, opts);
        };

        PluginDatePicker.defaults = {
            format: 'dd-mm-yyyy',
            todayHighlight: true,
            keyboardNavigation: true,
            language : '{{app()->getLocale()}}',
            //clearBtn: true,
            todayBtn: true,
            autoclose : true,
        };

        PluginDatePicker.prototype = {
            initialize: function($el, opts) {
                if ( $el.data( instanceName ) ) {
                    return this;
                }
                this.$el = $el;
                this.setVars()
                    .setData()
                    .setOptions(opts)
                    .build();
                return this;
            },
            setVars: function() {
                this.skin = this.$el.data( 'plugin-skin' );
                return this;
            },
            setData: function() {
                this.$el.data(instanceName, this);

                return this;
            },
            setOptions: function(opts) {
                this.options = $.extend( true, {}, PluginDatePicker.defaults, opts );
                return this;
            },

            build: function() {
                this.$el.datepicker( this.options );
                if ( !!this.skin ) {
                    this.$el.data('datepicker').picker.addClass( 'datepicker-' + this.skin );
                }
                return this;
            }
        };

        // expose to scope
        $.extend(theme, {
            PluginDatePicker: PluginDatePicker
        });

        // jquery plugin
        $.fn.themePluginDatePicker = function(opts) {
            return this.each(function() {
                var $this = $(this);

                if ($this.data(instanceName)) {
                    return $this.data(instanceName);
                } else {
                    return new PluginDatePicker($this, opts);
                }

            });
        }

    }).apply(this, [ window.theme, jQuery ]);

    var init_datepicker = function () {
        // $('[data-plugin-datepicker]').each(function() {
        //     var $that = $( this );
        //     var opts = {};
        //     //var pluginOptions = JSON.parse($that.data('plugin-options'));
        //     var pluginOptions = $that.data('plugin-options');
        //     if (pluginOptions)
        //         opts = pluginOptions;
        //
        //     //$that.dtDateTime()
        //
        // });
        if ( $.isFunction($.fn[ 'datepicker' ]) ) {
            $(function() {
                $('[data-plugin-datepicker]').each(function() {
                    var $that = $( this );
                        opts = {};
                    var pluginOptions = $that.data('plugin-options');
                    if (pluginOptions)
                        opts = pluginOptions;

                    $that.themePluginDatePicker(opts);
                });
            });

        }
    };

    var init_bsMultiselect = function () {
        let default_config = {
            templates: {
                button: '<button type="button" class="multiselect dropdown-toggle" data-toggle="dropdown"></button>',
                ul: '<ul class="multiselect-container dropdown-menu"></ul>',
                //filter: '<div class="input-group"><span class="input-group-prepend"><i class="fa fa-search"></i></span><input class="form-control-sm multiselect-search" type="text"></div>',
                filter: '<div class="input-group"><input class="form-control form-control-sm multiselect-search" type="text"></div>',
                li: '<li><a class="dropdown-item" href="javascript:void(0);"><label></label></a></li>',
                divider: '<li class="divider"></li>',
                liGroup: '<li><label class="multiselect-group"></label></li>'
            },
            {{--NoSelectedText: '{{__("Aucune Selection")}}',--}}
            {{--nSelectedText: '{{__("Selection(s)")}}',--}}
            maxHeight: 400,
            filterPlaceholder: '{{__("Search")}}',
            selectAllText: '{{__("Select All")}}',
            selectAllValue: 'multiselect-all',
            numberDisplayed: 1,
            enableFiltering: false,
            enableCaseInsensitiveFiltering: true,
            //checkboxName: 'multiselect',
           // enableHtml: true,
            includeSelectAllOption: true,
            includeSelectAllIfMoreThan: 10,
            enableClickableOptGroups: true,
            enableCollapsibleOptGroups: true,
            collapseOptGroupsByDefault: true,
            //disableIfEmpty: true,
            //disabledText: 'Disabled ...',
            buttonWidth: '100%',
            // dropRight: true,
            //dropUp: true,
        };

        let $selects = $('select[data-plugin-multiselect]');
        $selects.each(function () {
           // console.log("bs-multiselect-id = "+$(this).attr("id"));
            let $this = $(this);

            let pluginOptions =  $this.data('plugin-options');

            if(typeof pluginOptions !== "undefined"){
                //console.log(pluginOptions,typeof pluginOptions)
                if(typeof pluginOptions === "string"){
                    pluginOptions = JSON.parse(pluginOptions);
                    console.log(pluginOptions,typeof pluginOptions);
                }
                if( !('checkboxName' in pluginOptions)){
                    pluginOptions.checkboxName = $this.attr('id')
                }
                if(!$.isEmptyObject(pluginOptions)){
                    $.each( pluginOptions, function( key, value ) {
                        default_config[key] = value;
                    });
                }
            }

            //$this.multiselect(default_config).multiselect("refresh");
            $this.multiselect(default_config).multiselect("rebuild").multiselect("refresh");
           // $(this).next().find("li.active").each(function () {
             // $(this).find("input.custom-control-input").attr("checked")
              //$(this).find("input.custom-control-input").prop("checked",true).trigger("click")
            //})
           //
        })
        $("ul.multiselect-container")
            .closest("div.btn-group")
            .css({
                width : "100%",
                border : "2px solid #d1d3e2",
                "background-color" : "#f8f9fc",
                "border-radius": "0.35rem" ,
                "text-align": "left" ,
                "height": "37px" ,
            })
    };

    var select_all_td = function(){
        $('table thead,table tfoot').on( 'click', 'tr th:first-child', function () {
            let table_html = $(this).parent().parent().parent(); //
            let tableId = table_html.attr('id');
            if ($.fn.dataTable.isDataTable('#'+tableId)){
                let table = $("#"+tableId).DataTable();
                if ($(this).find("input.dt-checkbox-all[type=checkbox]").is(':checked')) {
                    table.rows().select();
                } else {
                    table.rows().deselect();
                }
            }
        } );
    };

    var init_select2 = function (className = "select2") {

        function matchStart(params, data) {
            // If there are no search terms, return all of the data
            if ($.trim(params.term) === '') {
                return data;
            }
            // Skip if there is no 'children' property
            if (typeof data.children === 'undefined') {
                return null;
            }
            // `data.children` contains the actual options that we are matching against
            var filteredChildren = [];
            $.each(data.children, function (idx, child) {
                if (child.text.toUpperCase().indexOf(params.term.toUpperCase()) == 0) {
                    filteredChildren.push(child);
                }
            });

            // If we matched any of the timezone group's children, then set the matched children on the group
            // and return the group object
            if (filteredChildren.length) {
                var modifiedData = $.extend({}, data, true);
                modifiedData.children = filteredChildren;

                // You can return modified objects from here
                // This includes matching the `children` how you want in nested data sets
                return modifiedData;
            }

            // Return `null` if the term should not be displayed
            return null;
        }

        $("."+className).select2({
            tags: true,
            closeOnSelect: false,
            minimumResultsForSearch: Infinity,
            matcher: matchStart
        });
    };

    function getUlErrorsValidation(data) {
        var  $ul = "<ul>";
        $.each( data, function( key, value ) {
            $ul = $ul + '<li>'+value+'</li>';
        });
        //retourne une liste html
        return $ul+"</ul>";
    }
    function printAlertMsg (msg) {
        $(".print-error-msg").find("ul").html('').css('display','block');
        $.each( msg, function( key, value ) {
            $(".print-error-msg").find("ul").append('<li>'+value+'</li>');
        });
    };

    var refresh_datatable = function (tableId,url = "") {
        //console.log(tableId)
        if ($.fn.dataTable.isDataTable('#'+tableId)){
            let table = $('#'+tableId).DataTable();
            // recharge le tableau
           if(url !== ""){
             return table.ajax.url(url).load();
           }else{
              return table.draw();
           }
        }
    };

    var initDTEditor = function(api){
        let editor = api.table().editor();
        if(typeof editor !== 'undefined'){
            editor.on('open', function ( e, type ) {
                init_bsMultiselect();
                init_datepicker();
            } );
        }
    };

    var arround = function (number,precision = 0) {
        let diviser = "1";
        if (precision > 0){
            diviser = "1";
            for (let i = 1; i <= precision ; i++) {
                diviser += "0";
            }
            diviser = parseInt(diviser);
            return Math.round(number * diviser) / diviser
        }

        return number;
    };

    var getSum = function (data,column) {
        let sum = 0;
        if (data){

            $.each( data, function( key, value ) {
                if (value.length){
                    $.each( value, function( k, item ) {
                        if (column in item){
                            sum += parseFloat(item[column]);
                        }
                    })
                }else{
                    if (column in value){
                        sum += parseFloat(value[column]);
                    }
                }

            });
        }
        return sum;
    };

    const DataTableEditor = (config={}) => new $.fn.dataTable.Editor(config);

    var pluck = function (datas, value,key = "") {
        let result = [];
        if (!$.isEmptyObject(datas)){
            $.each( datas, function( index, data ) {
                if (value in data){
                    if(key === ""){
                        result.push(data[value]);
                    }else{
                        result.push(key,data[value]);
                    }
                }
            });
        }
        return result;
    };

    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });


    // $('.multiselect-container .multiselect-filter').css({
    //     'position': 'sticky', 'top': '0px', 'z-index': 1,
    // });

    init_select2();

    init_bsMultiselect();
    init_datepicker();

    $('[data-toggle="tooltip"]').tooltip();
    $('[data-toggle="popover"]').popover();
   // $('input[data-toggle="toggle"]').bootstrapToggle();


    $('.nav a[data-toggle="tab"]').on('shown.bs.tab', function(e){
        var $activeTab = $(e.target); // active tab <a>
        var tabPaneID = $activeTab.attr("href"); // "#tab-cont-1"
        var $tabPane = $(tabPaneID); // tab-content <div class='tab-pane'>
        var url = $activeTab.attr("data-url");

        $tabPane.find("table.table").each(function () {
             let tableId = $(this).attr("id");
             refresh_datatable(tableId)
        });

    });

</script>
