var invoiceItems = [];
var noteModal = null;

function initializePartList() {
    $("#printButton").prop("disabled", false);
    $("#printButton + button").prop("disabled", false);

    initializeInvoiceIdentInputs($('#IdentSearch'), PriceType.PartList, DiscountType.SellerDiscount, $("#DefaultDecimalPlacesPrice").val(), null, null, null,
        { noResults: $("#NoResultsLoc").val(), name: $("#NameLoc").val(), ident: $("#IdentLoc").val(), price: $("#PriceLoc").val(), stock: $("#StockLoc").val(), advancedIdentSearch: $('#AdvancedIdentSearchLoc').val(), advancedSearch: $('AdvancedSearchLoc').val() });

    initializeIdentBasicTypeahead($('#copyPartListFrom').attr('dataUrl'), $('#copyPartListFrom'), $('#copyPartListFrom'), { item: $("#IdentLoc").val(), name: $("#NameLoc").val() }, null, function (item) {
        $("#copyPartListFrom").val(item.id);
        return { selected: true, value: item.id };
    });

    initializeIdentBasicTypeahead($('#copyPartListTo').attr('dataUrl'), $('#copyPartListTo'), $('#copyPartListTo'), { item: $("#IdentLoc").val(), name: $("#NameLoc").val() }, null, function (item) {
        $("#copyPartListTo").val(item.id);
        return { selected: true, value: item.id };
    });

    $("#copyPartListModal .modal-dialog").draggable();

    loadInvoiceItems();
}

function loadInvoiceItems() {
    $.post($('#partListGrid').attr("data-url") + '?ident=' + $("#Ident").val(),
        function (data) {
            invoiceItems = [];
            for (var i = 0; i < data.length; i++) {
                invoiceItems.push(data[i]);
                createPartListTableRow($("#partListGrid"), data[i], 2, $("#PrStDecPlacesQty").val());
                $("#measurementUnit-" + data[i].AnNo).val(data[i].Um);
            }

            initializeNumberInputs();
            updateTotalPrice();

            if (data.length > 0)
                displayShowHideDropdown();
        }, "json");
}

function createPartListTableRow($element, data, decimalPlacesPrice, decimalPlacesQuntity) {
    var canUpdate = paw.utils.value.strToBool($('#CanUpdate').val());
    var canDelete = paw.utils.value.strToBool($('#CanDelete').val());

    var customSelectClass = "custom-select-" + data.AnNo;
    var $row = $('<tr role="row" id="position-' + data.AnNo + '"></tr>');
    $row.append('<td class="no-space-td"><input id="anNo-' + data.AnNo + '" type="text" value="' + data.AnNo + '" class="form-control" readonly /></td>');
    $row.append('<td class="no-space-td" onclick="redirectToIdent(&quot;' + data.IdentChild + '&quot;)"><input id="id-' + data.AnNo + '" type="text" value="' + data.IdentChild + '" title="' + data.IdentChild + '" class="form-control" readonly /></td>');
    $row.append('<td class="no-space-td"><input id="name-' + data.AnNo + '" type="text" value="' + data.Name.replace(/"/g, '&quot;') + '" title="' + data.Name.replace(/"/g, '&quot;') + '" class="form-control" autocomplete="off" readonly /></td>');
    $row.append('<td class="no-space-td"><input id="quantity-' + data.AnNo + '" type="text" value="' + data.Qty + '" onblur="changePartData(' + data.AnNo + ')" step="' + decimalPlacesQuntity + '" min="0" class="form-control numberInput invoice-input editableInput text-right required" autocomplete="off"' + (!canUpdate? ' disabled' : '' ) + ' /></td>');
    $row.append('<td class="no-space-td"><select id="measurementUnit-' + data.AnNo + '" value="' + data.Um + '" onchange="changePartData(' + data.AnNo + ')" class="form-control custom-select element-editable"' + (!canUpdate ? ' disabled' : '') + '>' + $("#measUnitOptions").html() + '</select></td>');
    $row.append('<td class="no-space-td"><input id="rabate-' + data.AnNo + '" type="text" value="' + data.Rebate + '" onblur="changePartData(' + data.AnNo + ')" step="' + decimalPlacesPrice + '" data-min="0" data-max="100" class="form-control numberInput invoice-input editableInput text-right required" autocomplete="off"' + (!canUpdate ? ' disabled' : '') + ' /></td>');
    $row.append('<td class="no-space-td"><input id="price-' + data.AnNo + '" type="text" value="' + data.Price + '" step="' + decimalPlacesPrice + '" min="0" class="form-control numberInput invoice-input text-right required" autocomplete="off" readonly /></td>');

    var $actions = $('<td class="actions-cell no-space-td"></td>');
    $actions.append(
        '<button id="noteModal-' + data.AnNo + '" onclick="openPlIdentNoteModal(' + data.AnNo + ')" type="button" class="identNote btn btn-link ' + (data.Note && data.Note.trim() !== "" ? "btn-active" : "") + '"' + (!canUpdate ? ' disabled' : '') + '>' +
        '<i class="fa fa-comment"></i></button>' +
        '<input id="note-' + data.AnNo + '" value="' + data.Note + '" class="hidden" />'
    );
    $actions.append('<button type="button" id="identRemove-' + data.AnNo + '" onclick="removePart(' + data.AnNo + ')" class="btn btn-link editableInput"' + (!canDelete ? ' disabled' : '') + '><span class="far fa-trash-alt"></span></button>');
    $row.append($actions);

    $element.append($row);
    setDropdownSelectedValue("measurementUnit-" + data.AnNo, data.Um);
    $("." + customSelectClass).customSelect();
    setInputSelectFocus();
    $element[0].scrollIntoView(false);
    return $row;
}

function addPositionPartList(selectedInvoiceItemData) {
    if (selectedInvoiceItemData.setItemType === "G" || selectedInvoiceItemData.setItemType === "H") {
        $().customModal({
            destroyOnClose: true,
            showCloseButton: true,
            type: "error",
            text: $("#CannotAddSetItemTypePGHOnPartListLoc").val(),
            buttons: [
                {
                    icon: 'fa fa-check',
                    text: $("#ConfirmLoc").val(),
                    closeOnAction: true,
                    type: 'primary'
                }
            ]
        });
        return;
    }

    if (selectedInvoiceItemData != null) {
        var invoiceItem = {
            Ident: $("#Ident").val(),
            ParentQid: $("#IdentAnQid").val(),
            IdentChild: selectedInvoiceItemData.id,
            AnNo: invoiceItems.length > 0 ? invoiceItems[invoiceItems.length - 1].AnNo + 2 : 2,
            Name: selectedInvoiceItemData.name_only,
            Qty: toNumber(selectedInvoiceItemData.quantity),
            Um: selectedInvoiceItemData.measurementUnit,
            Price: toNumber(selectedInvoiceItemData.prStPrice),
            Rebate: toNumber(selectedInvoiceItemData.rabate),
            WasteQty: toNumber(selectedInvoiceItemData.wasteQty),
            Note: selectedInvoiceItemData.note
        }

        invoiceItems.push(invoiceItem);
        createPartListTableRow($("#partListGrid"), invoiceItem, 2, $("#PrStDecPlacesQty").val());
        $("#measurementUnit-" + invoiceItem.AnNo).val(invoiceItem.Um);
        $("#identSearchTable :input").prop("disabled", false);
        initializeNumberInputs();

        addPart(invoiceItem);
        updateTotalPrice();
    }
}

function updateTotalPrice() {
    var total = 0;
    for (var i = 0; i < invoiceItems.length; i++) {
        total += invoiceItems[i].Price << 0;
    }

    $("#grid-data-total-sum").text(formatDisplay(2, total));
}

function addPart(invoiceItem) {
    if (!paw.utils.strToBool($('#CanUpdate').val())) {
        return;
    }
    $.post($("#AddPartUrl").val(), invoiceItem)
        .done(function (response) {
            $("#identSearchTable input").prop('disabled', false);
            swapLoadingIcon(false, "add-position", "fa fa-plus");
        });
}

function changePartData(anNo) {
    let item = invoiceItems[getInvoiceItemIndex(anNo)];

    item.Qty = toNumber($("#quantity-" + anNo).val());
    item.Rebate = toNumber($("#rabate-" + anNo).val());
    item.Um = $("#measurementUnit-" + anNo + " option:selected").val();
    updatePart(item);
}

function updatePart(invoiceItem) {
    if (!paw.utils.strToBool($('#CanUpdate').val())){
        return;
    }
    $.post($("#UpdatePartUrl").val(), invoiceItem)
        .done(function (response) {
            if (response) {
                $("#price-" + invoiceItem.AnNo).val(response.Price);
                formatNumberInput($("#price-" + invoiceItem.AnNo));
                updateTotalPrice();
            }
        });
}

var selectedItemAnNo = '';
function openPlIdentNoteModal(anNo) {
    var ident = paw.utils.iterable.get(invoiceItems, function (item) {
        return item.AnNo === anNo;
    });
    selectedItemAnNo = anNo;
    noteModal.show(ident.Note, {
        onSave: function (content) {
            ident.Note = content;
            $("#noteModal-" + anNo)
                .removeClass("btn-link btn-active")
                .addClass(content != "" ? "btn-link btn-active" : "btn-link");
            changePartData(selectedItemAnNo);
        }
    });
}

function saveNote() {
    $("#note-" + selectedItemAnNo).val($("#item-note").val());
    $("#noteModal-" + selectedItemAnNo)
        .removeClass("btn-link btn-active")
        .addClass($("#note" + selectedItemAnNo).val() !== "" ? "btn-link btn-active" : "btn-link");

    changePartData(selectedItemAnNo);
}

function getInvoiceItemIndex(anNo) {
    for (var i = 0; i < invoiceItems.length; i++) {
        if (invoiceItems[i].AnNo === anNo) {
            return invoiceItems.indexOf(invoiceItems[i]);
        }
    }
}

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

    $.ajax({
        method: "POST",
        url: $("#SavePartListDataUrl").val(),
        data: {
            Ident: $("#Ident").val(),
            Unit: $("#Um option:selected").val(),
            QtySeries: toNumber($("#QtySeries").val()),
            WasteQty: toNumber($("#WasteQty").val()),
            PrStOptimalQty: toNumber($("#PrStOptimalQty").val()),
            DocTypeProd: $("#DocTypeProd option:selected").val(),
            OrderTransInMF: $("#OrderTransInMF option:selected").val()
        },
        success: function (response) {
            $("#saveButton").find("i").removeClass("fa-spinner fa-spin");
            $("#saveButton").prop("disabled", false);
        }
    });
}

function copyPartListModal() {
    $("#copyPartListTo").val($("#Ident").val()).change();
    $("#copyPartListModal").modal("show");
}

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

    $.ajax({
        method: "POST",
        url: $("#CopyPartListUrl").val(),
        data: {
            IdentFrom: $("#copyPartListFrom").val(),
            IdentTo: $("#copyPartListTo").val(),
            CopyMethod: $("#copyPartListMethod option:selected").val()
        },
        success: function (response) {
            loadInvoiceItems();
            $("#copyPartListBtn").find("i").removeClass("fa-spinner fa-spin");
            $("#copyPartListBtn").prop("disabled", false);

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

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

    $.ajax({
        method: "POST",
        url: $("#DeletePartListUrl").val(),
        data: {
            Ident: $("#Ident").val(),
        },
        success: function (response) {
            $("#deletePartListBtn").find("i").removeClass("fa-spinner fa-spin");
            $("#deletePartListBtn").prop("disabled", false);

            invoiceItems = [];
            $("#partListGrid tbody").empty();
        }
    });
}

function removePart(anNo) {
    $("#deletePartListBtn").find("i").addClass("fa-spinner fa-spin");
    $("#deletePartListBtn").prop("disabled", true);

    $.ajax({
        method: "POST",
        url: $("#DeletePositionPartListUrl").val(),
        data: {
            AcKey: $("#Ident").val(),
            AnNo: anNo,
        },
        success: function (response) {
            $("#deletePartListBtn").find("i").removeClass("fa-spinner fa-spin");
            $("#deletePartListBtn").prop("disabled", false);

            invoiceItems.splice(getInvoiceItemIndex(anNo), 1);
            $("#position-" + anNo).remove();
            updateTotalPrice();
        }
    });
}

function printPartList(reportCode) {
    swapLoadingIcon(true, "printButton", "far fa-print");
    printWindow = window.open();
    printWindow.document.write(generatePrintingPage());
    printPAAS("", false, false, $("#PrintPartListUrl").val() + "?Ident=" + $("#Ident").val() + "&ReportType=" + reportCode, false);
    swapLoadingIcon(false, "printButton", "far fa-print");
}