@model PantheonRA.BackOffice.Models.FixedAssetCreateViewModel
@using PantheonRA.BackOffice.Models
@using PantheonRA.BackOffice.Enums
@using PantheonRA.BackOffice;

@{
    ViewBag.Title = Loc.Edit;
}

@Html.Hidden("UrlFixedAssets", Url.Action("Index", "FixedAssets"))
@Html.Hidden("UrlSave", Url.Action("Save", "FixedAssets"))
@Html.Hidden("TxtConfirm", Loc.Confirm)
@Html.Hidden("TxtInfo", Loc.Info)
@Html.Hidden("TxtValidationModalError", Loc.ValidationModalError)

<div class="wrapper wrapper-content">
    <div class="tabs-container">
        @Html.Partial("~/Views/Products/_CodeListTabNavigation.cshtml")
        <div class="tab-content">
            <div class="row buttons-tabbed" id="fixedAsset-buttons">
                @Html.Partial("_FormButtons", new FormButtonsViewModel
                {
                    BackUrl = Url.Action("Index", "FixedAssets"),
                    SaveButtonGroup = new FormButtonGroup
                    {
                        Buttons = new List<FormButton>
                             {
                                 new FormButton { Text = Loc.Save, Icon = "fa fa-save fa-lg", IsSubmit = true, OnClick="saveFixedAsset()" }
                             }
                    },
                })

                <button id="invoiceDelete" type="button" onclick="canRemoveFixedAsset()" title="@Loc.Delete"
                        class="btn btn-danger btn-outline pull-right collapsable-form-button @(!string.IsNullOrEmpty(Model.InventNum) ? string.Empty : " hidden")">
                    <i class="far fa-trash-alt m-r-xs"></i>
                    <span class="visible-lg-inline visible-md-inline">@Loc.Delete</span>
                </button>
            </div>


            <div class="divided-content">
                @{
                    Html.RenderPartial("~/Views/FixedAssets/_CreateFixedAssetFormPartial.cshtml", Model);
                }
            </div>
        </div>
    </div>
</div>

<input type="hidden" id="RemoveFixedAssetsUrl" value="@Url.Action("Remove", "FixedAssets")" />
<input type="hidden" id="IsFixedAssetInUseUrl" value="@Url.Action("IsFixedAssetInUse", "FixedAssets")" />
<input type="hidden" id="FixedAssetsIndexUrl" value="@Url.Action("Index", "FixedAssets")" />
<input type="hidden" id="FixedAssetsAlreadyInUseLoc" value="@Loc.FixedAssetsAlreadyInUse" />
<input type="hidden" id="DeleteWasNotSuccessfulLoc" value="@Loc.DeleteWasNotSuccessful" />
<input type="hidden" id="ConfirmDeleteLoc" value="@Loc.ConfirmDeleteMessage" />
<input type="hidden" id="GeneralErrorLoc" value="@Loc.GeneralError" />
<input type="hidden" id="ConfirmLoc" value="@Loc.Confirm" />
<input type="hidden" id="YesLoc" value="@Loc.Yes" />
<input type="hidden" id="NoLoc" value="@Loc.No" />

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

    <script>
        function getFaData() {
            return {
                InventNum: $("#InventNum").val(),
                SetOf: $("#SetOf option:selected").val(),
                Active: $("#Active").val(),
                Name: $("#Name").val(),
                TypeSpec: $("#TypeSpec").val(),
                CarRegNo: $("#CarRegNo").val(),
                Quantity: $("#Quantity").val(),
                AmountAcqTxt: $("#AmountAcq").val(),
                DateOfAcqString: $("#DateOfAcq").val(),
                DateOfActivationString: $("#DateOfActivation").val(),
            };
        }

        function saveFixedAsset() {
            $('[id^="vl-"]').text("");
            $('[id^="vl-"]').css("display", "none");
            $.ajax({
                url: $("#UrlSave").val(),
                dataType: 'json',
                contentType: 'application/json',
                method: "POST",
                data: JSON.stringify(getFaData()),
                success: function (data) {
                    if (data.length == 1 && data[0].Key == 'id') {
                        let url = $("#UrlFixedAssets").val() + '?id=' + data[0].Value;

                        window.location.replace(url);
                    }

                    handleErrors(data);
                },
                fail: function (error) {
                    swal(error);
                }
            });
        }

        function handleErrors(errors) {
            if (!errors || errors.length == 0
                || errors.length == 1 && errors[0].Key == 'id') {
                return;
            }

            for (i = 0; i < errors.length; i++) {
                let id = "#vl-" + errors[i].Key;
                let err = errors[i].Value;

                $(id).text(err);
                $(id).css("display", "block");
            }
        }

        function canRemoveFixedAsset() {
            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                type: "question",
                text: $("#ConfirmDeleteLoc").val(),
                buttons: [
                    {
                        icon: 'fa fa-times',
                        text: $("#NoLoc").val(),
                        closeOnAction: true,
                        type: 'ghost'
                    },
                    {
                        icon: 'fa fa-check',
                        text: $("#YesLoc").val(),
                        action: async function () {
                            var elementId = $("#InventNum").val();
                            const config = {
                                method: 'POST',
                                headers: {
                                    'Accept': 'application/json',
                                    'Content-Type': 'application/json'
                                },
                                body: JSON.stringify({ id: elementId })
                            };

                            const response = await fetch($("#IsFixedAssetInUseUrl").val(), config);
                            if (response.ok) {
                                const json = await response.json();
                                if (json.Status !== true)
                                    removeFixedAsset();
                                else {
                                    $().customModal({
                                        destroyOnClose: true,
                                        showCloseButton: true,
                                        type: "alert",
                                        text: $("#FixedAssetsAlreadyInUseLoc").val(),
                                        buttons: [
                                            {
                                                icon: 'fa fa-check',
                                                text: $("#ConfirmLoc").val(),
                                                closeOnAction: true,
                                                type: 'primary'
                                            }
                                        ]
                                    });
                                }
                            }
                        },
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });
        }

        async function removeFixedAsset() {
            var elementId = $("#InventNum").val();
            const config = {
                method: 'POST',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ id: elementId })
            };

            const response = await fetch($("#RemoveFixedAssetsUrl").val(), config);
            if (response.ok) {
                const json = await response.json();
                if (json.IsDeleted === true)
                    window.location = $("#FixedAssetsIndexUrl").val();
                else {
                    $().customModal({
                        destroyOnClose: true,
                        showCloseButton: true,
                        type: "alert",
                        text: $("#DeleteWasNotSuccessfulLoc").val(),
                        buttons: [
                            {
                                icon: 'fa fa-check',
                                text: $("#ConfirmLoc").val(),
                                closeOnAction: true,
                                type: 'primary'
                            }
                        ]
                    });
                }
            }
        }
    </script>
}

<style>
    .divided-content-toggle {
        top: 30px !important;
    }
</style>