@model PantheonRA.BackOffice.Models.Reports.IssuedBillsListViewModel<PantheonRA.BackOffice.Models.Reports.ReceivedDocumentsDetailedFilter>
@{
    ViewBag.Title = Loc.ReceivedDocumentsDetailed;
}

<div class="row wrapper border-bottom white-bg page-heading">
    <div class="col-lg-10">
        <a class="navbar-minimalize btn btn-primary " href="#"><i class="fa fa-bars"></i> </a>
        <h2>@ViewBag.Title</h2>
        <span class="breadcrumb-divider">&bull;</span>
        <ol class="breadcrumb">
            <li>@Loc.Reports</li>
            <li class="active"><strong>@ViewBag.Title</strong></li>
        </ol>
    </div>
    <div class="col-lg-2">
    </div>
</div>
<div class="row buttons-ribbon">
    <div class="col-xs-12">
        <a id="downloadIssuedBills" data-url="@Url.Action("ReceivedDocumentsDetailedExport", "Reports")" class="btn btn-sm btn-primary pull-right"><i class="fa fa-file-excel-o"></i>&nbsp;&nbsp;<span class="bold">@Loc.ExportToExcel</span></a>
    </div>
</div>
<div class="wrapper wrapper-content  animated fadeInRight">
    <div class="row">

        <div class="col-sm-12">
            <div class="ibox">
                <div class="ibox-title">
                    <h5>@ViewBag.Title</h5>
                </div>
                <div class="ibox-content">
                    <div class="row m-b-sm m-t-sm">
                        <div class="col-md-2">
                            <div class="form-group">
                                @Html.LabelFor(model => model.Filter.DateFrom, Loc.From)
                                @Html.TextBoxFor(m => m.Filter.DateFrom, "{0:dd.MM.yyyy.}", new { @class = "form-control datepicker" })
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="form-group">
                                @Html.LabelFor(model => model.Filter.DateTo, Loc.To)
                                @Html.TextBoxFor(m => m.Filter.DateTo, "{0:dd.MM.yyyy.}", new { @class = "form-control datepicker" })
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="form-group">
                                @Html.LabelFor(model => model.Filter.DocType, Loc.DocType)
                                <select id="@Html.IdFor(m => m.Filter.DocType)" class="form-control">
                                    <option></option>
                                    @foreach (var option in Model.AcDocTypes)
                                    {
                                        <option value="@option.Value">@option.Text</option>
                                    }
                                </select>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="form-group">
                                @Html.LabelFor(model => model.Filter.PartnerId, Loc.Partner)
                                <select id="@Html.IdFor(m=>m.Filter.PartnerId)" class="form-control" data-url="@Url.Action("SubjectsPicker", "Reports")">
                                    <option></option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="form-group">
                                @Html.LabelFor(model => model.Filter.ProductId, Loc.Product)
                                <select id="@Html.IdFor(m => m.Filter.ProductId)" class="form-control" data-url="@Url.Action("ProductsPicker", "Reports")">
                                    <option></option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-1">
                            <div class="form-group">
                                <label>&nbsp;</label>
                                <button type="button" id="searchIssuedBills" class="btn btn-block btn-outline btn-primary">@Loc.Search</button>
                            </div>
                        </div>
                    </div>
                    <div class="project-list">
                        <div class="document-list">
                            <table id="grid-data" class="list-table">
                                <thead>
                                    <tr>
                                        <th data-column-id="InvoiceRef" data-sortable="false" data-width="80px">@Loc.InvoiceRef</th>
                                        <th data-column-id="DocType" data-sortable="false" data-width="60px">@Loc.DocType</th>
                                        <th data-column-id="IssuedDate" data-sortable="false" data-width="140px">@Loc.ReceivedBillDate</th>
                                        <th data-column-id="PartnerName" data-sortable="false">@Loc.Partner</th>
                                        <th data-column-id="ProductName" data-sortable="false">@Loc.Product</th>
                                        <th data-column-id="Quantity" data-sortable="false" data-type="numeric" data-headerAlign="right" data-align="right" data-width="7%">@Loc.Quantity</th>
                                        <th data-column-id="Price" data-visible="false" data-sortable="false" data-type="numeric" data-headeralign="right" data-align="right" data-width="7%">@Loc.Price</th>
                                        <th data-column-id="PriceWithTax" data-visible="true" data-sortable="false" data-type="numeric" data-headeralign="right" data-align="right" data-width="7%">@Loc.ToPay</th>
                                        <th data-column-id="ValueWithoutTax" data-visible="false" data-sortable="false" data-type="numeric" data-headeralign="right" data-align="right" data-width="7%">@Loc.ValueWithoutTax</th>
                                        <th data-column-id="ValueWithTax" data-visible="false" data-sortable="false" data-type="numeric" data-headeralign="right" data-align="right" data-width="7%">@Loc.ValueWithTax</th>
                                        <th data-column-id="TaxValue" data-visible="false" data-sortable="false" data-type="numeric" data-headeralign="right" data-align="right" data-width="7%">@Loc.TotalTax</th>
                                        <th data-column-id="TaxFactor" data-sortable="false" data-type="numeric" data-headeralign="right" data-align="right" data-width="7%">@Loc.TaxRate</th>
                                        <th data-column-id="Note" data-sortable="false" data-width="20%">@Loc.NoteDocument</th>
                                        <th data-column-id="NoteDate" data-sortable="false">@Loc.NoteDate</th>
                                    </tr>
                                </thead>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

@section pageCss{
    <link href="~/Content/jquery.bootgrid.css" rel="stylesheet" />
    <link href="~/Content/plugins/select2/select2.css" rel="stylesheet" />
    <link href="~/Content/plugins/datapicker/datepicker3.css" rel="stylesheet" />
    <link href="~/Content/plugins/select2/select2-bootstrap.css" rel="stylesheet" />
}

@section pageScripts{
    <script type="text/javascript" src="~/Scripts/jquery.bootgrid.js"></script>
    <script type="text/javascript" src="~/Scripts/plugins/select2/select2.js"></script>
    <script type="text/javascript" src="~/Scripts/plugins/datapicker/bootstrap-datepicker.js"></script>
    <script type="text/javascript" src="@Url.Content(string.Format("~/Scripts/plugins/datapicker/locales/bootstrap-datepicker.{0}.min.js", PantheonRA.BackOffice.CurrentUser.LocalizationDate.ToLower()))"></script>
    <script type="text/javascript" src="@Url.Content(string.Format("~/Scripts/plugins/select2/i18n/{0}.js", PantheonRA.BackOffice.CurrentUser.Localizationi18n.ToLower()))"></script>

    <script>

        $(function () {
            var language = '@PantheonRA.BackOffice.CurrentUser.Localization';

            // dd.MM.yyyy. -> yyyy-MM-dd
            function reformatDate(dateString) {
                var dateElements = dateString.split('.');
                return dateElements[2] + '-' + dateElements[1] + '-' + dateElements[0]
            }

            var getSearchData = function () {
                return {
                    DateFrom: reformatDate($("#Filter_DateFrom").val()),
                    DateTo: reformatDate($("#Filter_DateTo").val()),
                    PartnerId: $("#Filter_PartnerId").val(),
                    DocType: $("#Filter_DocType").val(),
                    ProductId: $("#Filter_ProductId").val()
                };
            };

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

            var select2AcDocType = $("#Filter_DocType").select2({
                allowClear: true,
                theme: "bootstrap",
                placeholder: "",
                language: language
            });

            var select2Partner = $("#Filter_PartnerId").select2({
                ajax: {
                    url: $("#Filter_PartnerId").data("url"),
                    dataType: 'json',
                    type: "POST",
                    delay: 250,
                    data: function (params) {
                        return {
                            filter: params.term, // search term
                            page: params.page
                        };
                    },
                    id: function (data) {
                        return data.Value;
                    },
                    processResults: function (data, params) {
                        // parse the results into the format expected by Select2
                        // since we are using custom formatting functions we do not need to
                        // alter the remote JSON data, except to indicate that infinite
                        // scrolling can be used
                        params.page = params.page || 1;

                        var select2Data = $.map(data.Items, function (obj) {
                            obj.id = obj.Value,
                            obj.text = obj.Text;

                            return obj;
                        });

                        return {
                            results: select2Data,
                            pagination: {
                                more: (params.page * 10) < data.TotalItems
                            }
                        };
                    },
                    cache: true
                },
                allowClear: true,
                placeholder: "",
                theme: "bootstrap",
                escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
                minimumInputLength: 1,
                templateResult: format, // omitted for brevity, see the source of this page
                templateSelection: format, // omitted for brevity, see the source of this page
                language: language
            });

            var select2User = $("#Filter_UserId").select2({
                ajax: {
                    url: $("#Filter_UserId").data("url"),
                    dataType: 'json',
                    type: "POST",
                    delay: 250,
                    data: function (params) {
                        return {
                            filter: params.term, // search term
                            page: params.page
                        };
                    },
                    id: function (data) {
                        return data.Value;
                    },
                    processResults: function (data, params) {
                        // parse the results into the format expected by Select2
                        // since we are using custom formatting functions we do not need to
                        // alter the remote JSON data, except to indicate that infinite
                        // scrolling can be used
                        params.page = params.page || 1;

                        var select2Data = $.map(data.Items, function (obj) {
                            obj.id = obj.Value,
                            obj.text = obj.Text;

                            return obj;
                        });

                        return {
                            results: select2Data,
                            pagination: {
                                more: (params.page * 10) < data.TotalItems
                            }
                        };
                    },
                    cache: true
                },
                allowClear: true,
                placeholder: "",
                theme: "bootstrap",
                escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
                minimumInputLength: 1,
                templateResult: format, // omitted for brevity, see the source of this page
                templateSelection: format, // omitted for brevity, see the source of this page
                language: language
            });

            var grid = $("#grid-data").bootgrid({
                ajax: true,
                type: 'POST',
                url: "@Url.Action("ReceivedDocumentsDetailedData", "Reports")",
                formatters: {
                },
                templates: {
                    search: "",
                    header: ""
                },
                labels: {
                    noResults: "@Loc.NoResultFound",
                    infos: "@Loc.Showing {{ctx.start}} @Loc.To.ToLower() {{ctx.end}} ({{ctx.total}})",
                    loading: "@Loc.Loading..."

                },
                post: function () {
                    /* To accumulate custom parameter with the request object */
                    return getSearchData();
                },
            });

            $("#searchIssuedBills").on("click", function () {
                $('#grid-data').bootgrid('reload');
            });

            $("#downloadIssuedBills").off("click");
            $("#downloadIssuedBills").on("click", function () {
                var href = $(this).attr("href");
                var params = getSearchData();

                var form = $('<form id="exportForm" method="POST" style="display:none;"></form>');
                form.attr("action", "@Url.Action("ReceivedDocumentsDetailedExport", "Reports")");
                var form_data = new FormData();

                for (var key in params) {
                    var input = $("<input>")
                   .attr("name", key).val(params[key]);
                    form.append(input);
                }

                $("body").append(form);
                form.submit();
                $("#exportForm").remove();
            });

            $('.datepicker').datepicker()
                .on('click', function (e) {
                    $(this).select();
                });
        });
    </script>
}