var App = function () {
    this.statisticGrid = $('#task-grid');
    this.selectedRow = [];
    this.Startup = function () {
        $('#manage').addClass('active');
        
        this.RedirectPage();
        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.RedirectPage = function () {
        var user = document.getElementById('user-info');
        if (user.getAttribute('class') === 'user-login')
            window.location.href = '/User/Login';
        else
            return;
    };
    this.ReLayout = function () {
        var width = $(window).width();
        var height = $(window).height();
        $('.manage-table, .manage-table .datagrid').width(width - 267);
        $('.manage-table, .manage-table .datagrid').height(height - 535);
    };
    this.OnStatisticTypeClick = function (event) {
        $('.statistic-type span').removeClass("active");
        $(event.target).addClass("active");
    };
    this.OnQueryButtonClick = function () {
        this.ReloadChartData();
        this.InitDataGrid();
        this.ReLoadTableData();
    };
    this.ReLoadTableData = function () {
        this.statisticGrid.datagrid({
            method: "POST",
            url: '/Task/GetList',
            queryParams: {
                fromDate: this.GetParams().fromTime,
                toDate: this.GetParams().toTime
            }
        });
    };
    this.InitDataGrid = function () {
        this.statisticGrid.datagrid({
            columns: [[
                { field: 'UserName', title: '用户名', align: 'center', width: 120 },
                { field: 'CreateTime', title: '提交时间', align: 'center', width: 180, formatter: this.formatTime.bind(this) },
                { field: 'ReleaseTime', title: '反馈时间', align: 'center', width: 180, formatter: this.formatTime.bind(this) },
                { field: 'Params', title: '参数', align: 'center', width: 550, formatter: this.formatParams.bind(this) },
                { field: 'OrgName', title: '计算状态', align: 'center', width: 100, formatter: this.formatState.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) {
                this.formatLastColumn();
            }.bind(this)
        });
    };
    this.ReloadChartData = function () {
        $.ajax({
            type: "POST",
            dataType: 'text',
            url: '/StatisticAnalysis/Query',
            data: this.GetParams(),
            success: function (result) {
                var rows = JSON.parse(result).rows;
                var type = this.GetParams().typeCode === 'user' ? 'column' : 'spline'; 
                var name = this.GetParams().typeCode === 'user' ? '根据用户' : '根据机构';
                var xAxises = this.GetSeries(rows, name).xAxises;
                var max = this.GetSeries(rows, name).max;
                var pieValues = this.GetSeries(rows, name).pieSeries;
                var defaultValues = this.GetSeries(rows, name).defaultSeries;
                var defaultData = this.GetElement(type, name, defaultValues);
                var pieData = this.GetElement('pie', '占比', pieValues);
                this.InitChart(defaultData, xAxises, rows, name, max);
                this.InitPieChart(pieData, name);
            }.bind(this)
        });
    };
    this.GetElement = function (type, name, values) {
        return {
            type: type,
            name: name,
            data: values
        };
    };
    this.GetSeries = function (result, name) {
        var max = null;
        var xAxises = [];
        var count = [];
        var pieSeries = [];
        var defaultSeries = [];
        
        result.forEach(function (item, index) {
            count.push(item.ComputeCount);
        }.bind(this));
        result.forEach(function (item, index) {
            var sum = count.reduce(function (prev, next) { return prev + next; });
            max = count.reduce(function (prev, cur) { return Math.max(prev, cur); });
            xAxises.push(name === '根据用户' ? item.UserName : item.OrgName);
            defaultSeries.push(item.ComputeCount);
            pieSeries.push({
                name: name === '根据用户' ? item.UserName : item.OrgName,
                y: this.formatDecimal(String(item.ComputeCount / sum) / 100) * 100
            });
        }.bind(this));
        return {
            max: max,
            xAxises: xAxises,
            pieSeries: pieSeries,
            defaultSeries: defaultSeries
        };
    };
    this.formatDecimal = function (value) {
        value = value.toString();
        let index = value.indexOf('.');
        if (index !== -1) {
            value = value.substring(0, 5 + index + 1);
        } else {
            value = value.substring(0);
        }
        return parseFloat(value).toFixed(5);
    };
    this.InitChart = function (series, xAxises, values, name, max) {
        Highcharts.chart('chart', {
            chart: {
                backgroundColor: 'rgba(0, 0, 0, 0)'
            },
            title: {
                useHTML: true,
                text: name.slice(2) + '计算次数统计' + '
' + moment(this.GetParams().fromTime).format('YYYY年MM月DD日') + ' 至 ' + moment(this.GetParams().toTime).format('YYYY年MM月DD日'),
                style: {
                    color: '#ffffff',
                    fontFamily: '微软雅黑'
                }
            },
            subtitle: {
                text: '计算次数',
                style: {
                    color: '#ffffff',
                    fontSize: '14px',
                    fontFamily: '微软雅黑'
                },
                verticalAlign: 'top',
                align: 'left',
                y: 50
            },
            credits: {
                enabled: false
            },
            colors: ['#00d5f6'],
            xAxis: {
                categories: xAxises,
                labels: {
                    style: {
                        color: '#ffffff',
                        fontSize: '14px',
                        fontFamily: '微软雅黑'
                    }
                },
                lineColor: '#234979',
                crosshair: true
            },
            yAxis: {
                title: {
                    text: null
                },
                //max: max * 3,
                labels: {
                    style: {
                        color: '#ffffff',
                        fontSize: '14px',
                        fontFamily: '微软雅黑'
                    }
                },
                gridLineColor: '#234979'
            },
            tooltip: {
                useHTML: true,
                shared: true,
                backgroundColor: '#002145',
                style: {
                    color: '#ffffff',
                    fontSize: '14px',
                    fontFamily: '微软雅黑'
                },
                formatter: function () {
                    return '' + this.x + '' + '
' +
                        '计算次数:' + '' + this.y + '' + '次' + '
' +
                        '最后计算时间:' + app.GetNames(values, this.x, name);
                }
            },
            legend: {
                itemStyle: {
                    color: '#ffffff',
                    fontSize: '14px',
                    fontFamily: '微软雅黑'
                },
                itemHoverStyle: {
                    color: '#ffffff',
                    fontSize: '14px',
                    fontFamily: '微软雅黑'
                }
            },
            plotOptions: {
                column: {
                    pointWidth: 30,
                    borderRadius: 3,
                    borderColor: ''
                },
                pie: {
                    center: [1000, 100],
                    size: 200,
                    tooltip: {
                        headerFormat: '{point.key}',
                        pointFormat: '{series.name}: {point.percentage:.2f}%',
                        useHTML: true,
                        crosshair: true,
                        backgroundColor: '#002145',
                        style: {
                            color: '#ffffff',
                            fontSize: '14px',
                            fontFamily: '微软雅黑'
                        }
                    }
                },
                series: {
                    color: {
                        linearGradient: {
                            x1: 0,
                            y1: 0,
                            x2: 0,
                            y2: 1
                        },
                        stops: [
                            [0, '#266cb9'],
                            [1, '#00d5f6']
                        ]
                    }
                }
            },
            series: [series]
        });
    };
    this.GetNames = function (values, name, type) {
        var time = values.find(function (item) {
            return (type === '根据用户' ? item.UserName : item.OrgName) === name;
        }).LastComputeTime;
        return moment(time).format('YYYY-MM-DD');
    };
    this.InitPieChart = function (series, name) {
        Highcharts.chart('pie-chart', {
            chart: {
                backgroundColor: 'rgba(0, 0, 0, 0)',
                type: 'pie'
            },
            title: {
                text: name.slice(2) + '占比',
                style: {
                    color: '#ffffff',
                    fontFamily: '微软雅黑'
                },
                y: 30
            },
            credits: {
                enabled: false
            },
            tooltip: {
                headerFormat: '{point.key}',
                pointFormat: '{series.name}: {point.percentage:.2f}%',
                useHTML: true,
                crosshair: true,
                backgroundColor: '#002145',
                style: {
                    color: '#ffffff',
                    fontSize: '14px',
                    fontFamily: '微软雅黑'
                }
            },
            legend: {
                itemStyle: {
                    color: '#ffffff',
                    fontFamily: '微软雅黑'
                },
                itemHoverStyle: {
                    color: '#ffffff',
                    fontSize: '14px',
                    fontFamily: '微软雅黑'
                }
            },
            plotOptions: {
                pie: {
                    allowPointSelect: true,
                    borderWidth: 0,
                    cursor: 'pointer',
                    dataLabels: {
                        useHTML: true,
                        enabled: true,
                        color: '#ffffff',
                        style: {
                            fontSize: '14px',
                            fontFamily: '微软雅黑',
                            textOutline: 'none'
                        },
                        formatter: function () {
                            return '' + this.point.name + '';
                        }
                    },
                    showInLegend: false
                }
            },
            series: [series]
        },function (chart) {
            this.SetGradientColor(chart);
        }.bind(this));
    };
    this.SetGradientColor = function (chart) {
        var pointsList = chart.series[0].points;
        for (var i = 0; i < pointsList.length; i++) {
            chart.series[0].points[i].update({
                color: {
                    linearGradient: { x1: 0, y1: 1, x2: 0, y2: 0 },
                    stops: [
                        [0, Highcharts.Color(i === 0 ? '#00d5f6' : '#fafafa').setOpacity(1).get('rgba')],
                        [1, i === 0 ? '#266cb9' : app.GetRandomColor()]
                    ]
                }
            });
        }
    }
    this.GetRandomColor = function () {
        var r = Math.floor(Math.random() * 255);
        var g = Math.floor(Math.random() * 255);
        var b = Math.floor(Math.random() * 255);
        return "rgb(" + r + ',' + g + ',' + b + ")";
    };
    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.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.formatTime = function (time) {
        return '{0}'.format(moment(time).format('YYYY/MM/DD HH:mm:ss'));
    };
    this.formatParams = function (params, row) {
        return '{0}(经度)、{1}(纬度)、{2}米(高度)、{3}分钟(模拟时长)、{4}分钟(分段时长)'.format(row.Longitude, row.Latitude, row.Height, row.SimulatedDuration, row.SimulatedInterval);
    };
    this.formatState = function () {
        return '';
    };
    this.formatLastColumn = function () {
        var width = $('.container').width();
        var headerTable = $('.datagrid-header');
        var bodyTable = $('.datagrid-body');
        var headerTd = headerTable.find('td:last');
        headerTd.css('width', width - 1130 + 'px');
        bodyTable.find('tr').find('td:last').css('width', width - 1130 + 'px');
    };
};
var app = null;
$(document).ready(function () {
    app = new App();
    app.Startup();
});