@using DashboardModel
@using C1.Web.Mvc.Grid

<script>
    var DEFAULT_UNIT = 1000000;//1M
    var BAD_UNIT = 0.0000005;
    var GOOD_UNIT = 0.0000008;
    var DEFAULT_THICKNESS = 0.5;
    var COMPLETE_LEVEL = 0.8;
    var AXIS_UNIT = 20;

    var tt = new wijmo.Tooltip();
    tt.showAtMouse = true;

    $(window).resize(function () {
        updateDashboard();
    });

    $(document).ready(function () {
        var categorySalesVsGoal = c1.getService('categorySalesVsGoal'),
            regionSalesVsGoal = c1.getService('regionSalesVsGoal');
        createGauges("#panGauges1", categorySalesVsGoal.items);
        createGauges("#panGauges2", regionSalesVsGoal.items);

        updateDashboard();
    });

    function resetTileContentsSize() {
        var eleIds = ['budgetVSProfitChart', 'chartSaleTopProd', 'chartSalesVsProfit'];
        for (var i = 0; i < eleIds.length; i++) {
            var domEle = document.getElementById(eleIds[i]);
            if (domEle) {
                domEle.removeAttribute('style');
            }
        }
    }

    function updateDashboard() {
        var dashboard = wijmo.Control.getControl('#dashboard');
        resetTileContentsSize();

        var wsSplitLayout = c1.getService('wsSplitLayout'),
            nsSplitLayout = c1.getService('nsSplitLayout'),
            layout = document.body.clientWidth < 1000 ? nsSplitLayout : wsSplitLayout;

        if (dashboard.layout === layout) {
            dashboard.refresh();
        } else {
            dashboard.layout = layout;
        }
    }

    function refreshAll(start, end) {
        refreshData(start, end, '@Url.Action("GetTopData")', function (data) {
            var top3SellingProducts = c1.getService('top3SellingProducts'),
                top7SaleCustomers = c1.getService('top7SaleCustomers'),
                categorySalesVsGoal = c1.getService('categorySalesVsGoal'),
                regionSalesVsGoal = c1.getService('regionSalesVsGoal');

            top3SellingProducts.sourceCollection = data[0].items;
            top7SaleCustomers.sourceCollection = data[1].items;
            categorySalesVsGoal.sourceCollection = data[2].items;
            regionSalesVsGoal.sourceCollection = data[3].items;
        });
    }

    function gaugeRefreshing(sender, e){
        var jEleGauge = $(sender.hostElement),
            jEleGaugeContainer = jEleGauge.closest('.gauge-container'),
            jEleTileGauge = jEleGaugeContainer.closest('.gaugesChart'),
            jEleLblGauge = jEleTileGauge.children('.lblGauges').first(),
            jEleTile = jEleTileGauge.closest('.wj-li-content'),
            jEleTitle = jEleGaugeContainer.children('.gauge-title');

        jEleGauge.width(jEleGaugeContainer.parent().width() - 100);
        var gaugesTotalHeight = jEleTile.innerHeight() - 10;
        jEleTileGauge.outerHeight(gaugesTotalHeight);
        var gauges = jEleTileGauge.find(".gauge-container");
        var gaugeHeight = (gaugesTotalHeight - jEleLblGauge.outerHeight()) / (gauges.length + 1);
        jEleGaugeContainer.outerHeight(gaugeHeight);
        jEleGauge.outerHeight(gaugeHeight);
        jEleTitle.css("top", gaugeHeight / 4);
        createGaugeAxes(jEleGaugeContainer.parent());
    }
    function createGauges(target, items) {
        if ($(target).length == 0) {
            return;
        }

        var gaugeElements = $(target + " .wj-gauge");
        for (var i = 0; i < gaugeElements.size() ; i++) {
            var gauge = wijmo.Control.getControl(gaugeElements.get(i));
            if (gauge != null)
                gauge.dispose();
        }

        $.each($(target).find(".gauge-container"), function (i, v) {
            tt.setTooltip(v, null);
        });
        $(target).empty();

        var panGause = $(target);
        var data = [];
        var max = Number.MIN_VALUE;
        for (var i = 0; i < items.length; i++) {
            var item = items[i];

            var goal = item.Goal / DEFAULT_UNIT;
            var sale = item.Sales / DEFAULT_UNIT;
            var badGoal = item.Goal * BAD_UNIT;
            var goodGoal = item.Goal * GOOD_UNIT;
            max = Math.max(max, sale);

            data.push({
                "goal": goal,
                "sale": sale,
                "badGoal": badGoal,
                "goodGoal": goodGoal

            });
        }

        max = Math.floor(max / AXIS_UNIT) * AXIS_UNIT + AXIS_UNIT;
        for (var i = 0; i < items.length; i++) {
            var item = data[i];

            var container = document.createElement("DIV");
            wijmo.addClass(container, "gauge-container");
            tt.setTooltip(container, wijmo.Globalize.format(item.sale, 'C0') + " (M)");
            panGause.append(container);

            // Create the bullet-graph
            var bullet = document.createElement("DIV");
            $(bullet).addClass("bullet-graph");
            $(container).append(bullet);
            var bulletGraph = new wijmo.gauge.BulletGraph(bullet, {
                min: 0,
                max: max,
                value: item.sale,
                bad: item.badGoal,
                good: item.goodGoal,
                target: item.goal,
                thickness: 0.7,
                refreshing: gaugeRefreshing
            });
            if (items[i].CompletePrecent < COMPLETE_LEVEL)
                bulletGraph.pointer.color = "red";
            bulletGraph.pointer.thickness = DEFAULT_THICKNESS;
            bulletGraph.face.thickness = 0;

            var title = document.createElement("DIV");
            $(title).addClass("gauge-title");
            $(title).html(items[i].Name);
            $(container).append(title);
        }
        panGause.data("max", max);
        createGaugeAxes(target);
    }
    function createGaugeAxes(target) {
        var panGause = $(target);
        if (panGause.children().count == 0) return;
        var count = panGause.data("max") / AXIS_UNIT;
        var axisLength = panGause.width() - 100;// 100 padding for title;
        var startLocation = 100;
        var step = axisLength / count;

        $(target).find(".gauge-axis-container").empty();

        var axisContainer = $(target).find(".gauge-axis-container");
        if (axisContainer.length == 0) {
            axisContainer = document.createElement("DIV");
            $(axisContainer).addClass("gauge-axis-container");
        } else {
            axisContainer.empty();
            axisContainer = axisContainer.get(0);
        }
        panGause.append(axisContainer);

        var bottom = $(axisContainer).prev().outerHeight();
        for (var i = 0; i <= count; i++) {
            var axis = document.createElement("DIV");
            $(axis).addClass("gauge-axis-marker");
            $(axis).css("left", (startLocation + i * step) + "px");
            $(axis).css("bottom", (bottom - 5) + "px");
            $(axisContainer).append(axis);

            var axisTitle = document.createElement("SPAN");
            $(axisTitle).html(i * AXIS_UNIT);
            $(axisTitle).addClass("gauge-axis-title");
            $(axisTitle).css("left", (startLocation + i * step - 5) + "px");
            $(axisTitle).css("bottom", (bottom - 25) + "px");
            $(axisContainer).append(axisTitle);
        }
    }

    function tooltipTemplate(ht) {
        return "<b>" + ht.name + "</b><br/>" + wijmo.Globalize.format(ht.x, 'MMM') + " " + wijmo.Globalize.format(ht.y, 'C0');
    }

    function categorySalesVsGoalChanged(sender, e) {
        createGauges("#panGauges1", sender.items);
    }

    function regionSalesVsGoalChanged(sender, e) {
        createGauges("#panGauges2", sender.items);
    }

    function tileContentRefreshing(sender, e) {
        var eleCtl = sender.hostElement,
            tileEle = eleCtl.parentElement.parentElement,
            height = $(tileEle).height() - 15;
        if (sender instanceof wijmo.chart.FlexChartBase) {
            height -= 12;
        } else if (sender instanceof wijmo.grid.FlexGrid) {
            height -= 5;
        }
        $(eleCtl).outerHeight(height);
    }

    function chartSaleTopProdRefreshing(sender, e) {
        tileContentRefreshing(sender, e);
        var width = sender.hostElement.clientWidth;
        var angle = null;
        if (width < 250) {
            angle = 90;
        } else if (width < 580) {
            angle = 45;
        }
        sender.axisX.labelAngle = angle;
    }
</script>

<style>
    .wj-tile-content>.wj-control{
        margin-bottom:0px;
    }
</style>

<div style="visibility:hidden;position:absolute;left:-10000px;top:-10000px">
    @(Html.C1().CollectionViewService()
        .Id("budgetItemList")
        .Bind(ViewBag.BudgetItemList as List<CurrentPriorBudgetItem>)
        .DisableServerRead(true))
    @(Html.C1().CollectionViewService()
        .Id("top3SellingProducts")
        .Bind(ViewBag.Top3SellingProducts as List<SaleItem>)
        .DisableServerRead(true))
    @(Html.C1().CollectionViewService()
        .Id("top7SaleCustomers")
        .Bind(ViewBag.Top7SaleCustomers as List<SaleItem>)
        .DisableServerRead(true))
    @(Html.C1().CollectionViewService()
        .Id("categorySalesVsGoal")
        .Bind(ViewBag.CategorySalesVsGoal as List<SaleGoalItem>)
        .DisableServerRead(true)
        .OnClientSourceCollectionChanged("categorySalesVsGoalChanged"))
    @(Html.C1().CollectionViewService()
        .Id("regionSalesVsGoal")
        .Bind(ViewBag.RegionSalesVsGoal as List<SaleGoalItem>)
        .DisableServerRead(true)
        .OnClientSourceCollectionChanged("regionSalesVsGoalChanged"))

    @(Html.C1().FlexChart()
                .Id("budgetVSProfitChart")
                .ItemsSourceId("budgetItemList")
                .BindingX("Date")
                .Series(sers =>
                {
                    sers.Add().Binding("Profit")
                    .Name(Resources.DashboardDemo.CurrentYear_Series)
                    .ChartType(C1.Web.Mvc.Chart.ChartType.LineSymbols);
                    sers.Add().Binding("ProirProfit")
                    .Name(Resources.DashboardDemo.PriorYear_Series)
                    .ChartType(C1.Web.Mvc.Chart.ChartType.LineSymbols);
                })
                .AxisX(x => x.Format("MMM"))
                .AxisY(y =>
                {
                    y.Format("N1,,");
                    y.MajorUnit(200000d);
                    y.Title("(US$ M)");
                })
                .HeaderStyle(x => x.Halign("left"))
                .Legend(C1.Web.Mvc.Chart.Position.Top)
                .Header(Resources.DashboardDemo.BudgetVSProfit_Header)
                .Tooltip(x =>
                {
                    x.Content("tooltipTemplate");
                })
                .OnClientRefreshing("tileContentRefreshing")
    )

    @(Html.C1().FlexChart()
                    .Id("chartSaleTopProd")
                    .ItemsSourceId("top3SellingProducts")
                    .BindingX("Name")
                    .Series(sers =>
                    {
                        sers.Add().Binding("Sales")
                        .Name(Resources.DashboardDemo.CurrentYear_Series)
                        .ChartType(C1.Web.Mvc.Chart.ChartType.Column);
                    })
                    .AxisY(y =>
                    {
                        y.Format("N0,,");
                        y.Title("(US$ M)");
                        y.MajorUnit(20000000d);
                    })
                    .HeaderStyle(x => x.Halign("left"))
                    .Legend(C1.Web.Mvc.Chart.Position.None)
                    .Header(Resources.DashboardDemo.TopSaleProducts_Header)
                    .OnClientRefreshing("chartSaleTopProdRefreshing")
    )
    <div id="topSaleCustomer">
        <div class="caption">
            @Resources.DashboardDemo.TopSaleCustomer_Header
        </div>
        @(Html.C1().FlexGrid()
                    .Id("gridTopSaleCustomer")
                    .ItemsSourceId("top7SaleCustomers")
                    .AutoSizeMode(AutoSizeMode.Both)
                    .AllowSorting(true)
                    .AutoGenerateColumns(false)
                    .SelectionMode(SelectionMode.Cell)
                    .CssClass("grid")
                    .IsReadOnly(true)
                    .Columns(bl =>
                    {
                        bl.Add(cb => cb.Binding("Name").Width("*"));
                        bl.Add(cb => cb.Binding("Sales").Format("C0").Width("*"));
                        bl.Add(cb => cb.Binding("Profit").Format("C0").Width("*"));
                    })
        )
    </div>


    @(Html.C1().FlexChart()
                .Id("chartSalesVsProfit")
                .ItemsSourceId("budgetItemList")
                .BindingX("Date")
                .Series(sers =>
                {
                    sers.Add().Binding("Sales")
                        .Name(Resources.DashboardDemo.Sale_Series)
                        .ChartType(C1.Web.Mvc.Chart.ChartType.Column);
                    sers.Add().Binding("Profit")
                        .Name(Resources.DashboardDemo.Profit_Series)
                        .ChartType(C1.Web.Mvc.Chart.ChartType.LineSymbols)
                        .AxisY(y =>
                        {
                            y.Format("N1,,");
                            y.MajorUnit(200000d);
                            y.Title(@Resources.DashboardDemo.Profit_Series + " (US$ M)");
                            y.Position(C1.Web.Mvc.Chart.Position.Left);
                        });
                }).AxisX(x =>
                {
                    x.OverlappingLabels(C1.Web.Mvc.Chart.AxisOverlappingLabels.Auto);
                    x.Format("MMMM");
                }).AxisY(y =>
                    {
                        y.Format("N0,,");
                        y.MajorUnit(4000000d);
                        y.Title(@Resources.DashboardDemo.Sale_Series + " (US$ M)");
                        y.Position(C1.Web.Mvc.Chart.Position.Right);
                    })
                .HeaderStyle(x =>
                {
                    x.Halign("left");
                }).Legend(C1.Web.Mvc.Chart.Position.Bottom)
                .Header(@Resources.DashboardDemo.SalesVsProfit_Header)
                .Tooltip(x =>
                {
                    x.Content("tooltipTemplate");
                })
                .OnClientRefreshing("tileContentRefreshing")
    )

    <div id="salesVSGoal" class="gaugesChart">
        <div class="lblGauges caption">@Resources.DashboardDemo.CategorySales_Header</div>
        <div class="labUnits caption">@Resources.DashboardDemo.Unit_Text</div>
        <div id="panGauges1"></div>
    </div>
    <div id="regionalSalesVsGoal" class="gaugesChart">
        <div class="lblGauges caption">@Resources.DashboardDemo.RegionSales_Header</div>
        <div class="labUnits caption">@Resources.DashboardDemo.Unit_Text</div>
        <div id="panGauges2"></div>
    </div>
</div>

@(Html.C1().SplitLayout()
    .Id("wsSplitLayout")
    .Orientation(LayoutOrientation.Horizontal)
    .Items(isb =>
    {
        isb.AddGroup().Orientation(LayoutOrientation.Vertical)
            .Size("6*")
            .Children(cb =>
            {
                cb.AddTile().Size("*").ShowHeader(false).Content("#budgetVSProfitChart");
                cb.AddGroup().Orientation(LayoutOrientation.Horizontal)
                    .Size("*")
                    .Children(scb =>
                    {
                        scb.AddTile().Size("*").ShowHeader(false)
                            .Content("#chartSaleTopProd");
                        scb.AddTile().Size("*").ShowHeader(false)
                            .Content("#topSaleCustomer");
                    });
            });
        isb.AddGroup().Orientation(LayoutOrientation.Vertical)
            .Size("4*")
            .Children(cb =>
            {
                cb.AddTile().Size("*").ShowHeader(false).Content("#chartSalesVsProfit");
                cb.AddTile().Size("*").ShowHeader(false).Content("#salesVSGoal");
                cb.AddTile().Size("*").ShowHeader(false).Content("#regionalSalesVsGoal");
            });
    }))

@(Html.C1().SplitLayout()
    .Id("nsSplitLayout")
    .Orientation(LayoutOrientation.Vertical)
    .Items(isb =>
    {
        isb.AddTile().ShowHeader(false).Content("#budgetVSProfitChart");
        isb.AddTile().ShowHeader(false).Content("#chartSaleTopProd");
        isb.AddTile().ShowHeader(false).Content("#topSaleCustomer");
        isb.AddTile().ShowHeader(false).Content("#chartSalesVsProfit");
        isb.AddTile().ShowHeader(false).Content("#salesVSGoal");
        isb.AddTile().ShowHeader(false).Content("#regionalSalesVsGoal");
    }))


<div class="flex vertical" style="width:100%;height:100%;overflow:hidden;">
    <div>
        <h3>
            @Resources.DashboardDemo.DashboardPage_Title
        </h3>
    </div>
    <div class="auto" style="overflow:auto">
        @(Html.C1().DashboardLayout()
                .Id("dashboard").CssStyle("height", "100%")
        )
    </div>
    <div class="rangeSelector-container">
        @Html.Partial("RangeSelector", ViewBag.RangeSelectorModel as RangeSelectorModel)
    </div>
</div>