@using PantheonRA.BackOffice.Enums
@using PantheonRA.BackOffice.Helpers
@using PantheonRA.WebApi.Contracts.Enums
@using PAW.Contracts.Enums
@model PantheonRA.BackOffice.Models.IssuedInvoicesBillingGridModel
@{
    ViewBag.Title = Loc.Stock;
}

<div class="wrapper wrapper-content">
    <div class="tabs-container">
        @Html.Partial("_ReportsTabNavigation")
        <div class="row btn-group pull-right buttons-tabbed">
            @Html.Partial("~/Views/Shared/Components/_PrintMenuButton.cshtml", new PantheonRA.BackOffice.Models.PrintMenuDropdownViewModel {
                PrintButtonGroup = ReportsHelper.FormatReportTree(
                    Model.ReportTree,
                    "print('{0}')",
                    null
                ),
                PrintType = ReportFormName.IssuedInvoicesBilling,
                PrintButtonId = "printButton"
            })
        </div>

        <div class="tab-content">
            <div class="row document-head">
                <div class="col-md-2 col-xs-6">
                    @Html.Partial("~/Views/Reports/_IssuedBillsBillingTabNavigation.cshtml", IssuedBillsType.IssuedInvoicesBillingDiffInPrice)
                </div>
                <div class="col-md-2 col-xs-6">
                    <div class="form-group">
                        <label class="control-label">@Loc.SearchFilter</label>
                        @Html.TextBoxFor(model => model.Keywords, new { @id = "Keywords", @class = "form-control search-input", @placeholder = Loc.Search, autocomplete = "off" })
                    </div>
                </div>
                <div class="col-md-2 col-xs-6" id="docTypeContainer">
                    <div class="form-group">
                        @Html.LabelFor(model => model.DocType, Loc.DocumentTypes, new { @class = "control-label" })
                        <div class="selectpicker-container">
                            @Html.DropDownListFor(model => model.DocType,
                                new SelectList(ViewBag.DocTypes != null ? ViewBag.DocTypes : new List<string>(), "Id", "Value"), Loc.DocumentTypes,
                                HtmlAttributesHelper.CreateInputAttributes("form-control selectpicker", "DocType", false, Loc.DocumentTypes, true, new { @multiple = "multiple", @title = Loc.All }))
                        </div>
                    </div>
                </div>
                <div class="col-md-2 col-xs-6">
                    <div class="form-group">
                        @Html.LabelFor(model => model.Buyers, Loc.Buyer, new { @class = "control-label" })
                        <div class="selectpicker-container">
                            @Html.DropDownListFor(model => model.Buyers,
                             new SelectList(ViewBag.Buyers != null ? ViewBag.Buyers : new List<string>(), "Id", "Display"),
                             HtmlAttributesHelper.CreateInputAttributes("form-control selectpicker", "Buyers", false, Loc.Buyers, true, new { @multiple = "multiple", data_live_search = "true", @title = Loc.All }))
                        </div>
                    </div>
                </div>
                <div class="col-md-1 col-xs-4">
                    <div class="form-group">
                        <label class="control-label">@Loc.ClerkShort</label>
                        @Html.DropDownListFor(model => model.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))
                    </div>
                </div>
                <div class="col-md-1 col-xs-4">
                    <div class="form-group">
                        <label class="control-label">@Loc.Referent</label>
                        @Html.DropDownListFor(model => model.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))
                    </div>
                </div>
                <div class="col-lg-1 col-md-2 col-xs-4 dateFilter">
                    <div class="form-group">
                        <label class="control-label">@Loc.DateFrom</label>
                        <div class="input-group">
                            <span class="input-group-addon"><i class="far fa-calendar alt"></i></span>
                            @Html.TextBoxFor(model => model.DateFrom, Model.DateFrom.HasValue ? Model.DateFrom.Value.ToString(Loc.DateFormat) : null,
                                HtmlAttributesHelper.CreateInputAttributes("form-control datepicker", "DateFrom", false, Loc.DateFrom))
                        </div>
                    </div>
                </div>
                <div class="col-lg-1 col-md-2 col-xs-4 dateFilter">
                    <div class="form-group">
                        <label class="control-label">@Loc.DateTo</label>
                        <div class="input-group">
                            <span class="input-group-addon"><i class="far fa-calendar alt"></i></span>
                            @Html.TextBoxFor(model => model.DateTo, Model.DateTo.HasValue ? Model.DateTo.Value.ToString(Loc.DateFormat) : null,
                                HtmlAttributesHelper.CreateInputAttributes("form-control datepicker", "DateTo", false, Loc.DateTo))
                        </div>
                    </div>
                </div>
            </div>

            <div class="project-list">
                <div class="document-list">
                    <table id="issuedInvoicesBillingGrid" data-grid-id="issued-invoices-billing" data-url="@Url.Action("IssuedInvoicesBillingList", "Reports")" data-height="calc(100vh - 330px)" class="list-table">
                        <thead>
                            <tr>
                                <th width="3%" data-function="openPdfPreview('@Url.Action("WholesalePdf", "Wholesale")?preview=true&paperSize=printer_A4&id={0}')"></th>
                                <th data-url="@Url.Action("Edit", "Wholesale")?id=">@Loc.Document</th>
                                <th width="12%" data-url="@Url.Action("Edit", "Subjects")?returnUrl=@(Url.Action("Index", "Wholesale"))&id=">@Loc.Buyer</th>
                                <th width="8%" class="dt-head-right">@Loc.PriceWithoutTax</th>
                                <th width="10%" class="dt-head-right">@Loc.PriceWithTax</th>
                                <th width="6%">@Loc.OrderFormDate</th>
                                <th width="7%">@Loc.InvoiceDateShort</th>
                                <th width="6%">@Loc.DateDue</th>
                                <th>@Loc.Order</th>
                                <th>@Loc.OrderForm</th>
                                <th>@Loc.BuyerType</th>
                                <th>@Loc.Status</th>
                            </tr>
                        </thead>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

@Html.Partial("~/Views/Shared/Components/_sidePanel.cshtml", new PantheonRA.BackOffice.Models.SidePanelViewModel { Id = "pdfPanel" })

<div class="modal inmodal fade" id="errorModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-sm" role="document">
        <div class="modal-content">
            <div class="modal-body">
                <span id="errorModalMessage"></span>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" data-dismiss="modal" onclick="">@Loc.OK</button>
            </div>
        </div>
    </div>
</div>

<input type="hidden" id="RepeatAnimation" value="@Url.Content("~/Content/Animations/DocumentLoading.gif")" />
<input type="hidden" id="LoadingDocumentLoc" value="@Loc.LoadingDocument" />
<input type="hidden" id="ConfirmLoc" value="@Loc.Confirm" />

@section pageScripts{
    <script>
        $(document).ready(function () {
            $("#printButton").prop("disabled", false);
            $("#printButton + button").prop("disabled", false);

            $('.datepicker').datepicker()
                .on('click', function (e) {
                    $(this).select();
                }).on('changeDate', function () {
                    $(this).datepicker('hide');
                    $.fn.dataTable.reload($dataTable);
                }).on('change', function () {
                    $(this).datepicker('hide');
                    $.fn.dataTable.reload($dataTable);
                });

            $dataTable = $('#issuedInvoicesBillingGrid');
            $dataTable.DataTable({
                ajax: {
                    url: $dataTable.attr('data-url'),
                    data: function (d) {
                        d.Keywords = $("#Keywords").val();
                        d.DateFrom = reformatDate($("#DateFrom").val());
                        d.DateTo = reformatDate($("#DateTo").val());
                        d.DocType = $("#DocType").val() ? $("#DocType").val().toString() : "";
                        d.Clerk = $("#Clerk").val();
                        d.Referent = $("#Referent").val();
                        d.Buyers = $("#Buyers").val() ? $("#Buyers").val().toString() : "";
                    }
                },
                columns: [
                    { data: "", name: "", render: $.fn.dataTable.render.preview("AcKey"), className: 'dt-body-center dt-head-center' },
                    { data: "AcKeyDisplay", name: "AcKey", filtertype: "text", render: $.fn.dataTable.render.link("AcKey") },
                    { data: "Receiver", name: "AcReceiver", filtertype: "text", render: $.fn.dataTable.render.link("Receiver") },
                    {
                        data: "Price",
                        name: "AnValue",
                        filtertype: "number",
                        render: function (data, type, full) {
                            return $.fn.dataTable.render.number('.', ',', 2, '', " " + full.Currency).display(data);
                        },
                        className: 'dt-body-right'
                    },
                    {
                        data: "PriceWithVAT",
                        name: "AnForPay",
                        filtertype: "number",
                        render: function (data, type, full) {
                            return $.fn.dataTable.render.number('.', ',', 2, '', " " + full.Currency).display(data);
                        },
                        className: 'dt-body-right'
                    },
                    { data: "Date", name: "AdDate", filtertype: "dateTime" },
                    { data: "InvoiceDate", name: "AdDateInv", filtertype: "dateTime" },
                    { data: "ExpiryDate", name: "AdDateDue", filtertype: "dateTime" },
                    { data: "Order", name: "AcDoc1", filtertype: "text" },
                    { data: "OrderForm", name: "AcDoc2", filtertype: "text" },
                    {
                        data: "Sales", name: "AcWayOfSale", filtertype: "text", render: function (data, type) {
                            if (type === 'display') {
                                switch (data) {
                                    case "Z":
                                        return '@Loc.IsTaxCommitedShort';
                                        break;
                                    case "K":
                                        return '@Loc.FinalBuyer';
                                        break;
                                    case "I":
                                        return '@Loc.ExportSale';
                                        break;
                                    case "E":
                                        return '@Loc.ExportSaleEU';
                                        break;
                                }
                            }

                            return data;
                        }
                    },
                    { data: "StatusDisplay", name: "AcVerifyStatus" }
                ],
                createdRow: function (row, data, dataIndex) {
                    if (data.CanceledInvoice) {
                        $(row).addClass('danger');
                    }
                }
            });

            $(".dropdown-select, .custom-select").off("change");
            $(".dropdown-select, .custom-select").on("change", function () {
                $.fn.dataTable.reload($dataTable);
            });

            $(".selectpicker-container").on("hide.bs.dropdown", function () {
                $.fn.dataTable.reload($dataTable);
            });

            var typingTimer;
            var doneTypingInterval = 600;
            $('#Keywords').off('keyup');
            $('#Keywords').on('keyup', function () {
                clearTimeout(typingTimer);
                typingTimer = setTimeout(function () { $.fn.dataTable.reload($dataTable); }, doneTypingInterval);
            });
        });

        function format(item) {
            return item.Text;
        }

        var printWindow;
        function print(type) {
            swapLoadingIcon(true, "printButton", "far fa-print");

            var url = "@Url.Action("IssuedInvoicesBillingDiffInPricePrint", "Reports")"
                + "?DateFrom=" + reformatDate($("#DateFrom").val())
                + "&DateTo=" + reformatDate($("#DateTo").val())
                + "&Clerk=" + $("#Clerk").val()
                + "&Referent=" + $("#Referent").val()
                + "&PrintType=" + type;

            var docType = $("#DocType").val() ? $("#DocType").val().toString() : "";
            var buyers = $("#Buyers").val() ? $("#Buyers").val().toString() : "";
            url = url + "&DocType=" + docType + "&Buyers=" + buyers;

            printWindow = createPrintWindow(printWindow);

            $.get(url,
                function (data) {
                    if (data) {
                        printPAAS(null, false, false, url, false);
                    }
                    else {
                        printWindow.close();
                        $("#errorModalMessage").text('@Loc.PrintingError');
                        $("#errorModal").modal('show');
                    }
                    swapLoadingIcon(false, "printButton", "far fa-print");
                }).fail(function () {
                    swapLoadingIcon(false, "printButton", "far fa-print");
                    printWindow.close();
                    $("#errorModalMessage").text('@Loc.GeneralError');
                    $("#errorModal").modal('show');
                });
        }

        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 openPdfPreview(url) {
            loadPdfPanelContent($("#pdfPanel"), url, true);
        }
    </script>
}