@using PantheonRA.BackOffice.Enums
@using PantheonRA.BackOffice.Models
@model InventoryExcessOrMissingViewModel

@{
    ViewBag.Title = Loc.InventoryCount;
}

<div class="wrapper wrapper-content">
    <div class="tabs-container">
        @Html.Partial("_InventoryTabNavigation")
        <div class="tab-content">
            <form method="post" id="ExcessOrMissingForm">
                @Html.HiddenFor(model => model.DefaultDecimalPlacesValue)
                @Html.HiddenFor(model => model.DefaultDecimalPlacesPrice)
                @Html.HiddenFor(model => model.DefaultDecimalPlacesQuantity)
                @Html.HiddenFor(model => model.IsVATObligee)
                @Html.HiddenFor(model => model.InventoryType)
                @Html.HiddenFor(model => model.InventoryAcKey)
                @Html.HiddenFor(model => model.WayOfSale)

                <div class="row buttons-tabbed">
                    @Html.Partial("_FormButtons", new FormButtonsViewModel
                    {
                        BackUrl = Url.Action("Index", "Inventory"),
                        SaveButtonGroup = new FormButtonGroup
                        {
                            Buttons = new List<FormButton>
                            {
                                new FormButton {
                                Text = Loc.Save,
                                Icon = "far fa-print fa-lg",
                                OnClick = "save()" },
                            }
                        },
                        PrintButtonGroup = new FormButtonGroup
                        {
                            Buttons = new List<FormButton>
                            {
                                new FormButton
                                {
                                    Text = Loc.Print,
                                    Icon = "far fa-print fa-lg",
                                    OnClick = "print()"
                                }
                            }
                        },
                    })
                </div>

                <div class="divided-content clearfix">
                    <div class="divided-content-main">
                        <div class="placeholder placeholder-clipboard"><span class="placeholder-text">@Loc.InventoryPlaceholder</span></div>
                        <div class="row document-head">
                            <div class="col-md-3 @(string.IsNullOrEmpty(Model.AcKey) ?  string.Empty : "document-head-disabled-input")">
                                <div class="form-group">
                                    @Html.LabelFor(model => model.DocType, Loc.DocType, new { @class = "control-label" })
                                    <div>
                                        @Html.TextBoxFor(model => model.DocType, HtmlAttributesHelper.CreateInputAttributes("form-control", "DocType", true, Loc.DocType))
                                        @Html.ValidationMessageFor(model => model.DocType, "", new { @class = "text-danger" })
                                    </div>
                                </div>
                            </div>

                            <div class="col-md-5 document-head-disabled-input">
                                <div class="form-group">
                                    @Html.Label("receiver-issuer", Loc.Warehouse, new { @class = "control-label", @title = Loc.Warehouse })
                                    @Html.ValidationMessageFor(model => model.ReceiverId, "", new { @class = "text-danger m-l-xs", @id = "ReceiverId-validation" })
                                    <div>
                                        @if (Model.InventoryType == InventoryType.Excess)
                                        {
                                            @Html.HiddenFor(model => model.ReceiverId)
                                            @Html.TextBoxFor(model => model.Receiver, !string.IsNullOrWhiteSpace(Model.Receiver) ? Model.Receiver.Trim() : "",
                                                         HtmlAttributesHelper.CreateInputAttributes("form-control typeahead_3 typeahead_wide", "Receiver", true, Loc.Warehouse, true,
                                                         new { @title = Model.ReceiverId }))
                                        }
                                        else
                                        {
                                            @Html.HiddenFor(model => model.IssuerId)
                                            @Html.TextBoxFor(model => model.Issuer, !string.IsNullOrWhiteSpace(Model.Issuer) ? Model.Issuer.Trim() : "",
                                                         HtmlAttributesHelper.CreateInputAttributes("form-control typeahead_3 typeahead_wide", "Issuer", true, Loc.Warehouse, true,
                                                         new { @title = Model.IssuerId }))
                                        }
                                    </div>
                                </div>
                            </div>

                            <div class="col-md-2">
                                <div class="form-group">
                                    @Html.LabelFor(model => model.Status, Loc.Status, new { @class = "control-label" })
                                    <div>
                                        @Html.DropDownListFor(model => model.Status,
                                            new SelectList(ViewBag.DocumentStatuses != null ? ViewBag.DocumentStatuses : new List<string>(), "Status", "Name"), Loc.Select,
                                            HtmlAttributesHelper.CreateInputAttributes("form-control", "Status", false, Loc.Status, true, new { @title = Model.StatusDisplay }))
                                        @Html.ValidationMessageFor(model => model.Status, "", new { @class = "text-danger" })
                                    </div>
                                </div>
                            </div>

                            <div class="col-md-2 document-head-disabled-input">
                                <div class="form-group">
                                    @Html.LabelFor(model => model.AcKey, Model.InventoryType == InventoryType.Shortage ? Loc.InventoryMissingNumber : Loc.InventoryExcessNumber,
                                        new { @class = "control-label m-t-xs" })
                                    <div>
                                        @Html.HiddenFor(model => model.AcKey)
                                        <h4 class="control-label" id="AcKeyDisplayContainer">
                                            @Model.AcKeyDisplay
                                        </h4>
                                        @Html.ValidationMessageFor(model => model.AcKey, "", new { @class = "text-danger" })
                                    </div>
                                </div>
                            </div>
                        </div>

                        @Html.Partial("_InvoiceIdentsTable", new IdentsTableViewModel
                        {
                            IsVATObligee = Model.IsVATObligee,
                            Author = AuthorType.ExcessOrMissing,
                            TableGridName = "inventory-invoice-idents"
                        })

                        <div class="row document-footer">
                            <div class="col-md-5">
                                <div class="form-group text-center pull-left @(string.IsNullOrEmpty(Model.Note) ? string.Empty : "btn-active")"
                                     onclick="openInvoiceNoteModal()">
                                    @Html.LabelFor(model => model.Note, Loc.Note)
                                    <i class="fa fa-comment clickable-icon"></i>
                                    @Html.TextAreaFor(model => model.Note,
                                        HtmlAttributesHelper.CreateInputAttributes("form-control", "Note", false, Loc.Note, false, new { @rows = 3, @maxlength = "4096", @class = "hidden" }))
                                    @Html.ValidationMessageFor(model => model.Note, "", new { @class = "text-danger", @id = "Note-validation" })
                                </div>
                            </div>
                            <div class="col-md-1 document-head-disabled-input" title="@Loc.Total @Model.Currency">
                                <div class="form-group text-right">
                                    <label>@Loc.Total @Model.Currency</label>
                                    <input type="text" id="TotalAmount" step="@Model.DefaultDecimalPlacesValue" value="@Model.Price" class="form-control text-right numberInput" disabled />
                                </div>
                            </div>
                            <div class="col-md-1 document-head-disabled-input">
                                <div class="form-group text-right">
                                    <label>@Loc.Discount %</label>
                                    <input type="text" id="DiscountPercent" step="@Model.DefaultDecimalPlacesValue" value="" class="form-control text-right numberInput" />
                                </div>
                            </div>
                            <div class="col-md-1 document-head-disabled-input">
                                <div class="form-group text-right">
                                    <label>@Loc.Discount  @Model.Currency</label>
                                    <input type="text" id="DiscountAmount" step="@Model.DefaultDecimalPlacesValue" value="@Model.Discount" class="form-control text-right numberInput" />
                                </div>
                            </div>
                            <div class="col-md-1 document-head-disabled-input" title="@Loc.PriceWithoutTax @Model.Currency">
                                <div class="form-group text-right">
                                    <label>@Loc.PriceWithoutTax</label>
                                    <input type="text" id="Value" value="" step="@Model.DefaultDecimalPlacesValue" class="form-control text-right numberInput" disabled />
                                </div>
                            </div>
                            @if (Model.IsVATObligee)
                            {
                                <div class="col-md-1 document-head-disabled-input">
                                    <div class="form-group text-right">
                                        <label>@Loc.VAT @Model.Currency</label>
                                        <input type="text" id="TaxAmount" step="@Model.DefaultDecimalPlacesValue" value="@Model.VAT" class="form-control text-right numberInput" disabled />
                                    </div>
                                </div>
                            }
                            <div class="@(Model.IsVATObligee ? "col-md-2" : "col-md-3") document-head-highlight-input">
                                <div class="form-group text-right">
                                    <label>@Loc.ToPay</label>
                                    <div>
                                        <span id="ToPayAmount">@Model.PriceWithVAT.ToString("n2")</span>
                                        <span id="Currency">@Model.Currency</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="divided-content-side">
                        <div class="tabs-container">
                            <ul class="nav nav-tabs horizontal-menu">
                                <li class="active divided-tab-1"><a data-toggle="tab" href="#home" class="local-tab">@Loc.BasicData</a></li>
                            </ul>
                        </div>
                        <div class="tab-content">
                            <div id="home" class="tab-pane fade in active">
                                <div class="form-horizontal form-md form-right m-t-lg">
                                    <div class="form-group">
                                        @Html.LabelFor(model => model.Date, Model.InventoryType == InventoryType.Shortage ? Loc.Issue : Loc.Receive, new { @class = "col-xs-3 control-label",
                                            @title = Loc.OrderForm })
                                        <div class="col-xs-9">
                                            <div class="input-group">
                                                <span class="input-group-addon"><i class="far fa-calendar alt"></i></span>
                                                @Html.TextBoxFor(model => model.Date, Model.Date.HasValue ? Model.Date.Value.ToString(Loc.DateFormat) : null,
                                                        HtmlAttributesHelper.CreateInputAttributes("form-control datepicker", "Date", false, Loc.Date))
                                            </div>
                                            @Html.ValidationMessageFor(model => model.Date, "", new { @class = "text-danger", @id = "Date-validation" })
                                        </div>
                                    </div>

                                    <hr class="hr-dashed" />

                                    @Html.HiddenFor(x => x.Order)
                                    @Html.HiddenFor(x => x.OrderForm)
                                    <div class="form-group doc1Container">
                                        @Html.LabelFor(model => model.OrderDisplay, Loc.DocumentOne, new { @class = "col-xs-3 control-label", @id = "OrderText" })
                                        <div class="col-xs-5">
                                            @Html.TextBoxFor(model => model.OrderDisplay,
                                                HtmlAttributesHelper.CreateInputAttributes("form-control", "OrderDisplay", false, Loc.DocumentOne))
                                            @Html.ValidationMessageFor(model => model.Order, "", new { @class = "text-danger", @id = "Order-validation" })
                                        </div>
                                        <div class="col-xs-4 padding-left-none">
                                            <div class="input-group">
                                                <span class="input-group-addon"><i class="far fa-calendar alt"></i></span>
                                                @Html.TextBoxFor(model => model.OrderDate, Model.OrderDate.HasValue ? Model.OrderDate.Value.ToString("dd.MM.yyyy") : null,
                                                    HtmlAttributesHelper.CreateInputAttributes("form-control datepicker", "OrderDate", false, Loc.DocumentOneDate))
                                            </div>
                                            @Html.ValidationMessageFor(model => model.OrderDate, "", new { @class = "text-danger", @id = "OrderDate-validation" })
                                        </div>
                                    </div>

                                    <div class="form-group doc2Container">
                                        @Html.LabelFor(model => model.OrderFormDisplay, Loc.DocumentTwo, new
                                        {
                                            @class = "col-xs-3 control-label",
                                            @title = Loc.OrderFormNumber,
                                            @id = "OrderFormText"
                                        })
                                        <div class="col-xs-5">
                                            @Html.TextBoxFor(model => model.OrderFormDisplay,
                                                HtmlAttributesHelper.CreateInputAttributes("form-control", "OrderFormDisplay", false, Loc.DocumentTwo))
                                            @Html.ValidationMessageFor(model => model.OrderForm, "", new { @class = "text-danger", @id = "OrderForm-validation" })
                                        </div>
                                        <div class="col-xs-4 padding-left-none">
                                            <div class="input-group">
                                                <span class="input-group-addon"><i class="far fa-calendar alt"></i></span>
                                                @Html.TextBoxFor(model => model.OrderFormDate, Model.OrderFormDate.HasValue ? Model.OrderFormDate.Value.ToString("dd.MM.yyyy") : null,
                                                      HtmlAttributesHelper.CreateInputAttributes("form-control datepicker", "OrderFormDate", false, Loc.DocumentTwoDate))
                                            </div>
                                            @Html.ValidationMessageFor(model => model.OrderFormDate, "", new { @class = "text-danger", @id = "OrderFormDate-validation" })
                                        </div>
                                    </div>

                                    <hr class="hr-dashed" />

                                    <div class="form-group">
                                        @Html.LabelFor(model => model.ClerkId, Loc.ClerkShort, new { @class = "col-xs-3 control-label" })
                                        <div class="col-xs-9">
                                            @Html.DropDownListFor(model => model.ClerkId,
                                                new SelectList(ViewBag.Users != null ? ViewBag.Users : new List<string>(), "Id", "Name"), Loc.Select,
                                                HtmlAttributesHelper.CreateInputAttributes("form-control", "Clerk", false, Loc.ClerkShort))
                                            @Html.ValidationMessageFor(model => model.ClerkId, "", new { @class = "text-danger" })
                                        </div>
                                    </div>

                                    <div class="form-group">
                                        @Html.LabelFor(model => model.Referent, Loc.Referent, new { @class = "col-xs-3 control-label" })
                                        <div class="col-xs-9">
                                            @Html.TextBoxFor(model => model.Referent,
                                                HtmlAttributesHelper.CreateInputAttributes("form-control", "Referent", true, Loc.Referent))
                                            @Html.ValidationMessageFor(model => model.Referent, "", new { @class = "text-danger" })
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </div>

        <div class="modal inmodal fade" id="noteModal" tabindex="-1" role="dialog" aria-hidden="true">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                        <h4 class="modal-title" id="exampleModalLabel"></h4>
                    </div>
                    <div class="modal-body">
                        <form>
                            <div class="form-group">
                                <label for="item-note" class="control-label">@Loc.Note:</label>
                                <textarea class="form-control" id="item-note" rows="3"></textarea>
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-primary" onclick="saveNote()" data-dismiss="modal">@Loc.Save</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="modal inmodal fade" id="invoiceNoteModal" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="exampleModalLabel"></h4>
                </div>
                <div class="modal-body">
                    <form>
                        <div class="form-group">
                            <label for="item-note" class="control-label">@Loc.Note:</label>
                            <textarea class="form-control" id="item-note" rows="3"></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary" onclick="saveInvoiceNote()" data-dismiss="modal">@Loc.Save</button>
                </div>
            </div>
        </div>
    </div>

    <div id="taxOptions" hidden>
        @foreach (var tax in ViewBag.Taxes)
        {
            <option value="@tax.VATCode" data-vat="@tax.VAT" data-displaytext="@(tax.VATCode + "  " + tax.VAT + "% - " + tax.Name)">
                @tax.VATCode
            </option>
        }
    </div>

    <div id="measUnitOptions" hidden>
        @foreach (var unit in ViewBag.MeasurementUnits)
        {
            <option value="@unit.Id">
                @unit.Id
            </option>
        }
    </div>
</div>

<div id="PrintPreview" data-url="@Url.Action("WholesalePdf", "Wholesale")" style="display:none"></div>
<div id="PaymentMethodRequiredError" data-value="@Loc.PaymentMethodIsRequired" style="display:none"></div>
<div id="LoadingLoc" data-text="@Loc.Loading" style="display:none" />
<div id="RabateValidationError" data-text="@Loc.RabateAmountValidation" style="display:none" />
<input id="DocTextsUrl" value="@Url.Action("GetDocTextsForDocType", "DocumentText")" type="hidden" />
<input id="ConfirmLoc" value="@Loc.Confirm" type="hidden" />
<input type="hidden" id="GetCostDrvUrl" value="@Url.Action("GetCostDrv", "CostDrv")" />

@section pageScripts{
    @Scripts.Render("~/bundles/invoiceIdent")

    <script type="text/javascript">
        var invoiceItems = [];
        var openStatus = "";

        $(document).ready(function () {
            loadInvoiceItems();
            checkFormEditable();

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

            $("#OrderDisplay").on("click", function () {
                if ($("#Order").val() && $("#Order").val() !== "")
                    window.location.href = '@Url.Action("Edit", "Inventory")?id=' + $("#Order").val();
            });
        });

        function loadInvoiceItems() {
            if (!$("#AcKey").val())
                return;

            swapLoadingIcon(true, "add-position", "fa fa-plus");
            $.post('@Url.Action("MoveItemsList", "MoveItem")?id=' + $("#AcKey").val(), function (data) {
                for (var i = 0; i < data.length; i++) {
                    data[i].TaxPrice = ($("#InventoryType").val() === "@InventoryType.Excess" ? data[i].TaxPrice : data[i].TaxPriceSale) + data[i].Excise;
                    invoiceItems.push(data[i]);
                    appendIdentToTable(data[i]);
                }

                updatePriceTable();
                checkFormEditable();
                swapLoadingIcon(false, "add-position", "fa fa-plus");

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

        function appendIdentToTable(data, isNewIdent = false) {
            let newRow = createIdentsTableRows($("#invoice"), data, SaleType.Inventory, $("#DefaultDecimalPlacesPrice").val(), $("#DefaultDecimalPlacesQuantity").val(), $("#IsVATObligee").val());
            initializeNumberInputs();
            if (isNewIdent) {
                reorderColumns(true, newRow);
            }
        }

        function changeIdentData(anNo) {
            var rabate = toNumber($("#rabate-" + anNo).val());
            var totalPrice = toNumber($("#quantity-" + anNo).val()) * toNumber($("#price-" + anNo).val());
            var discount = totalPrice / 100 * toNumber(rabate);
            var vat = (totalPrice - discount) / 100 * toNumber($("#vatPercent-" + anNo).val());

            let item = invoiceItems[getInvoiceItemIndex(anNo)];

            item.AcKey = $("#acKey-" + anNo).val();
            item.Quantity = toNumber($("#quantity-" + anNo).val());
            item.Price = toNumber($("#price-" + anNo).val());
            item.Rabate = toNumber($("#rabate-" + anNo).val());
            item.Note = $("#note-" + anNo).val();
            item.VAT = toNumber($("#vatPercent-" + anNo).val());
            item.VATCode = $("#vat-" + anNo + " option:selected").val();
            item.Name = $("#name-" + anNo).val();
            item.Ident = $("#id-" + anNo).val();
            item.MeasurementUnit = $("#measurementUnit-" + anNo + " option:selected").val();
            item.TaxPrice = toNumber(vat);
            item.PriceForValue = toNumber($("#priceForValue-" + anNo).val());
            item.BasisForTax = totalPrice - discount;

            var excise = calculatePriceWithExcise({
                quantity: item.Quantity,
                price: item.Price,
                rabate: item.Rabate,
                vat: item.VAT,
                incBase: item.IncBase,
                notIncBase: item.NotIncBase,
                incBaseP: item.IncBaseP,
                notIncBaseP: item.NotIncBaseP
            });

            item.TaxPrice = excise.vat;
            item.TotalPrice = excise.priceWithExcise;

            $("#totalPrice-" + anNo).val(item.TotalPrice);
            $("#basisForTax-" + anNo).val(totalPrice - discount);
            $("#taxPrice-" + anNo).val(item.TaxPrice);
            initializeNumberInputs();

            updatePriceTable();
        }

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

        function updatePriceTable() {
            var totalPrice = 0;
            var discountSum = 0;
            var taxAmount = 0;
            var excise = 0;

            for (var i = 0; i < invoiceItems.length; i++) {
                var price = invoiceItems[i].Price.toString();
                if (price) {
                    toNumber(price);
                }

                totalPrice = totalPrice + (toNumber(price) * invoiceItems[i].Quantity);
                var discount = ((invoiceItems[i].Price * invoiceItems[i].Rabate) / 100) * invoiceItems[i].Quantity;
                discountSum = discountSum + discount;
                excise += invoiceItems[i].Excise;
                taxAmount += invoiceItems[i].TaxPrice;
            }
            var toPayAmount = formatDisplay($("#DefaultDecimalPlacesValue").val(), totalPrice - discountSum + taxAmount + excise);

            var discountPercent = 0;
            if (totalPrice) {
                var discountOnePercentPrice = totalPrice / 100;
                discountPercent = discountSum / discountOnePercentPrice;
            }

            $("#TotalAmount").val(isNaN(totalPrice) ? 0 : totalPrice);
            $("#DiscountAmount").val(isNaN(discountSum) ? 0 : discountSum);
            $("#TaxAmount").val(isNaN(taxAmount) ? 0 : taxAmount);
            $("#ToPayAmount").text(toPayAmount);
            $("#DiscountPercent").val(isNaN(discountPercent) ? 0 : discountPercent);

            initializeNumberInputs();
            calculatePriceWithDiscount();
        }

        function changeIdentTax(anNo) {
            var vatPercent = toNumber($("#vat-" + anNo + " option:selected").attr("data-vat"));
            $("#vatPercent-" + anNo).val(vatPercent);
            changeIdentData(anNo);
        }

        function calculatePriceWithDiscount() {
            var value = toNumber($("#TotalAmount").val()) - toNumber($("#DiscountAmount").val());
            $("#Value").val(isNaN(value) ? 0 : value.toFixed(2));

            var toPayAmount = toNumber($("#Value").val()) + toNumber($("#TaxAmount").val());
            $("#ToPayAmount").text(formatDisplay($("#DefaultDecimalPlacesValue").val(), toPayAmount));

            initializeNumberInputs();
        }

        function calculateDiscountPercent() {
            var discountAmount = toNumber($("#DiscountAmount").val());
            var totalPrice = toNumber($("#TotalAmount").val());

            var percent = 0;
            if (discountAmount && totalPrice > 0)
                var percent = discountAmount / totalPrice * 100;

            $("#DiscountPercent").val(percent);

            updateInvoiceItemsDiscount(percent);
            calculatePriceWithDiscount();
        }

        function updateInvoiceItemsDiscount(percent) {
            for (var i = 0; i < invoiceItems.length; i++) {
                invoiceItems[i].Rabate = percent;
                $("#rabate-" + invoiceItems[i].AnNo).val(percent);
            }

            updatePriceTable();
        }

        function checkFormEditable() {
            if ($("#AcKey").val() && $("#Status").val() === "@VerifyStatus.Confirmed") {
                $("#ExcessOrMissingForm :input").prop("disabled", true);
            }

            var inputs = document.querySelectorAll(".numberInput, .element-editable");
            for (var i = 0; i < inputs.length; i++) {
                inputs[i].disabled = true;
                inputs[i].classList.add("no-border-right");
            }

            $("#Order").prop("disabled", false);
            $("#Order").prop("readonly", true);
            $("#OrderForm").prop("disabled", false);
            $("#OrderForm").prop("readonly", true);

        }

        function swapLoadingIcon(loading, buttonId, icon) {
            var $button = $("#" + buttonId);
            var $buttonIcon = $button.find("i");
            var $buttonGroupButtons = $button.parent().find("button");

            if (loading) {
                $buttonIcon.removeClass(icon).addClass("fa fa-spinner fa-spin fa-fw");
                $buttonGroupButtons.attr("disabled", true);
            }
            else {
                $buttonIcon.removeClass("fa fa-spinner fa-spin fa-fw").addClass(icon);
                $buttonGroupButtons.removeAttr("disabled");
            }
        }

        function print(type) {
            window.open("@Url.Action("InventoryPdf", "Inventory")?id=" + $("#AcKey").val() + "&inventoryType=" + $("#InventoryType").val() + "&inventoryAcKey=" + $("#InventoryAcKey").val());
        }

        function save() {
            if ($('input.numberInput.error-input-item')[0]) return;

            swapLoadingIcon(true, "saveButton", "fa fa-save");
            swapLoadingIcon(true, "printButton", "far fa-print");

            var formData = $("#ExcessOrMissingForm").serializeArray();
            formData.push({ name: 'InvoiceItemsJsonString', value: JSON.stringify(invoiceItems) });
            formData = changeFormDataValue(formData, 'Note', encodeURIComponent($("#Note").val()));

            $.post('@Url.Action("EditExcessOrMissing", "Inventory")', formData)
                .done(function (response) {
                    if (response.Success) {
                        displayErrors(response);

                        let errorText = '';
                        if (response.errors) {
                            response.errors.forEach(function (errorItem) {
                                errorText += errorItem;
                            });
                        }

                        if (errorText !== '') {
                            $().customModal({
                                destroyOnClose: true,
                                showCloseButton: true,
                                type: "error",
                                text: errorText,
                                buttons: [
                                    {
                                        icon: 'fa fa-check',
                                        text: "@Loc.Confirm",
                                        closeOnAction: true,
                                        type: 'primary'
                                    }
                                ]
                            });
                        } else {
                            setIdentsPriceForValue();
                        }

                        checkFormEditable();
                    } else {
                        clearValidationErrors();
                        displayErrors(response);

                        if (response.errors)
                            displayResponseValidationErrors(response);
                    }

                    swapLoadingIcon(false, "saveButton", "fa fa-save");
                    swapLoadingIcon(false, "printButton", "far fa-print");
                });
        }

        function setIdentsPriceForValue() {
            if (!$("#AcKey").val())
                return;

            swapLoadingIcon(true, "add-position", "fa fa-plus");
            $.post('@Url.Action("MoveItemsList", "MoveItem")?id=' + $("#AcKey").val(), function (data) {
                for (var i = 0; i < data.length; i++) {
                    $("#priceForValue-" + data[i].AnNo).val(formatDisplay($("#DefaultDecimalPlacesPrice").val(), data[i].PriceForValue));
                }

                swapLoadingIcon(false, "add-position", "fa fa-plus");
            }, "json");
        }

        function clearValidationErrors() {
            $(".field-validation-valid").text(' ');
        }

        function displayResponseValidationErrors(response) {
            for (var i = 0; i < response.errors.length; i++) {
                var span = document.getElementById(response.errors[i].Key + "-validation");
                errorText = document.createTextNode(response.errors[i].Value);
                if (span)
                    span.appendChild(errorText);

                if (response.errors[i].Key === "PaymentMethodId") {
                    $().customModal({
                        destroyOnClose: true,
                        showCloseButton: true,
                        type: "error",
                        text: "@Loc.PaymentMethodIsRequired",
                        buttons: [
                            {
                                icon: 'fa fa-check',
                                text: "@Loc.Confirm",
                                closeOnAction: true,
                                type: 'primary'
                            }
                        ]
                    });
                }
            }
        }

        var selectedItemAnNo = '';
        function openNoteModal(anNo) {
            selectedItemAnNo = anNo;
            $("#item-note").val($("#note-" + anNo).val());
            $("#noteModal").modal('show');
        }

        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");

            changeIdentData(selectedItemAnNo);
        }

        function openInvoiceNoteModal() {
            $("#invoiceNoteModal textarea").val($("#Note").val());
            $("#invoiceNoteModal").modal("show");
        }

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

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