@using PAW.Contracts.Enums
@using PantheonRA.BackOffice.Enums
@using PantheonRA.BackOffice.Models
@using PantheonRA.WebApi.Contracts.Enums
@model PantheonRA.BackOffice.Models.WholesaleGridFilterModel

@{
    ViewBag.Title = Loc.Invoicing;
}

<div class="wrapper wrapper-content">
    <div class="tabs-container">
        @if (Model.FormName == AuthorType.Wholesale)
        {
            @Html.Partial("~/Views/Wholesale/_WholesalesTabNavigation.cshtml")
        }
        else if(Model.FormName == AuthorType.ReceivingAdvancePayment)
        {
            @Html.Partial("~/Views/Wholesale/_ReceivedAdvancePaymentsTabNavigation.cshtml")
        }
        <div class="tab-content">
            @Html.HiddenFor(x => x.FormName)
            @Html.HiddenFor(x => x.LastPrint)
            <div class="row buttons-tabbed">
                <a href="@Url.Action("Index", "Wholesale")" class="btn btn-transparent pull-right close-btn"><i class="fal fa-times"></i></a>

                <button id="printButton" type="button" onclick="printMultiple()" title="@Loc.Print"
                        class="btn btn-primary pull-right">
                    <i class="far fa-print m-r-xs"></i>
                    <span class="visible-lg-inline visible-md-inline">@Loc.Print</span>
                </button>

                @if (PantheonRA.BackOffice.CurrentUser.Localization == Localization.Code.RS
                || PantheonRA.BackOffice.CurrentUser.Localization == Localization.Code.HR
                || PantheonRA.BackOffice.CurrentUser.Localization == Localization.Code.SI)
                {
                    @Html.Partial("_FormButtons", new FormButtonsViewModel
                    {
                        ShowCloseBtn = false,
                        IsWizardVisible = true,
                        WizardButtonGroup = new FormButtonGroup
                        {
                            ButtonName = Loc.EInvoice,
                            ButtonTitle = Loc.SendEInvoiceAndInDocumentation,
                            ButtonIcon = "eInvoice-icon",
                            Buttons = new List<FormButton>
                            {
                                new FormButton { Text = string.Empty, Icon = "", OnClick = "", IsHidden = true },
                                new FormButton { Text = Loc.MyEAccountSending, Icon = "", OnClick = "sendToDocumentation('" + WorkflowIdentify.MERSendRS + "')", IsHidden = !Model.CanSendMER, HideForLoc = PantheonRA.BackOffice.CurrentUser.Localization != Localization.Code.RS },
                                new FormButton { Text = Loc.EInvoiceSending, Icon = "", OnClick = "sendToDocumentation('" + WorkflowIdentify.SendEInvoiceRS + "')", IsHidden = !Model.CanSendSEF, HideForLoc = PantheonRA.BackOffice.CurrentUser.Localization != Localization.Code.RS },
                                new FormButton { Text = Loc.MyEAccountSending, Icon = "", OnClick = "sendToDocumentation('" + WorkflowIdentify.MERSendHR + "')", IsHidden = !Model.CanSendMER, HideForLoc = PantheonRA.BackOffice.CurrentUser.Localization != Localization.Code.HR },
                                new FormButton { Text = Loc.FINAEAccountSending, Icon = "", OnClick = "sendToDocumentation('" + WorkflowIdentify.FinaSendHR + "')", IsHidden = !Model.CanSendSEF, HideForLoc = PantheonRA.BackOffice.CurrentUser.Localization != Localization.Code.HR },
                                new FormButton { Text = Loc.EInvoiceBizBox, Icon = "", OnClick = "sendToDocumentation('" + WorkflowIdentify.SendBizBoxSI + "')", IsHidden = !Model.CanSendMER, HideForLoc = PantheonRA.BackOffice.CurrentUser.Localization != Localization.Code.SI },
                            }
                        }
                    })
                }

                <button id="sendToDocumentationButton" type="button" onclick="sendToDocumentation()" title="@Loc.SendToDocumentation"
                        class="btn btn-default btn-outline pull-right collapsable-form-button">
                    <i class="far fa-check m-r-xs"></i>
                    <span class="visible-lg-inline visible-md-inline">@Loc.SendToDocumentation</span>
                </button>
            </div>

            <div class="row full-height margin-b-none">
                <div class="col-md-3 col-xs-6 tabs-column-container full-height overflow-x-auto column-full-height-border-right">
                    <div class="tabs-container">
                        <ul class="nav nav-tabs horizontal-menu">
                            <li class="active divided-tab-1"><a data-toggle="tab" href="#printOptions" class="local-tab">@Loc.PrintoutType</a></li>
                        </ul>
                    </div>
                    <div class="tab-content">
                        <input id="ReportType" hidden />
                        <div id="printOptions" class="tab-pane fade in active m-l-n m-r-n">
                            <div class="print-options-container">
                                @if (Model.ReportTree != null)
                                {
                                    foreach (var report in Model.ReportTree)
                                    {
                                        <div class="print-option-group">
                                            <div class="print-option-label p-l-sm" onclick="togglePrintOptionGroup(this)">
                                                <div class="print-option-border"></div>
                                                <span class="caret caret-left"></span>
                                                <span>
                                                    @report.Category
                                                </span>
                                            </div>
                                            @foreach (var formReport in report.FormReports)
                                            {
                                                <div onclick="selectPrintType(this, '@formReport.Report')" class="preview-print-option cursor-pointer" data-print="@formReport.Report" data-fisc="@formReport.Fiscalize">
                                                    <div class="print-option-border"></div>
                                                    <div class="print-option-border-horizontal"></div>
                                                    <a title="@formReport.Report - @formReport.Name">
                                                        @formReport.Report - @formReport.Name
                                                    </a>
                                                </div>
                                            }
                                        </div>
                                    }
                                }
                            </div>
                        </div>
                    </div>
                </div>

                <div class="col-md-9 col-xs-6">
                    <h3 class="m-t-md">@Loc.Criteria</h3>
                    <div class="row">
                        <div class="form-horizontal form-md">
                            <div class="col-md-6">
                                <div class="form-group">
                                    @Html.Label("OrderBy", Loc.OrderBy, new { @class = "col-sm-3 control-label" })
                                    <div class="col-sm-9">
                                        @Html.DropDownList("OrderBy", new List<SelectListItem>() {
                                            new SelectListItem{ Text = Loc.DocumentNumberFull, Value = OrderBy.AcKeyAsc },
                                            new SelectListItem{ Text = Loc.Buyer, Value = OrderBy.BuyerAsc },
                                            new SelectListItem{ Text = Loc.Recipient, Value = OrderBy.RecipientAsc },
                                            new SelectListItem{ Text = Loc.Warehouse, Value = OrderBy.WarehouseAsc },
                                            new SelectListItem{ Text = Loc.Referent, Value = OrderBy.ReferentAsc },
                                            new SelectListItem{ Text = Loc.DeliveryType, Value = OrderBy.DeliveryAsc },
                                        }, HtmlAttributesHelper.CreateInputAttributes("form-control custom-select", "OrderBy", false, Loc.OrderBy))
                                    </div>
                                </div>
                                <div class="form-group">
                                    @Html.Label("Status", Loc.Status, new { @class = "col-sm-3 control-label" })
                                    <div class="col-sm-9">
                                        @Html.DropDownList("Status", new SelectList(ViewBag.DocumentStatuses != null ? ViewBag.DocumentStatuses : new List<string>(), "TemplateValue", "Name"), Loc.All,
                                            HtmlAttributesHelper.CreateInputAttributes("form-control custom-select", "Status", false, Loc.Status, true))
                                    </div>
                                </div>
                                <div class="form-group">
                                    @Html.Label("DocType", Loc.DocType, new { @class = "col-sm-3 control-label" })
                                    <div class="col-sm-9">
                                        <select id="DocType" name="DocType" class="form-control custom-select">
                                            <option value="">@Loc.Select</option>
                                            @foreach (var item in ViewBag.DocumentTypes)
                                            {
                                                <option value="@item.Id"
                                                        data-fiscalize="@item.CanFiscalize"
                                                        data-archive="@item.Archive"
                                                        data-classification="@item.Classification"
                                                        data-fiscAll="@item.FiscAll"
                                                        data-pinUrlLPFR="@item.PinUrlLPFR"
                                                        data-defaultReport="@item.DefaultReport"
                                                        @(Model.DocType == item.Id ? "selected" : string.Empty)>
                                                    @item.Value
                                                </option>
                                            }
                                        </select>
                                    </div>
                                </div>
                                <div class="form-group cancel-invoice-typeahead-container">
                                    @Html.Label("AcKeyFrom", Loc.NumberFrom, new { @class = "col-sm-3 control-label" })
                                    <div class="col-sm-4">
                                        <input id="AcKeyFromId" hidden />
                                        @Html.TextBox("AcKeyFrom", string.Empty, HtmlAttributesHelper.CreateInputAttributes("form-control typeahead_3", "AcKeyFrom", false, Loc.NumberFrom, true, null, string.IsNullOrEmpty(Model.DocType) ? true : false))
                                    </div>
                                    @Html.Label("AcKeyTo cancel-invoice-typeahead-container", Loc.To, new { @class = "col-sm-1 control-label padding-left-none" })
                                    <div class="col-sm-4 padding-left-none">
                                        <input id="AcKeyToId" hidden />
                                        @Html.TextBox("AcKeyTo", string.Empty, HtmlAttributesHelper.CreateInputAttributes("form-control typeahead_3", "AcKeyTo", false, Loc.To, true, null, string.IsNullOrEmpty(Model.DocType) ? true : false))
                                    </div>
                                </div>
                                <div class="form-group">
                                    @Html.Label("Warehouse", Loc.Warehouse, new { @class = "col-sm-3 control-label" })
                                    <div class="col-sm-9">
                                        @Html.DropDownList("Warehouse", new SelectList(ViewBag.Warehouses != null ? ViewBag.Warehouses : new List<string>(), "Id", "Name"), Loc.Select,
                                            HtmlAttributesHelper.CreateInputAttributes("form-control custom-select", "Warehouse", false, Loc.Status, true))
                                    </div>
                                </div>
                                <div class="form-group">
                                    @Html.Label("Buyer", Loc.Buyer, new { @class = "col-sm-3 control-label" })
                                    <div class="col-sm-9">
                                        @Html.TextBox("Buyer", string.Empty, HtmlAttributesHelper.CreateInputAttributes("form-control typeahead_3 typeahead_large", "Buyer", false, Loc.Buyer, true))
                                    </div>
                                </div>
                                <div class="form-group">
                                    @Html.Label("Recipient", Loc.Recipient, new { @class = "col-sm-3 control-label" })
                                    <div class="col-sm-9">
                                        @Html.TextBox("Recipient", string.Empty, HtmlAttributesHelper.CreateInputAttributes("form-control typeahead_3 typeahead_large", "Recipient", false, Loc.Recipient, true))
                                    </div>
                                </div>
                            </div>

                            <div class="col-md-6">
                                <div class="form-group">
                                    @Html.Label("Referent", Loc.Referent, new { @class = "col-sm-3 control-label" })
                                    <div class="col-sm-9">
                                        @Html.DropDownList("Referent", new SelectList(ViewBag.Users != null ? ViewBag.Users : new List<string>(), "Id", "Name"), Loc.Select,
                                            HtmlAttributesHelper.CreateInputAttributes("form-control custom-select", "Referent", false, Loc.Referent, true))
                                    </div>
                                </div>
                                <div class="form-group">
                                    @Html.Label("Clerk", Loc.ClerkShort, new { @class = "col-sm-3 control-label" })
                                    <div class="col-sm-9">
                                        @Html.DropDownList("Clerk", new SelectList(ViewBag.Users != null ? ViewBag.Users : new List<string>(), "Id", "Name"), Loc.Select,
                                            HtmlAttributesHelper.CreateInputAttributes("form-control custom-select", "Clerk", false, Loc.ClerkShort, true))
                                    </div>
                                </div>
                                <div class="form-group">
                                    @Html.Label("DeliveryType", Loc.DeliveryType, new { @class = "col-sm-3 control-label" })
                                    <div class="col-sm-9">
                                        @Html.DropDownList("DeliveryType", new SelectList(ViewBag.DeliveryTypes != null ? ViewBag.DeliveryTypes : new List<string>(), "Id", "Name"), Loc.Select,
                                            HtmlAttributesHelper.CreateInputAttributes("form-control custom-select", "DeliveryType", false, Loc.DeliveryType, true))
                                    </div>
                                </div>
                                <div class="form-group">
                                    @Html.Label("DeliveryNoteFrom", Loc.DeliveryNoteFrom, new { @class = "col-sm-3 control-label" })
                                    <div class="col-sm-4">
                                        <div class="input-group">
                                            <span class="input-group-addon">
                                                <i class="far fa-calendar alt"></i>
                                            </span>
                                            @Html.TextBox("DeliveryNoteFrom", null, HtmlAttributesHelper.CreateInputAttributes("form-control datepicker", "DeliveryNoteFrom", false, Loc.DeliveryNoteFrom))
                                        </div>
                                    </div>
                                    @Html.Label("DeliveryNoteTo", Loc.To, new { @class = "col-sm-1 control-label padding-left-none" })
                                    <div class="col-sm-4 padding-left-none">
                                        <div class="input-group">
                                            <span class="input-group-addon">
                                                <i class="far fa-calendar alt"></i>
                                            </span>
                                            @Html.TextBox("DeliveryNoteTo", null, HtmlAttributesHelper.CreateInputAttributes("form-control datepicker", "DeliveryNoteTo", false, Loc.To))
                                        </div>
                                    </div>
                                </div>
                                <div class="form-group">
                                    @Html.Label("VATDateFrom", Loc.VATDateFrom, new { @class = "col-sm-3 control-label" })
                                    <div class="col-sm-4">
                                        <div class="input-group">
                                            <span class="input-group-addon">
                                                <i class="far fa-calendar alt"></i>
                                            </span>
                                            @Html.TextBox("VATDateFrom", null, HtmlAttributesHelper.CreateInputAttributes("form-control datepicker", "VATDateFrom", false, Loc.VATDateFrom))
                                        </div>
                                    </div>
                                    @Html.Label("VATDateTo", Loc.To, new { @class = "col-sm-1 control-label padding-left-none" })
                                    <div class="col-sm-4 padding-left-none">
                                        <div class="input-group">
                                            <span class="input-group-addon">
                                                <i class="far fa-calendar alt"></i>
                                            </span>
                                            @Html.TextBox("VATDateTo", null, HtmlAttributesHelper.CreateInputAttributes("form-control datepicker", "VATDateTo", false, Loc.To))
                                        </div>
                                    </div>
                                </div>
                                <div class="form-group">
                                    @Html.Label("BillDateFrom", Loc.BillFrom, new { @class = "col-sm-3 control-label" })
                                    <div class="col-sm-4">
                                        <div class="input-group">
                                            <span class="input-group-addon">
                                                <i class="far fa-calendar alt"></i>
                                            </span>
                                            @Html.TextBox("BillDateFrom", null, HtmlAttributesHelper.CreateInputAttributes("form-control datepicker", "BillDateFrom", false, Loc.BillFrom))
                                        </div>
                                    </div>
                                    @Html.Label("BillDateTo", Loc.To, new { @class = "col-sm-1 control-label padding-left-none" })
                                    <div class="col-sm-4 padding-left-none">
                                        <div class="input-group">
                                            <span class="input-group-addon">
                                                <i class="far fa-calendar alt"></i>
                                            </span>
                                            @Html.TextBox("BillDateTo", null, HtmlAttributesHelper.CreateInputAttributes("form-control datepicker", "BillDateTo", false, Loc.To))
                                        </div>
                                    </div>
                                </div>
                                <div class="form-group">
                                    @Html.Label("DueDateFrom", Loc.DueDateFrom, new { @class = "col-sm-3 control-label" })
                                    <div class="col-sm-4">
                                        <div class="input-group">
                                            <span class="input-group-addon">
                                                <i class="far fa-calendar alt"></i>
                                            </span>
                                            @Html.TextBox("DueDateFrom", null, HtmlAttributesHelper.CreateInputAttributes("form-control datepicker", "DueDateFrom", false, Loc.DueDateFrom))
                                        </div>
                                    </div>
                                    @Html.Label("DueDateTo", Loc.To, new { @class = "col-sm-1 control-label padding-left-none" })
                                    <div class="col-sm-4 padding-left-none">
                                        <div class="input-group">
                                            <span class="input-group-addon">
                                                <i class="far fa-calendar alt"></i>
                                            </span>
                                            @Html.TextBox("DueDateTo", null, HtmlAttributesHelper.CreateInputAttributes("form-control datepicker", "DueDateTo", false, Loc.To))
                                        </div>
                                    </div>
                                </div>
                                <div class="form-group">
                                    @Html.Label("PaymentMethod", Loc.BusinessTypeShort, new { @class = "col-sm-3 control-label" })
                                    <div class="col-sm-9">
                                        <select id="PaymentMethod" name="PaymentMethod" class="form-control custom-select" title="@Loc.BusinessTypeShort">
                                            <option value="">@Loc.Select</option>
                                            <option value="K">@Loc.PaperAndElectronic</option>
                                            <option value="E">@Loc.EmailEStyleSimpleInvoice</option>
                                            <option value="P">@Loc.Paper</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<input type="hidden" id="ConfirmLoc" value="@Loc.Confirm" />

@Html.Partial("~/Views/Shared/Components/_CreateDocumentModals.cshtml")
@Scripts.Render("~/bundles/lpfr")

@section pageScripts{
    <script>
        $(document).ready(function () {
            $('.datepicker').datepicker()
                .on('click', function (e) {
                    $(this).select();
                }).on('changeDate', function () {
                    $(this).datepicker('hide');
                });

            initializePartnerTypeahead('@Url.Action("SearchPartners", "Wholesale")', $('#Buyer'), $("#Buyer"));
            initializePartnerTypeahead('@Url.Action("SearchPartners", "Wholesale")', $('#Recipient'), $("#Recipient"));

            initializeInvoiceTypeahead('@Url.Action("GetByDocType", "Move")', $('#AcKeyFrom'), $("#AcKeyFromId"), '@InvoiceType.Wholesale', null, null, $("#DocType"), function (item) {
                $("#AcKeyFromId").val(item.id);
                return { selected: true, value: item.name };
            });
            initializeInvoiceTypeahead('@Url.Action("GetByDocType", "Move")', $('#AcKeyTo'), $("#AcKeyToId"), '@InvoiceType.Wholesale', null, null, $("#DocType"), function (item) {
                $("#AcKeyToId").val(item.id);
                return { selected: true, value: item.name };
            });

            $("#DocType").on("change", function () {
                $('#AcKeyFrom').val("");
                $('#AcKeyTo').val("");
                if (!$(this).val()) {
                    $('#AcKeyFrom').attr("disabled", true);
                    $('#AcKeyTo').attr("disabled", true);
                } else {
                    $('#AcKeyFrom').attr("disabled", false);
                    $('#AcKeyTo').attr("disabled", false);
                }

                setDefaultPrintType();
            });

            if ($("#DocType option:selected").attr("data-defaultReport"))
                setDefaultPrintType();
            else {
                var printParts = $("#LastPrint").val() ? $("#LastPrint").val().split("_") : "";
                if (printParts && printParts.length > 1) {
                    var lastPrint = printParts[1];
                    selectPrintType($(".preview-print-option[data-print='" + lastPrint + "']"), lastPrint);
                } else
                    selectPrintType();
            }
        });

        function togglePrintOptionGroup(element) {
            $(element).parent().toggleClass("print-group-closed");
        }

        function setDefaultPrintType() {
            var printType = $("#DocType option:selected").attr("data-defaultReport");
            if (printType)
                selectPrintType($(".preview-print-option[data-print='" + printType + "']"), printType);
        }

        function selectPrintType($element, type) {
            if (!$element || $element.length <= 0) {
                $element = $(".preview-print-option").first();
                type = $element.attr("data-print");
            }

            $("#printOptions div.custom-option-selected").removeClass("custom-option-selected");
            $($element).addClass("custom-option-selected");
            $("#ReportType").val(type);
        }

        async function printMultiple() {
            prints = [];

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

            swapLoadingIcon(true, "printButton", "fa fa-print");

            $.post('@Url.Action("GetAcKeysForPrint", "Move")', {
                ReportType: $("#ReportType").val(),
                OrderBy: $("#OrderBy option:selected").val(),
                Status: $("#Status option:selected").val(),
                DocType: $("#DocType option:selected").val(),
                AcKeyFrom: $("#AcKeyFrom").val(),
                AcKeyTo: $("#AcKeyTo").val(),
                Warehouse: $("#Warehouse option:selected").val(),
                Buyer: $("#Buyer").val(),
                Recipient: $("#Recipient").val(),
                Document: $("#Document").val(),
                Referent: $("#Referent").val(),
                Clerk: $("#Clerk").val(),
                DeliveryType: $("#DeliveryType option:selected").val(),
                DeliveryNoteFrom: $("#DeliveryNoteFrom").val(),
                DeliveryNoteTo: $("#DeliveryNoteTo").val(),
                VATDateFrom: $("#VATDateFrom").val(),
                VATDateTo: $("#VATDateTo").val(),
                BillDateFrom: $("#BillDateFrom").val(),
                BillDateTo: $("#BillDateTo").val(),
                DueDateFrom: $("#DueDateFrom").val(),
                DueDateTo: $("#DueDateTo").val(),
                FormName: $("#FormName").val(),
            }).done(function (response) {
                if (response && !response.errors) {
                    printMultiplePAAS(response);
                }
            }).fail(function () {
                swapLoadingIcon(false, "printButton", "fa fa-print");

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

        var printWindow;
        var prints = [];
        async function printMultiplePAAS(response) {
            let pinUrlLpfr = $("#DocType option:selected").attr("data-pinUrlLpfr");
            printWindow = createPrintWindow(printWindow);

            for await (const doc of response) {
                var test = await printPAAS($("#ReportType").val(), true, false, "@Url.Action("PAASPrintByAcKeyAndType", "Move")" + "?acKey=" + doc.AcKey +
                    "&type=" + $("#ReportType").val() + "&fiscalize=" + true + "&preview=" + false, false, undefined, undefined, undefined,
                    '@Url.Action("LPFRUpdateInvoice", "Move")', pinUrlLpfr && doc.FiscStatus === "4" ? ("@Url.Action("GetLpfrFiscalizationData", "Move")" + "?acKey=" + doc.AcKey) : undefined, doc.AcKey, true);
            }

            if (prints && prints.length > 0) {
                $.post('@Url.Action("GetMultiplePdfs", "Move")', {
                    pdfContent: prints,
                }).done(function (response) {
                    swapLoadingIcon(false, "printButton", "fa fa-print");

                    if (response) {
                        if (printWindow && printWindow.closed)
                            printWindow = createPrintWindow(printWindow);

                        var byte = base64ToArrayBuffer(response);
                        var blob = new Blob([byte], { type: 'application/pdf' });
                        printWindow.location.href = URL.createObjectURL(blob);
                    }
                });
            }
        }

        function sendToDocumentation(sendEInvoiceType, checksum = null) {
            if (!$("#DocType option:selected").val()) {
                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    type: "error",
                    text: "@Loc.DocTypeMustBeSelected",
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: "@Loc.Confirm",
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });
                return;
            }

            if (!$("#DocType option:selected").attr("data-archive") || !$("#DocType option:selected").attr("data-classification")) {
                $("#createDocumentIrisMessage").text(stringFormat("@Loc.IncorrectDocTypeSettings", $("#DocType option:selected").val()));
                $("#openDocTypeSettings").attr("onclick", "window.open('@Url.Action("Edit", "DocumentType")?id=" + $("#DocType option:selected").val() + "', '_self')");
                $("#createDocumentErrorModal").modal("show");
                return;
            }

            $().customToast({
                type: 'success',
                text: "@Loc.SendingDocuments",
                id: 'sendToDocumentationToast'
            });

            swapLoadingIcon(true, "sendToDocumentationButton", "fa fa-check");

            $.post('@Url.Action("SendToDocumentation", "Move")', {
                ReportType: $("#ReportType").val(),
                OrderBy: $("#OrderBy option:selected").val(),
                Status: $("#Status option:selected").val(),
                DocType: $("#DocType option:selected").val(),
                AcKeyFrom: $("#AcKeyFromId").val(),
                AcKeyTo: $("#AcKeyToId").val(),
                Warehouse: $("#Warehouse option:selected").val(),
                Buyer: $("#Buyer").val(),
                Recipient: $("#Recipient").val(),
                Document: $("#Document").val(),
                Referent: $("#Referent").val(),
                Clerk: $("#Clerk").val(),
                DeliveryType: $("#DeliveryType option:selected").val(),
                PaymentMethod: $("#PaymentMethod option:selected").val(),
                DeliveryNoteFrom: $("#DeliveryNoteFrom").val(),
                DeliveryNoteTo: $("#DeliveryNoteTo").val(),
                VATDateFrom: $("#VATDateFrom").val(),
                VATDateTo: $("#VATDateTo").val(),
                BillDateFrom: $("#BillDateFrom").val(),
                BillDateTo: $("#BillDateTo").val(),
                DueDateFrom: $("#DueDateFrom").val(),
                DueDateTo: $("#DueDateTo").val(),
                Fiscalize: $("#DocType option:selected").attr("data-fiscalize"),
                SendEInvoiceType: sendEInvoiceType,
                Checksum: checksum,
                DialogResult: checksum ? "1" : ""
            }).done(function (response) {
                var toast = $("#sendToDocumentationToast");
                if (toast) {
                    toast.remove();
                }

                if (response && response.PrintingError) {
                    showPrintingError(sendEInvoiceType, response.PrintingError);
                    return;
                }

                swapLoadingIcon(false, "sendToDocumentationButton", "fa fa-check");
                if (response && response.SendEInvoiceResponse && response.SendEInvoiceResponse.Variables) {
                    var errMsg = response.SendEInvoiceResponse.Variables.ErrorMessages.replaceAll("\r\n", "");
                    errMsg = response.SendEInvoiceResponse.Variables.ErrorMessages.replaceAll("\r", "</br>");
                    if (errMsg) {
                        $().customModal({
                            destroyOnClose: true,
                            showCloseButton: true,
                            type: "error",
                            text: errMsg,
                            buttons: [
                                {
                                    icon: 'fa fa-check',
                                    text: "@Loc.Confirm",
                                    closeOnAction: true,
                                    type: 'primary'
                                }
                            ]
                        });
                    } else {
                        window.location = "@Url.Action("Index", "Documents")"
                    }
                } else if (response && response.Error && response.Error !== "") {
                    $().customModal({
                        destroyOnClose: true,
                        showCloseButton: true,
                        type: "error",
                        text: response.Error,
                        buttons: [
                            {
                                icon: 'fa fa-check',
                                text: "@Loc.Confirm",
                                closeOnAction: true,
                                type: 'primary'
                            }
                        ]
                    });
                } else if (response) {
                    window.location = "@Url.Action("Index", "Documents")"
                }
            }).fail(function () {
                swapLoadingIcon(false, "sendToDocumentationButton", "fa fa-check");

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

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

        function showPrintingError(sendEInvoiceType, errModel) {
            var errButtons = [];

            if (errModel && errModel.Buttons) {
                let buttonIndex = 0;
                errModel.Buttons.forEach(function (errBtn) {
                    let buttonType = errModel.Results && errModel.Results.length > buttonIndex ? errModel.Results[buttonIndex] : 0;
                    errButtons.push({
                        icon: '',
                        text: errBtn,
                        closeOnAction: true,
                        type: 'primary',
                        action: function () {
                            if (buttonType !== 2 && buttonType !== 5 && buttonType !== 8 && buttonType !== 9)
                                sendToDocumentation(sendEInvoiceType, errModel.Checksum);
                        }
                    });
                    buttonIndex++;
                });
            }

            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                type: "error",
                text: errModel.Error,
                title: errModel.Title,
                buttons: errButtons
            });
        }
    </script>
}
