const financialReviewsTableId = 'financialReviews';

$(document).ready(function () {
    const columns = [
        { data: "KeyView", name: "Key", filtertype: "text", render: $.fn.dataTable.render.link("Key") },
        { data: "Name", name: "Name", className: 'dt-body-left' },
        {
            data: "Date", name: "Date", className: 'dt-body-left', render: function formatDate(data) {
                return moment(data).format($("#DateFormatLOC").val().toUpperCase());
            }
        },
        { data: "Buyer", name: "Buyer", className: 'dt-body-left', render: $.fn.dataTable.render.link("Buyer") },
        { data: "Receiver", name: "Recipient", className: 'dt-body-left', render: $.fn.dataTable.render.link("Receiver") },
        { data: "Position", name: "Position", className: 'dt-body-left' },
        { data: "Department", name: "Department", className: 'dt-body-left' },
        { data: "Ident", name: "Ident", className: 'dt-body-left' },
        { data: "Quantity", name: "Quantity", className: 'dt-body-center' },
        { data: "Currency", name: "Currency", className: 'dt-body-center' },
        {
            data: "ProdVrednost",
            name: "SellingPrice",
            className: 'dt-body-right',
            render: function (data) {
                return parseFloat(data).toFixed(2);
            }
        }
    ]

    initializeFinancialReviewsDataTables(financialReviewsTableId, 'Keywords', columns);
});


function initializeFinancialReviewsDataTables(tableId, keywordsId, columns) {
    const doneTypingInterval = 600;
    let typingTimer;

    if (keywordsId.length > 0) {
        $('#' + keywordsId).off('keyup');
        $('#' + keywordsId).on('keyup', function () {
            clearTimeout(typingTimer);
            typingTimer = setTimeout(function () { reloadDataTable(tableId); }, doneTypingInterval);
        });
    }

    $('#Customer, .custom-datepicker').change(function () {
        reloadDataTable(tableId);
    });

    if ($('#' + tableId).length !== 0) {
        $dataTable = $('#' + tableId);
        $dataTable.DataTable({
            ajax: {
                url: $dataTable.attr('data-url'),
                data: function (d) {
                    d.Keywords = $('#' + keywordsId).val();
                    d.CaseNumber = $("#CaseNumber").val();
                    d.DateFrom = $("#DateFrom").val();
                    d.DateTo = $("#DateTo").val();
                    d.Customer = $("#Customer").val();
                }
            },
            columns: columns
        });
    }
}
