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

<div class="modal inmodal fade" id="advancePaymentCancelModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-xxl" role="document">
        <div class="modal-content">
            <div class="modal-body p-sm">
                <div class="row border-bottom">
                    <div class="col-xs-10">
                        <h3>@Loc.CloseAdvancePayment</h3>
                    </div>
                    <div class="col-xs-2 text-right">
                        <a class="btn-transparent m-r-sm" onclick="openPartialCancelUserManualHelp()" title="@Loc.CheckSamples"><i class="fas fa-book-reader clickable-icon"></i></a>
                        <a class="btn-transparent m-r-sm" onclick="openPartialCancelHelp()" title="@Loc.CheckInstructions"><i class="fas fa-question clickable-icon"></i></a>
                        <i class="fa fa-times clickable-icon" data-dismiss="modal" title="@Loc.Close"></i>
                    </div>
                </div>
                <div class="row padding-top-10">
                    <div class="col-xs-4 employees-title-padding">
                        <div class="form-group">
                            <label class="col-md-3 control-label padding-top-10">@Loc.Date</label>
                            <div class="col-md-8">
                                <div class="input-group">
                                    <span class="input-group-addon">
                                        <i class="far fa-calendar alt"></i>
                                    </span>
                                    @Html.TextBox("AdvancePaymentCancelDate", DateTime.Now.ToString(Loc.DateFormat),
                                        HtmlAttributesHelper.CreateInputAttributes("form-control datepicker", "AdvancePaymentCancelDate", false, Loc.Date))
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-xs-7">
                        <div class="form-group">
                            <label class="col-md-4 control-label padding-top-10">@Loc.DocType</label>
                            <div class="col-md-8 employees-title-padding">
                                <select id="AdvancePaymentCancelDocTypeSelect" class="form-control custom-select">
                                    <option></option>
                                    @foreach (var item in ViewBag.DocumentTypes)
                                    {
                                        <option value="@item.IdView">
                                            @item.Value
                                        </option>
                                    }
                                </select>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="row m-t-sm">
                    <div class="col-xs-12">
                        <div class="project-list">
                            <table id="advancePaymentCancelGrid" data-url="@Url.Action("AdvancePaymentPrepareCancel", "AdvancePayment")" class="list-table">
                                <thead>
                                    <tr>
                                        <th width="5%">@Loc.Marked</th>
                                        <th width="15%">@Loc.Subject</th>
                                        <th width="15%">@Loc.Document</th>
                                        <th width="10%">@Loc.DocumentDate</th>
                                        <th width="10%">@Loc.Currency</th>
                                        <th width="10%" class="dt-head-right">@Loc.Expenses</th>
                                        <th width="10%" class="dt-head-right">@Loc.PaidAdvancePayment</th>
                                        <th width="10%" class="dt-head-right">@Loc.Difference</th>
                                        <th width="10%" class="dt-head-right">@Loc.ForClosing</th>
                                        <th width="5%">@Loc.NewDocument</th>
                                    </tr>
                                </thead>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <div class="row">
                    <div class="col-xs-12 text-right">
                        <button type="button" class="btn btn-link" data-dismiss="modal"><i class="fas fa-times m-r-xs"></i>@Loc.Cancel</button>
                        <button type="button" id="btnAdvancePaymentCancelCreate" class="btn btn-primary" onclick="createAdvancePaymentCancel()"><i class="fas fa-check m-r-xs"></i>@Loc.CreateDocument</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>


<script>
    var $advancePaymentCancelDataTable;
    var advancePaymentCancelIdents = [];

    $(document).ready(function () {
    });

    function advancePaymentCancelModal() {
        getAdvancePaymentCancelItems();
        if ($("#DocTypeSelect option:selected").attr("data-docTypeAssmbly"))
            $("#AdvancePaymentCancelDocTypeSelect").val($("#DocTypeSelect option:selected").attr("data-docTypeAssmbly").substring(0, 3));

        $("#advancePaymentCancelModal").modal("show");
    }

    function getAdvancePaymentCancelItems() {
        $.ajax({
            type: "POST",
            data: JSON.stringify({
                AcKey: $("#AcKey").val(),
                DateRate: $("#Date").datepicker("getDate"), // TODO: From Settings AK when currency is added
                Date: $("#AdvancePaymentCancelDate").datepicker("getDate"),
                Subject: $("#AdvancePaymentType").val() === "@AdvancePaymentType.Issued" ? $("#IssuerId").val() : $("#ReceiverId").val(),
                AdvancePaymentType: $("#AdvancePaymentType").val(),
            }),
            url: $("#advancePaymentCancelGrid").attr('data-url'),
            contentType: "application/json"
        }).done(function (response) {
            if (response && response.length > 0) {
                loadAdvancePaymentCancelTable(response);
                $("#btnAdvancePaymentCancelCreate").prop("disabled", false);
            } else
                $("#btnAdvancePaymentCancelCreate").prop("disabled", true);
        });
    }

    function loadAdvancePaymentCancelTable(AdvancePaymentCancelItems) {
        advancePaymentCancelIdents = AdvancePaymentCancelItems;
        $advancePaymentCancelDataTable = $('#advancePaymentCancelGrid');
        if ($.fn.dataTable.isDataTable('#advancePaymentCancelGrid'))
            $advancePaymentCancelDataTable.DataTable().destroy();

        $advancePaymentCancelDataTable.DataTable({
            serverSide: false,
            ajax: undefined,
            scroller: false,
            responsive: false,
            paging: false,
            info: false,
            data: AdvancePaymentCancelItems,
            columns: [
                {
                    data: "Marked",
                    className: 'dt-body-center',
                    render: function (data, type, full) {
                        return '<input class="ackey" id="selected-' + full.AcKey + '" onclick=selectedAdvancePaymentCancelItem("' + full.AcKey + '")  value="' + full.AcKey + '" type="checkbox" checked />'
                    }
                },
                { data: "Subject" },
                { data: "AcKeyView" },
                { data: "Date" },
                { data: "Currency" },
                {
                    data: "TotalPrice",
                    render: function (data, type, full) {
                        return '<input class="form-control numberInput text-right" id="adpTotalPrice-' + full.AcKey + '" value="' + full.TotalPrice + '" data-maxTotalPrice="' + full.TotalPrice + '" step="2" type="text" autocomplete="off" disabled />'
                    },
                    className: 'dt-body-right'
                },
                {
                    data: "Paid",
                    render: function (data, type, full) {
                        return '<input class="form-control numberInput text-right" id="adpPaid-' + full.AcKey + '" value="' + full.Paid + '" step="2" type="text" autocomplete="off" disabled />'
                    },
                    className: 'dt-body-right'
                },
                {
                    data: "Difference",
                    render: function (data, type, full) {
                        return '<input class="form-control numberInput text-right" id="adpDifference-' + full.AcKey + '" value="' + full.Difference + '" step="2" type="text" autocomplete="off" disabled />'
                    },
                    className: 'dt-body-right'
                },
                {
                    data: "ForClosing",
                    render: function (data, type, full) {
                        return '<input class="form-control numberInput text-right" id="adpForClosing-' + full.AcKey + '" onchange=selectedAdvancePaymentCancelItem("' + full.AcKey + '") value="' + full.ForClosing + '" step="2" type="text" autocomplete="off" />'
                    },
                    className: 'dt-body-right'
                },
                {
                    data: "CreateNewDoc",
                    className: 'dt-body-center',
                    render: function (data, type, full) {
                        return '<input id="adpNewDocument-' + full.AcKey + '" value="' + data + '" type="checkbox" onchange=selectedAdvancePaymentCancelItem("' + full.AcKey + '") checked />'
                    }
                },
            ],
            initComplete: function (settings, json) {
                $advancePaymentCancelDataTable.DataTable().rows().recalcHeight().draw();
                $("#advancePaymentCancelGrid_wrapper .dataTables_scrollBody").height("225px");
            }
        });

        initializeNumberInputs();
    }

    function selectedAdvancePaymentCancelItem(acKey) {
        var index = advancePaymentCancelIdents.findIndex(x => x.AcKey === acKey);

        var maxTotalPrice = toNumber($("#adpTotalPrice-" + acKey).attr("data-maxTotalPrice"));
        if (maxTotalPrice < toNumber($("#adpTotalPrice-" + acKey).val())) {
            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                type: "error",
                text: "@Loc.PriceForClosingExceedsAdvancePaymentTotalPrice",
                buttons: [
                    {
                        icon: 'fa fa-check',
                        text: "@Loc.Confirm",
                        closeOnAction: true,
                        action: function () {
                            $("#adpTotalPrice-" + acKey).val(maxTotalPrice);
                            formatNumberInput($("#adpTotalPrice-" + acKey));
                            changeAdvancePaymentCanceltemData(acKey, index);
                        },
                        type: 'primary'
                    }
                ]
            });
        } else
            changeAdvancePaymentCanceltemData(acKey, index);
    }

    function changeAdvancePaymentCanceltemData(acKey, index) {
        if (index !== -1) {
            advancePaymentCancelIdents[index].Marked = $("#selected-" + acKey).is(':checked') ? "@Status.Active" : "@Status.Inactive";
            advancePaymentCancelIdents[index].CreateNewDoc = $("#adpNewDocument-" + acKey).is(':checked') ? "@Status.Active" : "@Status.Inactive";
            advancePaymentCancelIdents[index].ForClosing = formatDisplay(2, $("#adpForClosing-" + acKey).val(), true);
        }
    }

    function createAdvancePaymentCancel() {
        if (!advancePaymentCancelIdents || !advancePaymentCancelIdents.some(x => x.Marked === "@Status.Active")) {
            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                type: "error",
                text: "@Loc.DocumentMustBeSelected",
                buttons: [
                    {
                        icon: 'fa fa-check',
                        text: "@Loc.Confirm",
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });

            return;
        }

        var validationMsg = "";
        if (!$("#AdvancePaymentCancelDate").datepicker("getDate"))
            validationMsg = "@Loc.DateMustBeSelected";
        else if (!$("#AdvancePaymentCancelDocTypeSelect option:selected").val())
            validationMsg = "@Loc.DocTypeMustBeSelected";

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

            return;
        }

        swapLoadingIcon(true, "btnAdvancePaymentCancelCreate");
        $.ajax({
            type: "POST",
            data: JSON.stringify({
                AcKey: $("#AcKey").val(),
                DocType: $("#AdvancePaymentCancelDocTypeSelect option:selected").val(),
                DateRate: $("#Date").datepicker("getDate"), // TODO: From Settings AK when currency is added
                Date: $("#AdvancePaymentCancelDate").datepicker("getDate"),
                AdvancePaymentType: $("#AdvancePaymentType").val(),
                Subject: $("#AdvancePaymentType").val() === "@AdvancePaymentType.Issued" ? $("#IssuerId").val() : $("#ReceiverId").val(),
                CancelItems: advancePaymentCancelIdents
            }),
            url: '@Url.Action("AdvancePaymentCancel", "AdvancePayment")',
            contentType: "application/json"
        }).done(function (data) {
            var modalType = "";
            var modalText = "";

            if (data.Success) {
                modalType = "success";
                modalText = "@Loc.CreatedCancelAdvancePaymentsNumbers" + " " + data.AcKeyCopy;
            } else {
                modalType = "alert";
                modalText = data.Error;
            }

            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                type: modalType,
                text: modalText,
                buttons: [
                    {
                        icon: 'fa fa-check',
                        text: "@Loc.Confirm",
                        action: function () {
                            var url = $("#AdvancePaymentType").val() === "@AdvancePaymentType.Issued" ? "@Url.Action("EditIssuedAdvancePayment", "AdvancePayment")" : "@Url.Action("EditReceivingAdvancePayment", "AdvancePayment")";
                            if (data.Success) {
                                window.location = url + "?id=" + data.AcKey;
                            }
                        },
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });

            swapLoadingIcon(false, "btnAdvancePaymentCancelCreate");
        });
    }

    function openPartialCancelHelp() {
        if ($("#AdvancePaymentType").val() === "@AdvancePaymentType.Issued")
            window.open('@SiteHelpAttributeHelper.GetHelpUrl(HelpIds.AdvancePaymentCancelSupplier)', '_blank');
        else
            window.open('@SiteHelpAttributeHelper.GetHelpUrl(HelpIds.AdvancePaymentCancelBuyer)', '_blank');
    }

    function openPartialCancelUserManualHelp() {
        if($("#AdvancePaymentType").val() === "@AdvancePaymentType.Issued")
            window.open('@SiteHelpAttributeHelper.GetHelpUrl(HelpIds.ExampleIssuedAdvancePaymentCancel)', '_blank');
        else
            window.open('@SiteHelpAttributeHelper.GetHelpUrl(HelpIds.ExampleReceivedAdvancePaymentCancel)', '_blank');
    }

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