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

<div class="modal inmodal fade" id="advancePaymentConnectModal" 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.ConnectWithPreviousAdvancePayment</h3>
                    </div>
                    <div class="col-xs-2 text-right">
                        <i class="fa fa-times clickable-icon" data-dismiss="modal" title="@Loc.Close"></i>
                    </div>
                </div>
                <div class="row m-t-sm">
                    <div class="col-xs-12">
                        <div class="project-list">
                            <table id="advancePaymentPreviousMovesGrid" data-url="@Url.Action("AdvancePaymentStornoPreparedData", "AdvancePayment")" class="list-table">
                                <thead>
                                    <tr>
                                        <th width="5%">@Loc.Marked</th>
                                        <th width="20%">@Loc.Subject</th>
                                        <th width="15%">@Loc.Document</th>
                                        <th width="10%">@Loc.DocumentDate</th>
                                        <th width="10%">@Loc.Currency</th>
                                        <th width="10%">@Loc.Amount</th>
                                        <th width="20%">@Loc.SDCShort</th>
                                        <th width="10%">@Loc.SDCTime</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="btnAdvancePaymentPreviousConnect" class="btn btn-primary" onclick="connectAdvancePaymentWithPrevious()"><i class="fas fa-check m-r-xs"></i>@Loc.Connect</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>


<script>
    var $advancePaymentConnectPreviousDataTable;
    var selectedAdvPayAcKey;

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

    function connectWithPreviousAdvancePayment() {
        getAdvancePaymentPreviousMoves();
        $("#advancePaymentConnectModal").modal("show");
    }

    function getAdvancePaymentPreviousMoves() {
        $.ajax({
            type: "POST",
            data: JSON.stringify({
                AcKey: $("#AcKey").val(),
                DocType: $("#DocType").val(),
                Subject: $("#ReceiverId").val(),
            }),
            url: $("#advancePaymentPreviousMovesGrid").attr('data-url'),
            contentType: "application/json"
        }).done(function (response) {
            if (response && response.length > 0) {
                loadAdvancePaymentConnectPreviousTable(response);
                $("#btnAdvancePaymentPreviousConnect").prop("disabled", false);
            } else
                $("#btnAdvancePaymentPreviousConnect").prop("disabled", true);
        });
    }

    function loadAdvancePaymentConnectPreviousTable(AdvancePaymentCancelItems) {
        $advancePaymentConnectPreviousDataTable = $('#advancePaymentPreviousMovesGrid');
        if ($.fn.dataTable.isDataTable('#advancePaymentPreviousMovesGrid'))
            $advancePaymentConnectPreviousDataTable.DataTable().destroy();

        $advancePaymentConnectPreviousDataTable.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 cbAdvancePaymentAcKey" id="cbConnWP-'+ full.AcKey +'" onclick="selectedAdvancePaymentPreviousAcKey(\'' + full.AcKey + '\', \'' + full.SDC + '\')"  value="' + full.AcKey + '" type="checkbox" />'
                    }
                },
                { data: "Subject" },
                { data: "AcKeyView" },
                { data: "Date" },
                { data: "Currency" },
                {
                    data: "Total", render: function (data, type, full) {
                        return $.fn.dataTable.render.number('.', ',', $("#DefaultDecimalPlacesPrice").val(), '').display(data);
                    }
                },
                { data: "SDC" },
                { data: "SDCTime" }
            ],
            initComplete: function (settings, json) {
                $advancePaymentConnectPreviousDataTable.DataTable().rows().recalcHeight().draw();
                $("#advancePaymentCancelGrid_wrapper .dataTables_scrollBody").height("225px");
            }
        });

        initializeNumberInputs();
    }

    function selectedAdvancePaymentPreviousAcKey(acKey, sdc) {
        if ($('input.cbAdvancePaymentAcKey:checked').length > 1) {
            $("#cbConnWP-" + acKey).prop("checked", false);
            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                type: "error",
                text: "@Loc.OnlyOneDocumentCanBeSelected",
                buttons: [
                    {
                        icon: 'fa fa-check',
                        text: "@Loc.Confirm",
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });

            return;
        } else if (!sdc) {
            $("#cbConnWP-" + acKey).prop("checked", false);
            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                type: "error",
                text: "@Loc.AdvancePaymentHasNotBeenFiscalizedEnterTheNumberAndTimeOfIssuance",
                buttons: [
                    {
                        icon: 'fa fa-check',
                        text: "@Loc.Confirm",
                        action: function () {
                            $("#advancePaymentConnectModal").modal("hide");
                            $("#RefundRelatedDoc").focus();
                        },
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });

            return;
        }

        selectedAdvPayAcKey = acKey;
    }

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

            return;
        }

        if ($("#connection-" + selectedAdvPayAcKey).length > 0) {
            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                type: "error",
                text: "@Loc.ConnectionAlreadyExists",
                buttons: [
                    {
                        icon: 'fa fa-check',
                        text: "@Loc.Confirm",
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });

            return;
        }

        swapLoadingIcon(true, "btnAdvancePaymentPreviousConnect");
        $.get("@Url.Action("ConnectWithOldAdvPay", "AdvancePayment")" + "?acKey=" + selectedAdvPayAcKey + "&acLnkKey=" + $("#AcKey").val(), function (response) {
            swapLoadingIcon(false, "btnAdvancePaymentPreviousConnect");
            if (response && response.length > 0) {
                AddInvoiceDocumentConnections(response, 'A');

                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    type: "success",
                    text: "@Loc.Success",
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: "@Loc.Confirm",
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });
            } else {
                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    type: "error",
                    text: "@Loc.GeneralError",
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: "@Loc.Confirm",
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });
            }
        });
    }

    function openPartialCancelHelp() {
        if ($("#AdvancePaymentType").val() === "@AdvancePaymentType.Issued")
            window.open('@SiteHelpAttributeHelper.GetHelpUrl(HelpIds.AdvancePaymentCancelSupplier)', '_blank');
        else
            window.open('@SiteHelpAttributeHelper.GetHelpUrl(HelpIds.AdvancePaymentCancelBuyer)', '_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>