@inject Nop.Services.Common.IGenericAttributeService genericAttributeService
@inject IWorkContext workContext
@{
    const string prefix = "order-statistics";
    const string hideCardAttributeName = "Reports.HideOrderStatisticsCard";
    var hideCard = await genericAttributeService.GetAttributeAsync<bool>(await workContext.GetCurrentCustomerAsync(), hideCardAttributeName);
}

<script src="~/lib_npm/chart.js/chart.umd.min.js"></script>

<div class="card card-primary card-outline @if (hideCard){<text>collapsed-card</text>}" id="@(prefix)-card">
    <div class="card-header with-border">
        <h3 class="card-title">
            <i class="fas fa-cart-shopping"></i>
            @T("Admin.SalesReport.OrderStatistics")
        </h3>
        <div class="card-tools float-right">
            <button class="btn btn-xs btn-info btn-flat margin-r-5" @if (hideCard) { <text> disabled="disabled" </text> } data-chart-role="toggle-chart" data-chart-period="year">@T("Admin.SalesReport.OrderStatistics.Year")</button>
            <button class="btn btn-xs btn-info btn-flat margin-r-5" @if (hideCard) { <text> disabled="disabled" </text> } data-chart-role="toggle-chart" data-chart-period="month">@T("Admin.SalesReport.OrderStatistics.Month")</button>
            <button class="btn btn-xs btn-info btn-flat" @if (hideCard) { <text> disabled="disabled" </text> } data-chart-role="toggle-chart" data-chart-period="week">@T("Admin.SalesReport.OrderStatistics.Week")</button>
            <button type="button" class="btn btn-tool margin-l-10" data-card-widget="collapse">
                @if (hideCard)
                {
                    <text><i class="fas fa-plus"></i></text>
                }
                else
                {
                    <text><i class="fas fa-minus"></i></text>
                }
            </button>
        </div>
    </div>
    <div class="card-body">
        <div class="chart" style="height: 300px;">
            <canvas id="@(prefix)-chart" height="300"></canvas>
        </div>
    </div>
</div>

<script>
    $(function() {
        var osCurrentPeriod;

        $('#@(prefix)-card').on('click', 'button[data-card-widget="collapse"]', function () {
            var collapsed = !$('#@(prefix)-card').hasClass('collapsed-card');
            saveUserPreferences('@(Url.Action("SavePreference", "Preferences"))', '@hideCardAttributeName', collapsed);
            
            if (!collapsed) {
                $('#@(prefix)-card button[data-chart-role="toggle-chart"]').removeAttr('disabled');
                if (!osCurrentPeriod) {
                    $('#@(prefix)-card button[data-chart-role="toggle-chart"][data-chart-period="week"]').trigger('click');
                }
            } else {
                $('#@(prefix)-card button[data-chart-role="toggle-chart"]').attr('disabled', 'disabled');
            }
        });

        var osConfig = {
            type: 'line',
            data: {
                labels: [],
                datasets: [
                    {
                        backgroundColor: 'rgba(44, 152, 214, 0.5)',
                        fill: 'origin',
                        label: "@T("Admin.SalesReport.OrderStatistics")",
                        borderColor: 'rgba(44, 152, 214, .5)',
                        pointBorderColor: 'rgba(37, 103, 142, 0.9)',
                        pointBackgroundColor: 'rgba(60, 141, 188, 0.2)',
                        pointHoverBackgroundColor: '#fff',
                        pointHoverBorderColor: 'rgba(60,141,188,1)',
                        data: []
                    }
                ]
            },
            options: {
                plugins: {
                    legend: {
                        display: false,
                    },
                },
                scales: {
                    x: {
                        display: true,
                        ticks: {
                            callback: function (dataLabel, index) {
                                var labels = this.chart.config.data.labels;
                                return labels.length <= 12 || index % 5 === 0 ? labels[index] : '';
                            }
                        },
                        grid: {
                            display: true,
                            color: 'rgba(0,0,0,.05)',
                            lineWidth: 1,
                        },
                    },
                    y: {
                        display: true,
                        ticks: {
                            stepSize: 1
                        },
                        grid: {
                            display: true,
                            color: 'rgba(0,0,0,.05)',
                            lineWidth: 1,
                        },
                    }
                },
                elements: {
                    line: {
                        borderWidth: 1,
                        tension: 0.3
                    },
                    point: {
                        pointStyle: 'circle',
                        radius: 4,
                        borderWidth: 1,
                        hitRadius: 20,
                        hoverRadius: 6,
                    },
                },
                maintainAspectRatio: false,
            }
        };

        function changeOsPeriod(period) {
            var osLabels = [];
            var osData = [];

            $.ajax({
                cache: false,
                type: "GET",
                url: "@Url.Action("LoadOrderStatistics", "Order")",
                data: {
                    period: period
                },
                success: function (data, textStatus, jqXHR) {
                    for (var i = 0; i < data.length; i++) {
                        osLabels.push(data[i].date);
                        osData.push(data[i].value);
                    }

                    if (!window.orderStatistics) {
                        osConfig.data.labels = osLabels;
                        osConfig.data.datasets[0].data = osData;
                        osConfig.data.scales =
                        window.orderStatistics = new Chart(document.getElementById("@prefix-chart").getContext("2d"), osConfig);
                    } else {
                        window.orderStatistics.config.data.labels = osLabels;
                        window.orderStatistics.config.data.datasets[0].data = osData;
                        window.orderStatistics.update();
                    }
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    $("#loadOrderStatisticsAlert").trigger("click");
                }
            });
        }

        $('#@(prefix)-card button[data-chart-role="toggle-chart"]').on('click', function () {
            var period = $(this).attr('data-chart-period');
            osCurrentPeriod = period;
            changeOsPeriod(period);
            $('#@(prefix)-card button[data-chart-role="toggle-chart"]').removeClass('bg-light-blue');
            $(this).addClass('bg-light-blue');
        });

        @if (!hideCard)
        {
            
            <text>
                $('#@(prefix)-card button[data-chart-role="toggle-chart"][data-chart-period="week"]').trigger('click');
            </text>
        }
    });
</script>
