@using PantheonRA.BackOffice.Enums

<div class="modal inmodal fade" id="invoiceErrorCorrectiveModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-xl" role="document">
        <div class="modal-content">
            <div class="modal-body p-sm">
                <div class="row border-bottom">
                    <div class="col-xs-10">
                        <h4 class="m-t-xs m-b-xs">@Loc.CorrectFiscalInvoice</h4>
                    </div>
                    <div class="col-xs-2 text-right">
                        <a class="btn-transparent m-r-sm" href="@SiteHelpAttributeHelper.GetHelpUrl(HelpIds.MoveErrorCorrective)" target="_blank"><i class="fas fa-question clickable-icon"></i></a>
                        <i class="fa fa-times pull-right clickable-icon m-t-xs m-b-xs" data-dismiss="modal"></i>
                    </div>
                </div>
                <div class="tabs-container">
                    <ul class="nav nav-tabs horizontal-menu custom-scrollable-tabs">
                        <li class="active"><a data-toggle="tab" href="#invoiceErrorCorrectiveCreateTab" class="local-tab">@Loc.CreateDocumentFull</a></li>
                        <li><a data-toggle="tab" href="#invoiceErrorCorrectiveTransferTab" class="local-tab">@Loc.DownloadStatistics</a></li>
                    </ul>

                    <div class="tab-content">
                        <div id="invoiceErrorCorrectiveCreateTab" class="tab-pane fade in active">
                            <div class="form-horizontal">
                                <div class="m-t-sm">
                                    <div class="form-group">
                                        <label class="control-label col-xs-4 control-label-left">@Loc.CancelDocumentType</label>
                                        <div class=" col-xs-5">
                                            @Html.DropDownList("invoiceErrorCorrectiveCancelDocType",
                                                new SelectList(ViewBag.InvoiceErrorCorrectiveCancelDocTypes != null ? ViewBag.InvoiceErrorCorrectiveCancelDocTypes : new List<string>(), "Id", "Value"), "",
                                                HtmlAttributesHelper.CreateInputAttributes("form-control invoiceErrorCorrctiveInput", "invoiceErrorCorrectiveCancelDocType", false, Loc.CancelDocumentType, true))
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <label class="control-label col-xs-4 control-label-left">@Loc.CreateOnDocumentType</label>
                                        <div class=" col-xs-5">
                                            @Html.DropDownList("invoiceErrorCorrectiveCreateOnDocType",
                                                new SelectList(ViewBag.InvoiceErrorCorrectiveCreateOnDocTypes != null ? ViewBag.InvoiceErrorCorrectiveCreateOnDocTypes : new List<string>(), "Id", "Value"), "",
                                                HtmlAttributesHelper.CreateInputAttributes("form-control invoiceErrorCorrctiveInput", "invoiceErrorCorrectiveCreateOnDocType", false, Loc.CreateOnDocumentType, true))
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <label class="control-label col-xs-4 control-label-left">@Loc.Date</label>
                                        <div class=" col-xs-5">
                                            <div class="input-group">
                                                <span class="input-group-addon">
                                                    <i class="far fa-calendar alt"></i>
                                                </span>
                                                <input id="invoiceErrorCorrectiveDate" value="@DateTime.Now.ToString(Loc.DateFormat)" class="form-control datepicker invoiceErrorCorrctiveInput" />
                                            </div>
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <label class="control-label col-xs-4 control-label-left">@Loc.CorrectExistingInvoice</label>
                                        <div class=" col-xs-8 m-t-xs">
                                            <input type="checkbox" class="form-control js-switch invoiceErrorCorrectiveSwitch" id="correctExistingInvoice" />
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div id="invoiceErrorCorrectiveTransferTab" class="tab-pane fade">
                            <div class="project-list m-t-xs">
                                <table id="invoiceTransferStatisticGrid" data-grid-id="invoice-transfer-stat" class="list-table">
                                    <thead>
                                        <tr>
                                            <th width="15%">@Loc.KeyFrom</th>
                                            <th width="15%">@Loc.KeyTo</th>
                                            <th width="10%">@Loc.Error</th>
                                            <th width="60%">@Loc.Comment</th>
                                        </tr>
                                    </thead>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-ghost" data-dismiss="modal"><i class="fa fa-times m-r-xs"></i>@Loc.Cancel</button>
                <button id="invoiceErrorCorrectiveBtnCreate" onclick="createInvoiceErrorCorrective()" type="button" class="btn btn-primary" data-dismiss="modal">
                    <i class="fa fa-check m-r-xs"></i>
                    <span id="invoiceErrorCorrectiveBtnText">@Loc.Create</span>
                </button>
            </div>
        </div>
    </div>
</div>

<script>
    $(document).ready(function () {
        var elems = Array.prototype.slice.call(document.querySelectorAll('.invoiceErrorCorrectiveSwitch'));
        elems.forEach(function (html) {
            var switchery = new Switchery(html, { size: 'small' });
        });

        $("#correctExistingInvoice").on("change", function () {
            if ($("#correctExistingInvoice").is(":checked")) {
                $("#invoiceErrorCorrectiveBtnText").text("@Loc.Fix");
                $(".invoiceErrorCorrctiveInput").attr("disabled", true);
            } else {
                $("#invoiceErrorCorrectiveBtnText").text("@Loc.Create");
                $(".invoiceErrorCorrctiveInput").attr("disabled", false);
            }
        });


        $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
            var target = $(e.target).attr("href");
            if ((target == '#invoiceErrorCorrectiveTransferTab')) {
                $(".modal-footer").attr("hidden", true);
            } else {
                $(".modal-footer").attr("hidden", false);
            }
        });
    });

    function openInvoiceErrorCorrectiveModal() {
        if ($("#CanceledInvoice").val() === "True") {
            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                type: "error",
                text: "@Loc.CancelDocumentAlreadyExistsCorrectionNotPossible",
                buttons: [
                    {
                        icon: 'fa fa-check',
                        text: "@Loc.Confirm",
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });

            return;
        }

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

            return;
        }

        $('[href="#invoiceErrorCorrectiveCreateTab"]').tab('show');

        if ($("#DocTypeSelect option:selected").attr("data-docTypeCancel"))
            $("#invoiceErrorCorrectiveCancelDocType").val($("#DocTypeSelect option:selected").attr("data-docTypeCancel"));
        else
            $("#invoiceErrorCorrectiveCancelDocType").val("");

        if ($("#DocTypeSelect option:selected").val())
            $("#invoiceErrorCorrectiveCreateOnDocType").val($("#DocTypeSelect option:selected").val());
        else
            $("#invoiceErrorCorrectiveCreateOnDocType").val("");

        if ($("#correctExistingInvoice").is(":checked"))
            $("#correctExistingInvoice").click();

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

    function createInvoiceErrorCorrective() {
        if ($("#correctExistingInvoice").is(":checked"))
            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                type: "alert",
                text: "@Loc.MarkInvoiceAsErrorCorrective",
                buttons: [
                    {
                        icon: 'fa fa-times',
                        text: '@Loc.No',
                        closeOnAction: true,
                        type: 'ghost'
                    },
                    {
                        icon: 'fa fa-check',
                        text: "@Loc.Yes",
                        action: function () {
                            invoiceErrorCorrective();
                        },
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });
        else
            createPositiveAndStornoDocCG()
    }

    function createPositiveAndStornoDocCG() {
        invoiceErrorCorrectiveSwapLoadingIcon(true, "invoiceErrorCorrectiveBtnCreate", "fa fa-plus");

        $.post('@Url.Action("CreatePositiveAndStornoDocCG", "Move")?AcKey=' + $("#AcKey").val()
            + "&DocTypeCancel=" + $("#invoiceErrorCorrectiveCancelDocType option:selected").val()
            + "&DocTypePositive=" + $("#invoiceErrorCorrectiveCreateOnDocType option:selected").val()
            + "&Date=" + $("#invoiceErrorCorrectiveDate").datepicker("getDate").toISOString(),
            function (data) {
                if (data && data.length > 0) {
                    $().customModal({
                        destroyOnClose: true,
                        showCloseButton: true,
                        type: "success",
                        text: "@Loc.OperationFinished",
                        buttons: [
                            {
                                icon: 'fa fa-check',
                                text: "@Loc.Confirm",
                                action: function () {
                                    loadInvoiceTransferStatistics(data);
                                    $('[href="#invoiceErrorCorrectiveTransferTab"]').tab('show');
                                },
                                closeOnAction: true,
                                type: 'primary'
                            }
                        ]
                    });
                } else
                    showGeneralErrorModal();

                invoiceErrorCorrectiveSwapLoadingIcon(false, "invoiceErrorCorrectiveBtnCreate", "fa fa-plus");
            }, "json").fail(function () {
                showGeneralErrorModal();
            });
    }

    function invoiceErrorCorrective() {
        $.get("@Url.Action("InvoiceErrorCorrective", "Move")" + "?acKey=" + $("#AcKey").val(), function (response) {
            if (response !== null && response === true) {
                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    type: "success",
                    text: "@Loc.OperationFinished",
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: "@Loc.Confirm",
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });

                window.location.reload();
            } else
                showGeneralErrorModal();
        });
    }

    function showGeneralErrorModal() {
        invoiceErrorCorrectiveSwapLoadingIcon(false, "invoiceErrorCorrectiveBtnCreate", "fa fa-plus");

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

    function loadInvoiceTransferStatistics(items) {
        var $invoiceTransferStatisticDataTable = $('#invoiceTransferStatisticGrid');
        if ($.fn.dataTable.isDataTable('#invoiceTransferStatisticGrid'))
            $invoiceTransferStatisticDataTable.DataTable().destroy();

        $invoiceTransferStatisticDataTable.DataTable({
            serverSide: false,
            ajax: undefined,
            scroller: true,
            responsive: false,
            info: false,
            data: items,
            columns: [
                { data: "AcKey" },
                { data: "AcKeyAdd" },
                { data: "AcError" },
                { data: "AcComment" }
            ]
        });
    }

    function invoiceErrorCorrectiveSwapLoadingIcon(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>