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

@model PantheonRA.WebApi.Contracts.PaWoExItem

@{
    Model.ProdType = ViewBag.ProdType;
    string issuer = (string)ViewBag.Issuer;
    bool _autoInvoSerialNo = (bool)ViewBag.AutoInvoSerialNo;
    var _isMobile = Request.Browser.IsMobileDevice;
}

@Html.HiddenFor(model => model.WoExDecPlacesMate)

@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("Service/_ProcessingTabNavigation")

            <div class="tab-content">
                <div class="row buttons-tabbed @(_isMobile ? "hidden" : "")">

                    @if (PantheonRA.BackOffice.CurrentUser.CanAccess(Permissions.PRODUCTION))
                    {
                        @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(this)"
                                        }
                                   }
                               }
                           })
                    }

                </div>

                @Html.HiddenFor(model => model.AcKey)
                @Html.HiddenFor(model => model.AnNo)
                @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="divided-content">
                    <div class="divided-content-main divided-content-full">
                        <div class="row document-head @(_isMobile ? "d-head-m-b-0" : "")">

                            @* AcKey *@
                            <div class="col-xs-4 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>

                            @* Ident *@
                            <div class="col-xs-4 document-head-disabled-input">
                                <div class="form-group">
                                    @Html.LabelFor(model => model.Ident, Loc.Ident, new { @class = "control-label m-t-xs" })
                                    <input class="form-control" id="ident" disabled="disabled" type="text" value=" @Model.Ident">
                                </div>
                            </div>

                            @* Position *@
                            <div class="col-xs-4 document-head-disabled-input">
                                <div class="form-group">
                                    @Html.LabelFor(model => model.AcKey, Loc.Position, new { @class = "control-label m-t-xs" })
                                    <input class="form-control" id="position" disabled="disabled" type="text" value=" @Model.AnNo">
                                </div>
                            </div>

                        </div>
                        <div class="project-list">
                            <div class="row">
                                <div class="form-horizontal form-md @(_isMobile ? string.Empty : "col-lg-6 col-md-8")">
                                    <div class="@(_isMobile ? "col-xs-12" : "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="@(_isMobile ? "col-xs-12" : "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-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="@(_isMobile ? "col-xs-12" : "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>@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="@(_isMobile ? "col-xs-12" : "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">
                                                <input id="date" type="date" name="Date" class="input-lg text-center col-xs-12" value="@DateTime.Now.Date.ToString("yyyy-MM-dd")">
                                            </div>
                                        </div>
                                    </div>
                                    <div class="@(_isMobile ? "col-xs-12" : "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-warehouse text-primary fa-lg m-r-sm"></i>  @Loc.Warehouse</h3>
                                            </div>
                                            <div class="card-body text-center">
                                                @if (_isMobile)
                                                {
                                                    <span class="form-control fa-lg" name="Issuer" id="mWarehouse">@ViewBag.Issuer</span>
                                                }
                                                else
                                                {
                                                    <select id="issueWarehouse" name="Issuer" 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 class="text-center m-t-sm">
                                                <span>@Loc.Stock: </span>
                                                <span id="stock">@String.Format("{0:0.##}", ViewBag.Stock)</span>
                                                <span> @Model.UM</span>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="@(_isMobile ? "col-xs-12" : "col-xs-6") card-work-reg-card">
                                        <div class="card card-work-reg ">
                                            <div class="card-body text-center" style="height:100%">
                                                @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 class="divided-content-side">
                        <div class="tabs-container">
                            <ul class="nav nav-tabs horizontal-menu" id="tabNav">
                                <li class="active divided-tab-1" id="homeTab"><a id="tabCaption" data-toggle="tab" href="#warehouse-list" class="local-tab">@Loc.Warehouse</a></li>
                            </ul>
                        </div>
                        <div class="tab-content" id="sideNavBar">
                            <div id="warehouse-list" class="tab-pane additonal-options m-l-n-sm m-r-n-sm" style="padding-bottom:100px" data-control="#issueWarehouse">

                                @foreach (var item in ViewBag.Warehouses)
                                {
                                    <div class="border-bottom p-l-10 warehouse-list-item @(ViewBag.Issuer == item.Id ? "active" : string.Empty)" data-value="@item.Id" data-display="@item.Name">
                                        <a data-toggle="tab">
                                            <h3 class="text-default" data-toggle="tab">
                                                @item.Name
                                                <i class="fa text-primary p-r-sm pull-right @(ViewBag.Issuer == item.Id ? "fa-check" : string.Empty)"></i>
                                            </h3>
                                        </a>
                                    </div>
                                }
                            </div>

                            <button type="button" class="btn btn-rounded btn-back btn-close-side-panel">
                                <i class="fas fa-chevron-left"></i>
                            </button>

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

            @if (CurrentUser.CanAccess(Permissions.PRODUCTION))
            {
                <div class="@(_isMobile ? string.Empty : "hidden")">
                    <a href="@Url.Action("WorkOrderMaterials", "Manufacturing", new { key = Model.AcKey })" id="back" class="btn btn-light btn-rounded text-primary btn-back">
                        <i class="fas fa-chevron-left"></i>
                    </a>
                    <div class="cont-right m-r-n-sm @(Model.IssueFinished == "Y" ? "hidden" : String.Empty) ">
                        <button id="mConfirmButton" role="button" class="btn btn-primary pull-right btn-rounded m-l-sm" onclick="saveMaterial(this);">
                            <i class="fa fa-check"></i> <span>@Loc.Confirm</span>
                        </button>
                        <button id="comment" type="button" class="btn pull-right btn-rounded hidden">
                            <i class="fas fa-comment"></i>
                        </button>
                    </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 btn-rounded" 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/services")
    @Scripts.Render("~/bundles/serialnumbers")
<script>
        $(document).ready(function () {

            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(roundToPercision(decPlaces, Number(control.val()) + 1));
                };

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

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

            $('#comment').on("click", function () {
                $('#sideNavBar>#home').addClass("fade").addClass("in").addClass("active");
                $(".divided-content").addClass("divided-content-side-opened").removeClass("divided-content-side-closed");
            });

            $('#apply').on("click", function () {
                $(".divided-content").addClass("divided-content-side-closed").removeClass("divided-content-side-opened");
            });

            $('#back1').on("click", function () {
                $(".divided-content").addClass("divided-content-side-closed").removeClass("divided-content-side-opened");
            });

            $('#image').on("click", function () {
                $("#imageModal").modal('show');
            });

            $('#mWarehouse').on("click", function () {
                $('#sideNavBar>.tab-pane').removeClass("active");
                $('#sideNavBar>.nav>.nav-item').removeClass("active");
                $('#sideNavBar>#warehouse-list').addClass("fade").addClass("in").addClass("active");

                $(".divided-content").addClass("divided-content-side-opened").removeClass("divided-content-side-closed");
            });

            $('.warehouse-list-item').on("click", function () {
                $('.warehouse-list-item').find('i').removeClass('fa-check');
                $('.warehouse-list-item').removeClass('active');

                $('#issueWarehouse').val($(this).data("value"));
                $('#mWarehouse').text($(this).data("value"));

                $(this).find('i').toggleClass('fa-check');
                $(this).addClass("active");

                loadIdentStockForWarehouse($('#ident').val(), $(this).data("value"));
            });

            $('#issueWarehouse').on("change", function () {
                loadIdentStockForWarehouse($('#ident').val(), $('#issueWarehouse').val());
            });

            $('.btn-back').on("click", function () {
                $(".divided-content").addClass("divided-content-side-closed").removeClass("divided-content-side-opened");
            });

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

        function loadIdentStockForWarehouse(ident, warehouse) {
            $.ajax({
                type: 'GET',
                url: '@Url.Action("GetIdentStockOnWarehouse", "Manufacturing")',
                data: {
                    ident: ident,
                    warehouse: warehouse
                },
                success: function (response) {
                    $('#stock').text(response.Stock);
                },
                error: function (error) {
                    console.error(error);
                }
            });
        }
</script>
}
