var getFiscalSearchData = function () {
    return {
        DateFrom: reformatDate($("#Filter_DateFrom").val()),
        DateTo: reformatDate($("#Filter_DateTo").val()),
        PartnerId: $("#Filter_PartnerId").val(),
        Fiscalized: $("#Filter_Fiscalized").val(),
        IsTip: $("#documentCategory option:selected").hasClass("tips-unconfirmed-option"),
        DocType: $("#Filter_DocType").val(),
        ProductId: $("#Filter_ProductId").val(),
        IsWholesale: $("#Filter_IsWholesale").val(),
        Author: $("#Filter_Author").val(),
        Keywords: $("#Filter_Keywords").val()
    };
};

function invoiceSelectionChanged(cb) {
    selectionChanged(cb);
}

function onClickFiscalizeAllUnconfirmedBills() {
    $("#confirmBills").append('<i id="confirmBillsSpinner" class="fa fa-spinner fa-spin fa-fw"></i>');
    $.post("/CashRegister/FiscalizeAllUnconfirmedDocuments")
        .done(function (response) {
            if (response !== null) {
                var errors = "";
                for (var i = 0; i < response.length; i++) {
                    if (response[i] !== null && !response[i].Success) {
                        errors = errors + response[i].Errors + "\n";
                    }
                }

                if (errors) {
                    alert(errors);
                }
            }

            $.fn.dataTable.reload($dataTable);
            $("#confirmBillsSpinner").remove();
        })
        .fail(function (err) {
            alert(err.statusText);
            $.fn.dataTable.reload($dataTable);
            $("#confirmBillsSpinner").remove();
        });
}

function onClickFiscalizeSelectedBills() {
    fiscalize(getFiscalSearchData(), $dataTable);
}

function initializeReportsIssuedBills() {
    let helpUrl = $("#documentCategory option:selected").attr("data-helpurl");
    if (helpUrl)
        setGlobalHelpUrl(helpUrl);
    $("#documentCategory").on("change", function () {
        filters = [];
        sortColumn = "";
        sortOrder = "";
        var urlString = window.location.href;
        var urlCR = new URL(urlString);
        var dateISO = decodeURI(urlCR.searchParams.get("date"));
        var url = $(this).val();
        var urlParts = $(this).val().split("/");
        var methodName = $(this).find(":selected").attr("data-method") ? $(this).find(":selected").attr("data-method") : ("initializeReports" + (urlParts.length > 0 ? urlParts[urlParts.length - 1] : ""));
        $("#issuedBillsContent").html($("#datatable-loading").val());
        resetSelection();

        let helpUrl = $("#documentCategory option:selected").attr("data-helpurl");
        if (helpUrl)
            setGlobalHelpUrl(helpUrl);

        $.get(url, function (data) {
            $("#issuedBillsContent").html(data);
            if (typeof window[methodName] === "function") {
                window[methodName]();
            }

            $("#Filter_DocType").trigger("change");
            $("#confirmBills").off("click");
            $("#confirmBills").on("click", function () {
                fiscalize(getFiscalSearchData(), $dataTable);
            });


            if ($("#documentCategory option:selected").hasClass("unconfirmed-bills")) {
                $("#Filter_DateFrom").val($("#UnconfirmedBillsDateFrom").val());
                $("#Filter_DateFrom").datepicker('setDate', $("#UnconfirmedBillsDateFrom").val());
                $("#fiscalizeSelectedBills").removeClass("hidden");
            } else {
                if (urlString.includes("date")) {
                    var date = fromISOToStandardDateFormatString(dateISO);
                    $("#Filter_DateFrom").val(date);
                } else {
                    $("#Filter_DateFrom").val($("#DateFromDefault").val());
                    $("#Filter_DateFrom").datepicker('setDate', $("#DateFromDefault").val());
                    $("#fiscalizeSelectedBills").addClass("hidden");
                }
            }
        }).fail(function () {
            $("#issuedBillsContent").html("<div class='text-danger text-center'>" + $("#GeneralErrorMessage").val() + "!</div>");
        });
    });

    $(document).ready(function () {
        $("#documentCategory").trigger("change");
    });

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

    $("#DocType").on("change", function () {
        var docTypes = "";
        if ($("#DocType").val())
            docTypes = $("#DocType").val().join(",");

        $("#Filter_DocType").val(docTypes);
        $.fn.dataTable.reload($dataTable);
    });
}

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

function openPdfPreview(url) {
    loadPdfPanelContentPAAS($("#pdfPanel"), url, true);
}