@using PantheonRA.BackOffice.Enums
@using PantheonRA.BackOffice.Models
@using PAW.Contracts.Enums;
@model InventoryCreateViewModel
@{
    ViewBag.Title = Loc.InventoryCount;
}

<div class="wrapper wrapper-content">
    <div class="tabs-container">
        @Html.Partial("_InventoryTabNavigation")
        <div class="tab-content">
            <form method="post" id="InventoryForm">
                @Html.HiddenFor(model => model.DefaultDecimalPlacesValue)
                @Html.HiddenFor(model => model.DefaultDecimalPlacesPrice)
                @Html.HiddenFor(model => model.DefaultDecimalPlacesQuantity)
                @Html.HiddenFor(model => model.AcKeyM)
                @Html.HiddenFor(model => model.AcKeyV)
                @Html.HiddenFor(model => model.VerifiedPrices)
                @Html.HiddenFor(model => model.MoveNonMatOpenDate)
                @Html.Hidden("MoveNonMatOpenDateFormatted", Model.MoveNonMatOpenDate.HasValue ? Model.MoveNonMatOpenDate.Value.ToString(Loc.DateFormat) : null)
                <div class="row buttons-tabbed">
                    @Html.Partial("_FormButtons", new FormButtonsViewModel
                    {
                        ShowCloseBtn = false,
                        BackUrl = Url.Action("Index", "Inventory"),
                        IsWizardVisible = true,
                        SaveButtonGroup = new FormButtonGroup
                        {
                            Buttons = new List<FormButton>
                            {
                                new FormButton { Text = Loc.Save, Icon = "far fa-print fa-lg", OnClick = "save()"}
                            }
                        },
                        PrintType = ReportFormName.Inventory,
                        PrintMenuButtonGroup = ReportsHelper.FormatReportTree(
                            Model.ReportTreeViewModel,
                            "save(false, false, '" + InvoiceSaveType.SaveAndPrint + "', '{0}')",
                            "save(false, false, '" + InvoiceSaveType.SaveAndPreview + "', '{0}')"
                        ),
                        ConfirmButtonGroup = new FormButtonGroup
                        {
                            Buttons = new List<FormButton>
                            {
                                new FormButton { Text = Loc.Confirm, Icon = "fa fa-check fa-lg", Class = (string.IsNullOrEmpty(Model.AcKey) ? "disabled" : string.Empty), OnClick = "confirm()"}
                            }
                        },
                        WizardButtonGroup = new FormButtonGroup
                        {
                            Buttons = new List<FormButton>
                            {
                                new FormButton { Text = Loc.InventoryState, OnClick = "onClickInventoryState()" },
                                new FormButton { Text = Loc.PartialState, OnClick = "onClickInventoryPartialState()" },
                                new FormButton { Text = Loc.TransferSerialNumbersWizard, OnClick = "onClickTransferSerialNumbers()" }
                            }
                        }
                    })

                    <button id="invoiceDeleteButton" type="button" onclick="canDeleteInventory()"
                            class="btn btn-primary btn-outline pull-right collapsable-form-button @(string.IsNullOrEmpty(Model.AcKey) ? "hidden" : string.Empty)">
                        <i class="far fa-trash-alt m-r-xs"></i>
                        <span class="visible-lg-inline visible-md-inline">@Loc.Delete</span>
                    </button>

                    <a title="@Loc.New" id="newInventory" onclick="createNewInvoice('@Url.Action("Create", "Inventory")', 'DocType')"
                       class="btn btn-primary btn-outline pull-right collapsable-form-button @(string.IsNullOrEmpty(Model.AcKey) ? "hidden" : string.Empty)">
                        <i class="fas fa-plus m-r-xs"></i>
                        <span class="visible-lg-inline">@Loc.New</span>
                    </a>
                </div>

                <div class="divided-content">
                    <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-2 col-sm-6 @(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" })
                                    @Html.HiddenFor(model => model.DocType)
                                    <select id="DocTypeSelect" name="DocTypeSelect" class="form-control custom-select" @(string.IsNullOrEmpty(Model.AcKey) ? "" : "disabled")>
                                        @foreach (var item in ViewBag.DocumentTypes)
                                        {
                                            <option value="@item.DocType"
                                                    data-warehouse="@item.WarehouseReceivedBills"
                                                    data-department="@item.Department"
                                                    data-doc1="@item.Doc1Name"
                                                    data-doc2="@item.Doc2Name"
                                                    @(Model.DocType == item.DocType ? "selected" : string.Empty)>
                                                @item.DocTypeView - @item.Name
                                            </option>
                                        }
                                    </select>
                                </div>
                            </div>

                            <div class="col-md-3 col-sm-6 @(string.IsNullOrEmpty(Model.AcKey) ?  string.Empty : "document-head-disabled-input")">
                                <div class="form-group">
                                    @Html.LabelFor(model => model.ReceiverId, Loc.Warehouse, new { @class = "control-label", @title = Loc.Supplier })
                                    @Html.ValidationMessageFor(model => model.ReceiverId, "", new { @class = "text-danger m-l-xs", @id = "ReceiverId-validation" })
                                    @Html.HiddenFor(model => model.ReceiverId)
                                    @Html.DropDownListFor(model => model.Receiver,
                                    new SelectList(ViewBag.Warehouses != null ? ViewBag.Warehouses : new List<string>(), "Id", "Name"), Loc.Select,
                                    HtmlAttributesHelper.CreateInputAttributes("form-control custom-select", "Receiver", false, Loc.Warehouse, true, new { @title = Model.Receiver }))
                                </div>
                            </div>

                            <div class="col-md-3 col-sm-6">
                                <div class="form-group">
                                    @Html.LabelFor(model => model.Department, Loc.Department, new { @class = "control-label" })
                                    @Html.ValidationMessageFor(model => model.ReceiverId, "", new { @class = "text-danger", @id = "Department-validation" })
                                    @Html.DropDownListFor(model => model.Department,
                                        new SelectList(ViewBag.Departments != null ? ViewBag.Departments : new List<string>(), "Id", "Name"), Loc.Select,
                                        HtmlAttributesHelper.CreateInputAttributes("form-control custom-select", "Department", false, Loc.Department, true, new { @title = Model.Department }))
                                </div>
                            </div>

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

                            <div class="col-md-2 col-sm-12 document-head-disabled-input">
                                <div class="form-group">
                                    @Html.LabelFor(model => model.AcKey, Loc.InventoryNumber, new { @class = "control-label m-t-xs" })
                                    @Html.HiddenFor(model => model.AcKey)
                                    <h4 class="control-label" id="AcKeyDisplayContainer">
                                        @{
                                            Html.RenderPartial("~/Views/Shared/Components/_PrevNextKeyDisplay.cshtml",
                                            new PrevNextKeyDisplayViewModel
                                            {
                                                KeyDisplayHint = Loc.OpenListOfInventory,
                                                KeyDisplayValue = Model.AcKeyDisplay,
                                                NextNavigation = Url.Action("Next", "Move", new
                                                {
                                                    Id = string.IsNullOrEmpty(Model.AcKey) ? "{modelId}" : Model.AcKey,
                                                    DocType = string.IsNullOrEmpty(Model.AcKey) ? "{docTypeId}" : Model.DocType,
                                                    RedirectUrl = Url.Action("Edit", "Inventory", new { id = "{id}" })
                                                }),
                                                PrevNavigation = Url.Action("Prev", "Move", new
                                                {
                                                    Id = string.IsNullOrEmpty(Model.AcKey) ? "{modelId}" : Model.AcKey,
                                                    DocType = string.IsNullOrEmpty(Model.AcKey) ? "{docTypeId}" : Model.DocType,
                                                    RedirectUrl = Url.Action("Edit", "Inventory", new { id = "{id}" })
                                                }),
                                                KeyNavigation = Url.Action("Index", "Inventory", new { acKey = Model.AcKey, date = Model.Date.Value.ToString("o") })
                                            });
                                        }
                                    </h4>
                                    @Html.ValidationMessageFor(model => model.AcKey, "", new { @class = "text-danger" })
                                </div>
                            </div>
                        </div>

                        <div class="document-body">
                            <div class="row">
                                <div class="col-lg-8 col-md-10 col-sm-11 col-xs-12">
                                    @Html.Partial("_InvoiceIdentInput", new DecimalPlacesViewModel
                                    {
                                        DefaultDecimalPlacesPrice = Model.DefaultDecimalPlacesPrice,
                                        DefaultDecimalPlacesQuantity = Model.DefaultDecimalPlacesQuantity,
                                        DefaultDecimalPlacesValue = Model.DefaultDecimalPlacesValue,
                                        Price1Text = Model.Price1Text,
                                        Price2Text = Model.Price2Text,
                                        Price3Text = Model.Price3Text,
                                        Price4Text = Model.Price4Text,
                                        Disabled = true,
                                        Author = AuthorType.Inventory
                                    })
                                </div>
                            </div>

                            <div class="table-responsive document-table m-b-md">
                                <div class="dt-bootstrap" style="position:relative">
                                    <table id="idents" data-grid-id="create-inventory-main" data-dynamic-table="true" class="table table-bordered showhidecolumns" role="grid">
                                        <thead>
                                            <tr role="row">
                                                <th data-column-id="Position" style="min-width:3%" data-sortable="false">@Loc.PositionShort</th>
                                                @if (PantheonRA.BackOffice.CurrentUser.Localization == Localization.Code.HR)
                                                {
                                                    <th data-column-id="Ident" style="min-width:12%">@Loc.Ident</th>
                                                }
                                                else
                                                {
                                                    <th data-column-id="IdentW" style="min-width:20%">@Loc.Ident</th>
                                                }
                                                @if (PantheonRA.BackOffice.CurrentUser.Localization == Localization.Code.HR)
                                                {
                                                    <th data-column-id="Name" style="min-width:12%">@Loc.Name</th>
                                                }
                                                else
                                                {
                                                    <th data-column-id="NameW" style="min-width:17%">@Loc.Name</th>
                                                }
                                                <th data-column-id="MeasUnit" style="width:7%; min-width:65px">@Loc.MeasUnit</th>
                                                <th data-column-id="InventoryCount" style="min-width:7%" class="text-right">@Loc.InventoryCount</th>
                                                <th data-column-id="InventoryState" style="min-width:7%" class="text-right">@Loc.InventoryState</th>
                                                <th data-column-id="Difference" style="min-width:6%" class="text-right">@Loc.Difference</th>
                                                <th data-column-id="WarehousePrice" style="min-width:7%" class="text-right">@Loc.WarehousePrice</th>
                                                <th data-column-id="SellingPrice" style="min-width:7%" class="text-right">@Loc.SellingPrice</th>
                                                <th data-column-id="RetailPrice" style="min-width:7%" class="text-right">@Loc.RetailPrice</th>
                                                <th data-column-id="StorageValue" style="min-width:7%" class="text-right">@Loc.StorageValue</th>
                                                @*Columns only for HR*@
                                                @if (PantheonRA.BackOffice.CurrentUser.Localization == Localization.Code.HR)
                                                {
                                                    <th data-column-id="AllowedShortagePercent" style="min-width:5%" class="text-right">@Loc.AllowedShortagePercent</th>
                                                    <th data-column-id="TrafficQuantity" style="min-width:5%" class="text-right">@Loc.TrafficQuantity</th>
                                                    <th data-column-id="AllowedShortage" style="min-width:5%" class="text-right">@Loc.AllowedShortage</th>
                                                }
                                                <th data-column-id="CommentDelete" style="min-width:85px; width:85px;" data-sortable="false"></th>
                                            </tr>
                                        </thead>
                                        <tbody id="identRows"></tbody>
                                    </table>
                                </div>
                            </div>
                        </div>

                        <div class="row document-footer">
                            <div class="col-md-6 col-sm-6">
                                <div class="form-group text-left text-center-sm" onclick="openInvoiceNoteModal()">
                                    @Html.LabelFor(model => model.Note, Loc.Note)
                                    <i id="noteIcon" class="fa fa-comment m-l-sm margin-none-sm clickable-icon @(string.IsNullOrEmpty(Model.Note) ? string.Empty : "btn-active")"></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-2 col-sm-6 document-head-disabled-input" title="@Loc.TotalSalePrice">
                                <div class="form-group text-right">
                                    <label>@Loc.TotalSalePrice</label>
                                    <input type="text" id="TotalPC" value="@Model.TotalRP" step="@Model.DefaultDecimalPlacesValue" class="form-control text-right numberInput" disabled />
                                </div>
                            </div>
                            <div class="col-md-2 col-sm-6 document-head-disabled-input" title="@Loc.TotalRetailprice">
                                <div class="form-group text-right">
                                    <label>@Loc.TotalRetailprice</label>
                                    <input type="text" id="TotalMPC" step="@Model.DefaultDecimalPlacesValue" value="@Model.TotalSP" class="form-control text-right numberInput" disabled />
                                </div>
                            </div>
                            <div class="col-md-2 col-sm-6 document-head-highlight-input">
                                <div class="form-group text-right">
                                    <label>@Loc.Total</label>
                                    <div>
                                        <span id="Total">@Math.Round(Model.Price, Model.DefaultDecimalPlacesValue)</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, Loc.InventoryDate, new
                                        {
                                            @class = "col-md-4 control-label",
                                            @title = Loc.InventoryDate
                                        })
                                        <div class="col-md-8">
                                            <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.TakeoverDate))
                                            </div>
                                            @Html.ValidationMessageFor(model => model.Date, "", new { @class = "text-danger", @id = "Date-validation" })
                                        </div>
                                    </div>

                                    <div class="form-group">
                                        <div class="col-md-4 m-t-sm text-right text-left-sm text-left-xs">
                                            <input id="allowNoStock" type="checkbox" class="m-r-xs js-switch inventory-js-switch" />
                                            @Html.Label("allowNoStock", Loc.ShowIdentsWithNoStock, new { @class = "hidden-lg hidden-md m-l-sm" })
                                        </div>
                                        @Html.Label("allowNoStock", Loc.ShowIdentsWithNoStock, new { @class = "col-md-8 hidden-sm hidden-xs control-label" })
                                    </div>

                                    <div class="form-group">
                                        <div class="col-md-4 m-t-sm text-right text-left-sm text-left-xs">
                                            <input id="allowPackagedGoods" type="checkbox" class="m-r-xs inventory-js-switch" />
                                            @Html.Label("allowPackagedGoods", Loc.ConsiderPackagingAndCompositeGoods, new { @class = "hidden-lg hidden-md m-l-sm" })
                                        </div>
                                        @Html.Label("allowPackagedGoods", Loc.ConsiderPackagingAndCompositeGoods, new { @class = "col-xs-8 hidden-sm hidden-xs control-label" })
                                    </div>

                                    <hr class="hr-dashed" />

                                    <div class="form-group doc1Container">
                                        @Html.LabelFor(model => model.Doc1, Loc.DocumentOne, new { @class = "col-md-4 col-sm-12 control-label text-left-sm", @id = "OrderText" })
                                        <div class="col-md-4 col-sm-6">
                                            @Html.TextBoxFor(model => model.Doc1,
                                                HtmlAttributesHelper.CreateInputAttributes("form-control", "Doc1", false, Loc.DocumentOne))
                                            @Html.ValidationMessageFor(model => model.Doc1, "", new { @class = "text-danger", @id = "Doc1-validation" })
                                        </div>
                                        <div class="col-md-4 col-sm-6 padding-left-none-lg padding-left-none-md padding-left-none-sm">
                                            <div class="input-group">
                                                <span class="input-group-addon"><i class="far fa-calendar alt"></i></span>
                                                @Html.TextBoxFor(model => model.Doc1Date, Model.Doc1Date.HasValue ? Model.Doc1Date.Value.ToString("dd.MM.yyyy") : null,
                                                    HtmlAttributesHelper.CreateInputAttributes("form-control datepicker", "Doc1Date", false, Loc.DocumentOneDate))
                                            </div>
                                            @Html.ValidationMessageFor(model => model.Doc1Date, "", new { @class = "text-danger", @id = "Doc1Date-validation" })
                                        </div>
                                    </div>

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

                                    <hr class="hr-dashed" />

                                    <div class="form-group">
                                        @Html.LabelFor(model => model.ClerkId, Loc.ClerkShort, new { @class = "col-md-4 control-label" })
                                        <div class="col-md-8">
                                            @Html.DropDownListFor(model => model.ClerkId,
                                                new SelectList(ViewBag.Users != null ? ViewBag.Users : new List<string>(), "Id", "Name"), Loc.Select,
                                                HtmlAttributesHelper.CreateInputAttributes("form-control custom-select", "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-md-4 control-label" })
                                        <div class="col-md-8">
                                            @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>

    <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 class="modal inmodal fade" id="errorModal" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-body">
                    <span id="errorModalMessage"></span>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary" data-dismiss="modal" onclick="">@Loc.OK</button>
                </div>
            </div>
        </div>
    </div>

    <div class="modal inmodal fade" id="warehousesModal" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-body">
                    <div class="project-list">
                        <table id="warehousesGrid" data-grid-id="create-inventory" data-url="@Url.Action("DocTypePrChList", "DocTypePrCh")" class="list-table">
                            <thead>
                                <tr>
                                    <th width="5%" class="dt-head-center"></th>
                                    <th width="80%">@Loc.Warehouse</th>
                                    <th width="15%">@Loc.DocTypeShort</th>
                                </tr>
                            </thead>
                        </table>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary" data-dismiss="modal" onclick="confirmWarehousesSelection()">@Loc.Confirm</button>
                </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="invoice-note" class="control-label">@Loc.Note:</label>
                            <textarea class="form-control" id="invoice-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>

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

<input type="hidden" id="IdentEditUrl" value="@Url.Action("Edit", "Products")" />
<input type="hidden" id="PAASPrintByAcKeyAndTypeUrl" value="@Url.Action("PAASPrintByAcKeyAndType", "Move")" />
<input type="hidden" id="ConfirmLoc" value="@Loc.Confirm" />
<input type="hidden" id="GetCostDrvUrl" value="@Url.Action("GetCostDrv", "CostDrv")" />
@{Html.RenderPartial("~/Views/Shared/Components/_IdentSerialNoModal.cshtml");}

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

<script>
        var invoiceItems = [];
        var selectedWarehouses = [];
        var openStatus = "";
        var selectedInvoiceItem;
        var warehousesWithoutDocTypeExist = false;

        $(document).ready(function () {
            $("#Total").text(formatDisplay($("#DefaultDecimalPlacesValue").val(), $("#Total").text()));
            loadInvoiceItems();
            checkFormEditable();

            if (!$("#AcKey").val()) {
                $("#wizardButton").prop("disabled", true);
                $("#wizardButton + button").prop("disabled", true);
            }

            $(".datepicker").datepicker({
                format: 'dd.mm.yyyy',
                language: '@Loc.Language'
            }).on('changeDate', function () {
                $(this).datepicker('hide');
            });

            initializeInvoiceIdentInputs($('#IdentSearch'), null, DiscountType.SellerDiscount, $("#DefaultDecimalPlacesPrice").val(), $("#ReceiverId"), null, null,
            { noResults: '@Loc.NoResults', name: '@Loc.Name', ident: '@Loc.Ident', price: '@Loc.Price', stock: '@Loc.Stock' }, null, null);

            $("#DocTypeSelect").on('change', async function () {
                $("#DocType").val($("#DocTypeSelect").val());
                $("#DocTypeSelect").prop("title", $("#DocTypeSelect option:selected").text());

                if ($("#DocTypeSelect option:selected").attr("data-warehouse") && !$("#AcKey").val()) {
                    $("#ReceiverId").val($("#DocTypeSelect option:selected").attr("data-warehouse"));
                    $("#ReceiverId").trigger("change");
                }

                if (!$("#AcKey").val() && $("#DocTypeSelect option:selected").attr("data-department")) {
                    $("#Department").val($("#DocTypeSelect option:selected").attr("data-department"));
                    $("#Department").trigger("change");
                }

                if ($("#DocTypeSelect option:selected").attr("data-doc1") === "")
                    $(".doc1Container").prop("hidden", true);
                else {
                    $("#OrderText").text($("#DocTypeSelect option:selected").attr("data-doc1"));
                    $(".doc1Container").prop("hidden", false);
                }

                if ($("#DocTypeSelect option:selected").attr("data-doc2") === "")
                    $(".doc2Container").prop("hidden", true);
                else {
                    $("#OrderFormText").text($("#DocTypeSelect option:selected").attr("data-doc2"));
                    $(".doc2Container").prop("hidden", false);
                }

                if (!$("#AcKey").val())
                    await setDocTypeStatusOptions($("#DocTypeSelect option:selected").val(), $("#Status"));
            });

            $("#DocTypeSelect").trigger("change");

            $dataTableWarehouses = $('#warehousesGrid');
            $dataTableWarehouses.DataTable({
                ajax: {
                    url: $dataTableWarehouses.attr('data-url'),
                },
                columns: [
                    { data: "AnQid", orderable: false, render: $.fn.dataTable.render.checkbox("warehousesSelectionChanged"), className: 'dt-body-center' },
                    { data: "Warehouse", name: "AcWarehouse" },
                    { data: "DocType", name: "AcDocType" },
                ],
                createdRow: function (row, data, dataIndex) {
                    if (data.DocType === "") {
                        warehousesWithoutDocTypeExist = true;
                    }
                }
            });

            $("#Receiver").on("change", function () {
                $("#ReceiverId").val($("#Receiver").val());
                $("#Receiver").prop("title", $("#Receiver").val());
                $("#wizardButton").prop("disabled", false);
                $("#wizardButton + button").prop("disabled", false);
            });

            $("#Department").on("change", function () {
                $("#Department").prop("title", $("#Department").val());
            });

            var elems = Array.prototype.slice.call(document.querySelectorAll('.inventory-js-switch'));
            elems.forEach(function (html) {
                var switchery = new Switchery(html, { size: 'small' });
            });

            $("#Status").on('change', function () {
                if ($("#AcKeyM").val() || $("#AcKeyV").val()) {
                    $().customModal({
                        destroyOnClose: true,
                        showCloseButton: true,
                        type: "error",
                        text: "@Loc.InventoryHasExcessOrMissingDocumentCannotChangeStatus",
                        buttons: [
                            {
                                icon: 'fa fa-check',
                                text: "@Loc.Confirm",
                                closeOnAction: true,
                                type: 'primary'
                            }
                        ]
                    });

                    $("#Status").val($("#SelectedStatus").val());
                } else {
                    $("#SelectedStatus").val($("#Status").val());
                    $("#Status").prop("title", $("#Status option:selected").text());
                }
                checkFormEditable();
            });

            $('#Receiver').focus();
        });

        function addPosition(invoiceItemData) {
            if (invoiceItemData != null) {
                selectedInvoiceItem = invoiceItemData;

                if (!$("#AcKey").val()) {
                    save();
                } else {
                    addIdent();
                }

                $("#DocTypeSelect").attr("disabled", true);
                $("#DocTypeSelect").closest("div:not(.form-group)").addClass("document-head-disabled-input");
            }
        }

        function appendIdentToTable(data, isNewIdent = false, append = true) {
            let newRow = createIdentTableRow($("#idents"), data, $("#DefaultDecimalPlacesPrice").val(), $("#DefaultDecimalPlacesQuantity").val(), append);
            if (isNewIdent) {
                initializeNumberInputs();
                reorderColumns(true, newRow);
            }

            return newRow;
        }

        function createIdentTableRow($element, data, decimalPlacesPrice, decimalPlacesQuantity, append) {
            var row = createTableRowElement("tr", "position-" + data.AnNo, "", null, false, "row");
            row.appendChild(createTableRowElement("input", "anNo-" + data.AnNo, "form-control", data.AnNo, true, null, "text", null, null, true));
            row.appendChild(createTableRowElement("input", "id-" + data.AnNo, "form-control" + (data.IsActive === false ? " text-danger" : ""), data.Ident, true, null, "text", () => redirectToIdent(data.Ident), null, true));
            row.appendChild(createTableRowElement("input", "name-" + data.AnNo, "form-control border-left-solid" + (data.IsActive === false ? " text-danger" : ""), data.Name, false, null, "text", null, () => updateIdentBasicData(data.AnNo), true));
            row.appendChild(createTableRowElement("select", "measurementUnit-" + data.AnNo, "form-control", data.MeasurementUnit, false, null, null, null, () => updateIdentBasicData(data.AnNo), true, null, $("#measUnitOptions").html()));
            row.appendChild(createTableRowElement("input", "quantity-" + data.AnNo, "form-control numberInput invoice-input editableInput text-right required", data.Quantity, false, null, "text", null, () => onChangeQuantity(data.AnNo), true, decimalPlacesQuantity));
            row.appendChild(createTableRowElement("input", "directCost-" + data.AnNo, "form-control numberInput invoice-input editableInput text-right required", data.DirectCost, true, null, "text", null, null, true, decimalPlacesQuantity));
            row.appendChild(createTableRowElement("input", "duty-" + data.AnNo, "form-control numberInput invoice-input editableInput text-right required", data.Duty, false, null, "text", null, () => onChangeDuty(data.AnNo), true, decimalPlacesQuantity));
            row.appendChild(createTableRowElement("input", "priceForValue-" + data.AnNo, "form-control numberInput invoice-input editableInput text-right required", data.PriceForValue, false, null, "text", null, () => updatePriceForValue(data.AnNo), true, decimalPlacesPrice));
            row.appendChild(createTableRowElement("input", "newRetailPrice-" + data.AnNo, "form-control numberInput invoice-input editableInput text-right required", data.NewRetailPrice, false, null, "text", null, () => onChangeRetailPrice(data.AnNo), true, decimalPlacesPrice));
            row.appendChild(createTableRowElement("input", "salePrice-" + data.AnNo, "form-control numberInput invoice-input editableInput text-right required", data.SalePrice, false, null, "text", null, () => onChangeSalePrice(data.AnNo), true, decimalPlacesPrice));
            row.appendChild(createTableRowElement("input", "warehouseValue-" + data.AnNo, "form-control numberInput invoice-input editableInput text-right required", data.WarehouseValue, true, null, "text", null, null, true, decimalPlacesPrice));
            if ("@PantheonRA.BackOffice.CurrentUser.Localization" == "@Localization.Code.HR") {
                row.appendChild(createTableRowElement("input", "allowedShortagePercent-" + data.AnNo, "form-control numberInput invoice-input editableInput text-right required", data.AllowedShortagePercent, true, null, "text", null, null, true, decimalPlacesPrice));
                row.appendChild(createTableRowElement("input", "turnoverQuantity-" + data.AnNo, "form-control numberInput invoice-input editableInput text-right required", data.TurnoverQuantity, true, null, "text", null, null, true, decimalPlacesPrice));
                row.appendChild(createTableRowElement("input", "allowedShortage-" + data.AnNo, "form-control numberInput invoice-input editableInput text-right required", data.AllowedShortage, false, null, "text", null, null, true, decimalPlacesPrice));
            }

            var actions = createTableRowElement("td", null, "actions-cell");
            var button = createTableRowElement("button", "noteModal-" + data.AnNo, "identNote btn btn-link " + (data.Note !== "" ? "btn-active" : ""), null, false, null, "button", () => openNoteModal(data.AnNo));
            button.appendChild(createTableRowElement("i", null, "fa fa-comment"));
            button.appendChild(createTableRowElement("input", "note-" + data.AnNo, "hidden", data.Note));
            button.appendChild(createTableRowElement("input", "acKey-" + data.AnNo, "hidden", data.AcKey));
            button.appendChild(createTableRowElement("input", "vat-" + data.AnNo, "hidden", data.VAT));
            button.appendChild(createTableRowElement("input", "priceCurrency-" + data.AnNo, "hidden", data.PriceCurrency));
            button.appendChild(createTableRowElement("input", "serialNo-" + data.AnNo, "hidden", data.SerialNo));
            button.appendChild(createTableRowElement("input", "dateDue-" + data.AnNo, "hidden", data.DateDue));
            button.appendChild(createTableRowElement("input", "qtyOld-" + data.AnNo, "hidden", 0));
            actions.appendChild(button);

            if (data.SerialNo && data.SerialNo !== "N") {
                var serialsBtn = createTableRowElement("button", "identSerialNo-" + data.AnNo, "btn btn-outline no-padding", null, false, null, "button", () => checkIdentSerialNo(data.AnNo, "M", null, null, "true"));
                serialsBtn.appendChild(createTableRowElement("span", null, "btn serialNo-icon"));
                actions.appendChild(serialsBtn);

                var serialsInvStateBtn = createTableRowElement("button", "identInvStateSerialNo-" + data.AnNo, "btn btn-outline", null, false, null, "button", () => checkIdentSerialNo(data.AnNo, "M", null, null, "true", "true"));
                serialsInvStateBtn.appendChild(createTableRowElement("span", null, "fa fa-solid fa-barcode"));
                actions.appendChild(serialsInvStateBtn);
            }

            var deleteBtn = createTableRowElement("button", "identRemove-" + data.AnNo, "btn btn-outline editableInput", null, false, null, "button", () => canDeleteInventory(data.AnNo));
            deleteBtn.appendChild(createTableRowElement("span", null, "far fa-trash-alt"));
            actions.appendChild(deleteBtn);
            row.appendChild(actions);

            if (append) {
                var element = document.getElementById("identRows");
                element.appendChild(row);
            }

            selectedInvoiceItem = null;

            return row;
        }

        function onChangeQuantity(anNo) {
            var duty = toNumber($("#quantity-" + anNo).val()) - toNumber($("#directCost-" + anNo).val());
            $("#duty-" + anNo).val(formatDisplay($("#DefaultDecimalPlacesQuantity").val(), duty));

            updateIdentByAnNo(anNo);
            updatePriceTable();
            checkIdentSerialNo(anNo, "M");
        }

        function onChangeDuty(anNo) {
            var quantity = toNumber($("#duty-" + anNo).val()) + toNumber($("#directCost-" + anNo).val());
            $("#quantity-" + anNo).val(formatDisplay($("#DefaultDecimalPlacesQuantity").val(), quantity));

            updateIdentByAnNo(anNo);
            updatePriceTable();
        }

        function onChangeSalePrice(anNo) {
            var retailPrice = toNumber($("#salePrice-" + anNo).val()) / (1 + (toNumber($("#vat-" + anNo).val()) / 100));
            $("#newRetailPrice-" + anNo).val(formatDisplay($("#DefaultDecimalPlacesPrice").val(), retailPrice));

            updateIdentByAnNo(anNo);
            updatePriceTable();
        }

        function onChangeRetailPrice(anNo) {
            var salePrice = toNumber($("#newRetailPrice-" + anNo).val()) * (1 + (toNumber($("#vat-" + anNo).val()) / 100));
            $("#salePrice-" + anNo).val(formatDisplay($("#DefaultDecimalPlacesPrice").val(), salePrice));

            updateIdentByAnNo(anNo);
            updatePriceTable();
        }

        function changeIdentData(anNo) {
            updateIdentByAnNo(anNo);
            updatePriceTable();
        }

        function updateIdentByAnNo(anNo) {
            var index = invoiceItems.map(function (e) { return e.AnNo; }).indexOf(anNo);
            invoiceItems[index].Duty = toNumber($("#duty-" + anNo).val());
            invoiceItems[index].Quantity = toNumber($("#quantity-" + anNo).val());
            invoiceItems[index].NewRetailPrice = toNumber($("#newRetailPrice-" + anNo).val());
            invoiceItems[index].SalePrice = toNumber($("#salePrice-" + anNo).val());
        }

        function updateIdentBasicData(anNo) {
            var index = invoiceItems.map(function (e) { return e.AnNo; }).indexOf(anNo);
            invoiceItems[index].Name = $("#name-" + anNo).val();
            invoiceItems[index].MeasurementUnit = $("#measurementUnit-" + anNo).val();
        }

        function updatePriceForValue(anNo) {
            var index = invoiceItems.map(function (e) { return e.AnNo; }).indexOf(anNo);
            invoiceItems[index].PriceForValue = toNumber($("#priceForValue-" + anNo).val());
            updatePriceTable();
        }

        function updatePriceTable() {
            var totalPC = 0;
            var totalMPC = 0;
            var total = 0;

            for (var i = 0; i < invoiceItems.length; i++) {
                totalPC += invoiceItems[i].Duty * invoiceItems[i].NewRetailPrice;
                totalMPC += invoiceItems[i].Duty * invoiceItems[i].SalePrice;
                total += invoiceItems[i].Duty * invoiceItems[i].PriceForValue;
            }

            $("#TotalMPC").val(isNaN(totalMPC) ? 0 : totalMPC);
            $("#TotalPC").val(isNaN(totalPC) ? 0 : totalPC);
            $("#Total").text(isNaN(total) ? 0 : formatDisplay($("#DefaultDecimalPlacesValue").val(), total));

            formatNumberInput($("#TotalMPC"));
            formatNumberInput($("#TotalPC"));
        }

        var printWindow;
        function save(getState, isPartialState, option, printType = null) {
            if (option === '@InvoiceSaveType.SaveAndPrint' || option === '@InvoiceSaveType.SaveAndPreview') {
                printWindow = createPrintWindow(printWindow);
            }

            if (checkFormEditable() === false && option) {
                print(option, printType);
                return;
            } else if (checkFormEditable() === false)
                return;

            swapLoadingIcon(true, "saveButton", "fa fa-save");

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

            var url;
            if ($("#AcKey").val()) {
                url = '@Url.Action("Edit", "Inventory")';
            } else {
                url = '@Url.Action("Create", "Inventory")';
            }

            $.post(url, formData)
                .done(function (response) {
                    if (response.Success) {
                        if (!$("#AcKey").val()) {
                            $("#AcKey").val(response.data.AcKey);
                            refreshArrows(response.data.AcKey, response.data.AcKeyDisplay, $("#DocTypeSelect").val());
                            $("#Referent").val(response.data.Referent);
                            $("#DocTypeSelect").attr("disabled", true);
                            $("#invoiceDeleteButton").removeClass("hidden");
                            $("#newInventory").removeClass("hidden");
                            $("#confirmButton").removeClass("disabled");
                            $("#wizardButton").prop("disabled", false);
                            $("#wizardButton + button").prop("disabled", false);
                            window.history.pushState({}, null, "@Url.Action("Edit", "Inventory")?id=" + response.data.AcKey);
                            clearValidationErrors();
                        }

                        openStatus = $("#Status option:selected").val();
                        displayErrors(response);

                        if (response.data && response.data.AcKey) {
                            $("#AcKey").val(response.data.AcKey);
                        }

                        addIdent();

                        if (getState)
                            getInventoryState(isPartialState);

                        if (option) {
                            print(option, printType);
                        }

                    } else {
                        if (printWindow) {
                            printWindow.close();
                        }

                        clearValidationErrors();
                        displayErrors(response);

                        if (response.errors)
                            displayResponseValidationErrors(response);
                    }
                    swapLoadingIcon(false, "saveButton", "fa fa-save");
                });
        }

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

            swapLoadingIcon(true, "add-position", "fa fa-plus");
            $.post('@Url.Action("InventoryItemsList", "MoveItem")?id=' + $("#AcKey").val(), function (data) {
                var docFragment = document.createDocumentFragment();
                for (var i = 0; i < data.length; i++) {
                    invoiceItems.push(data[i]);
                    docFragment.appendChild(appendIdentToTable(data[i], false, false));
                }

                document.getElementById("identRows").appendChild(docFragment);
                initializeNumberInputs();
                checkFormEditable();
                swapLoadingIcon(false, "add-position", "fa fa-plus");

                // TODO: Functionality slows down perfomance. Uncomment if needed. UPDATE: Do not comment it. Hiding columns will not work.
                if (data.length > 0) {
                    displayShowHideDropdown();
                }
            }, "json");
        }

        function addIdent() {
            if (selectedInvoiceItem != null) {
                swapLoadingIcon(true, "add-position", "fa fa-plus");

                $.post('@Url.Action("CreateItem", "Inventory")', {
                    AcKey: $("#AcKey").val(),
                    Ident: selectedInvoiceItem.id,
                    Quantity: 0,
                    AnNo: invoiceItems.length > 0 ? invoiceItems[invoiceItems.length - 1].AnNo + 1 : 1
                }).done(function (response) {
                    if (response.Success) {
                        invoiceItems.push(response.ident);
                        appendIdentToTable(response.ident, true);

                        $("#Receiver").attr("disabled", true);
                        $("#Receiver").closest("div:not(.form-group)").addClass("document-head-disabled-input");

                        updatePriceTable();
                    } else {
                        if (response.response) {
                            $().customModal({
                                destroyOnClose: true,
                                showCloseButton: true,
                                type: "error",
                                text: response.response.Error,
                                buttons: [
                                    {
                                        icon: 'fa fa-check',
                                        text: "@Loc.Confirm",
                                        closeOnAction: true,
                                        type: 'primary'
                                    }
                                ]
                            });
                        }
                    }
                    swapLoadingIcon(false, "add-position", "fa fa-plus");
                });
            }
        }

        function savePosition(anNo) {
            swapLoadingIcon(true, "save-" + anNo, "fa fa-check");
            $.post('@Url.Action("UpdateInventoryItem", "MoveItem")', getIdentData(anNo))
                .done(function (response) {
                    if ("@PantheonRA.BackOffice.CurrentUser.Localization" == "@Localization.Code.HR") {
                        $.post('@Url.Action("GetAllowedInventoryShortageValues", "MoveItem")', {
                            Ident: $("#id-" + anNo).val(),
                            Warehouse: $("#ReceiverId").val(),
                            IdentAllowedShortagePercent: $("#allowedShortagePercent-" + anNo).val(),
                            AllowedShortageTurnoverQty: $("#turnoverQuantity-" + anNo).val(),
                            AllowedShortage: $("#allowedShortage-" + anNo).val()
                        }).done(function (response) {
                            swapLoadingIcon(false, "save-" + anNo, "fa fa-check");
                        });
                    } else {
                        swapLoadingIcon(false, "save-" + anNo, "fa fa-check");
                    }
                });
        }

        function getIdentData(anNo) {
            var ident = {
                AnNo: anNo,
                AcKey: $("#acKey-" + anNo).val(),
                Note: $("#note-" + anNo).val(),
                Name: $("#name-" + anNo).val(),
                Ident: $("#id-" + anNo).val(),
                Quantity: formatDisplay($("#DefaultDecimalPlacesQuantity").val(), $("#quantity-" + anNo).val(), true),
                MeasurementUnit: $("#measurementUnit-" + anNo + " option:selected").val(),
                DirectCost: formatDisplay($("#DefaultDecimalPlacesPrice").val(), $("#directCost-" + anNo).val(), true),
                Duty: formatDisplay($("#DefaultDecimalPlacesPrice").val(), $("#duty-" + anNo).val(), true),
                PriceForValue: formatDisplay($("#DefaultDecimalPlacesPrice").val(), $("#priceForValue-" + anNo).val(), true),
                SalePrice: formatDisplay($("#DefaultDecimalPlacesPrice").val(), $("#salePrice-" + anNo).val(), true),
                NewRetailPrice: formatDisplay($("#DefaultDecimalPlacesPrice").val(), $("#newRetailPrice-" + anNo).val(), true),
                WarehouseValue: formatDisplay($("#DefaultDecimalPlacesPrice").val(), $("#warehouseValue-" + anNo).val(), true),
            };

            if ("@PantheonRA.BackOffice.CurrentUser.Localization" == "@Localization.Code.HR") {
                ident.AllowedShortage = formatDisplay($("#DefaultDecimalPlacesPrice").val(), $("#allowedShortage-" + anNo).val(), true);
                ident.AllowedShortagePercent = formatDisplay($("#DefaultDecimalPlacesPrice").val(), $("#allowedShortagePercent-" + anNo).val(), true);
                ident.TurnoverQuantity = formatDisplay($("#DefaultDecimalPlacesPrice").val(), $("#turnoverQuantity-" + anNo).val(), true);
            }

            invoiceItems[getInvoiceItemIndex(anNo)] = ident;
            return ident;
        }

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

        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 deletePosition(anNo) {
            $().customModal({
                title: "",
                destroyOnClose: true,
                showCloseButton: true,
                id: "removeIdentAlertModal",
                type: "question",
                text: "@Loc.ConfirmDeleteItemMessage",
                buttons: [
                    {
                        icon: 'fa fa-times',
                        text: '@Loc.No',
                        closeOnAction: true,
                        type: 'ghost'
                    },
                    {
                        icon: 'fa fa-check',
                        text: '@Loc.Yes',
                        action: async function () {
                            tryDelete(anNo);
                        },
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });
        }

        function inventoryState(isPartial) {
            swapLoadingIcon(true, "saveButton", "fa fa-save");
            swapLoadingIcon(true, "wizardButton", "fas fa-wand-magic");

            if (!$("#AcKey").val() || $("#AcKey").val() === "") {
                save(true, isPartial);
            }
            else {
                getInventoryState(isPartial);
            }
        }

        function getInventoryState(isPartial) {
            $.post('@Url.Action("InventoryState", "Inventory")',
                {
                    AcKey: $("#AcKey").val(),
                    Receiver: $("#ReceiverId").val(),
                    Date: $("#Date").val(),
                    IsPartialState: isPartial,
                    AllowNoStock: $("#allowNoStock").is(':checked'),
                    AllowPackagedGoods: $("#allowPackagedGoods").is(':checked')
                }).done(function (response) {
                    location.reload();
                });
        }

        function onClickInventoryPartialState() {
            inventoryState(true);
        }

        function onClickInventoryState() {
            inventoryState(false);
        }

        function print(option, printType) {
            printPAAS(printType, false, option === '@InvoiceSaveType.SaveAndPreview');
        }

        confirm = async function() {
            swapLoadingIcon(true, "confirmButton", "fa fa-check");
            await save();

            $.post('@Url.Action("Confirm", "Inventory")', { id: $("#AcKey").val() })
                .done(function (response) {
                    if (response.result.Success) {
                        $().customModal({
                            destroyOnClose: true,
                            showCloseButton: true,
                            type: "success",
                            text: '@Loc.InventorySuccess',
                            buttons: [
                                {
                                    icon: 'fa fa-check',
                                    text: "@Loc.Confirm",
                                    closeOnAction: true,
                                    type: 'primary'
                                }
                            ]
                        });
                        $("#Status").val("@VerifyStatus.Confirmed");

                        if (response.result.Inventory) {
                            if (response.result.Inventory.AcKeyM && response.result.Inventory.AcKeyM !== "") {
                                $("#AcKeyM").val(response.result.Inventory.AcKeyM);
                                $(".invShortage").parent().removeClass("hidden");
                            }
                            if (response.result.Inventory.AcKeyV && response.result.Inventory.AcKeyV !== "") {
                                $("#AcKeyV").val(response.result.Inventory.AcKeyV);
                                $(".invExcess").parent().removeClass("hidden");
                            }
                        }
                    } else {
                        $().customModal({
                            destroyOnClose: true,
                            showCloseButton: true,
                            type: "error",
                            text: response.result.Error,
                            buttons: [
                                {
                                    icon: 'fa fa-check',
                                    text: "@Loc.Confirm",
                                    closeOnAction: true,
                                    type: 'primary'
                                }
                            ]
                        });
                    }

                    swapLoadingIcon(false, "confirmButton", "fa fa-check");
                    checkFormEditable();
                });
        }

        function canDeleteInventory(anNo) {
            if ($("#VerifiedPrices").val() === "@true" || $("#Status option:selected").val() === "@VerifyStatus.Confirmed") {
                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    type: "error",
                    text: "@Loc.InventoryIsConfirmedCannotDelete",
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: "@Loc.Confirm",
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });
            } else if ($("#MoveNonMatOpenDateFormatted").val() && ($("#MoveNonMatOpenDate").val() > $("#Date").datepicker("getDate"))) {
                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    type: "error",
                    text: stringFormat("@Loc.TheIntangiblePeriodIsAlreadyOverYouCantChangeAnymore", $("#MoveNonMatOpenDateFormatted").val()),
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: "@Loc.Confirm",
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });
            } else if (anNo) {
                deletePosition(anNo);
            } else
                deleteInventory();
        }

        function deleteInventory() {
            $().customModal({
                title: "",
                destroyOnClose: true,
                showCloseButton: true,
                id: "deleteInventoryAlertModal",
                type: "question",
                text: "@Loc.DeleteInventoryDocument",
                buttons: [
                    {
                        icon: 'fa fa-times',
                        text: '@Loc.No',
                        closeOnAction: true,
                        type: 'ghost'
                    },
                    {
                        icon: 'fa fa-check',
                        text: '@Loc.Yes',
                        action: async function () {
                            tryDelete();
                        },
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });
        }

        function tryDelete(anNo) {
            $.get("@Url.Action("Remove", "Inventory")"
                + "?acKey=" + $("#AcKey").val()
                + "&anNo=" + anNo
                + "&date=" + $("#Date").datepicker("getDate").toISOString(),
                function (response) {
                    if (response.ShowError === true) {
                        if (response.MissingDeletePermission === true)
                            showDefaultErrorCustomModal('@Loc.PermissionForDeleteMissing', '@Loc.Confirm');
                        else if (response.IsVATPeriodClosed === true) {
                            $().customModal({
                                destroyOnClose: true,
                                showCloseButton: true,
                                type: "error",
                                text: stringFormat("@Loc.TaxPeriodIsClosed", response.Period),
                                buttons: [
                                    {
                                        icon: 'fa fa-check',
                                        text: "@Loc.Confirm",
                                        closeOnAction: true,
                                        type: 'primary'
                                    }
                                ]
                            });
                        }
                    } else {
                        if (anNo) {
                            swapLoadingIcon(true, "add-position", "fa fa-plus");
                            invoiceItems.splice(getInvoiceItemIndex(anNo), 1);
                            $("#position-" + anNo).remove();
                            updatePriceTable();

                            if (invoiceItems.length < 1) {
                                if (!$("#AcKey").val() || $("#AcKey").val() === "")
                                    $("#DocTypeSelect").attr("disabled", false);

                                $("#Receiver").attr("disabled", false);
                                $("#sh-dropdown-menu").remove();
                            }

                            swapLoadingIcon(false, "add-position", "fa fa-plus");
                        } else
                            location.href = '@Url.Action("Index", "Inventory")';
                    }
                    displayLoading(false);
                });
        }

        function checkFormEditable() {
            if (invoiceItems.length > 0) {
                $("#Receiver").attr("disabled", true);
            }

            var isLocked = $("#AcKeyM").val() || $("#AcKeyV").val() || $("#Status").val() === "@VerifyStatus.Confirmed" ? true : false;

            $("#InventoryForm :input").prop("disabled", isLocked);
            if (isLocked)
                $("#InventoryForm :input").closest("div:not(.form-group)").addClass("document-head-disabled-input");
            else
                $("#InventoryForm :input").closest("div:not(.form-group)").removeClass("document-head-disabled-input");
            $("#printButton").prop("disabled", false);
            $("#printButton + button").prop("disabled", false);
            $("#wizardButton").prop("disabled", isLocked);
            $("#wizardButton + button").prop("disabled", isLocked);
            $("#confirmButton").prop("disabled", isLocked);
            $("#saveButton").attr("disabled", isLocked);
            $("#invoiceDeleteButton").prop("disabled", isLocked);

            if ($("#AcKeyM").val() || $("#AcKeyV").val()) {
                $("#Status").prop("disabled", true);
                $("#Status").closest("div:not(.form-group)").addClass("document-head-disabled-input");
            } else {
                $("#Status").prop("disabled", false);
                $("#Status").closest("div:not(.form-group)").removeClass("document-head-disabled-input");
            }

            var inputs = document.getElementsByClassName("form-control numberInput");
            for (var i = 0; i < inputs.length; i++) {
                inputs[i].disabled = isLocked;
            }

            if ($("#AcKey").val()) {
                $("#printButton").attr("disabled", false);
                $("#printButton + button").prop("disabled", false);
            }

            if ($("#AcKeyM").val() || $("#AcKeyV").val() || $("#Status").val() === "@VerifyStatus.Confirmed")
                return false;

            return true;
        }

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

            getIdentData(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" : "");
        }

        function onClickTransferSerialNumbers() {
            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                type: "question",
                text: "@Loc.TransferSerialNumbersToInventory",
                buttons: [
                    {
                        icon: 'fa fa-times',
                        text: '@Loc.Cancel',
                        closeOnAction: true,
                        type: 'ghost'
                    },
                    {
                        icon: 'fa fa-check',
                        text: '@Loc.Confirm',
                        action: async function () {
                            transferSerialNumbers();
                        },
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });
    }

    function transferSerialNumbers() {
        $.get("@Url.Action("InventorySerialNoSearch", "SerialNumbers")" + "?acKey=" + $("#AcKey").val(),
            function (response) {
                if (response && response === true)
                    location.reload();
                else
                    $().customModal({
                        destroyOnClose: true,
                        showCloseButton: true,
                        type: "error",
                        text: "@Loc.GeneralError",
                        buttons: [
                            {
                                icon: 'fa fa-check',
                                text: "@Loc.Confirm",
                                closeOnAction: true,
                                type: 'primary'
                            }
                        ]
                    });
            });
    }
</script>
}