var $identSerialNoDataTable;
var $identFreeSerialNoDataTable;
var freeSerialNumbersList = [];
var selectedFreeSerialNumbers = [];
var globalIssuedSerialNumbersLocalization;
var globalIssuedSerialNumbersUrls;
var serialNoWarehouseId;

function initializeIssuedSerialNumbers(localization, urls, warehouseId = "WarehouseId") {
    globalIssuedSerialNumbersLocalization = localization;
    globalIssuedSerialNumbersUrls = urls;
    serialNoWarehouseId = warehouseId;

    $('#identSerialNoIssueModal .modal-dialog').draggable();

    $('.partialIdentSerialNoIssueModalContent').resizable({
        alsoResize: ".partialIdentSerialNoIssueModalBody",
        minHeight: 500
    });

    $('#identSerialNoIssueModal').on('show.bs.modal', function () {
        $(this).find('.partialIdentSerialNoIssueModalBody').css({
            'max-height': '95%',
            'min-height': '50%',
            'min-width': '100%'
        });
    });

    $(".partialIdentSerialNoIssueModalContent").resize(function () {
        if ($(".partialIdentSerialNoIssueModalContent").height() > 100) {
            $(".partialIdentSerialNoIssueModalBody").css("height", $(".partialIdentSerialNoIssueModalContent").height() - 80);
            $(".list-free-serials").css("max-height", $(".partialIdentSerialNoIssueModalContent").height() - 320);
        }
        jsRenderDataTable("identSerialNoGrid", "partialIdentSerialNoIssueModalBody", 300, true);
        jsRenderDataTable("identFreeSerialNoGrid", "partialIdentSerialNoIssueModalBody", 300, true);
    });

    displayModalByTypeIssue();

    $('#identSerialNoIssueModal').on('hidden.bs.modal', async function (e) {
        if ($("#IdentSerialNoType").val() === "P") {
            await deleteUnusedItemSerials();
        }

        var anNo = toNumber($("#IdentAnNo").val());
        var serialNoQtySum = getSerialNoQtySum();

        $("#quantity-" + anNo).val(toNumber(serialNoQtySum));
        $("#qtyOld-" + anNo).val(toNumber(serialNoQtySum));
        formatNumberInput($("#quantity-" + anNo));
        changeIdentData(anNo);
        save();
    });

    var typingTimer;
    var doneTypingInterval = 600;
    $('#identFreeSerialNo').off('keyup');
    $('#identFreeSerialNo').on('keyup', function () {
        clearTimeout(typingTimer);
        typingTimer = setTimeout(function () { getFreeSerialNumbers(); }, doneTypingInterval);
    });
}

function checkIdentSerialNoIssue(anNo, type, serialNo = null, quantity = null, open = null) {
    serialNo = serialNo ? serialNo : $("#serialNo-" + anNo).val();
    quantity = quantity ? toNumber(quantity) : toNumber($("#quantity-" + anNo).val());

    if ($("#DocTypeSelect option:selected").attr("data-acEnterSn" + serialNo) === "F")
        return;

    $("#IdentSerialNoType").val(serialNo);
    $("#InvoiceType").val(type);
    $("#IdentAnNo").val(anNo);
    $("#IdentSerialDateDue").val($("#dateDue-" + anNo).val());

    if ((serialNo !== "N" && (quantity > 0 || toNumber($("#qtyOld-" + anNo).val()) > 0)) && open !== "true" && $("#DocTypeSelect option:selected").attr("data-autoInvoSerialNo") === "True")
        serialNoAutoEdition(anNo);
    else if ((serialNo !== "N" && quantity > 0) || open === "true") {
        openIdentSerialNoIssueModal(toNumber(anNo));
    }
}

function displayModalByTypeIssue() {
    if ($("#IdentSerialNoType").val() === "O" || $("#IdentSerialNoType").val() === "P") {
        $("#multiplySerialsContainer").addClass("hidden");
    } else {
        $("#multiplySerialsContainer").removeClass("hidden");
    }

    if ($("#IdentSerialNoType").val() === "S" || $("#IdentSerialNoType").val() === "E") {
        if ($("#IdentSerialDateDue").val() === "true") {
            $(".serialNumberCol").attr('width', "60%");
            $(".dateDue-col").show();
        } else {
            $(".serialNumberCol").attr('width', "76%");
            $(".dateDue-col").hide();
        }
        $(".qty-col").hide();
    } else {
        if ($("#IdentSerialDateDue").val() === "true") {
            $(".serialNumberCol").attr('width', "60%");
            $(".dateDue-col").show();
        } else {
            $(".serialNumberCol").attr('width', "80%");
            $(".dateDue-col").hide();
        }
        $(".qty-col").show();
    }
}

async function openIdentSerialNoIssueModal(anNo) {
    displayModalByTypeIssue();
    $("#identSerialNoIdent").val($("#id-" + anNo).val());
    $("#identSerialNoReqQuantity").val($("#quantity-" + anNo).val());
    $("#identSerialNoPrefix").val("");
    $("#identSerialNoSerial").val(0);
    $("#identSerialNoQty").val(0);
    await getFreeSerialNumbers();

    if ($("#IdentSerialNoType").val() === "P")
        await moveSerialAddSales(anNo);
    else
        await getSerialNumbersIssueForIdent(anNo);

    $("#identSerialNoIssueModal").modal("show");
    jsRenderDataTable("identSerialNoGrid", "partialIdentSerialNoIssueModalBody", 300, true);
    jsRenderDataTable("identFreeSerialNoGrid", "partialIdentSerialNoIssueModalBody", 300, true);
}

async function moveSerialAddSales(anNo) {
    var data = {
        AcKey: $("#AcKey").val(),
        AnNo: $("#IdentAnNo").val(),
        Ident: $("#identSerialNoIdent").val(),
        Type: "K",
        Column: ""
    };

    await fetch(globalIssuedSerialNumbersUrls.moveSerialNoAddSalesUrl, {
        method: "POST",
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data)
    }).then((response) => response.json()
    ).then(async (response) => {
        getSerialNumbersIssueForIdent(anNo);
    });
}

async function getSerialNumbersIssueForIdent(anNo) {
    await fetch(globalIssuedSerialNumbersUrls.getByAcKeyAndAnNoUrl + "?acKey=" + $("#AcKey").val() + "&anNo=" + anNo, {
        method: "GET",
        headers: { 'Content-Type': 'application/json' }
    }).then((response) => response.json()
    ).then(async (data) => {
        $('#identSerialNoGrid tbody tr').remove();
        var qty = 0;
        if (data && data.length) {
            for (var i = 0; i < data.length; i++) {
                addSerialNumberIssueRow(data[i].SerialNo, data[i].Qty, null, data[i].DateDue);
                qty = qty + data[i].Qty;
            }
        }

        $("#identSerialNoQuantity").val(qty);
        $("#identSerialNoDifference").val(toNumber($("#identSerialNoReqQuantity").val()) - toNumber($("#identSerialNoQuantity").val()));
        formatNumberInput($("#identSerialNoQuantity"));
        formatNumberInput($("#identSerialNoDifference"));
    });
}

function addSerialNumberIssueRow(serialNo, qty, oldQty = null, dateDue) {
    var id = serialNo.replace(/ /g, '');
    var isQtyHidden = $("#IdentSerialNoType").val() === "S" || $("#IdentSerialNoType").val() === "E" ? true : false;
    var isDateDueHidden = $("#IdentSerialDateDue").val() === "true" ? false : true;

    $('#identSerialNoGrid > tbody:last-child').append(
        '<tr id="tr-serial-' + id + '" class="sortable-row">' +
        '<td class="serial-numbers-td"><input class="form-control border-bottom-none serialNoCode" value="' + serialNo + '" disabled /></td>' +
        '<td class="serial-numbers-td qty-col ' + (isQtyHidden ? "hidden" : "") + '"><input class="form-control border-bottom-none serialNoQty" id="serialNoQty-' + id + '" value="' + qty + '" onchange="saveSerialNoIssue(\'' + serialNo + '\')" />' +
        '<input id="savedSerialNoQty-' + id + '" value="' + (oldQty !== null ? oldQty : qty) + '" hidden/></td>' +
        '<td class="serial-numbers-td dateDue-col ' + (isDateDueHidden ? "hidden" : "") + '"><input class="form-control border-bottom-none datepicker serialNoDateDue" id="serialNoDateDue-' + id + '" value="' + dateDue + '" onchange="saveSerialNoIssue(\'' + serialNo + '\')" />' +
        '<input id="savedSerialNoDateDue-' + id + '" class="datepicker" value="' + dateDue + '" hidden/></td>' +
        '<td class="td-action"><p class="text-center"><span onclick="deleteSerialNoIssue(\'' + serialNo + '\')" style="margin-top: 12px" class="far fa-trash-alt cursor-pointer" aria-hidden="true"></span></p></td>' +
        '</tr>'
    );

    $('#serialNoDateDue-' + id).datepicker()
        .on('click', function (e) {
            $(this).select();
        }).on('changeDate', function () {
            $(this).datepicker('hide');
        });
}

async function saveSerialNoIssue(serialNo = null) {
    var $serialCodes = $(".serialNoCode");
    if ($serialCodes && $serialCodes.length) {
        for (var i = 0; i < $serialCodes.length; i++) {
            if ($serialCodes[i].value === $("#input-serial-no").val()) {
                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    type: "error",
                    text: globalIssuedSerialNumbersLocalization.errorSaving,
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: globalIssuedSerialNumbersLocalization.confirm,
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });

                return;
            }
        }
    }

    var serialNoQtySum = getSerialNoQtySum();
    if (!serialNo)
        serialNoQtySum = serialNoQtySum + toNumber($("#input-serial-quantity").val());

    serialNo = serialNo ? serialNo : $("#input-serial-no").val();
    var id = serialNo.replace(/ /g, '');
    serialNoDateDue = $("#serialNoDateDue-" + id).val() ? $("#serialNoDateDue-" + id).datepicker("getDate") : $("#input-serial-dateDue").datepicker("getDate");

    var data = {
        AcKey: $("#AcKey").val(),
        AnNo: $("#IdentAnNo").val(),
        Issuer: $("#" + serialNoWarehouseId).val(),
        Ident: $("#identSerialNoIdent").val(),
        SerialNo: serialNo,
        Quantity: serialNoQtySum,
        QuantityOld: $("#savedSerialNoQty-" + id).val() ? $("#savedSerialNoQty-" + id).val() : 0,
        QuantityNew: $("#serialNoQty-" + id).val() ? $("#serialNoQty-" + id).val() : $("#input-serial-quantity").val(),
        DateDueNew: $("#IdentSerialDateDue").val() === "true" ? serialNoDateDue : null,
        DateDue: $("#IdentSerialDateDue").val() === "true" && $("#savedSerialNoDateDue-" + id).val() ? $("#savedSerialNoDateDue-" + id).val() : null,
        Type: "K",
        SNWOType: "",
        Package: "",
        PackQty: 0,
        InvoiceType: $("#InvoiceType").val()
    };

    if (toNumber(serialNoQtySum) === toNumber($("#identSerialNoReqQuantity").val())) {
        $().customModal({
            destroyOnClose: true,
            showCloseButton: true,
            type: "success",
            text: globalIssuedSerialNumbersLocalization.serialNumberQuantityIsReached,
            buttons: [
                {
                    icon: 'fa fa-check',
                    text: globalIssuedSerialNumbersLocalization.confirm,
                    closeOnAction: true,
                    type: 'primary'
                }
            ]
        });
    }

    await fetch(globalIssuedSerialNumbersUrls.moveUpdateSerialNoUrl, {
        method: "POST",
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data)
    }).then((response) => response.json()
    ).then(async (response) => {
        if (!response || response === false) {
            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                type: "alert",
                text: globalIssuedSerialNumbersLocalization.errorSaving,
                buttons: [
                    {
                        icon: 'fa fa-check',
                        text: globalIssuedSerialNumbersLocalization.confirm,
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });
        } else {
            if ($("#input-serial-no").val()) {
                addSerialNumberIssueRow($("#input-serial-no").val(), $("#input-serial-quantity").val());
                $("#input-serial-no").val("");
                $("#input-serial-quantity").val(1);
            } else {
                $("#savedSerialNoQty-" + serialNo).val(data.QuantityNew);
                $("#savedSerialNoDateDue-" + serialNo).val(data.DateDueNew);
                $("#identSerialNoQuantity").val(0);
                addReqQuantity(getSerialNoQtySum());
            }

            await getFreeSerialNumbers();
        }
    });
}

function onMultiplySerialNumberIssue() {
    var serialNoQtySum = getSerialNoQtySum();
    if ((serialNoQtySum + toNumber($("#identSerialNoQty").val())) > toNumber($("#identSerialNoReqQuantity").val())) {
        $().customModal({
            title: "",
            destroyOnClose: true,
            showCloseButton: true,
            type: "question",
            text: globalIssuedSerialNumbersLocalization.numberOfSerialNumbersIsGreaterThanOnDocument,
            buttons: [
                {
                    icon: 'fa fa-times',
                    text: globalIssuedSerialNumbersLocalization.cancel,
                    closeOnAction: true,
                    type: 'ghost'
                },
                {
                    icon: 'fa fa-check',
                    text: globalIssuedSerialNumbersLocalization.confirm,
                    action: async function () {
                        multiplySerialNumbersIssue();
                    },
                    closeOnAction: true,
                    type: 'primary'
                }
            ]
        });
    } else
        multiplySerialNumbersIssue();
}

async function multiplySerialNumbersIssue() {
    if ($("#identSerialNoQty").val() > 0) {
        $("#multiplySerialsBtn").find("i").addClass("fa-spinner fa-spin");
        $("#multiplySerialsBtn").prop("disabled", true);

        var serialNoQtySum = getSerialNoQtySum();
        var serial = $("#identSerialNoSerial").val();
        var serialLength = serial.length;

        for (var i = 0; i < $("#identSerialNoQty").val(); i++) {
            var freeSerialExists = freeSerialNumbersList.some(function (item) {
                return item.SerialNo === ($("#identSerialNoPrefix").val() + serial);
            });

            if ($("#InvoiceType").val() === "M" && !freeSerialExists) {
                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    type: "alert",
                    text: stringFormat(globalIssuedSerialNumbersLocalization.selectedSerialNumberDoesNotExistInWarehouse, $("#identSerialNoPrefix").val() + serial),
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: globalIssuedSerialNumbersLocalization.confirm,
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });

                $("#multiplySerialsBtn").find("i").removeClass("fa-spinner fa-spin");
                $("#multiplySerialsBtn").prop("disabled", false);
                return;
            }

            var data = {
                AcKey: $("#AcKey").val(),
                AnNo: $("#IdentAnNo").val(),
                Issuer: $("#" + serialNoWarehouseId).val(),
                Ident: $("#identSerialNoIdent").val(),
                SerialNo: $("#identSerialNoPrefix").val() + serial,
                Quantity: serialNoQtySum,
                QuantityOld: 0,
                QuantityNew: $("#IdentSerialNoType").val() === "S" || $("#IdentSerialNoType").val() === "E" ? 1 : 0,
                Type: "K",
                SNWOType: "",
                Package: "",
                PackQty: 0,
                InvoiceType: $("#InvoiceType").val()
            };

            await fetch(globalIssuedSerialNumbersUrls.serialNoUpdUrl, {
                method: "POST",
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(data)
            }).then((response) => response.json()
            ).then(async (response) => {
                if (!response || response === false) {
                    $().customModal({
                        destroyOnClose: true,
                        showCloseButton: true,
                        type: "alert",
                        text: globalIssuedSerialNumbersLocalization.errorSaving,
                        buttons: [
                            {
                                icon: 'fa fa-check',
                                text: globalIssuedSerialNumbersLocalization.confirm,
                                closeOnAction: true,
                                type: 'primary'
                            }
                        ]
                    });
                } else {
                    addSerialNumberIssueRow($("#identSerialNoPrefix").val() + serial, data.QuantityNew);
                    await getFreeSerialNumbers();

                    if (data.QuantityNew > 0)
                        addReqQuantity(data.QuantityNew);
                }
            });

            serial = pad(toNumber(serial) + 1, serialLength);
        }

        $("#multiplySerialsBtn").find("i").removeClass("fa-spinner fa-spin");
        $("#multiplySerialsBtn").prop("disabled", false);
    }
}

async function deleteSerialNoIssue(serialNo) {
    var data = {
        AcKey: $("#AcKey").val(),
        AnNo: $("#IdentAnNo").val(),
        SerialNo: serialNo,
        Receiver: $("#" + serialNoWarehouseId).val(),
        Ident: $("#identSerialNoIdent").val(),
        Quantity: toNumber($("#serialNoQty-" + serialNo).val()),
        QuantityOld: 0,
        QuantityNew: toNumber($("#serialNoQty-" + serialNo).val()),
        Date: $("#Date").datepicker("getDate"),
        InvoiceType: $("#InvoiceType").val()
    };

    await fetch(globalIssuedSerialNumbersUrls.deleteIssuedByAcKeyAndSerialNo, {
        method: "POST",
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data)
    }).then((response) => response.json()
    ).then((data) => {
        if (data && data === true) {
            addReqQuantity(toNumber($("#serialNoQty-" + serialNo).val()), true);
            $("#tr-serial-" + serialNo).remove();

            getFreeSerialNumbers();
        }
    });
}

async function deleteAll() {
    var data = {
        AcKey: $("#AcKey").val(),
        AnNo: $("#IdentAnNo").val(),
        Receiver: $("#" + serialNoWarehouseId).val(),
        Ident: $("#identSerialNoIdent").val(),
        Date: $("#Date").datepicker("getDate"),
        InvoiceType: $("#InvoiceType").val()
    };

    await fetch(globalIssuedSerialNumbersUrls.deleteAllIssuedByAcKey, {
        method: "POST",
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data)
    }).then((response) => response.json()
    ).then((data) => {
        if (data && data === true) {
            $('#identSerialNoGrid tbody tr').remove();
            $("#identSerialNoQuantity").val(0);
            addReqQuantity(0);

            getFreeSerialNumbers();
        }
    });
}

async function deleteUnusedItemSerials() {
    await fetch(globalIssuedSerialNumbersUrls.deleteUnusedItemSerialsUrl + "?acKey=" + $("#AcKey").val() + "&anNo=" + $("#IdentAnNo").val() + "&type=" + "K" + "&invoiceType=" + $("#InvoiceType").val(), {
        method: "GET",
        headers: { 'Content-Type': 'application/json' }
    }).then((response) => response.json()
    ).then(async (data) => {
        if (data && data === true) {
            var items = $(".serialNoQty");
            for (var i = 0; i < items.length; i++) {
                if (items[i].value === 0) {
                    items[i].closest("tr").remove();
                }
            }
        }
    });
}

function addReqQuantity(qty, isRemove = null) {
    if (isRemove)
        $("#identSerialNoQuantity").val(toNumber($("#identSerialNoQuantity").val()) - qty);
    else
        $("#identSerialNoQuantity").val(toNumber($("#identSerialNoQuantity").val()) + qty);

    $("#identSerialNoDifference").val(toNumber($("#identSerialNoReqQuantity").val()) - toNumber($("#identSerialNoQuantity").val()));
    formatNumberInput($("#identSerialNoReqQuantity"));
    formatNumberInput($("#identSerialNoQuantity"));
    formatNumberInput($("#identSerialNoDifference"));
}

function getSerialNoQtySum() {
    var serialNoQtySum = 0;
    var $qtyElements = $(".serialNoQty");
    if ($qtyElements && $qtyElements.length) {
        for (var i = 0; i < $qtyElements.length; i++) {
            serialNoQtySum = serialNoQtySum + toNumber($qtyElements[i].value);
        }
    }
    return toNumber(serialNoQtySum);
}

async function getFreeSerialNumbers() {
    $.ajax({
        type: "POST",
        data: JSON.stringify({
            ident: $("#identSerialNoIdent").val(),
            anNo: $("#IdentAnNo").val(),
            warehouse: $("#" + serialNoWarehouseId).val(),
            search: $("#identFreeSerialNo").val()
        }),
        url: globalIssuedSerialNumbersUrls.getFreeSerialNumbers,
        contentType: "application/json"
    }).done(function (response) {
        loadFreeSerialNumbers(response);
    });
}

function loadFreeSerialNumbers(freeSerialNumbers) {
    selectedFreeSerialNumbers = [];
    freeSerialNumbersList = freeSerialNumbers;

    $identFreeSerialNoDataTable = $('#identFreeSerialNoGrid');
    if ($.fn.dataTable.isDataTable('#identFreeSerialNoGrid'))
        $identFreeSerialNoDataTable.DataTable().destroy();

    $identFreeSerialNoDataTable.DataTable({
        serverSide: false,
        ajax: undefined,
        scroller: false,
        responsive: false,
        paging: false,
        info: false,
        data: freeSerialNumbers,
        columns: [
            {
                data: "",
                className: 'dt-body-center',
                render: function (data, type, full) {
                    return '<input class="ackey" onclick="selectedFreeSerialNumber(\'' + full.SerialNo + '\', \'' + full.Warehouse + '\', \'' + full.Stock + '\', \'' + full.DateDue + '\')" type="checkbox" />';
                }
            },
            { data: "SerialNo" },
            { data: "Stock", visible: $("#IdentSerialNoType").val() === "E" || $("#IdentSerialNoType").val() === "S" ? false : true },
            { data: "DateDue", visible: $("#IdentSerialDateDue").val() === "true" ? true : false }
        ],
        initComplete: function (settings, json) {
            $(".partialIdentSerialNoIssueModalContent").trigger("resize");
        }
    });
}

function selectedFreeSerialNumber(serialNo, warehouse, qty, dateDue) {
    qty = toNumber(qty);
    var index = selectedFreeSerialNumbers.findIndex(x => x.SerialNo === serialNo && x.Warehouse === warehouse);

    var selectedQtySum = selectedFreeSerialNumbers.reduce(function (s, a) {
        return toNumber(s + a.Qty);
    }, 0);

    if ($("#IdentSerialNoType").val() === "E" || $("#IdentSerialNoType").val() === "S")
        qty = 1;
    else {
        if (qty <= (toNumber($("#identSerialNoDifference").val()) - toNumber(selectedQtySum)) || selectedQtySum >= toNumber($("#identSerialNoDifference").val()))
            qty = qty;
        else if (qty > (toNumber($("#identSerialNoDifference").val()) - selectedQtySum) && toNumber($("#identSerialNoDifference").val()) > 0 && toNumber($("#identSerialNoDifference").val()) > selectedQtySum)
            qty = toNumber($("#identSerialNoDifference").val()) - selectedQtySum;
        else
            qty = 1;
    }

    if (index !== -1)
        selectedFreeSerialNumbers.splice(index, 1);
    else
        selectedFreeSerialNumbers.push({ SerialNo: serialNo, Warehouse: warehouse, Qty: qty, DateDue: dateDue });
}

async function transferSelectedFreeSerialNumbers() {
    $("#transferSerialNumbersBtn").find("i").addClass("fa-spinner fa-spin");
    $("#transferSerialNumbersBtn").prop("disabled", true);

    var selectedFreeSN = selectedFreeSerialNumbers;
    for (var i = 0; i < selectedFreeSN.length; i++) {
        var serialAlreadyExists = false;
        var $serialCodes = $(".serialNoCode");
        if ($serialCodes && $serialCodes.length) {
            for (var c = 0; c < $serialCodes.length; c++) {
                if ($serialCodes[c].value.trim() === selectedFreeSN[i].SerialNo.trim()) {
                    serialAlreadyExists = true;
                }
            }
        }

        if (serialAlreadyExists) {
            if ($("#IdentSerialNoType").val() === "K" || $("#IdentSerialNoType").val() === "O" || $("#IdentSerialNoType").val() === "P") {
                $("#serialNoQty-" + selectedFreeSN[i].SerialNo).val(toNumber($("#serialNoQty-" + selectedFreeSN[i].SerialNo).val()) + 1);
                saveSerialNoIssue(selectedFreeSN[i].SerialNo);
                addReqQuantity(1);

                if (i === selectedFreeSN.length - 1) {
                    await getFreeSerialNumbers();
                    $("#transferSerialNumbersBtn").find("i").removeClass("fa-spinner fa-spin");
                    $("#transferSerialNumbersBtn").prop("disabled", false);
                }
            }
            continue;
        }

        var data = {
            AcKey: $("#AcKey").val(),
            AnNo: $("#IdentAnNo").val(),
            Issuer: $("#" + serialNoWarehouseId).val(),
            Ident: $("#identSerialNoIdent").val(),
            SerialNo: selectedFreeSN[i].SerialNo,
            Qty: selectedFreeSN[i].Qty,
            DateDue: selectedFreeSN[i].DateDue,
            Type: "K",
            SNWOType: "",
            Package: "",
            PackQty: 0,
            InvoiceType: $("#InvoiceType").val()
        };

        await fetch(globalIssuedSerialNumbersUrls.createSerialNoUrl, {
            method: "POST",
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(data)
        }).then((response) => response.json()
        ).then(async (response) => {
            if (!response || response === false) {
                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    type: "alert",
                    text: globalIssuedSerialNumbersLocalization.errorSaving,
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: globalIssuedSerialNumbersLocalization.confirm,
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });
            } else {
                addSerialNumberIssueRow(selectedFreeSN[i].SerialNo, selectedFreeSN[i].Qty, 0, selectedFreeSN[i].DateDue);
                await saveSerialNoIssue(selectedFreeSN[i].SerialNo);
            }
        });
    }

    await getFreeSerialNumbers();
    $("#transferSerialNumbersBtn").find("i").removeClass("fa-spinner fa-spin");
    $("#transferSerialNumbersBtn").prop("disabled", false);
}

async function serialNoAutoEdition(anNo) {
    var data = {
        AcKey: $("#AcKey").val(),
        DocType: $("#DocType").val(),
        AnNo: $("#IdentAnNo").val(),
        Issuer: $("#IssuerId").val(),
        Ident: $("#id-" + anNo).val(),
        QuantityOld: $("#qtyOld-" + anNo).val(),
        QuantityNew: $("#quantity-" + anNo).val(),
        Type: "K"
    };

    await fetch(globalIssuedSerialNumbersUrls.serialNoAutoEditionUrl, {
        method: "POST",
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data)
    }).then((response) => response.json()
    ).then(async (response) => {
        if (toNumber($("#quantity-" + anNo).val()) > toNumber(response.KolicSN)) {
            let err = globalIssuedSerialNumbersLocalization.automaticIssueOfSerialNumbersNotPossible + "<br>"
                + globalIssuedSerialNumbersLocalization.desiredQuantity + ": " + formatDisplay("2", $("#quantity-" + anNo).val()) + "<br>"
                + globalIssuedSerialNumbersLocalization.actualQuantity + ": " + formatDisplay("2", response.KolicSN) + "<br>"
                + globalIssuedSerialNumbersLocalization.difference + ": " + formatDisplay("2", toNumber($("#quantity-" + anNo).val()) - toNumber(response.KolicSN));

            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                type: "success",
                text: err,
                buttons: [
                    {
                        icon: 'fa fa-check',
                        text: globalIssuedSerialNumbersLocalization.confirm,
                        action: async function () {
                            checkIdentSerialNoIssue(anNo, "M", null, null, "true");
                        },
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });
        }

        $("#quantity-" + anNo).val(toNumber(response.KolicSN));
        $("#qtyOld-" + anNo).val(toNumber(response.KolicSN));
        formatNumberInput($("#quantity-" + anNo));
    });
}