angular
    .module('universal')
    .controller('StatisticsController', ['$scope', '$http', '$interval', 'uiGridGroupingConstants', function ($scope, $http, $interval, uiGridGroupingConstants) {

        $scope.VIEW = {};
        $scope.VIEW.isDate = false;
        $scope.formatters = {};

        $scope.gridOptions = {
            enableGridMenu: true,
            enableFiltering: true,
            treeRowHeaderAlwaysVisible: false,
            enableColumnResizing: true,
            columnDefs: [
                {
                    name: 'ProcessName',
                    grouping: { groupPriority: 0 },
                    sort: { priority: 0, direction: 'desc' },
                    cellTemplate: '<div><div ng-if="!col.grouping || col.grouping.groupPriority === undefined || col.grouping.groupPriority === null || ( row.groupHeader && col.grouping.groupPriority === row.treeLevel )" class="ui-grid-cell-contents" title="TOOLTIP">{{COL_FIELD CUSTOM_FILTERS}}</div></div>',
                    width: '250',
                    displayName: 'Наименование процесса'
                },
                {
                    name: 'RuleType',
                    sort: { priority: 0, direction: 'desc' },
                    width: '200',
                    displayName: 'Тип правила'
                },
                {
                    name: 'EntityType',
                    sort: { priority: 0, direction: 'desc' },
                    width: '210',
                    displayName: 'Тип факта/несоответствия'
                },
                /*{
                    name: 'RuleConfigId',
                    sort: { priority: 0, direction: 'desc' },
                    width: '350',
                    displayName: 'Название процесса'
                },*/
                {
                    name: 'Status',
                    width: '80',
                    displayName: 'Cтатус'
                },
                {
                    name: 'FileName',
                    width: '100',
                    displayName: 'Просмотр',
                    cellTemplate: '<div style="text-align:center;" ng-if="!row.groupHeader"><a href="/files/{{row.entity.FileName}}" target="_blank">Файл</a></div>'
                },
                /*{
                    name: 'Text',
                    width: '100'
                },
                {
                    name: 'BeginChar',
                    width: '100'
                },
                {
                    name: 'EndChar',
                    width: '100'
                },*/
                {
                    name: 'DateTimeCreated',
                    sort: { priority: 0, direction: 'desc' },
                    width: '150',
                    displayName: 'Дата создания',
                    /*cellTemplate: '<div><div ng-if="!row.groupHeader" class="ui-grid-cell-contents">{{grid.appScope.parseDate(row.entity.DateTimeCreated)}}</div></div>'*/
                },
                {
                    name: 'Rating',
                    treeAggregationType: uiGridGroupingConstants.aggregation.AVG,
                    customTreeAggregationFinalizerFn: function (aggregation) {
                        aggregation.rendered = aggregation.value;
                    },
                    width: '80',
                    displayName: 'Рейтинг'
                },

                /*{ name: 'name', width: '30%' },
                { name: 'gender', grouping: { groupPriority: 1 }, sort: { priority: 1, direction: 'asc' }, width: '20%', cellFilter: 'mapGender' },
                { name: 'age', treeAggregationType: uiGridGroupingConstants.aggregation.MAX, width: '20%' },
                { name: 'company', width: '25%' },
                { name: 'registered', width: '40%', cellFilter: 'date', type: 'date' },
                { name: 'state', grouping: { groupPriority: 0 }, sort: { priority: 0, direction: 'desc' }, width: '35%', cellTemplate: '<div><div ng-if="!col.grouping || col.grouping.groupPriority === undefined || col.grouping.groupPriority === null || ( row.groupHeader && col.grouping.groupPriority === row.treeLevel )" class="ui-grid-cell-contents" title="TOOLTIP">{{COL_FIELD CUSTOM_FILTERS}}</div></div>' },
                { name: 'balance', width: '25%', cellFilter: 'currency', treeAggregationType: uiGridGroupingConstants.aggregation.AVG, customTreeAggregationFinalizerFn: function( aggregation ) {
                  aggregation.rendered = aggregation.value;
                } }*/
            ],

            exporterMenuCsv: false,
            exporterMenuPdf: false,
            exporterExcelFilename: 'Точность работы правил.xlsx',
            exporterExcelSheetName: 'Sheet1',
            exporterExcelCustomFormatters: function (grid, workbook, docDefinition) {

                var stylesheet = workbook.getStyleSheet();
                var stdStyle = stylesheet.createFontStyle({
                    size: 9, fontName: 'Calibri'
                });
                var boldStyle = stylesheet.createFontStyle({
                    size: 9, fontName: 'Calibri', bold: true
                });
                var aFormatDefn = {
                    "font": boldStyle.id,
                    "alignment": { "wrapText": true }
                };
                var formatter = stylesheet.createFormat(aFormatDefn);
                // save the formatter
                $scope.formatters['bold'] = formatter;
                var dateFormatter = stylesheet.createSimpleFormatter('date');
                $scope.formatters['date'] = dateFormatter;

                aFormatDefn = {
                    "font": stdStyle.id,
                    "fill": { "type": "pattern", "patternType": "solid", "fgColor": "FFFFC7CE" },
                    "alignment": { "wrapText": true }
                };
                var singleDefn = {
                    font: stdStyle.id,
                    format: '#,##0.0'
                };
                formatter = stylesheet.createFormat(aFormatDefn);
                // save the formatter
                $scope.formatters['red'] = formatter;

                Object.assign(docDefinition.styles, $scope.formatters);

                return docDefinition;
            },
            exporterExcelHeader: function (grid, workbook, sheet, docDefinition) {
                // this can be defined outside this method
                var stylesheet = workbook.getStyleSheet();
                var aFormatDefn = {
                    "font": { "size": 11, "fontName": "Calibri", "bold": true },
                    "alignment": { "wrapText": true }
                };
                var formatterId = stylesheet.createFormat(aFormatDefn);

                // excel cells start with A1 which is upper left corner
                sheet.mergeCells('B1', 'C1');
                var cols = [];
                // push empty data
                cols.push({ value: '' });
                // push data in B1 cell with metadata formatter
                cols.push({ value: 'My header that is long enough to wrap', metadata: { style: formatterId.id } });
                sheet.data.push(cols);
            },
            exporterFieldApplyFilters: true,


            onRegisterApi: function (gridApi) {
                $scope.gridApi = gridApi;
            }

        };


        $scope.gridOptions2 = {
            enableGridMenu: true,
            enableFiltering: true,
            treeRowHeaderAlwaysVisible: false,
            enableColumnResizing: true,
            columnDefs: [
                {
                    name: 'ProcessName',
                    grouping: { groupPriority: 0 },
                    sort: { priority: 0, direction: 'desc' },
                    cellTemplate: '<div><div ng-if="!col.grouping || col.grouping.groupPriority === undefined || col.grouping.groupPriority === null || ( row.groupHeader && col.grouping.groupPriority === row.treeLevel )" class="ui-grid-cell-contents" title="TOOLTIP">{{COL_FIELD CUSTOM_FILTERS}}</div></div>',
                    width: '250',
                    displayName: 'Наименование процесса'
                },
                {
                    name: 'RuleTypeName',
                    sort: { priority: 0, direction: 'desc' },
                    width: '200',
                    displayName: 'Тип правила'
                },
                /*{
                    name: 'EntityTypeNames',
                    width: '200',
                    displayName: 'Выявленные типы'
                },*/
                {
                    name: 'Status',
                    width: '80',
                    displayName: 'Cтатус'
                },
                {
                    name: 'Rating',
                    treeAggregationType: uiGridGroupingConstants.aggregation.AVG,
                    customTreeAggregationFinalizerFn: function (aggregation) {
                        aggregation.rendered = aggregation.value;
                    },
                    width: '80',
                    displayName: 'Рейтинг'
                },
                {
                    name: 'Duration',
                    width: '150',
                    displayName: 'Длительность'
                },

                /*{ name: 'name', width: '30%' },
                { name: 'gender', grouping: { groupPriority: 1 }, sort: { priority: 1, direction: 'asc' }, width: '20%', cellFilter: 'mapGender' },
                { name: 'age', treeAggregationType: uiGridGroupingConstants.aggregation.MAX, width: '20%' },
                { name: 'company', width: '25%' },
                { name: 'registered', width: '40%', cellFilter: 'date', type: 'date' },
                { name: 'state', grouping: { groupPriority: 0 }, sort: { priority: 0, direction: 'desc' }, width: '35%', cellTemplate: '<div><div ng-if="!col.grouping || col.grouping.groupPriority === undefined || col.grouping.groupPriority === null || ( row.groupHeader && col.grouping.groupPriority === row.treeLevel )" class="ui-grid-cell-contents" title="TOOLTIP">{{COL_FIELD CUSTOM_FILTERS}}</div></div>' },
                { name: 'balance', width: '25%', cellFilter: 'currency', treeAggregationType: uiGridGroupingConstants.aggregation.AVG, customTreeAggregationFinalizerFn: function( aggregation ) {
                  aggregation.rendered = aggregation.value;
                } }*/
            ],


            exporterMenuCsv: false,
            exporterMenuPdf: false,
            exporterExcelFilename: 'Общее журналирование работы правил.xlsx',
            exporterExcelSheetName: 'Sheet1',
            exporterExcelCustomFormatters: function (grid, workbook, docDefinition) {

                var stylesheet = workbook.getStyleSheet();
                var stdStyle = stylesheet.createFontStyle({
                    size: 9, fontName: 'Calibri'
                });
                var boldStyle = stylesheet.createFontStyle({
                    size: 9, fontName: 'Calibri', bold: true
                });
                var aFormatDefn = {
                    "font": boldStyle.id,
                    "alignment": { "wrapText": true }
                };
                var formatter = stylesheet.createFormat(aFormatDefn);
                // save the formatter
                $scope.formatters['bold'] = formatter;
                var dateFormatter = stylesheet.createSimpleFormatter('date');
                $scope.formatters['date'] = dateFormatter;

                aFormatDefn = {
                    "font": stdStyle.id,
                    "fill": { "type": "pattern", "patternType": "solid", "fgColor": "FFFFC7CE" },
                    "alignment": { "wrapText": true }
                };
                var singleDefn = {
                    font: stdStyle.id,
                    format: '#,##0.0'
                };
                formatter = stylesheet.createFormat(aFormatDefn);
                // save the formatter
                $scope.formatters['red'] = formatter;

                Object.assign(docDefinition.styles, $scope.formatters);

                return docDefinition;
            },
            exporterExcelHeader: function (grid, workbook, sheet, docDefinition) {
                // this can be defined outside this method
                var stylesheet = workbook.getStyleSheet();
                var aFormatDefn = {
                    "font": { "size": 11, "fontName": "Calibri", "bold": true },
                    "alignment": { "wrapText": true }
                };
                var formatterId = stylesheet.createFormat(aFormatDefn);

                // excel cells start with A1 which is upper left corner
                sheet.mergeCells('B1', 'C1');
                var cols = [];
                // push empty data
                cols.push({ value: '' });
                // push data in B1 cell with metadata formatter
                cols.push({ value: 'My header that is long enough to wrap', metadata: { style: formatterId.id } });
                sheet.data.push(cols);
            },
            exporterFieldApplyFilters: true,


            onRegisterApi: function (gridApi) {
                $scope.gridApi = gridApi;
            }

        };

        $http.post('/Statistics/RuleStatisticsLogs', { })
            .then(function (response) {
                var data = response.data;

                for (o in data) {
                    data[o].DateTimeCreated = $scope.parseDate(data[o].DateTimeCreated);
                }

                $scope.gridOptions.data = data;
            });

        $http.post('/Statistics/InstanceRulesLogs', {})
            .then(function (response) {
                var data = response.data;
                $scope.gridOptions2.data = data;
            });

        $scope.parseDate = function (p) {
            return moment(p).format('DD/MM/YYYY h:mm:ss');
        }

        $scope.startDate = moment(new Date()).add(-30, 'days');
        $scope.endDate = moment(new Date());

        $scope.getRuleStatisticsData = function () {

            $.post(encodeURI('/Statistics/RuleStatisticsLogs'),
                {
                    startDate: $scope.startDate.format ? $scope.startDate.format() : moment($scope.startDate).format(),
                    endDate: $scope.endDate.format ? $scope.endDate.format() : moment($scope.endDate).format()
                },
                function (data) {

                    for (o in data) {
                        data[o].DateTimeCreated = $scope.parseDate(data[o].DateTimeCreated);
                    }

                    $scope.$apply(function () {
                        $scope.gridOptions.data = data;
                    });
                }
            );
        }

        $scope.getInstanceRuleData = function () {
            $.post(encodeURI('/Statistics/InstanceRulesLogs'),
                {
                    startDate: $scope.startDate.format ? $scope.startDate.format() : moment($scope.startDate).format(),
                    endDate: $scope.endDate.format ? $scope.endDate.format() : moment($scope.endDate).format()
                },
                function (data) {

                    $scope.$apply(function () {
                        $scope.gridOptions2.data = data;
                    });
                }
            );
        }

        $scope.expandAll = function () {
            $scope.gridApi.treeBase.expandAllRows();
        };

        $scope.toggleRow = function (rowNum) {
            $scope.gridApi.treeBase.toggleRowTreeState($scope.gridApi.grid.renderContainers.body.visibleRowCache[rowNum]);
        };

        $scope.changeGrouping = function () {
            $scope.gridApi.grouping.clearGrouping();
            $scope.gridApi.grouping.groupColumn('age');
            $scope.gridApi.grouping.aggregateColumn('state', uiGridGroupingConstants.aggregation.COUNT);
        };

        $scope.getAggregates = function () {
            var aggregatesTree = [];
            var gender

            var recursiveExtract = function (treeChildren) {
                return treeChildren.map(function (node) {
                    var newNode = {};
                    angular.forEach(node.row.entity, function (attributeCol) {
                        if (typeof (attributeCol.groupVal) !== 'undefined') {
                            newNode.groupVal = attributeCol.groupVal;
                            newNode.aggVal = attributeCol.value;
                        }
                    });
                    newNode.otherAggregations = node.aggregations.map(function (aggregation) {
                        return { colName: aggregation.col.name, value: aggregation.value, type: aggregation.type };
                    });
                    if (node.children) {
                        newNode.children = recursiveExtract(node.children);
                    }
                    return newNode;
                });
            }

            aggregatesTree = recursiveExtract($scope.gridApi.grid.treeBase.tree);

            console.log(aggregatesTree);
        };
    }])
    .filter('mapGender', function () {
        var genderHash = {
            1: 'male',
            2: 'female'
        };

        return function (input) {
            var result;
            var match;
            if (!input) {
                return '';
            } else if (result = genderHash[input]) {
                return result;
            } else if ((match = input.match(/(.+)( \(\d+\))/)) && (result = genderHash[match[1]])) {
                return result + match[2];
            } else {
                return input;
            }
        };
    });