var isFiscalPrinterGlobal;
async function initializeJournal(localization, isFiscalPrinter, centralApiUrl, localApiUrl) {
    isFiscalPrinterGlobal = isFiscalPrinter;
    var getSearchData = function () {
        return {
            DateTo: reformatDate($("#Filter_DateTo").val()),
        };
    };

    function format(item) { return item.Text; };

    $dataTable = $('#grid-data');
    $dataTable.DataTable({
        ajax: {
            url: $dataTable.attr('data-url'),
            data: function (d) {
                d.Keywords = $("#Keywords").val();
                d.DateTo = $("#Filter_DateTo").val();
                d.AcKeyTo = $("#Filter_AcKeyTo").val();
                d.DocType = $("#DocType").val();
            }
        },
        columns: [
            { data: "AcKeyView", name: "AcKey", render: $.fn.dataTable.render.link("AcKey"), filtertype: "text" },
            { data: "Date", name: "AdDate", filtertype: "dateTime" },
            { data: "Receiver", name: "AcReceiver", filtertype: "text" },
            { data: "Amount", name: "AnForPay", render: $.fn.dataTable.render.number('.', ',', 2), className: 'dt-body-right', filtertype: "number" },
            { data: "User", name: "AcName", filtertype: "text" }

        ],
        createdRow: function (row, data, dataIndex) {
            if ((data.IsPayment === '0' || data.IsPayment === '-1' || data.IsPayment === '-2') && $("#PreventCreateJournal").val() === "True") {
                $(row).addClass('danger');
            }
        }
    }).on('xhr.dt', function (e, settings, json, xhr) {
        $('#grid-data-total-sum').html($.fn.dataTable.render.number('.', ',', 2).display(json.prop.SumAmount));
        $('#grid-data-start-items').html(json.recordsTotal === 0 ? '0' : '1');
        $('#grid-data-total-items').html(json.recordsTotal);

        if (json.recordsTotal > 0)
            $('#createButton').prop('disabled', false);
    });

    $("#searchIssuedBills").on("click", function () {
        $.fn.dataTable.reload($dataTable);
    });

    $("#Filter_AcKeyTo").on("change", function () {
        $.fn.dataTable.reload($dataTable);
    });

    $("select").off("change.tableReload");
    $("select").on("change.tableReload", async function () {
        if (this.id === "DocType")
            await getPosDocTypeSettings();

        $.fn.dataTable.reload($dataTable);
    });

    $('.datepicker').datepicker()
        .on('click', function (e) {
            $(this).select();
        }).on('changeDate', function () {
            $(this).datepicker('hide');
            $.fn.dataTable.reload($dataTable);
        });

    $("#searchIssuedBills").on("click", function () {
        $.fn.dataTable.reload($dataTable);
    });

    $(".datepicker").datepicker({
        format: 'dd.mm.yyyy',
        language: $('#i18n').val()
    });

    $("#createButton").on('click', function (e) {
        $().customModal({
            destroyOnClose: true,
            showCloseButton: true,
            type: "question",
            text: stringFormat($("#CreateJournalForDateLoc").val(), $("#Filter_DateTo").val()),
            buttons: [
                {
                    icon: 'fa fa-times',
                    text: $("#NoLoc").val(),
                    closeOnAction: true,
                    type: 'ghost'
                },
                {
                    icon: 'fa fa-check',
                    text: $("#YesLoc").val(),
                    action: function () {
                        createJournal($(this));
                    },
                    closeOnAction: true,
                    type: 'primary'
                }
            ]
        });
    });
}

function createJournal(button) {
    var billsWithErrors = document.getElementsByClassName('danger');

    if (billsWithErrors.length > 0) {
        generateErrorModal($("#createCashRegJournalError").val());
        e.preventDefault();
        return;
    }

    $.post($("#CreateJournalUrl").val(), { DateTo: $("#Filter_DateTo").val(), AcKeyTo: $("#Filter_AcKeyTo").val(), DocType: $("#DocType").val() })
        .done(function (response) {
            if (response && response.result) {
                if (response.isPosFinancialOnly === true)
                    $.fn.dataTable.reload($dataTable);
                else {
                    if (isFiscalPrinterGlobal)
                        fiscalPrinterZReport(centralApiUrl, localApiUrl, localization.zReportTitle, localization.zReportSuccessMessage, button, function () { window.location = $("#JournalUrl").val(); });
                    else {
                        $().customModal({
                            destroyOnClose: true,
                            showCloseButton: true,
                            type: "success",
                            text: $("#JournalSuccessfullyCreatedLoc").val(),
                            buttons: [
                                {
                                    icon: 'fa fa-check',
                                    text: $("#ConfirmLoc").val(),
                                    action: function () {
                                        window.location = $("#JournalUrl").val();
                                    },
                                    closeOnAction: true,
                                    type: 'primary'
                                }
                            ]
                        });
                    }
                }
            }
            else if (response && response.result === "") {
                generateErrorModal($("#cashRegJournalNoEligibleInvoicesError").val());
            }
            else {
                generateErrorModal($("#cashRegJournalGeneralError").val());
            }
        }).fail(function () {
            generateErrorModal($("#cashRegJournalGeneralError").val());
        });
}

function initializeJournalCloseLastOpenedJournal() {
    initializeJournal();
}

function generateErrorModal(displayText) {
    $().customModal({
        destroyOnClose: true,
        title: "",
        showCloseButton: true,
        type: "error",
        text: displayText,
        buttons: [
            {
                icon: 'fa fa-check',
                text: $("#okLoc").val(),
                closeOnAction: true,
                type: 'primary'
            }
        ]
    });
}

async function getPosDocTypeSettings() {
    await fetch($("#GetPosSettingsUrl").val() + "?docType=" + $("#DocType").val() + "&setting=ZReportPreventCreate", {
        method: "GET",
        headers: {
            'Content-Type': 'application/json'
        }
    }).then((response) => response.json()
    ).then(async (data) => {
        if (data && data.Value) {
            $("#PreventCreateJournal").val(data.Value);
        }
    }).catch(async (error) => {});
}