var noteModal = null;

$(document).ajaxError(function () {
    location.reload();
});

function initializeCashTransactions() {
    var urlString = window.location.href;
    var url = new URL(urlString);
    var acKey = decodeURI(url.searchParams.get("acKey"));
    var date = decodeURI(url.searchParams.get("date"));

    date === "null" ? date = null : date = fromISOToStandardDateFormatString(date);

    var columns = [
        { data: "", name: "", className: 'dt-body-center dt-head-center', render: $.fn.dataTable.render.previewReportTreeOptions("AcKey", null, "Type") },
        { data: "AcKeyView", name: "AcKeyView", filtertype: "text", render: $.fn.dataTable.render.link("AcKey") },
        { data: "SubjectId", name: "SubjectId", filtertype: "text" },
        {
            data: "Date", name: "Date", filtertype: "text", render: function (data) {
                if (data === null) {
                    return "";
                } else {
                    return moment(data).format('DD.MM.YYYY');
                }
            }
        },
        { data: "ValueReceipt", name: "ValueReceipt", filtertype: "number", render: $.fn.dataTable.render.number('.', ',', 2), className: 'dt-body-right' },
        { data: "ValueDisbursement", name: "ValueDisbursement", filtertype: "number", render: $.fn.dataTable.render.number('.', ',', 2), className: 'dt-body-right' },
        { data: "Currency", name: "Currency", filtertype: "text" },
        { data: "DocumentNumber", name: "DocumentNumber", filtertype: "text" },
        { data: "PaymentMethod", name: "PaymentMethod", filtertype: "text" },
        {
            data: "Status", name: "Status", filtertype: "text",
            render: function (data) {
                if (data === "P") {
                    return '<span class="label label-default">' + $("#lblConfirmed").val() + '</span>';
                }
                else if (data === "N") {
                    return '<span class="label label-primary"> ' + $("#lblNotConfirmed").val() + '</span>';
                }

                return "";
            }
        }
    ];

    initializeDataTables('cashtransactions', 'Keywords', columns, acKey, null, null, true, date);

    $dataTable = $('#cashtransactions');

    $dataTable.on('xhr.dt', function (e, settings, json, xhr) {
        reloadTableTotals(json.prop);
    });
}

function initializeCashReports() {

    var columns = [
        { data: "SubjectOrPaymentMethod", name: "SubjectOrPaymentMethod", filtertype: "text" },
        { data: "Prejemek", name: "Prejemek", filtertype: "number", render: $.fn.dataTable.render.number('.', ',', 2), className: 'dt-body-right' },
        { data: "Izdatek", name: "Izdatek", filtertype: "number", render: $.fn.dataTable.render.number('.', ',', 2), className: 'dt-body-right' },
        {
            data: "Saldo", name: "Saldo", filtertype: "number", className: 'dt-body-right', render: $.fn.dataTable.render.number('.', ',', 2),
        }
    ];

    initializeDataTables('cashreport', 'Keywords', columns);

    $dataTable = $('#cashreport');

    $dataTable.on('xhr.dt', function (e, settings, json, xhr) {
        reloadReportTotals(json.prop);
    });
}

function reloadReportTotals(data) {
    $("#ReceiptSum").text(data.ReceiptSum);
    $("#ExpenditureSum").text(data.ExpenditureSum);
    $("#TotalSum").text(data.TotalSum + " " + data.Currency);
}

function reloadTableTotals(data) {
    $("#TotalItems").text(data.TotalItems);
    $("#ReceiptSum").text(data.Currency ? data.ReceiptSum + " " + data.Currency  : "-");
    $("#DisbursementSum").text(data.Currency ? data.DisbursementSum + " " + data.Currency  : "-");
    $("#TotalSum").text(data.Currency ? data.Sum + " " + data.Currency : "-");
}

function firstColumnName(paymentMethod, subject) {
    var id = $("#DDW").val();
    var subjectDDW = $("#SubjectDDW").val();

    if (id === subjectDDW) {
        $("#th-payment-or-subject").text(subject);
    }
    else {
        $("#th-payment-or-subject").text(paymentMethod);
    }
}

function addCashRegItem() {
    checkStatus(addCashRegItemCallback, 0);
}

function addCashRegItemCallback(qid) {
    var acKey = $("#AcKey").val();
    var txtName = $("#txtName");
    var txtPaymentMethod = $("#txtPaymentMethod");
    var txtLinkDocKey = $("#txtLinkDocKey");
    var txtLinkKey = $("#txtLinkKey");
    var nmAmount = $("#nmAmount");

    if (acKey.length > 0) {
        $.ajax({
            url: $("#AddItem").val(),
            type: 'POST',
            data: {
                acKey: acKey,
                name: txtName.val(),
                paymentMethodId: txtPaymentMethod.val(),
                linkDocumentKey: txtLinkDocKey.val(),
                linkKey: txtLinkKey.val(),
                amountString: nmAmount.val()
            },
            success: function () {
                reloadItems();
            }
        });
    } else {
        appendCashRegItem(txtName.val(), txtLinkDocKey.val(), txtLinkKey.val(), txtPaymentMethod.val(), nmAmount.val());

        saveCashReg();
    }
}

function removeCashItem(qId) {
    checkStatus(removeCashItemCallback, qId);
}

function removeCashItemCallback(qId) {
    $.ajax({
        url: $("#DeleteCashItem").val() + '?qId=' + qId,
        type: 'GET',
        success: function () {
            reloadItems();
        }
    });
}

function checkStatus(yesCallbackFn, qId) {

    if ($("#DocStatus").val() === 'N') {
        yesCallbackFn(qId);

        return;
    }

    $(document).ready(function () {
        $().customModal({
            destroyOnClose: true,
            title: '',
            showCloseButton: true,
            id: "modalAlreadyConfirmed",
            type: "alert",
            text: $("#LocDocumentIsAlreadyConfirmed").data('text'),
            buttons: [
                {
                    icon: 'fa fa-times',
                    text: $("#LocNo").data('text'),
                    closeOnAction: true,
                    type: 'ghost'
                },
                {
                    icon: 'fa fa-check',
                    text: $("#LocYes").data('text'),
                    closeOnAction: true,
                    action: function () {
                        yesCallbackFn(qId);
                    },
                    type: 'primary'
                }]
        });
    });
}

function reloadItems() {
    var acKey = $("#AcKey").val();
    var type = $("#CashRegDocument_Type").val();

    $.ajax({
        url: $("#CashItems").val() + '?acKey=' + acKey + '&type=' + type,
        type: 'GET',
        data: { test: 'json' },
        success: function (data) {
            $('#tblCashItemsDiv').html(data);
            reloadTotals();
            select2withAPI();
            initalizeComponents();
        }
    });
}

function initalizeComponents() {
    var divPos = $("#divCashItems").position();
    var footerPos = $("#footer-cash-transactions").position();

    var height = (footerPos.top  - divPos.top - 90) + "px";

    $("#divCashItems").css("max-height", height);
}

function reloadTotals() {
    var paid = parseFloat($("#nmPaid").val().replace(".", "").replace(",", "."));

    if (!paid) {
        paid = 0;
    }

    var total = 0;

    $(".amount").each(function () {
        let value = $(this).val();

        total += toNumber(value.replace(".", ""));
        let formatted = formatDisplay(2, toNumber(value));
        $(this).text(formatted);
    });

    $("#nmPaid").val(formatDisplay(2, paid));
    $("#nmTotal").val(formatDisplay(2, total));
    $("#nmDifference").text(formatDisplay(2, total - paid));

    reloadVisibilites();
}

function reloadVisibilites() {
    var type = $("#CashRegDocument_Type").val();
    let totalItems = $("#TotalItems").val();

    if (totalItems > 0) {
        $("#tblCashItems").removeClass("invisible");
        $("#placeholder" + type).addClass("invisible");
    }
    else {
        $("#tblCashItems").addClass("invisible");
        $("#placeholder" + type).removeClass("invisible");
    }
}

function changeView(tabId) {
    window.location.href = $(tabId).val();
}

function onEnterAddItem(e) {
    if (e.keyCode === 13) {
        e.preventDefault();
        document.getElementById("add-position").click();
    }
}

$(document).on("keydown", "form", function (event) {
    return event.key !== "Enter";
});

function onHeaderCurrencyChange() {
    let currency = $("#Currency").val();

    $("#CashRegDocument_Currency").val(currency);
}

function appendCashRegItem(txtName, txtLinkDocKey, txtLinkKey, paymentMethodId, nmAmount) {
    var contentLength = $('#tblCashItems tbody > tr').length;
    var rowId = parseInt(contentLength) + 1;
    var type = $("#CashRegDocument_Type").val();
    var select2columns = $('#receipt-select2-columns').val();

    var newRowContent = "";
    newRowContent += "<tr id='cash-item-row-" + rowId + "'>"
        + "<td><select name='Items[" + contentLength + "].Name' tags='true' class='form-control select2withAPI' data-url='/CashTransactions/GetCashReceipts?type=" + type + "'"
        + "data-column-names='" + select2columns + "'"
        + "data-bootstrap-columns='col-md-4,col-md-2,col-md-3,col-md-3' required>"
        + "<option value='" + txtName + "' selected>" + txtName + "</option>"
        + "</select></td>"
        + "<td><input class='form-control' name='Items[" + contentLength + "].LinkDocumentKey' value='" + txtLinkDocKey + "'/><input name='Items[" + contentLength + "].LinkKey' value='" + txtLinkKey + "'/></td>"
        + "<td><select name='Items[" + contentLength + "].PaymentMethodId' tags='true' class='form-control select2withAPI' data-url='/CashTransactions/GetCashReceipts?type=" + type + "'"
        + "data-column-names='" + select2columns + "'"
        + "data-bootstrap-columns='col-md-4,col-md-2,col-md-3,col-md-3' required>"
        + "<option value='" + paymentMethodId + "' selected>" + paymentMethodId + "</option>"
        + "</select></td>"
        + "<td><input class='amount form-control' name='Items[" + contentLength + "].AmountString' value='" + nmAmount + "'/></td>"
        + "<td><button type='button' onclick='removeAppendedCashItem(" + rowId + ")' class='btn btn-outline editableInput'>"
        + "<span class='far fa-trash-alt' aria-hidden='true'></span>"
        + "</button></td>"
        + "</tr>";

    $("#tblCashItems tbody").append(newRowContent);
    $("#txtName").val("");
    $("#txtLinkDocKey").val("");
    $("#txtLinkKey").val("");
    $("#nmAmount").val("");
    reloadTotals();
    select2withAPI();
}

function removeAppendedCashItem(rowId) {
    $("#cash-item-row-" + rowId).remove();
    reloadTotals();
}

function ChangeFormValue(oldValue, name) {
    var id = $('#' + name);

    if (name == "PaymentMethodId") {
        let pmKey = $("#PaymentMethodId").val();
        let pmTxt = $("#select2-PaymentMethodId-container").text();

        var pmVal = new Option(pmTxt, pmKey, false, true);
        $('#txtPaymentMethod').append(pmVal).trigger('change');
    }

    if ($("#DocStatus").val() === 'N') {
        changeDocName(name);
        return;
    }
    swal({
        title: '',
        text: $("#LocDocumentIsAlreadyConfirmed").data('text'),
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: $("#LocYes").data('text'),
        cancelButtonText: $("#LocNo").data('text'),
        closeOnConfirm: true
    }, function (isConfirm) {
        if (isConfirm) {
            changeValue(true, oldValue, id);
            changeDocName(name);
        } else {
            changeValue(false, oldValue, id);
        }
    });
}

function changeDocName(name) {
    let fullText = $('#select2-Subject-container').text();

    let commaIndex = fullText.indexOf(",");

    if (commaIndex > 1) {
        fullText = fullText.substring(0, commaIndex);
    }
    if (name === 'Subject') {
        $('#document-name').val(fullText);
    }
}

function changeValue(shouldChange, oldValue, id) {
    if (!shouldChange) {
        $(id).val(oldValue).change();
    }
}

function openInvoiceNoteModal() {
    noteModal.show($("#Note").val(), {
        onSave: function (content) {
            $("#Note").val(content)
            $("#noteIcon")
                .removeClass("btn-active")
                .addClass(content !== "" ? "btn-active" : "");
        }
    });
}

function saveInvoiceNote() {
    $("#invoiceNoteModal").modal("hide");
    $("#Note").val($("#invoiceNoteModal textarea").val());

    $("#noteIcon")
        .removeClass("btn-active")
        .addClass($("#Note").val() !== "" ? "btn-active" : "");
}

function deleteCashTransaction(acKey, type) {
    var deleteText = $("#TxtDeleteQuestion").val();
    var deleteTitle = $("#TxtConfirmation").val();
    var confirmText = $("#TxtConfirm").val();
    var cancelText = $("#TxtCancel").val();

    $(document).ready(function () {
        $().customModal({
            destroyOnClose: true,
            title: deleteTitle,
            showCloseButton: true,
            help: function () {

            },
            id: "modalDeleteCashTransaction",
            type: "question",
            text: deleteText,
            buttons: [{
                icon: 'fa fa-times',
                text: cancelText,
                closeOnAction: true,
                type: 'ghost'
            },
            {
                icon: 'fa fa-check',
                text: confirmText,
                closeOnAction: true,
                action: async function () {
                    $.ajax({
                        url: $("#DeleteCashTransaction").val() + "?acKey=" + acKey + "&type=" + type,
                        type: 'GET',
                        success: function (data) {
                            if (data.Status) {
                                window.location = $("#IndexUrl").val() + "?type=" + type;
                            }
                            else {
                                showDeletingNotPossible(data.Message);
                            }
                        }
                    });
                },
                type: 'primary'
            }]
        });
    });
}

function showDeletingNotPossible(acKey) {
    let info = $("#LinkedDocInfo").val();
    let info2 = $("#LinkedDocInfo2").val();

    let infoFullText = info + " " + acKey + "<br>" + info2;

    $(document).ready(function () {
        $().customModal({
            destroyOnClose: true,
            showCloseButton: true,
            id: "modalDeletingNotPossible",
            type: "alert",
            text: infoFullText,
            buttons: [{
                icon: 'fa fa-check',
                text: $("#TxtConfirm").val(),
                closeOnAction: true,
                type: 'primary'
            }]
        });
    });
}

function saveCashReg() {
    var title = $("#TxtConfirmation").val();
    var text = $("#TxtCashRegSaveText").val();
    var confirmText = $("#TxtConfirm").val();
    var cancelText = $("#TxtCancel").val();

    if ($("#DocStatus").val() === 'N') {
        SubmitFormByFormId('cashRegisterForm');

        return;
    }

    $(document).ready(function () {
        $().customModal({
            destroyOnClose: true,
            title: title,
            showCloseButton: true,
            id: "modalSaveCashReg",
            type: "question",
            text: text,
            buttons: [{
                icon: 'fa fa-times',
                text: cancelText,
                closeOnAction: true,
                type: 'ghost'
            },
            {
                icon: 'fa fa-check',
                text: confirmText,
                closeOnAction: true,
                action: async function () {
                    SubmitFormByFormId('cashRegisterForm');
                },
                type: 'primary'
            }]
        });
    });
}

$(document).ready(function () {
    $('#PeriodFilter').on('change', function () {
        if ($('#PeriodFilter').val() !== $("#customDateEnum").val()) {
            $('.dateFilter').addClass('hide');
        }
        else {
            $('.dateFilter').removeClass('hide');
        }

        reloadDataTable('cashtransactions');
    });

    $('#PaymentMethod').on('change', function () {
        let vals = $("#PaymentMethod").val();

        if (vals && vals.find(q => q === 0)) {
            $("#PaymentMethod").val([]);

            $('#PaymentMethod').empty().multiSelect('refresh');
        }

        reloadDataTable('cashtransactions');
    });

    $('.reload-on-change').on('change', function () {
        reloadDataTable('cashtransactions');
    });
});

var printWindow;
function print(option, printType) {
    printWindow = createPrintWindow(printWindow);
    printPAAS(printType, false, false);
}

function redirectToTransactionDocument(acKey, orderType, docType = "") {
    if (orderType == $('#OrderTypeIssuedBill').val())
        window.location = $('#IssuedBillsUrl').val() + "?acKey=" + acKey;
    else if (orderType == $('#OrderTypeCashTransaction').val()) {
        window.location = $('#CashTransactionUrl').val() + "?type=" + docType + "&acKey=" + acKey;
    }
    else if (orderType == $('#OrderTypeWholesale').val()) {
        window.location = $('#WholesaleUrl').val() + "?id=" + acKey;
    }
    else if (orderType == $('#OrderTypeTravelOrder').val()) {
        window.location = $('#TravelOrderAllDataUrl').val() + "?acKey=" + acKey;
    }
}