var App = function () {
    this.statisticGrid = $('#task-grid');
    this.selectedRow = [];

    this.Startup = function () {
        $('#manage').addClass('active');
        
        this.ReLayout();
        this.InitDate();

        $('.statistic-type span').on('click', this.OnStatisticTypeClick.bind(this));
        $('#query-btn').on('click', this.OnQueryButtonClick.bind(this));
        $('#query-btn').trigger('click');

        window.onresize = this.ReLayout.bind(this);
    };

    this.ReLayout = function () {
        var width = $(window).width();
        var height = $(window).height();

        $('.manage-table, .manage-table .datagrid').width(width - 247);
        $('.manage-table, .manage-table .datagrid').height(height - 109);
        this.formatLastColumn();
    };

    this.OnStatisticTypeClick = function (event) {
        $('.statistic-type span').removeClass("active");
        $(event.target).addClass("active");
    };

    this.OnQueryButtonClick = function () {
        //this.ReLoadTableData();
        this.ReloadChartData();
    };

    this.ReloadChartData = function () {
        $.ajax({
            type: "POST",
            dataType: 'text',
            url: '/StatisticAnalysis/Query',
            data: this.GetParams(),
            success: function (result) {
                var type = this.GetParams().typeCode === 'user' ? 'column' : 'spline'; 
                var name = this.GetParams().typeCode === 'user' ? '根据用户' : '根据机构';
                var xAxises = this.GetSeries(JSON.parse(result).rows).xAxises;
                var values = this.GetSeries(JSON.parse(result).rows).series;
                var series = this.GetElementSerie(type, name, values);
                this.InitChart(series, xAxises, JSON.parse(result).rows);
            }.bind(this)
        });
    };

    this.GetElementSerie = function (type, name, values) {
        return {
            type: type,
            name: name,
            data: values,
            pointWidth: 30
        };
    };

    this.GetSeries = function (result) {
        var series = [];
        var xAxises = [];
        result.forEach(function (item, index) {
            var time = moment(item.LastComputeTime).format("YYYY-MM-DD");
            xAxises.push(time);
            series.push(item.ComputeCount);
        });

        return {
            series: series,
            xAxises: xAxises
        };
    };

    this.InitChart = function (series, xAxises, values) {
        Highcharts.chart('chart', {
            title: {
                text: this.GetParams().fromTime + ' 至 ' + this.GetParams().toTime,
                style: {
                    color: '#3a3a3a',
                    fontFamily: '微软雅黑'
                }
            },
            subtitle: {
                text: '计算次数',
                style: {
                    color: '#3a3a3a',
                    fontFamily: '微软雅黑'
                },
                verticalAlign: 'top',
                align: 'left',
                y: 25
            },
            credits: {
                enabled: false
            },
            xAxis: {
                categories: xAxises
            },
            yAxis: {
                title: {
                    text: null
                }
            },
            tooltip: {
                formatter: function () {
                    return '<b>' + this.x + '</b>' + '<br/>' +
                        '计算次数:' + '<b>' + this.y + '</b>' + '次' + '<br/>' +
                        '计算用户:' + app.GetNames(values, this.x);
                }
            },
            series: [series]
        });
    };

    this.GetNames = function (values, time) {
        var names = [];
        var result = values.filter(function (item) {
            return moment(item.LastComputeTime).format("YYYY-MM-DD") === time;
        });
        result.forEach(function (item, index) {
            names.push(item.UserName);
        });
        return names.join('、');
    };

    this.ReLoadTableData = function () {
        this.statisticGrid.datagrid({
            method: "POST",
            url: '/StatisticAnalysis/Query',
            queryParams: {
                typeCode: $('.statistic-type span.active').attr('type'),
                fromTime: $("#from-date").datetimebox('getValue'),
                toTime: $("#to-date").datetimebox('getValue')
            }
        });
    };

    this.InitDate = function () {
        $('#from-date').datebox({
            panelAlign: 'right',
            panelWidth: 200,
            panelHeight: 230,
            showSeconds: false,
            currentText: '现在',
            onSelect: function (date) {
                var startTime = date.getTime();
                var endDate = $('#to-date').val();

                if (endDate) {
                    var endTime = new Date(endDate).getTime();
                    if (startTime > endTime)
                        alert('开始日期不能大于结束日期,请重新选择。');
                }
            }
        });

        $('#to-date').datebox({
            panelWidth: 190,
            panelHeight: 230,
            panelAlign: 'right',
            showSeconds: false,
            currentText: '现在',
            onSelect: function (date) {
                var endTime = date.getTime();
                var startDate = $('#from-date').val();

                if (startDate) {
                    var startTime = new Date(startDate).getTime();
                    if (startTime > endTime)
                        alert('结束日期不能小于开始日期,请重新选择。');
                }
            }
        });

        $("#from-date").datebox('setValue', moment().add(-30, 'days').format('YYYY/MM/DD'));
    };

    this.InitDataGrid = function () {
        this.statisticGrid.datagrid({
            columns: [[
                { field: 'UserName', title: '姓名', align: 'center', width: 120 },
                { field: 'OrgName', title: '所属机构', align: 'left', width: 180 },
                { field: 'OrgName2', title: '名称', align: 'left', width: 180, hidden: 'true' },
                { field: 'ComputeCount', title: '计算次数', align: 'center', width: 100 },
                { field: 'LastComputeTime', title: '最后计算时间', align: 'center', width: 160, formatter: this.formatTime.bind(this) },
                { field: 'Null', title: '', align: 'left' }
            ]],
            striped: true,
            singleSelect: false,
            fit: true,
            scrollbarSize: 0,
            pagination: true,
            pageNumber: 1,
            pageSize: 50,
            pageList: [10, 20, 50, 100, 150, 200],
            onSelect: this.OnTaskSelected.bind(this),
            onUnselect: this.OnTaskUnselected.bind(this),
            onBeforeLoad: this.OnTableGridBeforeLoad.bind(this),
            onLoadSuccess: function (data) {
                if (data.total === 0) {
                    var body = $('.datagrid-body');
                    body.addClass('null-data-body');
                    body.append('<div class="null-data"><span></span><p>暂无数据</p></div>');
                }

                if ($('.statistic-type span.active').attr('type') === 'user') {
                    this.statisticGrid.datagrid('showColumn', 'UserName'); 
                    this.statisticGrid.datagrid('showColumn', 'OrgName');
                    this.statisticGrid.datagrid('hideColumn', 'OrgName2');
                }
                else {
                    this.statisticGrid.datagrid('hideColumn', 'UserName');
                    this.statisticGrid.datagrid('hideColumn', 'OrgName');
                    this.statisticGrid.datagrid('showColumn', 'OrgName2');
                }

                this.formatLastColumn();
            }.bind(this)
        });
    };

    this.formatLastColumn = function () {
        var type = $('.statistic-type span.active').attr('type');
        var width = $('.container').width();
        var headerTable = $('.datagrid-header');
        var bodyTable = $('.datagrid-body');
        var headerTd = headerTable.find('td:last');
        var clipWidth = type === 'user' ? 562 : 442;
        headerTd.css('width', (width - clipWidth) + 'px');
        bodyTable.find('tr').find('td:last').css('width', (width - clipWidth) + 'px');
    };

    this.toggleUserColuum = function () {
        if ($('.statistic-type span.active').attr('type') === 'user')
            this.statisticGrid.datagrid('showColumn', 'UserName');
        else 
            this.statisticGrid.datagrid('hideColumn', 'UserName');
    };

    this.formatTime = function (time) {
        return '<span>{0}</span>'.format(moment(time).format('YYYY/MM/DD HH:mm:ss'));
    };

    this.OnTaskSelected = function (index, row) {
        this.selectedRow = row;
        $('.datagrid-btable tr').removeClass('datagrid-row-selected');
        $('.datagrid-btable tr').eq(index).addClass('datagrid-row-selected');

        //set buttons disabled state
        $('#edit-btn').prop('disabled', row === null);
        $('#delete-btn').prop('disabled', row === null);
        $('#enable-btn').prop('disabled', row.isEnable !== 1 ? null : true);
        $('#disable-btn').prop('disabled', row.isEnable === 1 ? null : true);
    };

    this.OnTaskUnselected = function (index, row) {
        $('#edit-btn').prop('disabled', true);
        $('#delete-btn').prop('disabled', true);
        $('#enable-btn').prop('disabled', true);
        $('#disable-btn').prop('disabled', true);
    };

    this.GetParams = function () {
        return {
            typeCode: $('.statistic-type span.active').attr('type'),
            fromTime: $("#from-date").datetimebox('getValue'),
            toTime: $("#to-date").datetimebox('getValue'),
            page: 1,
            rows: 1000
        };
    };

    this.OnAddButtonClick = function () {
    this.onEditButtonClick = function () {
        this.EditDialog.Show(this.selectedRow);
    };
        this.AddDialog.Show();
    };


    this.onDeleteButtonClick = function () {
        $('.dialog-delete').show();
        $('.dialog-clear h2').text('确定删除名为「{0}」的账户吗?'.format(this.selectedRow.Name));
    };

    this.CloseDeleteDialog = function () {
        $('.dialog-delete').hide();
    };

    this.OnTableGridBeforeLoad = function () {
        this.statisticGrid.datagrid('getPager').pagination({
            beforePageText: '第',
            afterPageText: '页&nbsp;&nbsp;&nbsp;共{pages}页',
            displayMsg: '当前显示{from}-{to}条记录&nbsp;&nbsp;&nbsp;共{total}条记录',
            layout: ['list', 'sep', 'first', 'prev', 'sep', 'manual', 'sep', 'next', 'last', 'sep', 'refresh', 'info']
        });
    };
};

var app = null;
$(document).ready(function () {
    app = new App();
    app.Startup();
});