@extends('layouts.admin')

@section("styles")

@endsection

@push("js")

    <script>
        var $main_tab_content = $("#tab-content-stocks-management");

        var showPreviewValidateImportData = function(warehouse_id){
            let data = {
                'warehouse_id' : warehouse_id,
                'operation' : "show-dt-validate-preview",
            };
            {{--execute_requete_ajax("div-global-result-ajax-query",--}}
            {{--    '{{route("auth_stocks_management_importation_fetchAsync")}}','get',data);--}}
        };

        var showModalNouveauTransfertStock = function(warehouse_id){
            let data = {
                'warehouse_id' : warehouse_id,
                'operation' : "show-modal-nouveau-transfert-stock",
            };
            {{--execute_requete_ajax("div-global-result-ajax-query",--}}
            {{--    '{{route("auth_stocks_management_transfert_fetchAsync")}}','get',data,$loader_20);--}}
        };

        var showModalNouvelleDemandeStock = function(sender_id,sender_type){
            let data = {
                'sender_id' : sender_id,
                'sender_type' : sender_type,
            };
            {{--execute_requete_ajax("div-global-result-ajax-query",--}}
            {{--    '{{route("auth_stocks_management_demand_showModalNewDemand")}}','get',data,$loader_20);--}}
        };

            @can("st-request-create")
            var showModalNewAdvancedDemandeStock = function(){
                {{--execute_requete_ajax("div-global-result-ajax-query",--}}
                {{--    '{{route("auth_stocks_management_demand_advanced_showModalNewAdvancedDemand")}}','get',{},$loader_20);--}}
            };
            @endcan

        var showModalEditLotsDemand = function(id_demand,id_table_demande ){
                let data = {
                    'id_demand' : id_demand,
                    'id_table_demande' : id_table_demande,
                };
                {{--execute_requete_ajax("div-global-result-ajax-query",--}}
                {{--    '{{route("auth_stocks_management_demand_showModalEditLotsDemand")}}','get',data,$loader_20);--}}
            };


        var openOrClosePVs = function () {
            let $toogles = $('input[name=switch-pvs][type=checkbox]');
            let val = [];
            $.each($toogles,function() {
                let $this = $(this);
                val.push({
                    'state' : $this.prop('checked'),
                    'id_pv' : $this.attr('data-id-pv'),
                });
            });

            let url = 'admin/login';
            let param = {body: {datas : val}, method:'post',};

            swal.fire({
                title: '{{__("Clôture de points de ventes")}}',
                text : "{{__("Confirmer les modifications?")}}",
                icon: 'question',
                showCancelButton : true,
                showConfirmButton: true,
                reverseButtons : true,
                cancelButtonText : '{{__("Non")}}',
                confirmButtonText : '{{__("Oui")}}',
            })
                .then((result) => {
                    if (result.isConfirmed) {
                        request(url,param)
                            .then(reponse => {
                                let success = reponse.is_success;
                                toast({title:reponse.message,icon : (success) ? "success" : "error"});
                                if(success){
                                    hideModal();
                                }
                            });
                    }
                });
        };

        var receiveTransferts = function(id_table){
            let data = [];

            $("table#"+id_table+' tbody tr.selected')
                .each(function (index) {
                    let $input = $(this).find("td input[type='number']");
                    let $select = $(this).find("td select");
                    let values = {
                        'id_transfert': $input.attr('data-id-transfert'),
                        "received_qty": $input.val(),
                        "id_type_ajustement": $select.val(),
                    };
                    data.push(values);
                });

            let count = data.length;

            if(count > 0){
                swal.fire({
                    title: "{{__('Stocks en Transit')}}",
                    text: "{{__("Recevoir ces stocks ?")}}",
                    icon: 'question',
                    showCancelButton : true,
                    reverseButtons : true,
                    confirmButtonText: '{{__("Oui")}}',
                    cancelButtonText: '{{__("Non")}}',
                })
                    .then((result) => {
                        if (result.isConfirmed) {
                            let param = {
                                body: { datas : data,},
                                method:'post',
                            };
                            let url = "";

                            request(url,param)
                                .then(result => {
                                    // if(!result.is_success){}
                                    $("#"+id_table).DataTable().draw();
                                    let type = (result.is_success) ? "success" : 'error';
                                    toast(type,{'title' : "{{__('Transit')}}","msg" : result.message});
                                });
                        }
                    });
            }
            else{
                toast("error",{'title':"{{__('Transit')}}","msg":"{{__("Veuillez cochez au moins 01 ligne dans le tableau.")}}"});
            }
        };

        var getSelectedDatasInTableDemande = function(id_table){
            let data = [];
            let table = $("#"+id_table).DataTable();
            $("#"+id_table+" tbody tr.selected").each(function (index,tr) {
                let rowData = table.row(tr).data();
                data.push(rowData.id);
            });
            return data;
        };

        var changeStatutDemand = function($btn){
            let id_table = $btn.attr('data-id-table');
            let datas = getSelectedDatasInTableDemande(id_table);
            let url = $btn.attr("data-url");

            if (datas.length > 0){
                swal.fire({
                    icon: 'question',
                    title: "{{__('Demands')}}",
                    text: "{{__("Put")}} "+datas.length+" {{__('row(s)')}} "+$btn.attr("data-libelle-statut")+" ?",
                    showCancelButton: true,
                    confirmButtonText: '{{__("Yes")}}',
                    cancelButtonText: '{{__("No")}}',
                })
                    .then((result) => {
                        if (result.isConfirmed) {
                            let param = { body: {ids : datas}, method:'post',};
                            request(url,param)
                                .then(result => {
                                    refresh_datatable(id_table);
                                    toast({icon : result.type, title :result.title,text : result.message});
                                });
                        }
                    });
            }else{
                toast({icon:"error", title :'{{__("Veuillez cochez au moins 01 ligne dans le tableau.")}}'});
            }
        };


        var loadEditorUploadStock = function (warehouse_id,formTitle,tableId,config) {
            uploadStockEditor.field("warehouse_id").s.opts.def = warehouse_id ;

            uploadStockEditor.create({
                title: formTitle,
                message: `<div class="fs-13 font-weight-bold text-center m-b-20">
                            <div>Upload your stocks files</div>
                             <div>
                                 <a href="{{ url('backend/uploads/stock-imports-model.xlsx') }}"
                                     target="_blank"
                                     class="kt-font-info fs-10 text-underline text-blue">
                                     Click here to get a file model
                                 </a>
                             </div>
                         </div>`,
                buttons: {
                    className: "btn-success",
                    text: "{{__("Import")}} <i class='fa fa-upload' />",
                    action: function () {
                        this.submit(
                            function (response) {
                                const that = this;
                                $(".DTE_Form_Error").hide();
                                if (('fieldErrors' in response) && !$.isEmptyObject(response.fieldErrors)){
                                    response.fieldErrors.forEach(error => {
                                       that.field(error.name).error(error.status)
                                    });
                                    return ;
                                }

                                const success = response.success ?? false;
                                if(success) {
                                    refresh_datatable(tableId);
                                    dispatchBrowserEvent("stocks:importations.preview.loaded",{warehouse_id})
                                }
                                toast({title : response.message , icon : success ? "success" : 'error' })
                            },
                            (response) =>{
                                $(".DTE_Form_Error").show().html(response.message)
                            },
                            false,
                            true //  close modal
                        );
                    },

                }
            });
        };

        var loadEditorCreateLot = function (warehouse_id,formTitle,tableId,config) {
            createLotEditor.field("warehouse_id").s.opts.def = warehouse_id ;
            createLotEditor.create({
                title: formTitle,
                buttons: {
                    className: config.className,
                    text: config.attr.icon+config.attr.title,
                    action: function () {
                        this.submit(
                            function (response) {
                                if(typeof response === 'object'){
                                    if (('fieldErrors' in response) && $.isEmptyObject(response.fieldErrors)){
                                        if (response.success){
                                            toast({title: response.message,});
                                            refresh_datatable(tableId);
                                            loadEditorCreateLot(warehouse_id,formTitle,tableId,config);
                                            return ;
                                        }
                                    }
                                    if (('message' in response) && !response.success){
                                        toast({icon : "error",'title':response.message});
                                    }
                                }
                            },
                            false,
                            false,
                            false //  close modal
                        );
                    },

                }
            });
        };

        var loadEditorCreateAdjustment = function (stock,tableId) {
             createAdjustmentEditor.field("stock_id").s.opts.def = stock.id ;
             createAdjustmentEditor.field("info").s.opts.def = stock.info ;
             createAdjustmentEditor.s.table = "#"+tableId;
             createAdjustmentEditor.create({
                title : "{{strtoupper(__("Adjustment"))}} : "+stock.lot_id,
                buttons: {
                    className: "btn-success",
                    text: "{{__("Adjust")}} <i class='fa fa-save' />",
                    action: function () {
                        this.submit(
                            function (response) {
                                if(typeof response === 'object'){
                                    if (('fieldErrors' in response) && $.isEmptyObject(response.fieldErrors)){
                                        if (response.success){
                                            toast({icon : "success",title: response.message});
                                            refresh_datatable(tableId);
                                            //loadEditorCreateAdjustment(stock,tableId);
                                            return ;
                                        }
                                    }
                                    if (('message' in response) && !response.success){
                                        toast({icon : "error",'title':response.message});
                                    }
                                }
                            },
                            false,
                            false,
                            true //  close modal
                        );
                    },

                }
            });
        };

        var getEditorTransferdQtyDemand = function(id_table){
            return DataTableEditor( {
                ajax: {url : "admin/login", type : "post",},
                idSrc:  'id',
                table: "#"+id_table,
                fields: [
                    {
                        label : "{{__('Tranfered Qty')}}",
                        name : "transfered_qty",
                        data : "transfered_qty",
                        attr : { type : "number", },
                    },
                ]
            } );
        };

        var getEditorReceivedQtyDemand = function(id_table){
            return  DataTableEditor( {
                ajax: {url : "admin/login", type : "post",},
                idSrc:  'id',
                table: "#"+id_table,
                fields: [
                    {
                        label : "{{__('Received Qty')}}",
                        name : "received_qty",
                        data : "received_qty",
                        attr : { type : "number", }
                    },
                    {
                        label : "{{__('Message')}}",
                        name : "message_tmp",
                        type :'textarea',
                        data : "message_tmp",
                        attr : {rows : "5", cols : "4",}
                    },
                    {
                        label: "{{__('Type')}}",
                        name: "id_type_ajustement",
                        type: "select",
                        data : "id_type_ajustement",
                        attr : {
                            "data-plugin-multiselects" : "",
                            "data-plugin-optionss" : '{ "enableCaseInsensitiveFiltering": true}',
                        },
                        options : [],
                    },
                ]
            } );
        };

        let $body_container = $("#body-container");
        let $tabs_content_menus = $body_container.find('#tab-content-menus-entrepots');
        let $menus = $body_container.find('.nav a[data-toggle="tab"]');

        var uploadStockEditor =  DataTableEditor( {
            ajax: {url : "{{route('admin.stocks.importations.create')}}", type : "post",},
            idSrc:  'id',
            // table: "#"+tableId,
            fields: [
                {
                    label: "{{__('Warehouse Id')}}",
                    name: "warehouse_id" ,
                    data: "warehouse_id" ,
                    type : "hidden",
                },
                {
                    label: "{{__('File')}} : ",
                    name: "file" ,
                    type: "upload",
                    display: (id)=> {
                        // return `<img src="${this.file('files',id).web_path}"/>`
                        // return `<img src="${that.editor.file('file',id).web_path}" alt="Preview" style="max-width: 200px; max-height: 200px;">`
                        return `<small class="fs-10 text-primary"> ${id}</small>`
                    },
                    noImageText: 'No File',
                    clearText: 'Remove',
                    fieldInfo: "{{__("Excel File(.xlsx, .xls)")}}",
                    dragDropText :"Drag and drop your file here.",
                    fileReadText : "Downloading ...",
                    uploadText : "Choose a file",
                    attr : { accept : '.xlsx,.xlx'}
                },
                {
                    label: "{{__('My File has headers')}} ? ",
                    name: "file_has_headers" ,
                    def:  1,
                    type: "radio",
                    options : [
                        {label : "{{yesNo(1)}}" , value : 1},
                        {label : "{{yesNo(0)}}", value : 0},
                    ],
                },
            ]
        } );

        var createLotEditor =  DataTableEditor( {
            ajax: {url : "{{route('admin.stocks.create')}}", type : "post",},
            idSrc:  'id',
            // table: "#"+tableId,
            fields: [
                {
                    label: "{{__('Warehouse Id')}}",
                    name: "warehouse_id" ,
                    data: "warehouse_id" ,
                    // def : id_entrepot,
                    type : "hidden",
                },
                {
                    label: "{{__('Lot id')}}",
                    name: "lot_id" ,
                },
                {
                    label: "{{__('Expired At')}}",
                    name: "expired_at" ,
                    def : "{{date("d-m-Y")}}",
                    type : 'datetime',
                    attr: {
                        "readonly" : true,
                        //type : "text",
                        "data-plugin-datepickers" : "",
                        "data-plugin-options" : '{ format:"dd-mm-yyyy"}',
                    }
                },
                {
                    label: "{{__('Quantity')}}",
                    name: "qty" ,
                    attr: {type : "number",}
                },
                {
                    label : "{{__('Product')}}",
                    name : "product_id",
                    type :'select',
                    attr : {
                        "data-plugin-multiselect" : "",
                    },
                    options : @json($products),
                },
            ]
        } );

        var updateRowStockEditor =  DataTableEditor( {
            ajax: {url : "admin/login", type : "post",},
            idSrc:  'id',
            //table: "#"+tableId,
            fields: [
                {
                    label: "{{__('Lot id')}}",
                    name: "lot_id" ,
                    data : "lot_id",
                },
                {
                    label: "{{__('Expired At')}}",
                    name: "expired_at" ,
                    data: "expired_at" ,
                    attr: {
                        "readonly" : true,
                        "data-plugin-datepicker" : "",
                        "data-plugin-options" : '{ format:"dd-mm-yyyy"}',
                    }
                },
                {
                    label : "{{__('Product')}}",
                    name : "product_id",
                    data : "product_id",
                    type :'select',
                    attr : {
                        "data-plugin-multiselect" : "",
                    },
                    options : @json($products),
                },
            ]
        } );

        var createAdjustmentEditor = DataTableEditor( {
            ajax : {
                // "contentType": "application/json, charset=utf-8",
                url : "{{route('admin.stocks.adjustments.create')}}",
                type : "post",
            },
            idSrc:  'id',
            fields: [
                {
                    label: "{{__('Infos')}}", name: "info" ,
                    attr: {"readonly" : true, "disabled" : true, class : "bg-success text-white"}
                },
                {label: "{{__('Id Stock')}}", name: "stock_id" , type : "hidden",},
                { label: "{{__('Ajusted Qty')}}", name: "qty_adjusted" , attr: {type : "number",}},
                {
                    label : "{{__('Operation')}}", name : "operation_code", type :'select',
                    attr : {
                        "data-plugin-multiselect" : '',
                        "data-plugin-options" : '{"enableCaseInsensitiveFiltering":false}',
                    },
                    options : @json($adjustmentsOperations),
                },
                {
                    label : "{{__('Reason')}}", name : "reason_code", type :'select',
                    attr : {
                        "data-plugin-multiselect" : '',
                        "data-plugin-options" : '{"enableCaseInsensitiveFiltering":false}',
                    },
                    options : @json($adjustmentsReasons),
                },
                {
                    label: "{{__('Comment')}}", name: "comment" , type :'textarea',
                    attr: { rows : 4, cols : 6,}
                },

            ]
        } );

        var $card = $("#card-stock-management");
        var $warehouse = $card.find();

        var showTableByTabIndex = function(tab_index = 1){
             //console.clear();
            const $tab = $card.find('a[data-toggle="tab"][data-tab-index='+tab_index+']');
            const tableId = $tab.attr("data-id-table");
            let has_checkbox = $tab.attr("data-has-checkbox");
            const table_html = $('#'+tableId);
            const $parentActiveTab = $("ul#tab-stocks-management a.active");
            const $parentActiveTabContent = $($parentActiveTab.attr("href"))
            const $warehouse = $parentActiveTabContent.find("select.warehouse-filter");
            let datatable;
            let url = $tab.attr('data-route');
            let cols = [];
            let options = {
                lengthChange: true,
                processing: true,
                serverSide: true,
                dom : "Bfrtilp",
                // ajax : {
                //     url : url,
                //     type : "get",
                //     data : function (d) {
                //           d.warehouse_id = $warehouse.val();
                //     }
                // }
            };
            console.log("active-tab-index = "+tab_index );
            if($warehouse.length){
                url += "?warehouse_id="+$warehouse.val()
            }
            let buttons = [
                { extend: "reload" },
                { extend: "export", },
            ];


            let table_filter_dates = [
                4, //ajustements
                5, //demandes
                51, //demandes-reçues
                511, //demandes-reçues-pv
                512, //demandes-reçues-magasin
                52, //demandes-reçues-magasin
                521, //demandes-reçues-magasin
                522, //demandes-reçues-magasin

                6, //transits
                61, //transits-pv
                611, //transits-pv-reçues
                612, //transits-pv-envoyées
                62, //transits-magasin
                621, //transits-magasin-reçues
                622, //transits-magasin-envoyées
            ];

           // console.log("table-id = "+tableId)

            if($.inArray(tab_index,[111,112,211,212]) !== -1){ // par Lots
                if($.inArray(tab_index,[111,211]) !== -1){
                    url += "&available_only=true";
                    //options.ajax.data['available_only'] = true;
                }else{
                    url += "&available_only=false";
                }
                cols = [
                    {data: 'lot_id', name: 'lot_id' ,searchable: true,
                        className: "{{auth(activeGuard())->user()->can('st-stock-update')
                                   ? "text-success cursor-pointer text-success"
                                   :''}} left",
                        @can("st-stock-update")
                        render: editIcon
                        @endcan
                    },
                    {data: 'product_id', name: 'product_id' ,searchable: true, className : 'left',},
                    {data: 'product.name', name: 'name_product' ,searchable: true},
                    {
                        data: 'qty', name: 'qty',
                        searchable: true ,
                        className: "{{auth(activeGuard())->user()->can('st-adjustment-create')
                                   ? "text-success cursor-pointer editable qty-editable text-success"
                                   :''}} right",
                        @can("st-adjustment-create")
                        render: editIcon
                        @endcan
                    },
                    {{--{--}}
                    {{--    data: 'qty', name: 'qty',--}}
                    {{--    searchable: true ,--}}
                    {{--    className: "{{auth(activeGuard())->user()->can('st-adjustment-create')--}}
                    {{--               ? "text-success cursor-pointer text-underline"--}}
                    {{--               :''}} right",--}}

                    {{--    @can("st-adjustment-create")--}}
                    {{--      render: editIcon--}}
                    {{--    @endcan--}}

                    {{--},--}}
                    {data: 'product.category.name', name: 'category' ,searchable: false},
                    {data: 'expired_at', name: 'expired_at',searchable: true,
                        className: "{{auth(activeGuard())->user()->can('st-stock-update')
                                   ? "text-success cursor-pointer text-success"
                                   :''}} left",
                        @can("st-stock-update")
                        render: editIcon
                        @endcan
                    },
{{--                    @canany(["st-adjustment-create","st-stock-adjustments-list",])--}}
                  //  {data: 'action', name: 'action', searchable: false,},
{{--                    @endcanany--}}
                ];

                @can("st-stock-create")
                    globalBtnCreate.action = function(e, dt, button, config){
                                                    let formTitle = " {{strtoupper(__("New Lot"))}} >>>"+ $warehouse.find("option:selected").text();
                                                    loadEditorCreateLot($warehouse.val(),formTitle,tableId,config);
                                                };
                //ajoute le btn à la positon 0
                buttons.unshift(globalBtnCreate);
                @endcan
            }
            else if($.inArray(tab_index,[12,22,]) !== -1){ // grouper par id_produit
                cols = [
                    {data: 'product_id', name: 'product_id' ,searchable: true,className: "left"},
                    {data: 'name', name: 'name' ,searchable: true,className: "left"},
                    {data: 'qty', name: 'qty',searchable: false ,className: "right"},
                    {data: 'lots_count', name: 'lots_count',searchable: false ,className: "right"},
                    {data: 'category', name: 'category' ,searchable: false,className: "left"},
                ]
            }
            else if($.inArray(tab_index,[13,23]) !== -1){ // importations
                @can("st-importations-create")
                    globalBtnCreate.text = `<i class="fa fa-upload"></i>`;
                    globalBtnCreate.action = function(e, dt, button, config){
                    let formTitle = " {{strtoupper(__("Importation"))}} >>"+ $warehouse.find("option:selected").text();
                    loadEditorUploadStock($warehouse.val(),formTitle,tableId,config);
                };
                 buttons.push({
                         className: "btn-warning",
                         attr : {
                             title: '{{__("Preview imported data")}}',
                             icon: '<i class="fa fa-eye"></i> ',
                             "data-toggle":"tooltip",
                             "data-original-title" : '{{__("Preview imported data")}}',
                         },
                         text: function (dt,button,config) {
                             let label = config.attr.title;
                             return config.attr.icon;
                         },
                         // columns: 'th:nth-child(n+2)',
                         action:  () => {
                             return dispatchBrowserEvent(
                                         "stocks:importations.preview.loaded",
                                         {
                                             warehouse : {
                                                 id : $warehouse.val() ,
                                                 name : $warehouse.find("option:selected").text()
                                             }
                                         }
                                     )
                         }
                     },
                 )
                //ajoute le btn à la positon 0
                buttons.unshift(globalBtnCreate);
                @endcan

                    cols = [
                    {data: 'lot_id', name: 'lot_id' ,searchable: true,className: "left"},
                    {data: 'product_id', name: 'product_id' ,searchable: true},
                    {data: 'product_name', name: 'name_product' ,searchable: true},
                    {data: 'real_qty', name: 'stock_reel',searchable: false ,className: "right"},
                    {data: 'theoretical_qty', name: 'theoretical_qty',searchable: false ,className: "right"},
                    {data: 'gap', name: 'gap',searchable: false ,className: "right"},
                    {data: 'product_category', name: 'product_category' ,searchable: false},
                    {data: 'created_by', name: 'created_by',searchable: false},
                    {data: 'expired_at', name: 'expired_at',searchable: false},
                    {data: 'created_at', name: 'created_at',searchable: false},
                ];
            }
            else if($.inArray(tab_index,[14,24]) !== -1){ // ajustements
                cols = [
                    {data: 'stock.lot_id', name: 'lot_id' ,searchable: true,className: "left"},
                    {data: 'product', name: 'product' ,searchable: false},
                    {data: 'qty_before', name: 'qty_before',searchable: true ,className: "right"},
                    {data: 'qty_adjusted', name: 'qty_adjusted',searchable: true ,className: "right"},
                    {data: 'qty_after', name: 'qty_after',searchable: true ,className: "right"},
                    {data: 'reason', name: 'reason',searchable: false ,className: "left"},
                    {data: 'operation', name: 'operation',searchable: false ,className: "left"},
                    {data: 'comment', name: 'comment',searchable: false ,className: "left"},
                    {data: 'created_by', name: 'created_by',searchable: false},
                    {data: 'created_at', name: 'created_at',searchable: false},
                ];
            }

            //[Demandes] PV->Reçues ou Magasin->Reçues
            else if($.inArray(tab_index,[511,521]) !== -1){
                cols = [
                    {data: 'checkbox', name: 'checkbox_all' ,searchable: false,ordering:false,exportable:false,className: "center select-checkbox"},
                    {data: 'lot_id', name: 'lot_id' ,searchable: true,className: "left"},
                    {data: 'expired_at', name: 'expired_at',className: "left",searchable: true,exportable:false},
                    {data: 'product', name: 'product' ,searchable: true,className: "left"},
                    {data: 'requested_qty', name: 'requested_qty',searchable: true ,className: "right"},
                    {data: 'transfered_qty', name: 'transfered_qty',searchable: true ,
                        className: "{{auth(activeGuard())->user()->can('st-request-update')
                                   ? "text-success cursor-pointer text-success"
                                   :''}} right",
                        @can("st-request-update")
                        render : editIcon,
                        @endcan
                    },
                    {data: 'at', name: 'at',className: "left",searchable: true,exportable:false},
                ];
            }

            //[Demandes] PV->Envoyées ou Magasin->Envoyées
            else if($.inArray(tab_index,[512,522]) !== -1){
                cols = [
                    {data: 'product_id', name: 'product_id' ,searchable: true},
                    {data: 'product.name', name: 'name_product' ,searchable: false},
                    {data: 'requested_qty', name: 'qte',searchable: false ,className: "right"},
                    {data: 'user', name: 'created_by',searchable: false},
                    {data: 'created_at', name: 'created_at',searchable: false},
                ];
            }

            //[Transits] PV->Envoyées ou Magasin->Envoyées
            else if($.inArray(tab_index,[612,622]) !== -1){
                cols = [
                    {data: 'checkbox', name: 'checkbox_all' ,searchable: false,ordering:false,exportable:false,className: " select-checkbox"},
                    {data: 'product_id', name: 'product_id' ,searchable: true},
                    {data: 'product.name', name: 'name_product' ,searchable: false},
                    {data: 'requested_qty', name: 'requested_qty',searchable: false ,className: "right"},
                    {data: 'transfered_qty', name: 'transfered_qty',searchable: false ,className: "right"},
                    {data: 'edit_received_qty', name: 'received_qty',searchable: false ,className: "right"},
                    {data: 'edit_message_tmp', name: 'message',searchable: false ,className: "left",},
                    {data: 'edit_type', name: 'type',searchable: false ,className: "left",},
                    {data: 'statut', name: 'statut',searchable: false},
                ];
            }

            //[Transits] PV->Reçues ou Magasin->Reçues
            else if($.inArray(tab_index,[611,621]) !== -1){
                cols = [
                    {data: 'lot_id', name: 'lot_id' ,searchable: true,className: "left"},
                    {data: 'expired_at', name: 'expired_at',className: "left",searchable: true,exportable:false},
                    {data: 'product', name: 'product' ,searchable: true,className: "left"},
                    {data: 'requested_qty', name: 'requested_qty',searchable: true ,className: "right"},
                    {data: 'transfered_qty', name: 'transfered_qty',searchable: true ,className: "right",},
                    {data: 'received_qty', name: 'received_qty',searchable: true ,className: "right"},
                    {data: 'statut', name: 'statut',searchable: false ,className: "left"},
                ];
            }

            if (has_checkbox){
                options.columnDefs = [ {
                    orderable: false,
                    className: 'select-checkbox',
                    targets:   0,
                    content : "",
                } ];

                options.select = {
                    style :    'multi',
                    selector : 'td.select-checkbox',
                };
            }
            options.ajax = url;

            if ($.fn.dataTable.isDataTable('#'+tableId)){
                let table = table_html.DataTable();
                datatable = table.ajax.url(url).load();
                //datatable = table.draw();
            }
            else{
                append_dt_footer(tableId);
                options.columns = cols; // add columns
                options.buttons = buttons; // add buttons
                datatable = table_html.DataTable(options); // generate datatable
            }

            dispatchBrowserEvent("stocks:dataTable.opened",{
                table_id : tableId,
                warehouse_id : $warehouse.val(),
                url ,
                has_checkbox
            })
            return datatable;
        };
        var active_tab_index = 111;
        $(function () {
            showTableByTabIndex(active_tab_index);

            $card.find('select').on('change',function (e) {
                showTableByTabIndex(active_tab_index);
            });

           // $menus.eq(0).tab("show"); // affiche le premier menus
            $card.find('.nav a[data-toggle="tab"]').on('shown.bs.tab', function(e){
                var $active_tab = $(e.target); // active tab
                 active_tab_index = parseInt($active_tab.attr("data-tab-index"));
               // console.clear();
                //if(active_tab_index > 0){
                    showTableByTabIndex(active_tab_index)
                //}
            });

            // $("button.btn-demande-change-statut").on('click',function (e) {
            //     changeStatutDemand($(this));
            // })
        });
    </script>
    <script>

        $(function () {
            const $first_table = $card.find("div.tab-pane.active.show")
                                          .eq(0)
                                          .find('div.tab-pane.active.show')
                                          .eq(0).find('div.tab-pane.active.show')
                                          .eq(0)
                                          .find("table")
                                          .eq(0)

            if ($first_table){
               // refresh_datatable($first_table.attr('id'));
            }

        });
    </script>
@endpush

@section('content')

<div class="card shadow mb-4" id="card-stock-management">
    <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
        <h6 class="m-0 font-weight-bold text-success">{{$title}}</h6>
        <div class="dropdown no-arrow">
            <a class="dropdown-toggle" href="#" role="button" id="dropdownMenuLink"
               data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                <i class="fas fa-ellipsis-v fa-sm fa-fw text-gray-400"></i>
            </a>
{{--            <div class="dropdown-menu dropdown-menu-right shadow animated--fade-in" aria-labelledby="dropdownMenuLink">--}}
{{--                <div class="dropdown-header">Dropdown Header:</div>--}}
{{--                <a class="dropdown-item" href="#"--}}
{{--                   title = "{{__("Effectuer une nouvelle demande de stocks")}}">--}}
{{--                    <i class="text-success fas fa-trademark"></i>--}}
{{--                    {{__("Nouvelle demande")}}--}}
{{--                </a>--}}
{{--                <a class="dropdown-item" href="#"--}}
{{--                   title = "{{__("Ouvrir/Fermer les points de ventes")}}">--}}
{{--                    <i class="text-warning fas fa-server"></i>--}}
{{--                    {{__("Clôturer")}}--}}
{{--                </a>--}}
{{--                <div class="dropdown-divider"></div>--}}
{{--                <a class="dropdown-item" href="#">Something else here</a>--}}
{{--            </div>--}}
        </div>
    </div>
    <ul class="nav nav-tabs" id="tab-stocks-management" role="tablist">
        @foreach($tabs as $index => $options)
            <li class="nav-item">
                <a data-toggle="tab" role="tab"
                   class="nav-link {{($loop->first) ?"border-left-0 active show":""}}"
                   id="{{$options['id']}}"
                   href="#{{$options['href']}}"
                   aria-controls="{{$options['id']}}"
                   aria-selected="{{($loop->first) ?"true":"false"}}">
                    <span class="{{$options['icon'] }}"></span>
                    {{__($options['title'])}}
                </a>
            </li>
        @endforeach
    </ul>

    <div class="tab-content" id="tab-content-stocks-management">
        @foreach($tabs as $index => $options)
            <div role="tabpanel"
                 class="tab-pane fade {{($loop->first) ?"active show":""}}"
                 id="{{$options['href']}}"
                 aria-labelledby="{{$options['id']}}">
                @includeIf(($options['content']['file']), ['options' => $options])
            </div>
        @endforeach
    </div>
</div>
@endsection
