$(document).ready(function () {
    var urlString = window.location.href;
    var url = new URL(urlString);
    var acKey = decodeURI(url.searchParams.get("acKey"));
    var dateISO = decodeURI(url.searchParams.get("date"));
    var productionType = $("#ProductionType").val();

    if (urlString.includes("date")) {
        var date = fromISOToStandardDateFormatString(dateISO);
        $("#Filter_DateFrom").val(date);
    }

    initializeIdentBasicTypeahead(
        $('#IdentFilterSearch').attr('dataUrl'),
        $('#IdentFilterSearch'),
        $('#IdentFilterSearch'),
        { item: $("#identFilterItem").val(), name: $("#identFilterName").val() },
        null,
        function (item) {
            $("#IdentFilterSearch").val(item.id);
            $.fn.dataTable.reload($mainGridTable);
            return { selected: true, value: item.id };
    });


    $(".datepicker").datepicker({
        format: 'dd.mm.yyyy',
        language: $('#languageDate').val()
    }).on('changeDate', function () {
        $(this).datepicker('hide');
        $.fn.dataTable.reload($mainGridTable);
    });

    $mainGridTable = $('#mainGrid');

    var mainTable = $mainGridTable.DataTable({
        ajax: {
            url: $mainGridTable.attr('data-url'),
            data: function (d) {
                d.DocType = $("#DocType").val();
                d.Status = $("#Status").val();
                d.Product = $("#IdentFilterSearch").val();
                d.ProductionType = $("#ProductionType").val();
                d.DateFrom = reformatDate($("#Filter_DateFrom").val());
                d.DateTo = reformatDate($("#Filter_DateTo").val());
            }
        },
        columns: [
            {
                data: function (data) {
                    return "<span class='span'> <img class='picture' src='" + data.Picture + "' /> </span>";
                },
                orderable: false,
                render: function (data) {
                    return data;
                },
                createdCell: function (td, cellData, full) {
                    $(td)
                        .attr('data-toggle', 'tooltip')
                        .attr('title', '')
                        .attr('data-placement', 'bottom')
                        .attr('data-original-title', full.Product);

                }
            },
            {
                data: "Product",
                name: "acName",
                filtertype: "text",
                className: "card-label",
                createdCell: function (td, cellData) {
                    $(td)
                        .attr('data-toggle', 'tooltip')
                        .attr('title', '')
                        .attr('data-placement', 'top')
                        .attr('data-original-title', cellData);

                }
            },
            {
                data: "AcKeyDisplay",
                name: "AcKey",
                filtertype: "text",
                className: "dt-body-left",

                render: function (data, type, full) {
                    return type === 'display' ?
                        '<span style="margin-right:2px"> <i class="far fa-hashtag"></i> </span> <span>' + data + '</span>' : data;
                }
            },
            {
                data: 'Date',
                name: "adDate",
                render: function (data, type, full) {
                    return type === 'display' ?
                        '<span style="margin-right:2px"> <i class="far fa-calendar alt"></i> </span> <span>' + data + '</span>' : data;
                }
            },

            {
                data: 'CompletedPrc',
                render: function (data, type, row, meta) {
                    return type === 'display' ?
                        '<progress value=' + data + ' max="100"></progress>' :
                        data;
                }
            },

            {
                data: 'Status',
                render: function (data, type, full) {
                    var completedPrc = $.fn.dataTable.render.number('.', ',', 0, '', " ").display(full.CompletedPrc);
                    return type === 'display' ?
                        '<span>' + data + '</span>  <span class="pull-right">' + completedPrc + ' %</span>' : data;
                }
            },

        ],
        createdRow: function (row, data, dataIndex) {
            $(row).css('cursor', 'pointer');
        },
        drawCallback: function () {
            $("[data-toggle='tooltip']").tooltip({
                container: 'body'
            });
        }

    });

    $("select").off("change");
    $("select").on("change", function () {
        $.fn.dataTable.reload($mainGridTable);
    });

    mainTable.on('click', 'tr', function () {
        var data = mainTable.row($(this)).data();
        window.location.href = "Manufacturing/IssueMat?id=" + data.AcKey + '&type=' + productionType;;
    });


    $identTable = $('#stockGrid');
    $identTable.DataTable({
        ajax: {
            url: $identTable.attr('data-url'),
            data: function (d) {
                d.DateFrom = reformatDate($("#DateFromToday").val());
                d.DocType = $("#DocType").val() ? $("#DocType").val().toString() : "";
                d.Ident = $("#IdentFilterSearch").val();
                d.SetOfItem = $("#SetOfItem").val() ? $("#SetOfItem").val().toString() : "";
                d.Subject = $("#SubjectFilterSearch").val();
                d.Warehouse = $("#Warehouse").val() ? $("#Warehouse").val().toString() : "";
            }
        },
        columns: [
            { data: "Ident", name: "AcIdent", filtertype: "text", render: $.fn.dataTable.render.link("Ident") },
            { data: "Name", name: "AcIdentNavigation.AcName", filtertype: "text", render: $.fn.dataTable.render.link("Ident") },
            { data: "Warehouse", name: "AcWarehouse", filtertype: "text", render: $.fn.dataTable.render.link("Warehouse") },
            { data: "Stock", name: "AnStockQty", filtertype: "number", className: 'dt-body-right', render: $.fn.dataTable.render.number('.', ',', $("#DefaultDecimalPlacesQuantity").val()) },
            { data: "Unit", name: "AcIdentNavigation.AcUm", filtertype: "text" },
            {
                data: "RetailPrice", name: "AnLastPrice", filtertype: "number", className: 'dt-body-right', render: $.fn.dataTable.render.number('.', ',', $("#DefaultDecimalPlacesPrice").val())
            },
            {
                data: "SellingPrice", name: "AnValue", filtertype: "number", className: 'dt-body-right', render: $.fn.dataTable.render.number('.', ',', $("#DefaultDecimalPlacesPrice").val())
            },
            { data: "Currency", name: "AcCurrency", filtertype: "text" },
        ]
    });

});

