define("ticketChartsControllers", ["SHARED/jquery", "SHARED/juzu-ajax"], function ($, jz) {
    var ticketChartsCtrl = function ($scope, $q, $timeout, $http, $filter) {
        var ticketChartsContainer = $('#ticketCharts');
        var deferred = $q.defer();
        $scope.selectedSpace = null;
        $scope.spaces=[];
        $scope.showGraphs = false;
        $scope.showSpaces = false;
        $scope.showSpaceCharts = true;
        $scope.showAllCustomerCharts = false;
        $scope.assignees=[];

		$scope.startDate=0;
		$scope.endDate=(new Date()).getTime();


                  var lessThan3Day = new Date();
                  lessThan3Day.setDate(lessThan3Day.getDate() - 2);
                  $scope.customTemplates = [
                    {
                      name: 'Last 3 Days',
                      dateStart: lessThan3Day,
                      dateEnd: new Date(),
                    }
                  ];
                  $scope.calendarModel = { selectedTemplate: 'Last 3 Days' };
                  $scope.pickerModel = { selectedTemplate: 'Last 3 Days' };
                  $scope.advancedModel = { selectedTemplate: 'Last 3 Days' };
                  $scope.serviceModel = { selectedTemplate: 'Last 3 Days' };
                  $scope.selectedDate = {};
                  $scope.selectedDates = [];
                  $scope.selectDateRange = function ($event, autoConfirm) {
                    $mdDateRangePicker.show({
                      model: $scope.serviceModel,
                      autoConfirm: autoConfirm,
                      targetEvent: $event,
                      customTemplates: $scope.customTemplates,
                    }).then(function (result) {
                      Object.assign($scope.serviceModel, result);
                    }).catch(function () {
                      console.log('Cancelled');
                    });
                  }
                  $scope.format = function (dateStart, dateEnd, template, templateName) {
                    return template ? 'Range of ' + (templateName || template) : (dateStart && dateEnd && (dateStart.toLocaleDateString() + ' to ' + dateEnd.toLocaleDateString()));
                  }
                  $scope.isDisabledDate = function (d) {
                    return d.getDay() === 0 || d.getDay() === 6;
                  }


            $scope.periods = [
                {name: "By week", value: "weekly"},
                {name: "By month", value: "mounthly"}
            ];

        $scope.setRange = function (dates) {
			$scope.startDate=dates[0].getTime();
			$scope.endDate=dates[dates.length-1].getTime();
			$scope.getCustomerOpenVsClosedTicketsByDates();
            $scope.getTicketsByStatusAndDatesChartData();
            $scope.getOpenVSClosedLineChartData();
        }

    $scope.getDisplayName = function(username){
      for (var i = 0; i < $scope.assignees.length; i++) {
        if ($scope.assignees[i].userName === username) {
           return $scope.assignees[i].displayName;
        }
      }
      return $scope.i18n.empty;
    }

        $scope.loadAssignees = function() {
           $http({
              method: 'GET',
              url : ticketChartsContainer.jzURL('TicketChartsController.getSupportUsernames')
           }).then(function successCallback(data) {
               $scope.assignees = data.data;
               $timeout(function() {
                 //   $scope.setResultMessage("", "info")
               }, 3000);
           },function errorCallback(data) {
               $scope.setResultMessage(data, "error");
           });
        }


        $scope.hideClvsOpSeries = function (selectedItem) {
            var col = selectedItem.column;
            if (selectedItem.row === null) {
                if ($scope.lineClvsOpChartObject.view.columns[col] == col) {
                    $scope.lineClvsOpChartObject.view.columns[col] = {
                        label: $scope.lineClvsOpChartObject.data.cols[col].label,
                        type: $scope.lineClvsOpChartObject.data.cols[col].type,
                        calc: function () {
                            return null;
                        }
                    };
                    $scope.lineClvsOpChartObject.options.colors[col - 1] = '#CCCCCC';
                } else {
                    $scope.lineClvsOpChartObject.view.columns[col] = col;
                    $scope.lineClvsOpChartObject.options.colors[col - 1] = $scope.lineClvsOpChartObject.options.defaultColors[col - 1];
                }
            }
        }

        $scope.lineClvsOpChartObject = {};
        $scope.lineClvsOpChartObject.type = "LineChart";
        $scope.lineClvsOpChartObject.displayed = false;


        $scope.lineClvsOpChartObject.options = {
			"backgroundColor": 'transparent',
            "colors": ['#4285f4', '#db4437'],
            "series": {
                0: {lineWidth: 3},
                1: {lineWidth: 3}
            },
            "defaultColors": ['#4285f4', '#db4437'],
            "isStacked": "false",
            "fill": 100,
            "displayExactValues": true,
            "curveType": "function",
            "tooltip": {isHtml: true},
            "focusTarget": 'category',
            "height": 450
        };
        $scope.lineClvsOpChartObject.view = {
            columns: [0, 1, 2]
        };





        $scope.hideLogbyStatusSeries = function (selectedItem) {
            var col = selectedItem.column;
            if (selectedItem.row === null) {
                if ($scope.lineLogbyStatusChartObject.view.columns[col] == col) {
                    $scope.lineLogbyStatusChartObject.view.columns[col] = {
                        label: $scope.lineLogbyStatusChartObject.data.cols[col].label,
                        type: $scope.lineLogbyStatusChartObject.data.cols[col].type,
                        calc: function () {
                            return null;
                        }
                    };
                    $scope.lineLogbyStatusChartObject.options.colors[col - 1] = '#CCCCCC';
                } else {
                    $scope.lineLogbyStatusChartObject.view.columns[col] = col;
                    $scope.lineLogbyStatusChartObject.options.colors[col - 1] = $scope.lineLogbyStatusChartObject.options.defaultColors[col - 1];
                }
            }
        }

        $scope.lineLogbyStatusChartObject = {};
        $scope.lineLogbyStatusChartObject.type = "LineChart";
        $scope.lineLogbyStatusChartObject.displayed = false;


        $scope.lineLogbyStatusChartObject.options = {
			"backgroundColor": 'transparent',
           // "colors": ['#4285f4', '#db4437'],
           /* "series": {
                0: {lineWidth: 3},
                1: {lineWidth: 3}
            },*/
            //"defaultColors": ['#4285f4', '#db4437'],
            "isStacked": "false",
            "fill": 100,
            "displayExactValues": true,
            "curveType": "function",
            "tooltip": {isHtml: true},
            "focusTarget": 'category',
            "height": 450
        };
        $scope.lineLogbyStatusChartObject.view = {
            columns: [0, 1, 2, 3,4,5]
        };


        $scope.pieChartSpaceByStatusObject = {};
        $scope.pieChartSpaceByStatusObject.options = {
            backgroundColor: 'transparent',
            pieHole: 0.3,
            title: 'Space tickets by status'
        };
        $scope.pieChartSpaceByStatusObject.type = "ColumnChart";

        $scope.pieChartSpaceByOwnerObject = {};
        $scope.pieChartSpaceByOwnerObject.options = {
            backgroundColor: 'transparent',
            pieHole: 0.3,
            title: 'Space tickets by Owner'
        };
        $scope.pieChartSpaceByOwnerObject.type = "PieChart";

        $scope.pieChartSpaceByAssigneeObject = {};
        $scope.pieChartSpaceByAssigneeObject.options = {
            backgroundColor: 'transparent',
            pieHole: 0.3,
            title: 'Space tickets by Assignee'
        };
        $scope.pieChartSpaceByAssigneeObject.type = "PieChart";



        $scope.pieChartBySpaceObject = {};
        $scope.pieChartBySpaceObject.options = {
            backgroundColor: 'transparent',
            pieHole: 0.3,
            title: 'All customer tickets by space'
        };
        $scope.pieChartBySpaceObject.type = "PieChart";

        $scope.pieChartByOwnerObject = {};
        $scope.pieChartByOwnerObject.options = {
            backgroundColor: 'transparent',
            pieHole: 0.3,
            title: 'All customer tickets by owner'
        };
        $scope.pieChartByOwnerObject.type = "PieChart";

        $scope.pieChartByStatusObject = {};
        $scope.pieChartByStatusObject.options = {
            backgroundColor: 'transparent',
            pieHole: 0.3,
            title: 'All customer tickets by status'
        };
        $scope.pieChartByStatusObject.type = "ColumnChart";


        $scope.pieChartClosedVsOpenedObject = {};
        $scope.pieChartClosedVsOpenedObject.options = {
            backgroundColor: 'transparent',
            pieHole: 0.3,
            title: 'Closed VS Opened Customer tickets'
        };
        $scope.pieChartClosedVsOpenedObject.type = "PieChart";


                $scope.columnChartBySpaceObject = {};
                $scope.columnChartBySpaceObject.options = {
                backgroundColor: 'transparent',
                title: 'All customer tickets by space'
                };
                $scope.columnChartBySpaceObject.type = "BarChart";



        $scope.setResultMessage = function (text, type) {
            $scope.resultMessageClass = "alert-" + type;
            $scope.resultMessageClassExt = "uiIcon" + type.charAt(0).toUpperCase()+ type.slice(1);
            $scope.showAlert = true;
            $scope.resultMessage = text;
        }


        $scope.loadBundle = function () {
            $http({
                method: 'GET',
                url: ticketChartsContainer.jzURL('TicketChartsController.getBundle') + "&locale=" + eXo.env.portal.language
            }).then(function successCallback(data) {
                $scope.i18n = data.data;
                deferred.resolve(data);
                /*$scope.setResultMessage(data, "success");*/
                $scope.showAlert = false;
            }, function errorCallback(data) {
                $scope.setResultMessage($scope.i18n.defaultError, "error");
            });
        }





                $scope.getSpaceTicketsByAssigneeChartData = function (spaceId) {
                    $http({
                        method: 'GET',
                        url: ticketChartsContainer.jzURL('TicketChartsController.countSpaceTicketsGroupdByAssignee')+ "&spaceId="+spaceId
                    }).then(function successCallback(data) {
                        $scope.ticketsNumberByStatusList = data.data;

                              var ticketsArray = [];
                                for(var i = 0; i < $scope.ticketsNumberByStatusList.length; i++) {
                                     var obj = $scope.ticketsNumberByStatusList[i];
                                              ticketsArray.push({ c: [{v:  $scope.getDisplayName(obj.assignee)}, {v: obj.ticketNumber}]});
                                         }
                            $scope.pieChartSpaceByAssigneeObject.data = {"cols": [
                                {id: "t", label: "Assignee", type: "string"},
                                {id: "s", label: "Tickets", type: "number"}
                            ], "rows":  ticketsArray
                            };

                        deferred.resolve(data);
                    }, function errorCallback(data) {
                        $scope.setResultMessage($scope.i18n.defaultError, "error");
                    });
                }





                $scope.getSpaceTicketsByStatusChartData = function (spaceId) {
                    $http({
                        method: 'GET',
                        url: ticketChartsContainer.jzURL('TicketChartsController.countSpaceTicketsGroupdByStatus')+ "&spaceId="+spaceId
                    }).then(function successCallback(data) {
                        $scope.ticketsNumberByStatusList = data.data;

                              var ticketsArray = [];
                                for(var i = 0; i < $scope.ticketsNumberByStatusList.length; i++) {
                                     var obj = $scope.ticketsNumberByStatusList[i];
                                              ticketsArray.push({ c: [{v: $scope.i18n[obj.status]}, {v: obj.ticketNumber}]});
                                         }
                            $scope.pieChartSpaceByStatusObject.data = {"cols": [
                                {id: "t", label: "Status", type: "string"},
                                {id: "s", label: "Tickets", type: "number"}
                            ], "rows":  ticketsArray
                            };

                        deferred.resolve(data);
                    }, function errorCallback(data) {
                        $scope.setResultMessage($scope.i18n.defaultError, "error");
                    });
                }




                $scope.getSpaceTicketsByOwnerChartData = function (spaceId) {
                    $http({
                        method: 'GET',
                        url: ticketChartsContainer.jzURL('TicketChartsController.countSpaceTicketsGroupdByOwner')+ "&spaceId="+spaceId
                    }).then(function successCallback(data) {
                        $scope.ticketsNumberByStatusList = data.data;

                              var ticketsArray = [];
                                for(var i = 0; i < $scope.ticketsNumberByStatusList.length; i++) {
                                     var obj = $scope.ticketsNumberByStatusList[i];
                                              ticketsArray.push({ c: [{v: obj.owner}, {v: obj.ticketNumber}]});
                                         }
                            $scope.pieChartSpaceByOwnerObject.data = {"cols": [
                                {id: "t", label: "Owner", type: "string"},
                                {id: "s", label: "Tickets", type: "number"}
                            ], "rows":  ticketsArray
                            };

                        deferred.resolve(data);
                    }, function errorCallback(data) {
                        $scope.setResultMessage($scope.i18n.defaultError, "error");
                    });
                }

                $scope.getTicketsBySpaceChartData = function () {
                    $http({
                        method: 'GET',
                        url: ticketChartsContainer.jzURL('TicketChartsController.getCustomerTicketsGroupdBySpace')
                    }).then(function successCallback(data) {
                        $scope.ticketsNumberBySpaceList = data.data;


                              var ticketsArray = [];
                                for(var i = 0; i < $scope.ticketsNumberBySpaceList.length; i++) {
                                     var obj = $scope.ticketsNumberBySpaceList[i];
                                              ticketsArray.push({ c: [{v: obj.space}, {v: obj.ticketNumber}]});
                                         }
                            $scope.pieChartBySpaceObject.data = {"cols": [
                                {id: "t", label: "Space", type: "string"},
                                {id: "s", label: "Tickets", type: "number"}
                            ], "rows":  ticketsArray
                            };
                            $scope.columnChartBySpaceObject.data = {"cols": [
                                {id: "t", label: "Space", type: "string"},
                                {id: "s", label: "Tickets", type: "number"}
                            ], "rows":  ticketsArray
                            };

                        deferred.resolve(data);
                    }, function errorCallback(data) {
                        $scope.setResultMessage($scope.i18n.defaultError, "error");
                    });
                }


                $scope.getTicketsByOwnerChartData = function () {
                    $http({
                        method: 'GET',
                        url: ticketChartsContainer.jzURL('TicketChartsController.getCustomerTicketsGroupdByOwner')
                    }).then(function successCallback(data) {
                        $scope.ticketsNumberByOwnerList = data.data;

                              var ticketsArray = [];
                                for(var i = 0; i < $scope.ticketsNumberByOwnerList.length; i++) {
                                     var obj = $scope.ticketsNumberByOwnerList[i];
                                              ticketsArray.push({ c: [{v: obj.owner}, {v: obj.ticketNumber}]});
                                         }
                            $scope.pieChartByOwnerObject.data = {"cols": [
                                {id: "t", label: "Owner", type: "string"},
                                {id: "s", label: "Tickets", type: "number"}
                            ], "rows":  ticketsArray
                            };

                        deferred.resolve(data);
                    }, function errorCallback(data) {
                        $scope.setResultMessage($scope.i18n.defaultError, "error");
                    });
                }

                $scope.getTicketsByStatusChartData = function () {
                    $http({
                        method: 'GET',
                        url: ticketChartsContainer.jzURL('TicketChartsController.getCustomerTicketsGroupdByStatus')
                    }).then(function successCallback(data) {
                        $scope.ticketsNumberByStatusList = data.data;

                              var ticketsArray = [];
                                for(var i = 0; i < $scope.ticketsNumberByStatusList.length; i++) {
                                     var obj = $scope.ticketsNumberByStatusList[i];
                                              ticketsArray.push({ c: [{v: $scope.i18n[obj.status]}, {v: obj.ticketNumber}]});
                                         }
                            $scope.pieChartByStatusObject.data = {"cols": [
                                {id: "t", label: "Status", type: "string"},
                                {id: "s", label: "Tickets", type: "number"}
                            ], "rows":  ticketsArray
                            };

                        deferred.resolve(data);
                    }, function errorCallback(data) {
                        $scope.setResultMessage($scope.i18n.defaultError, "error");
                    });
                }

                $scope.getCustomerOpenVsClosedTickets = function () {
                    $http({
                        method: 'GET',
                        url: ticketChartsContainer.jzURL('TicketChartsController.getCustomerOpenVsClosedTickets')
                    }).then(function successCallback(data) {
                        $scope.ticketsNumberClosedVsOpenedList = data.data;

                              var ticketsArray = [];
                                for(var i = 0; i < $scope.ticketsNumberClosedVsOpenedList.length; i++) {
                                     var obj = $scope.ticketsNumberClosedVsOpenedList[i];
                                              ticketsArray.push({ c: [{v: obj.status}, {v: obj.ticketNumber}]});
                                         }
                            $scope.pieChartClosedVsOpenedObject.data = {"cols": [
                                {id: "t", label: "Status", type: "string"},
                                {id: "s", label: "Tickets", type: "number"}
                            ], "rows":  ticketsArray
                            };

                        deferred.resolve(data);
                    }, function errorCallback(data) {
                        $scope.setResultMessage($scope.i18n.defaultError, "error");
                    });
                }


                 $scope.getCustomerOpenVsClosedTicketsByDates = function () {
                     $http({
                         method: 'GET',
                         url: ticketChartsContainer.jzURL('TicketChartsController.getCustomerOpenVsClosedTicketsByDates')+ "&startDate=" + $scope.startDate + "&endDate=" + $scope.endDate
                     }).then(function successCallback(data) {
                         $scope.ticketsNumberClosedVsOpenedList = data.data;

                               var ticketsArray = [];
                                 for(var i = 0; i < $scope.ticketsNumberClosedVsOpenedList.length; i++) {
                                      var obj = $scope.ticketsNumberClosedVsOpenedList[i];
                                               ticketsArray.push({ c: [{v: obj.status}, {v: obj.ticketNumber}]});
                                          }
                             $scope.pieChartClosedVsOpenedObject.data = {"cols": [
                                 {id: "t", label: "Status", type: "string"},
                                 {id: "s", label: "Tickets", type: "number"}
                             ], "rows":  ticketsArray
                             };

                         deferred.resolve(data);
                     }, function errorCallback(data) {
                         $scope.setResultMessage($scope.i18n.defaultError, "error");
                     });
                 }


                $scope.getTicketsByStatusAndDatesChartData = function () {
                    $http({
                        method: 'GET',
                        url: ticketChartsContainer.jzURL('TicketChartsController.getCustomerTicketsGroupdByStatusAndDates')+ "&startDate=" + $scope.startDate + "&endDate=" + $scope.endDate
                    }).then(function successCallback(data) {
                        $scope.ticketsNumberByStatusList = data.data;

                              var ticketsArray = [];
                                for(var i = 0; i < $scope.ticketsNumberByStatusList.length; i++) {
                                     var obj = $scope.ticketsNumberByStatusList[i];
                                              ticketsArray.push({ c: [{v: $scope.i18n[obj.status]}, {v: obj.ticketNumber}]});
                                         }
                            $scope.pieChartByStatusObject.data = {"cols": [
                                {id: "t", label: "Status", type: "string"},
                                {id: "s", label: "Tickets", type: "number"}
                            ], "rows":  ticketsArray
                            };

                        deferred.resolve(data);
                    }, function errorCallback(data) {
                        $scope.setResultMessage($scope.i18n.defaultError, "error");
                    });
                }




        $scope.loadData = function () {
            $http({
                method: 'GET',
                url: ticketChartsContainer.jzURL('TicketChartsController.getData')
            }).then(function successCallback(data) {
                d = data.data;
                if(d.currentSpace==null){
                 $scope.loadSpaces();
                 $scope.showSpaces = true;
                 $scope.showSpaceCharts = false;
                 $scope.showAllCustomerCharts = true;
                 $scope.getTicketsBySpaceChartData();
                 $scope.getTicketsByOwnerChartData();
                 $scope.getTicketsByStatusChartData();
                 $scope.getCustomerOpenVsClosedTickets();
                 $scope.getOpenVSClosedLineChartData();
				 $scope.getLogbyStatusChartData();
                }else{
                 $scope.showSpaceCharts = true;
                 $scope.showAllCustomerCharts = false;
                 $scope.getSpaceTicketsByAssigneeChartData(d.currentSpace);
                 $scope.getSpaceTicketsByStatusChartData(d.currentSpace);
                 $scope.getSpaceTicketsByOwnerChartData(d.currentSpace);
                }
                deferred.resolve(data);
            }, function errorCallback(data) {
                $scope.setResultMessage($scope.i18n.defaultError, "error");
            });
        }

        $scope.loadSpaces = function () {
            $http({
                method: 'GET',
                url: ticketChartsContainer.jzURL('TicketChartsController.getSpaces')
            }).then(function successCallback(data) {
                $scope.spaces = data.data;

                $scope.showAlert = false;
            }, function errorCallback(data) {
                $scope.setResultMessage($scope.i18n.defaultError, "error");
            });

        };


        $scope.getSpaceData = function (currentSpace) {
                 $scope.selectedSpace=currentSpace;
                 $scope.showSpaceCharts = true;
                 $scope.showAllCustomerCharts = false;
                 $scope.getSpaceTicketsByAssigneeChartData(currentSpace);
                 $scope.getSpaceTicketsByStatusChartData(currentSpace);
                 $scope.getSpaceTicketsByOwnerChartData(currentSpace);
        }


                $scope.getOpenVSClosedLineChartData = function () {
                    $http({
                        method: 'GET',
                        url: ticketChartsContainer.jzURL('TicketChartsController.getOpenVSClosedStatLog')
                    }).then(function successCallback(data) {
                 $scope.stats = data.data;

                 var statArray = [];
                 for (var i = 0; i < $scope.stats.length; i++) {
                     var obj = $scope.stats[i];

                     statArray.push({c: [{v: obj.statDate}, {v: obj.openedTicketNumber, f: ' '+obj.openedTicketNumber}, {v: obj.closedTicketNumber, f:' '+obj.closedTicketNumber }]});
                 }


                 $scope.lineClvsOpChartObject.data = {
                     "cols": [{
                             id: "day",
                             label: "Day",
                             type: "string"
                         }, {
                             id: "open",
                             label: $scope.i18n[open],
                             type: "number"
                         }, {
                             id: "close",
                             label: $scope.i18n[closed],
                             type: "number"
                         }],
                     "rows": statArray
                 };

                        deferred.resolve(data);
                    }, function errorCallback(data) {
                        $scope.setResultMessage($scope.i18n.defaultError, "error");
                    });
                }


				$scope.getLogbyStatusChartData = function () {
                    $http({
                        method: 'GET',
                        url: ticketChartsContainer.jzURL('TicketChartsController.getLogbyStatusChartData')
                    }).then(function successCallback(data) {
                 $scope.stats = data.data;

                 var statArray = [];
                 for (var i = 0; i < $scope.stats.length; i++) {
                     var obj = $scope.stats[i];

                     statArray.push({c: [{v: obj.statDate},
					 {v: obj.openedTicketNumber, f:  " "+obj.openedTicketNumber},
					 {v: obj.waitingCustomerTicketNumber, f: " "+obj.waitingCustomerTicketNumber},
					 {v: obj.waitingProductTicketNumber, f: " "+obj.waitingProductTicketNumber},
					 {v: obj.inProgressTicketNumber, f: " "+obj.inProgressTicketNumber},
					 {v: obj.resolvedTicketNumber, f: " "+obj.resolvedTicketNumber}
					 ]});
                 }


                 $scope.lineLogbyStatusChartObject.data = {
                     "cols": [{
                             id: "day",
                             label: "Day",
                             type: "string"
                         }, {
                             id: "open",
                             label: $scope.i18n["open"],
                             type: "number"
                         }, {
                             id: "waitingCustomer",
                             label: $scope.i18n["suspended_wfi"],
                             type: "number"
                         }, {
                             id: "waitingProduct",
                             label: $scope.i18n["resolved_maintenance"],
                             type: "number"
                         }, {
                             id: "inProgress",
                             label: $scope.i18n["inprogress"],
                             type: "number"
                         }, {
                             id: "resolved",
                             label: $scope.i18n["resolved_validated"],
                             type: "number"
                         }],
                     "rows": statArray
                 };

                        deferred.resolve(data);
                    }, function errorCallback(data) {
                        $scope.setResultMessage($scope.i18n.defaultError, "error");
                    });
                }


        $scope.loadBundle();
        $scope.loadData();
        $scope.loadAssignees();

        $('#ticketCharts').css('visibility', 'visible');
        $(".csLoadingBar").remove();

    };
        return ticketChartsCtrl;

});
