@using PantheonRA.BackOffice.Models
@using PantheonRA.BackOffice.Enums
@using PantheonRA.WebApi.Contracts.Enums

@model PantheonRA.WebApi.Contracts.PaWoExItem

@{
    Model.ProdType = ViewBag.ProdType;
    bool _autoInvoSerialNo = (bool)ViewBag.AutoInvoSerialNo;
}


@using (Html.BeginForm(null, null, FormMethod.Post, new { @id = "workOrderEditMat", enctype = "multipart/form-data" }))
{

<div class="wrapper wrapper-content">
    <div class="tabs-container">

        @Html.Partial("_ProcessingTabNavigation")

        <div class="tab-content">
            <div class="row buttons-tabbed">

            @Html.Partial("_FormButtons", new FormButtonsViewModel
                {

                    BackUrl = Url.Action("WorkOrderMaterials", "Manufacturing", new { @key = Model.AcKey }),
                    ConfirmButtonGroup = new FormButtonGroup
                    {
                        Buttons = new List<FormButton>
                                    {
                                        new FormButton { Text = Loc.Confirm,
                                                        Icon = "fa fa-dolly",
                                                        Class =  Model.IssueFinished == "Y" ? "hidden" : string.Empty,
                                                        OnClick = "saveMaterial();"
                                        }
                        }
                    }

                })

            </div>
            @Html.HiddenFor(model => model.AcKey)
            @Html.HiddenFor(model => model.WoExDecPlacesMate)
            @Html.HiddenFor(model => model.Ident)
            @Html.HiddenFor(model => model.ProdType)
            @Html.HiddenFor(model => model.WoEx.DocType)
            @Html.HiddenFor(model => model.SerialNo)

            @Html.Hidden("id-" + Model.AnNo, Model.Ident)
            @Html.Hidden("quantity-" + Model.AnNo, 0)
            @Html.Hidden("dateDue-" + Model.AnNo, "1900-01-01")
            @Html.Hidden("serialNoType-" + Model.AnNo, "X")
            @Html.Hidden("AutoInvoSerialNo", @_autoInvoSerialNo)

            <div class="row document-head">

                <div class="col-md-2 col-xs-2 document-head-disabled-input">
                    <div class="form-group">
                        @Html.LabelFor(model => model.AcKey, Loc.Key, new { @class = "control-label m-t-xs" })
                        <input class="form-control" id="acKeyDisplay" disabled="disabled" type="text" value=" @Model.KeyView">
                    </div>
                </div>
                <div class="col-sm-2 col-xs-2 document-head-disabled-input">
                    <div class="form-group">
                        @Html.LabelFor(model => model.AnNo, Loc.Position, new { @class = "control-label m-t-xs" })
                        @Html.TextBoxFor(model => model.AnNo, new { @id = "no", @class = "form-control", @readonly = "readonly", @placeholder = Loc.Position })
                    </div>
                </div>
                <div class="col-lg-2 col-xs-4 document-head-disabled-input">
                    <div class="form-group">
                        @Html.LabelFor(model => model.Ident, Loc.MaterialEnum, new { @class = "control-label m-t-xs" })
                        <input type="text" id="ident" readonly="readonly" class="form-control" value="@(Model.Ident + " - " + Model.Descr) " title="@(Model.Ident + " - " + Model.Descr) " />
                    </div>
                </div>
                <div class="col-lg-2 col-xs-4">
                    <div class="form-group">
                        <label class="control-label m-t-xs">@Loc.Warehouse</label>
                        <select id="issueWarehouse" class="form-control custom-select">
                            @foreach (var item in ViewBag.Warehouses)
                                {
                            <option value="@item.Id" @(ViewBag.Issuer == item.Id ? "selected" : string.Empty)>
                                @item.Name
                            </option>
                                }
                        </select>
                    </div>
                </div>

            </div>

            <div class="project-list">
                <div class="row">

                    <div class="form-horizontal form-md col-lg-6 col-md-8">

                        <div class="col-xs-6 card-work-reg-card">
                            <div class="card card-work-reg">
                                <div class="card-header">
                                    <h3 class="card-title"><i class="fas fa-thumbs-up text-primary fa-lg m-r-sm"></i>  @Loc.Quantity</h3>
                                </div>

                                <div class="card-body">

                                    <div class="input-group input-group-lg">
                                        <span class="input-group-btn">
                                            <button id="b_dQty" type="button" class="btn btn-plus-minus"><i class="fa fa-minus fa-lg text-primary"></i></button>
                                        </span>
                                        <input type="number" id="qty" name="Qty" required class="form-control col-md-8 text-center input-lg" onblur="changeQty(this.id, 'K')" autocomplete="off" min="0" />
                                        <span class="input-group-btn">
                                            <button id="b_iQty" type="button" class="btn btn-plus-minus"><i class="fa fa-plus fa-lg text-primary"></i></button>
                                        </span>
                                    </div>
                                    <div class="text-center m-t-sm">
                                        <span>/@String.Format("{0:0.##}", Model.RestQtyCalc) @Model.UM</span>
                                    </div>

                                </div>

                            </div>

                        </div>

                        <div class="col-xs-6 card-work-reg-card  @((ViewBag.ProdType == ProductionType.MF)?String.Empty:"hidden")">
                            <div class="card card-work-reg">
                                <div class="card-header">

                                    <h3 class="card-title"><i class="fas fa-wrench  text-primary fa-lg m-r-sm"></i>@Loc.WOScrap</h3>
                                </div>

                                <div class="card-body">

                                    <div class="input-group input-group-lg">
                                        <span class="input-group-btn">
                                            <button id="b_dScrapQty" type="button" class="btn btn-plus-minus"><i class="fa fa-minus fa-lg  text-primary"></i></button>
                                        </span>
                                        <input type="number" id="scrapQty" name="ScrapQty" required class="form-control col-md-8 text-center input-lg" onblur="changeQty(this.id, 'P')" autocomplete="off" min="0" />
                                        <span class="input-group-btn">
                                            <button id="b_iScrapQty" type="button" class="btn btn-plus-minus"><i class="fa fa-plus fa-lg text-primary"></i></button>
                                        </span>
                                    </div>

                                    <div class="text-center m-t-sm">
                                        <span>/@String.Format("{0:0.##}", Model.RestScrapQtyCalc) @Model.UM</span>
                                    </div>

                                </div>
                            </div>
                        </div>

                        <div class="col-xs-6  card-work-reg-card">
                            <div class="card card-work-reg">
                                <div class="card-header">

                                    <h3 class="card-title"><i class="fas fa-times text-primary fa-lg m-r-sm"></i> @((ViewBag.ProdType == ProductionType.MF)?Loc.WOWaste:Loc.Shrinkage)</h3>
                                </div>

                                <div class="card-body">

                                    <div class="input-group input-group-lg">
                                        <span class="input-group-btn">
                                            <button id="b_dWasteQty" type="button" class="btn btn-plus-minus"><i class="fa fa-minus fa-lg  text-primary"></i></button>
                                        </span>
                                        <input type="number" id="wasteQty" name="WasteQty" required class="form-control col-md-8 text-center input-lg" onblur="changeQty(this.id, 'O')" autocomplete="off" min="0" />
                                        <span class="input-group-btn">
                                            <button id="b_iWasteQty" type="button" class="btn btn-plus-minus"><i class="fa fa-plus fa-lg text-primary"></i></button>
                                        </span>
                                    </div>
                                    <div class="text-center m-t-sm">
                                        <span>/@String.Format("{0:0.##}", Model.RestWasteQtyCalc) @Model.UM</span>
                                    </div>

                                </div>
                            </div>
                        </div>

                        <div class="col-xs-6 card-work-reg-card">
                            <div class="card card-work-reg ">
                                <div class="card-header">

                                    <h3 class="card-title"><i class="far fa-calendar-alt text-primary fa-lg m-r-sm"></i>  @Loc.Date</h3>
                                </div>
                                <div class="card-body">
                                    <div class="input-group input-group-lg">
                                        <span class="input-group-addon"><i class="far fa-calendar alt"></i></span>
                                        @Html.TextBoxFor(model => model.Date, new { @id = "Date", @class = "form-control datepicker input-lg text-center", @type = "text", @Value = @DateTime.Now.Date.ToString(Loc.DateFormat) })
                                    </div>

                                </div>
                            </div>
                        </div>

                        <div class="card-work-reg-card @((ViewBag.ProdType == ProductionType.MF)?"col-xs-12":"col-xs-6")">
                            <div class="card card-work-reg ">
                                <div class="card-body text-center">

                                    @Html.Image(ImageHelper.GetImageThumbnail(Model.Picture, 200), "", new { id = "image" })
                                    <i id="noImage" class='fal fa-image fa-3x text-muted hidden' style='opacity:0.5'></i>

                                </div>
                            </div>

                        </div>
                    </div>

                </div>

            </div>

        </div>
    </div>
</div>
};

<div class="modal inmodal fade" id="imageModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-body text-center">
                @Html.Image(ImageHelper.GetImageThumbnail(Model.Picture, 400), "alt=''", new { id = "image" })
                <i id="noImage" class='fal fa-image fa-3x text-muted hidden' style='opacity:0.5'></i>
            </div>
            <div class="modal-footer" style="text-align:center !important;">
                <button type="button" class="btn btn-primary" data-dismiss="modal">@Loc.Close</button>
            </div>
        </div>
    </div>
</div>

@{Html.RenderPartial("~/Views/Shared/Components/_IdentSerialNoIssueModal.cshtml");}

<input type="hidden" id="receiveURL" value="@Url.Action("ConfirmMat", "Manufacturing")" />
<input type="hidden" id="buttonText" value="@Loc.OK" />
<input type="hidden" id="succesText" value="@Loc.SuccessIssueMsg" />
<input type="hidden" id="requiedQty" value="@Loc.RequiredInput @Loc.Quantity" />
<input type="hidden" id="productionTypeMF" value="@ProductionType.MF" />
<input type="hidden" id="productionTypeSE" value="@ProductionType.SE" />
<input type="hidden" id="manufacturingExampleMF" value="@SiteHelpAttributeHelper.GetHelpUrl(HelpIds.ManufacturingExampleMF)" />
<input type="hidden" id="manufacturingExampleSE" value="@SiteHelpAttributeHelper.GetHelpUrl(HelpIds.ManufacturingExampleSE)" />

@section pageScripts{
    @Scripts.Render("~/bundles/manufacturing")
    @Scripts.Render("~/bundles/serialnumbers")
    <script>

        $(document).ready(function () {

            $(".datepicker").datepicker({
                format: 'dd.mm.yyyy',
                language: $('#languageDate').val()
            }).on('changeDate', function () {
                $(this).datepicker('hide');
            });

            $('#image').on("click", function () {
                $("#imageModal").modal('show');
            }).hover(function () {
                $(this).css('cursor', 'pointer');
            });

            var decPlaces = $("#WoExDecPlacesMate").val();

            $('.card-work-reg').find('input[type=number]').val(round(0, decPlaces));

            $('.card-work-reg').find('input[type=number]').blur(function () {
                $(this).val(round(Number($(this).val()), decPlaces));
            });

            $('.btn-plus-minus').click(function () {
                var control = $(this).parents("div").children(".form-control");

                if ($(this).children().hasClass("fa-plus")) {
                    control.val(Number(control.val()) + 1);
                };

                if ($(this).children().hasClass("fa-minus")) {
                    if (Number(control.val()) > 0)
                        control.val(Number(control.val()) - 1);
                };

                control.trigger('change');
                control.trigger('blur');

            });

            initializeIssuedSerialNumbers({
                serialNumberQuantityIsReached: '@Loc.SerialNumberQuantityIsReached',
                numberOfSerialNumbersIsGreaterThanOnDocument: '@Loc.NumberOfSerialNumbersIsGreaterThanOnDocument',
                serialNumberValueAlreadyExist: '@Loc.SerialNumberValueAlreadyExist',
                automaticIssueOfSerialNumbersNotPossible: '@Loc.AutomaticIssueOfSerialNumbersNotPossible',
                selectedSerialNumberDoesNotExistInWarehouse: '@Loc.SelectedSerialNumberDoesNotExistInWarehouse',
                dateDueExpiredForSerialNumber: '@Loc.DateDueExpiredForSerialNumber',
                desiredQuantity: '@Loc.DesiredQuantity',
                actualQuantity: '@Loc.ActualQuantity',
                difference: '@Loc.Difference',
                errorSaving: '@Loc.ErrorSaving',
                confirm: '@Loc.Confirm',
                cancel: '@Loc.Cancel'
            },
            {
                moveUpdateSerialNoUrl:  '@Url.Action("MoveUpdateSerialNo", "Manufacturing")',
                serialNoUpdUrl: '@Url.Action("SerialNoUpd", "SerialNumbers")',
                deleteByAcKeyAndSerialNoUrl: '@Url.Action("DeleteByAcKeyAndSerialNo", "SerialNumbers")',
                deleteIssuedByAcKeyAndSerialNo: '@Url.Action("DeleteIssuedByAcKeyAndSerialNo", "Manufacturing")',
                deleteAllIssuedByAcKey: '@Url.Action("DeleteAllIssuedByAcKey", "Manufacturing")',
                deleteUnusedItemSerialsUrl: '@Url.Action("DeleteUnusedItemSerials", "SerialNumbers")',
                createSerialNoUrl: '@Url.Action("AddItemSerialNo", "Manufacturing")',
                moveSerialNoAddSalesUrl: '@Url.Action("MoveSerialNoAddSales", "SerialNumbers")',
                getByAcKeyAndAnNoUrl: '@Url.Action("GetItemSerialNumbers", "Manufacturing")',
                serialNoAutoEditionUrl: '@Url.Action("SerialNoAutoEdition", "Manufacturing")',
                getFreeSerialNumbers: '@Url.Action("GetFreeSerialNumbers", "SerialNumbers")',
                refreshStockSerialNoOnDay: '@Url.Action("RefreshStockSerialNoOnDay", "SerialNumbers")'
                }, "issueWarehouse");

            getSerialNumbersIssueForIdent(@Model.AnNo);

        });

    function changeQty(obj, type) {

        if ($("#SerialNo").val() == "N")
            return;

        $("#serialNoType-" + @Model.AnNo).val(type);
        $("#quantity-" + @Model.AnNo).val($('#' + obj).val());

        $("#SerialNoWOTypeIssue").val('@SerialNoWOType.IssueIssue');
        $("#SerialNoMoveTypeIssue").val(type);

        checkIdentSerialNoIssue(@Model.AnNo, "M", type, 1, 'false');

    }

    async function getSerialNumbersIssueForIdent(anNo) {

        await fetch(globalIssuedSerialNumbersUrls.getByAcKeyAndAnNoUrl + "?key=" + $("#AcKey").val() + "&no=" + anNo + "&type=" + $("#serialNoType-" +anNo).val(), {
            method: "GET",
            headers: { 'Content-Type': 'application/json' }
        }).then((response) => response.json()
        ).then(async (data) => {
            $('#identSerialNoGridIssue tbody tr').remove();
            var qty = 0;
            var qtyK = 0;
            var qtyO = 0;
            var qtyP = 0;

            if (data && data.length) {
                for (var i = 0; i < data.length; i++) {
                    addSerialNumberIssueRow(data[i].SerialNo, data[i].Qty, null, data[i].DateDue);
                    qty = qty + data[i].Qty;

                    if (data[i].Type == "K")
                        qtyK = qtyK + data[i].Qty;
                    if (data[i].Type == "O")
                        qtyO = qtyO + data[i].Qty;
                    if (data[i].Type == "P")
                        qtyP = qtyP + data[i].Qty;
                }

                if ($("#serialNoType-" + @Model.AnNo).val() == "X") {
                    $("#qty").val(qtyK);
                    $("#wasteQty").val(qtyO);
                    $("#scrapQty").val(qtyP);
                }

            }

            $("#identSerialNoQuantityIssue").val(qty);
            $("#identSerialNoDifferenceIssue").val(Math.abs(toNumber($("#identSerialNoReqQuantityIssue").val())) - toNumber($("#identSerialNoQuantityIssue").val()));
            formatNumberInput($("#identSerialNoQuantityIssue"));
            formatNumberInput($("#identSerialNoDifferenceIssue"));
        });
    }

    </script>

}

@section pageCss{
    <style>
        input::-webkit-outer-spin-button,
        input::-webkit-inner-spin-button {
            -webkit-appearance: none;
            margin: 0;
        }

        input[type=number] {
            -moz-appearance: textfield;
        }
    </style>

}
