var selectedBank = -1;

var localStorageMessageKey = "PayOrders_Message";
var localStorageMessageLastKey = "PayOrders_MessageLast";

function clearMessages() {
    localStorage.setItem(localStorageMessageKey, null);
    localStorage.setItem(localStorageMessageLastKey, null);
}

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

function openPayOrderIrisModal() {
    $('#pay-orders-iris').modal('show');
}

function initializeBankAccounts() {
    var columns = [
        { data: "BankNo", name: "BankNo", filtertype: "number" },
        {
            data: "Bank",
            name: "Bank",
            filtertype: "text",
            render: function (data) {
                if (data === null || data === "") {
                    return "";
                } else {
                    return '<a href="Subjects/Edit/?id=' + data + '">' + data + '</a>';
                }
            }
        },
        { data: "Trn", name: "Trn", filtertype: "text" },
        { data: "Currency", name: "Currency", filtertype: "number" },
        { data: "InitialState", name: "InitialState", filtertype: "number", render: $.fn.dataTable.render.number('.', ',', 2), className: 'dt-body-right' },
        { data: "Payment", name: "Payment", filtertype: "number", render: $.fn.dataTable.render.number('.', ',', 2), className: 'dt-body-right' },
        { data: "FinalState", name: "FinalState", filtertype: "number", render: $.fn.dataTable.render.number('.', ',', 2), className: 'dt-body-right' },
        { data: "Sent", name: "Sent", filtertype: "number", render: $.fn.dataTable.render.number('.', ',', 2), className: 'dt-body-right' }
    ];

    initializeDataTables('bankaccounts', '', columns);
}

$(".bank-data-row").click(function () {
    $(".bank-data-row").not(this).removeClass("bank-selected");
    $(this).addClass("bank-selected");

    selectedBank = $(this).data("bank");

    if (!$(this).hasClass('bank-selected')) {
        selectedBank = -1;
    }

    addClassToPayOrders();
    refreshExportState();
});

function initializePayOrders() {
    var columns = [
        {
            data: function (data) {
                return data;
            },
            orderable: false,
            className: 'dt-body-center',
            render: function (data) { return '<input name="PayOrderStatus" value="' + data.AcKey + '" data-status="' + data.Status + '" class="checkForStatus" onclick=CheckBoxClicked("' + data.AcKey + '") type="checkbox"/>'; }
        },
        {
            data: "AcKeyView",
            name: "AcKeyView",
            className: "ackey",
            orderable: true,
            filtertype: "text",
            render: function (data, type, row, meta) {
                return '<a id=Lnk' + row["AcKey"] + ' onclick = "openPayOrderPanel(&quot;' + row["AcKey"] + '&quot;)" > ' + data + '</a > ';
            }
        },
        {
            data: function (data) {
                return data;
            },
            render: function (data) {
                if (data.Status === "O" || data.Status === "R") {
                    return data.BankName;
                }
                else {
                    let bankName = data.BankName ? data.BankName : "";
                    return '<form id="form-' + data.AcKey + '" action="' + $("#ChangeBank").val() + '" method="post"> \
                    <input name="acKey" value="' + data.AcKey + '" type="hidden" /> \
                    <input name="status" value="' + data.Status + '" type="hidden" /> \
                     <input name="docType" value="' + data.DocType + '" type="hidden" /> \
                    <select onchange="this.form.submit()" name="bank" class="select2withAPI form-select2 table-font" data-url="'+ $("#GetBankAccountsAsync").val() + '" data-dtp="Write" data-dtp-state="disabled"> \
                    <option value="' + data.BankNo + '" selected>' + bankName + '</option>"/> \
                 </form>';
                }
            }
        },
        {
            data: "Date", name: "Date",
            filtertype: "dateTime",
            className: 'dt-body-left',
            render: function (data) {
                if (data === null) {
                    return "";
                } else {
                    return moment(data).format('DD.MM.YYYY');
                }
            }
        },
        {
            data: "Amount", name: "Amount", filtertype: "number", render: $.fn.dataTable.render.number('.', ',', $("#DefaultDecimalPlacesPrice").val()), className: 'dt-body-right'
        },
        {
            data: "DateDue", name: "DateDue", filtertype: "dateTime", render: function (data) {
                if (data === null) {
                    return "";
                } else {
                    return moment(data).format('DD.MM.YYYY');
                }
            }
        },
        {
            data: "Subject",
            name: "Subject",
            className: 'dt-body-left',
            filtertype: "text",
            render: function (data) {
                if (data === null || data === "") {
                    return "";
                } else {
                    return '<a href="Subjects/Edit/?id=' + data + '">' + data + '</a>';
                }
            }
        }
        ,
        {
            data: "AcKeyLinkView",
            className: 'dt-body-left dt-po-left',
            name: "AcKeyLinkView",
            filtertype: "text",
            render: $.fn.dataTable.render.link("LnkKey")
        },
        {
            data: "PayPurpose",
            className: 'dt-body-left dt-po-left',
            name: "PayPurpose",
            filtertype: "text"
        }
    ];

    initializeDataTables('payorders', 'Keywords', columns, null, 1);

    $dataTable = $('#payorders');

    $dataTable.on('xhr.dt', function (e, settings, json, xhr) {
        let message = localStorage.getItem(localStorageMessageKey);
        let lastMessage = localStorage.getItem(localStorageMessageLastKey);

        reloadTotals(json.prop);

        initializeDataTableHeight();

        let poAcKey = $("#OpenAcKeyPanel").val();

        if (poAcKey) {
            refreshPayOrderRow(poAcKey);
        }

        if (message && message.length > 1 && message != lastMessage) {
            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                title: $("#TxtInfo").val(),
                text: message,
                type: "success",
                buttons: [{
                    text: $("#TxtConfirm").val(),
                    icon: 'fa fa-check',
                    closeOnAction: true,
                    type: 'primary'
                }]
            });

            clearMessages();
        }
    });

    setDataTypeVisibility();
}

var heightInitialized = false;
function initializeDataTableHeight() {

    if (heightInitialized) {
        return;
    }
    heightInitialized = true;

    var rectTop = document.getElementById("payorders").getBoundingClientRect();
    var rectBottom = document.getElementById("payOrdersFooter").getBoundingClientRect();

    let offset = 0;
    let dtHeight = (rectBottom.top - rectTop.top - offset) + "px"; 

    $(".dataTables_scrollBody").css("height", dtHeight);
    $(".dataTables_scrollBody").css("min-height", dtHeight);
}

function setDataTypeVisibility() {
    let status = $("#status").val();
    let statusErr = $("#StatusError").val();

    if (status == statusErr) {
        $("#payOrdersData").hide();
        $("#payOrdersErrors").show();
    }
    else {
        $("#payOrdersData").show();
        $("#payOrdersErrors").hide();
    }
}

function setSelectedStatus(status) {
    $("#status").val(status);

    $(".side-panel").removeClass("open");

    clearMessages();

    setDataTypeVisibility();
    clearSelectedBoxes();
    refreshButtons(status);
    refreshBadgeClasses(status);

    $('#payorders').DataTable().ajax.reload();
    setTimeout(function () { addClassToPayOrders(); }, 600);
}

function refreshButtons(status) {
    var returnToPreparation = $("#ButtonNameReturnToPreparation").val();
    var returnToPayment = $("#ButtonNameReturnToPayment").val();
    var returnToShipped = $("#ButtonNameReturnToShipped").val();

    if (status === 'Z') {
        $("#exportXmlButton").hide();
        $(".btnBack").hide();
        $("#datePicker").hide();

        $("#createButton").show();
        $(".btnNext").show();
        $("#deleteButton").show();
    } else if (status === "P") {
        $("#createButton").hide();
        $("#deleteButton").hide();

        $(".btnNext").show();
        $(".btnBack").show();
        $("#exportXmlButton").show();
        $("#datePicker").show();
        $("#backButton > span").text(returnToPreparation);
    }
    else if (status === "O") {
        $("#exportXmlButton").hide();
        $("#createButton").hide();
        $("#datePicker").hide();
        $("#deleteButton").hide();

        $(".btnNext").show();
        $(".btnBack").show();
        $("#backButton > span").text(returnToPayment);
    } else if (status === "R") {
        $("#exportXmlButton").hide();
        $("#createButton").hide();
        $(".btnNext").hide();
        $("#datePicker").hide();
        $("#deleteButton").hide();

        $(".btnBack").show();
        $("#backButton > span").text(returnToShipped);
    }
}

$('.changeStatus').on('click', function () {

    var selectedKeys = [];
    var selectedKeyViews = [];
    $('.checkForStatus:checkbox:checked').each(function () {
        var Id = $(this).val();
        var text = $("#Lnk" + Id).text().trim();
        selectedKeys.push(Id);
        selectedKeyViews.push(text);
    });

    var status = $('#status').val();
    var isBackStatus = $(this).attr('data-back-status');
    var incompletePayOrdersLabel = $("#PacOrdersIncomplete").val();

    let statusChangeData = status + selectedKeys;
    let lastChange = localStorage.getItem("LastPoStatus");

    if (lastChange == statusChangeData) {
        return;
    }

    localStorage.setItem("LastPoStatus", statusChangeData);

    $.ajax({
        cache: false,
        type: "post",
        url: $("#ChangeStatus").val(),
        data: {
            keys: selectedKeys,
            status: status,
            isBackStatus: isBackStatus
        },
        success: function (result) {

            if (!result.Status) {

                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    type: "error",
                    text: incompletePayOrdersLabel +  ":<br>" + result.Message,
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: $("#TxtConfirm").val(),
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });

                return;
            }

            localStorage.setItem(localStorageMessageKey, $("#TxtPayOrderStatusChangedInfo").val() + ':<br><br>' + selectedKeyViews.toString());

            $('#payorders').DataTable().ajax.reload();

            $(".side-panel").removeClass("open");
            reloadBankAccounts();
            selectedKeys = [];
            selectedKeyViews = [];
            changeButtons(selectedKeys);
        },
        error: function (error) {
            swal($("#GeneralErrorMessage").val() + error);
        }
    });
});

function reloadBankAccounts() {
    $.ajax({
        url: $("#BankAccountsIndex").val(),
        type: 'GET',
        data: { test: 'json' },
        success: function (data) {
            $('#PayOrdersBankAccountsList').html(data);
        }
    });
}

function addClassToPayOrders() {
    var table = $('#payorders').DataTable();

    table.rows().every(function (rowIdx, tableLoop, rowLoop) {
        var rowData = this.data();
        if (rowData.BankNo !== undefined) {
            if (rowData.BankNo === selectedBank) {
                $(this.node()).addClass('bank-selected');
            }
            else {
                $(this.node()).removeClass('bank-selected');
            }
        }
    });
}

function focusOnOrderFromMove() {
    $('#payorders td.ackey a').each(function () {
        var cellText = $(this).html();
        var acKeyFromMove = $('#AcKeyFromMove').val();

        if (cellText === acKeyFromMove) {
            $(this).closest('tr').addClass("selected");
        }
    });
}

function exportXml() {
    var date = $("#DateFrom").val();

    window.open($("#ExportXml").val() + '?selectedBank=' + selectedBank + '&date=' + date, "_self");

    //setSelectedStatus('P');
}

var selectedKeys = [];
function CheckBoxClicked(acKey) {
    if (!selectedKeys.includes(acKey)) {
        selectedKeys.push(acKey);
    }
    else {
        let index = selectedKeys.indexOf(acKey);
        selectedKeys.splice(index, 1);
    }

    changeButtons(selectedKeys);
}

function clearSelectedBoxes() {
    selectedKeys = [];
    changeButtons(selectedKeys);
}

function changeButtons(selectedKeys) {
    if (selectedKeys.length > 0) {
        enablePnButton('deleteButton');
        enablePnButton('forwardButton');
        enablePnButton('backButton');
    }
    else {
        disablePnButton('deleteButton');
        disablePnButton('forwardButton');
        disablePnButton('backButton');
    }
}

function enablePnButton(buttonId) {
    $('#' + buttonId).removeClass('disabled');
    $('#' + buttonId).addClass('btn-success');
    $('#' + buttonId).removeClass('btn-outline');
}

function disablePnButton(buttonId) {
    $('#' + buttonId).addClass('disabled');
    $('#' + buttonId).removeClass('btn-success');
    $('#' + buttonId).addClass('btn-outline');
}

function deletePayOrder() {
    let url = $("#DeletePN").val();
    performAction(url);
}

function performAction(url) {
    $.ajax({
        cache: false,
        type: "post",
        url: url,
        data: {
            acKeys: selectedKeys
        },
        success: function (result) {
            location.reload();
        },
        error: function (error) {
            swal($("#GeneralErrorMessage").val() + error);
        }
    });
}

function reloadTotals(data) {
    $("#in-progress-count").empty();
    $("#on-payment-count").empty();
    $("#sent-count").empty();
    $("#realized-count").empty();
    $(".status-amount").empty();
    $(".status-count").empty();

    $("#in-progress-count").append(data.InProgress);
    $("#on-payment-count").append(data.OnPayment);
    $("#sent-count").append(data.Sent);
    $("#realized-count").append(data.Realized);
    $(".status-amount").append(data.StatusTotalAmountString);
    $(".status-count").append(data.StatusTotalCount);
}

function refreshBadgeClasses(status) {
    $("#in-progress-count").removeClass("badge-primary");
    $("#on-payment-count").removeClass("badge-primary");
    $("#sent-count").removeClass("badge-primary");
    $("#realized-count").removeClass("badge-primary");

    if (status == 'Z') $("#in-progress-count").addClass("badge-primary");
    if (status == 'P') $("#on-payment-count").addClass("badge-primary");
    if (status == 'O') $("#sent-count").addClass("badge-primary");
    if (status == 'R') $("#realized-count").addClass("badge-primary");
}

function refreshExportState() {
    if (selectedBank > 0) {
        $('#exportXmlButton').removeClass('disabled');
    } else {
        $('#exportXmlButton').addClass('disabled');
    }
}

function refreshPayOrderRow(acKey) {
    if (!acKey) {
        return;
    }

    setTimeout(() => {
        $('.bank-selected').removeClass('bank-selected');
        $("#Lnk" + acKey).parent().parent().addClass('bank-selected');
    }, 100);
}

$('#btnSubmit').on('click', function () {
    $("#submitPayOrder").click();
});

$(document).ready(function () {
    var status = $("#status").val();
    refreshButtons(status);

    $('[id^="vl-"]').css("display", "none");

    selectedBank = 1;
    $(".bank-data-row:first").addClass("bank-selected");

    refreshBadgeClasses(status);
    refreshExportState();

    $('#SubjectId').on('change', function (e) {

        $('#SubjAcct').val(0);
        $('#SubjAcct').text('');

        $.ajax({
            url: $("#SubjectInfo").val(),
            dataType: 'json',
            data: { subjectId: this.value },
            method: "GET",
            success: function (data) {
                var subjAcct = new Option(data.SubjAcctText, data.SubjAcct, false, false);
                $('#SubjAcct').append(subjAcct).trigger('change');

                var refCred = new Option(data.ReferenceCred, data.ReferenceCred, false, false);
                $('#ReferenceCred').append(refCred).trigger('change');

                setTimeout(function () { $("#select2-ReferenceCred-container").text(data.ReferenceCred); }, 100);

                $("#ReferenceCred").val(data.ReferenceCred);

                var acct1 = new Option(data.CreditorAcct1, data.CreditorAcct1, false, false);
                $('#CreditorAcct1').append(acct1).trigger('change');

                $('#Creditor3').val(data.Creditor2 + ', ' + data.Creditor3);

                if (!data.SubjAcct) {
                    let subjectId = $("#SubjectId").val();

                    $("#poIrisSubj1").text(subjectId);
                    $("#poIrisSubj2").text(subjectId);

                    openPayOrderIrisModal();
                }
            },
            fail: function (error) {
                swal(error);
            }
        });
    });

    $('#SubjAcct').on('change', function (e) {

        return;

        $.ajax({
            url: $("#BankInfo").val(),
            data: { subjectId: $("#SubjectId").val(), bankNo: this.value },
            dataType: 'json',
            method: "GET",
            success: function (data) {
                var acct2 = new Option(data.BankAccountNo2, data.Acct2, false, false);
                $('#CreditorAcct2').append(acct2).trigger('change');

                var acct3 = new Option(data.BankAccountNo3, data.Acct3, false, false);
                $('#CreditorAcct3').append(acct3).trigger('change');

                $('#CreditorAcct1').val(data.BankAccountNo1);
                $('#CreditorIbanPrefix').val(data.IbanPrefix);
                $('#CreditorSwiftCode').val(data.SwiftCode);
            },
            fail: function (error) {
                alert(error);
            }
        });
    });

    $('#CreditorAcct2').on('change', function (e) {
        let acct = $("#CreditorAcct2").val();
        setTimeout(function () { $("#select2-CreditorAcct2-container").text(acct); }, 100);
    });

    $('#DebtorAcct2').on('change', function (e) {
        let acct = $("#DebtorAcct2").val();
        setTimeout(function () { $("#select2-DebtorAcct2-container").text(acct); }, 100);
    });

    $('#DebtorAcct1').on('change', function (e) {
        $('#BankNo').val(this.value);

        return;

        $.ajax({
            url: $("#OurBankInfo").val() + '?bankNo=' + this.value + '&subjectId=' + $("#Debitor1").val(),
            dataType: 'json',
            method: "GET",
            success: function (data) {
                $('#DebtorAcct1').val(data.BankAccountNo1);
                $('#DebtorAcct2').val(data.BankAccountNo2);
                $('#DebtorAcct3').val(data.BankAccountNo3);
                $('#DebtorIbanPrefix').val(data.IbanPrefix);
                $('#DebtorSwiftCode').val(data.SwiftCode);
            },
            fail: function (error) {
                alert(error);
            }
        });

    });

    $('#Code1').on('change', function (e) {
        setSelect2Text('Code1', this.value.toString());
    });

    $('#Code2').on('change', function (e) {
        setSelect2Text('Code2', this.value.toString());
    });

    $('#dataTables_scrollBody').resize(function () {
        console.log("resize");
    });

    $('#dataTables_scrollBody').on('event', function () {
        console.log("log");
    });

    function setSelect2Text(select2Id, text) {
        setTimeout(function () { $("#select2-" + select2Id + "-container").text(text); }, 100);
    }

    refreshPayOrderRow($("#AcKey").val());
});