app.controller('sedaRemunerationCtrl',
	
function ($scope,$http,$cookies,$window, $location,$timeout, $mdDialog, $q, $mdBottomSheet, utilsSvc, userService, Remuneration) {
	var vm=this;
	
	vm.maxItems = 0;
	vm.maxDetailItems = 0;
	vm.itemsPerPage = 500;
	vm.records=[];
	vm.detailrecords=[];
	vm.currentDetailId = 0;
	vm.codiciSia=[];
	vm.codiceSiaSelezionato='';
	vm.selectedIndex = -1;
	vm.selectedDetailIndex = 0;
	
	vm.columnWidths=[
			70,  //0
			50,  //1
			80, //2
			220, //3
			180,  //4
			90, //5
			100, //6
			100, //7
			100,  //8
			80, //9
			100,  //10
			100,  //11
			100, //12
			120, //13
			100,  //14
			90, //15
			90, //16
			90, //17.
			90, //18
			150, //19
			150, //20
			90, //21
			120, //22
			120, //23
			90,
			320
		];

	vm.getListHeight = function() {
		containerHeight = $('#details').position().top - $('#container').position().top-8;
		  return {'height':  containerHeight + 'px'};
	};
	
	vm.getGridItemHeight = function() {
		return utilsSvc.getGridHeight();
	}
	
	vm.getGridWithButtonItemHeight = function() {
		return utilsSvc.getGridWithButtonHeight();
	}

	vm.getDetailListHeight = function() {
		
		detailsContainerHeight = window.innerHeight - document.getElementById('vertical-container-details').getBoundingClientRect().top-50;
		  return {'height':  detailsContainerHeight + 'px'};
	};
	
	$window.addEventListener('resize', onResize);
	function onResize() {
	  $scope.$digest();
	}
	
	$scope.$on('$destroy', function() {
	  $window.removeEventListener('resize', onResize);
	});
	
	vm.largeScreen =function(){
		return utilsSvc.largeScreen();
	}

		
	vm.getColumnWidth =  function(idx) {
		return {
				'width': vm.columnWidths[idx] + 'px', 
				'min-width':vm.columnWidths[idx] + 'px',
				//'padding-left':'6px',
				//'padding-right':'6px',
				'margin-left':'8px',
				'margin-right':'8px'
		};
	}
	
	vm.getMaxListWidth = function() {
		var res=0;
		for (var i=0;i<vm.columnWidths.length;i++)
			res += vm.columnWidths[i]+6+8+10;
		
		return {'width': res + 'px'}
	}
	
	vm.getStatusColor = function(statusCode) {
		var color;
		if (statusCode==0)
			color = 'red';
		else if (statusCode==1)
			color = 'green';
		else
			color = 'yellow';
		return {'color': color};
	}
	
	vm.decodeTipoDettaglio = function(tipo){
		if (tipo=='CMF')
			return 'Solo mandati rilasciati presso il beneficiario';
		if (tipo=='DMF')
			return 'Solo mandati rilasciati presso PSP (Banca) del pagatore';
		if (tipo=='ALL')
			return 'Tutti i mandati';
	}
	
	vm.decodeTipoRichiesta = function(tipo){
		if (tipo=='ALL')
			return 'Tutti i Mandati attivi nel periodo di riferimento';
		if (tipo=='CHG')
			return 'Mandati attivati nel periodo di riferimento e mandati revocati o disattivati nel periodo di riferimento precedente';
	}
	
	vm.getCodiciSia = function() {
		Remuneration.CodiciSia().$promise.then(function(data){
			vm.codiciSia = data;
		})
	}
	
	vm.setOrderField = function(field) {
		if (vm.filter.orderField!=field)
			vm.filter.orderField = field;
		else
			vm.filter.orderField = "-" +field;
		
		vm.getData();
	}
	
	vm.infiniteItems = {
	          numLoaded_: 0,
	          toLoad_: 0,
	          loading_:false,
	          lastStartIdx:-1,
	          listPromise:null,
	          canceler: $q.defer(),
	          // Required.
	          getItemAtIndex: function(index) {
	        	  if (vm.maxItems==0 || index>vm.maxItems)
	        		  return null;
	        	  if (!vm.infiniteItems.loading_)
	        		  if (index > vm.records.length) {
	        			  this.fetchMoreItems_(index);
	        			  return null;
	        		  }
	            return vm.records [index];
	          },
	          // Required.
	          // For infinite scroll behavior, we always return a slightly
				// higher
	          // number than the previously loaded items.
	          getLength: function() {
        		  return vm.maxItems;
	        	  
	          },
	          fetchMoreItems_: function(index) {
	            if (this.toLoad_ < index) {
	              this.toLoad_ += vm.itemsPerPage;
	              utilsSvc.showWaitMessage('Ricerca in corso...');
	              vm.infiniteItems.loading_ = true;
	              
		          this.listPromise = Remuneration.Header({codiceSia: vm.codiceSiaSelezionato, start: vm.records.length,size:Math.max(vm.records.length+index,vm.itemsPerPage)}).$promise;
		          var mod=this;
		          this.listPromise.then(
			              			function(data){
			              				vm.infiniteItems.loading_ = false;
			              				vm.infiniteItems.toLoad_=0;
			              				utilsSvc.cancelWaitMessage();
			              				vm.records = vm.records.concat(data);
			              				mod.numLoaded_ = vm.records.length;
			              				mod.lastStartIdx = vm.records.length;
			              				if (vm.records.length>0 && vm.selectedIndex==-1) {
			              					vm.selectedIndex=0;
			              					vm.getProvisioning(0, vm.records[0].idremuneration);
			              				}

			              			},
			              			function(error) {
			              				vm.infiniteItems.loading_ = false;
			              				vm.infiniteItems.toLoad_=0;
			              				utilsSvc.handleHttpError(error);
			              			}
			              	)
              
              }
	          }
	}	

	vm.infiniteDetailItems = {
	          numLoaded_: 0,
	          toLoad_: 0,
	          loading_:false,
	          lastStartIdx:-1,
	          listPromise:null,
	          canceler: $q.defer(),
	          // Required.
	          getItemAtIndex: function(index) {
	        	  if (vm.maxDetailItems==0 || index>vm.maxDetailItems)
	        		  return null;
	        	  if (!vm.infiniteDetailItems.loading_)
	        		  if (index > vm.detailrecords.length) {
	        			  this.fetchMoreItems_(index);
	        			  return null;
	        		  }
	        	  return vm.detailrecords [index];
	          },
	          // Required.
	          // For infinite scroll behavior, we always return a slightly
				// higher
	          // number than the previously loaded items.
	          getLength: function() {
	        	  return vm.maxDetailItems;
	          },
	          fetchMoreItems_: function(index) {
	            if (this.toLoad_ < index) {
	              this.toLoad_ += vm.itemsPerPage;
	              utilsSvc.showWaitMessage('Ricerca in corso...');
	              vm.infiniteDetailItems.loading_ = true;
	              
		              this.listPromise = Remuneration.Provisioning({id: vm.currentDetailId,start: vm.detailrecords.length,size:Math.max(vm.detailrecords.length+index,vm.itemsPerPage)}).$promise;
		              var moddetail=this;
		              this.listPromise.then(
			              			function(data){
			              				vm.infiniteDetailItems.loading_ = false;
			              				vm.infiniteDetailItems.toLoad_=0;
			              				utilsSvc.cancelWaitMessage();
			              				vm.detailrecords = vm.detailrecords.concat(data);
			              				moddetail.numLoaded_ = vm.detailrecords.length;
			              				moddetail.lastStartIdx = vm.detailrecords.length;
			              			},
			              			function(error) {
			              				vm.infiniteDetailItems.loading_ = false;
			              				vm.infiniteDetailItems.toLoad_=0;
			              				utilsSvc.handleHttpError(error);
			              			}
			              	)
            
            }
	          }
	}	
	
	

	vm.getData = function(){
		Remuneration.HeaderCount({codiceSia: vm.codiceSiaSelezionato}).$promise.then(
				function(data){
					vm.records=[];
					vm.maxItems = data.value;
					vm.infiniteItems.numLoaded_ = 0;
					vm.infiniteItems.toLoad_ = 0;
				}
		);
		
	}
	
	
	
	
	vm.getProvisioning = function(idx, idremuneration) {
		vm.selectedIndex = idx;
		vm.currentDetailId = idremuneration;
		Remuneration.ProvisioningCount({id: idremuneration}).$promise.then(
				function(data){
					vm.detailrecords=[];
					vm.maxDetailItems = data.value;
					vm.infiniteDetailItems.numLoaded_ = 0;
					vm.infiniteDetailItems.toLoad_ = 0;
				}
		);	
	}	
	
	vm.richiestaDettaglioTuttiTrimestri = function(idx, event) {
		$mdDialog.show({
    		targetEvent:event,
            templateUrl: 'templates/richiestaDettaglioMandatiSeda.html',
            controller: 'opzioniDettaglioCtrl',
            locals: {
            	dialogTitle:'Richiesta dettaglio mandati SEDA'
            },
            multiple: true
        }).then(function(opzioni){
        	Remuneration.GeneraRichiestaDettagli({id:vm.records[idx].idremuneration, all: true, tipoDettaglio:opzioni.tipologiaDettaglio,tipoRichiesta: opzioni.tipologiaRichiesta})
        		.$promise.then(function(data){
        			if (data.value=="")
        				utilsSvc.showMessage("Richiesta dettaglio mandati effettuata");
        			else
        				utilsSvc.showMessage("Si è verificato un errore durante l'esecuzione del comando: " + data.value);

        		})
        });
	}
	
	vm.exportMessaggi = function(idx, event) {
		if (vm.records[idx].flagUtil) {
			utilsSvc.showConfirm('Conferma', 'I messaggi SEDA Remuneration per il rendiconto corrente sono già stati creati, vuoi eseguire una nuova esportazione?')
				.then(function(){
					vm.doExportMessaggi(idx, event);
				})
		} else
			vm.doExportMessaggi(idx,event);
	}

	vm.doExportMessaggi = function(idx, event) {
		utilsSvc.showConfirm('Conferma',"Confermi l'esportazione dei messaggi SEDA Remuneration per il rendiconto corrente?")
			.then(function(res){
				Remuneration.ExportMessaggi({idremuneration:vm.records[idx].idremuneration})
					.$promise.then(function(data){
						vm.records[idx].flagUtil=true;
						var dt = new Date();
						utilsSvc.downloadFile('attachment/csv',data.response,'ExportRemunerationSeda_' + dt.getFullYear()+dt.getMonth().padZero(2)+dt.getDay().padZero(2)+'_'
								+dt.getHours().padZero(2)+  dt.getMinutes().padZero(2)
								+'.csv');

					}
				).catch(function(err){
					if (err.status == 404)
						utilsSvc.showForever('Messuna delega estratta');
					else
						utilsSvc.handleHttpError(err);
				});
			})
	}
	
	
	
	vm.ricalcolaQuadratura = function(event) {
		if (vm.records.length>0 && vm.detailrecords.length>0) {
			utilsSvc.showConfirm('Conferma',"Confermi il ricalcolo della quadratura mandati attivi per tutti i trimestri presenti?")
				.then(function(res){
					utilsSvc.showForever('Richiesta in corso...');
					Remuneration.QuadraRemuneration({id:vm.records[vm.selectedIndex].idremuneration})
						.$promise.then(function(data){
							if (data.value=="0")
								utilsSvc.showMessage("Ricalcolo quadratura effettuato.");
							else 
								utilsSvc.showMessage("Si è verificato un errore durante il ricalcolo: " +data.value);

							vm.getData();
						});
				})
		}
	}
	
	vm.ricalcolaQuadraturaDettaglio = function(event) {
		if (vm.records.length>0 && vm.detailrecords.length>0) {
			utilsSvc.showConfirm('Conferma',"Confermi il ricalcolo della quadratura mandati attivi per il rendiconto corrente?")
				.then(function(res){
					utilsSvc.showForever('Richiesta in corso...');
					Remuneration.QuadraDetail({id:vm.records[vm.selectedIndex].idremuneration, idDettaglio:vm.detailrecords[vm.selectedDetailIndex].idprevisioning})
						.$promise.then(function(data){
							if (data.value=="0")
								utilsSvc.showMessage("Ricalcolo quadratura effettuato.");
							else 
								utilsSvc.showMessage("Si è verificato un errore durante il ricalcolo: " +data.value);

							vm.getData();
						});
				})
		}
	}
	
	vm.richiestaDettaglioMandati = function(idx, event) {
		Remuneration.DetailCount({id: vm.detailrecords[idx].idprevisioning})
			.$promise.then(function(data){
				if (data.value==0)
					utilsSvc.showMessage('Non è presente il dettaglio dei mandati ');
				else {
					$mdDialog.show({
			    		targetEvent:event,
			            templateUrl: 'templates/dettaglioMandati.html',
			            controller: 'dettaglioMandatiCtrl',
			            locals: {
			            	dialogTitle:'Dettaglio mandati',
			            	maxItems: data.value,
			            	id: vm.detailrecords[idx].idprevisioning
			            },
			            multiple: true
			        }).then(function(opzioni){
			        });
					
				}
			})		
	}
	
	vm.stampaRendiconto = function(idx, event) {
		utilsSvc.showForever('Generazione report in corso...');
		Remuneration.PrintPrevisioning({id: vm.detailrecords[idx].idremuneration})
			.$promise.then(function(data){
				utilsSvc.downloadFile('application/pdf',data.response,'sedaRemuneration.pdf');
				utilsSvc.cancelMessage();
			}).catch(function(err){
				if (err.status==404) {
					utilsSvc.cancelMessage();
					utilsSvc.showMessage('Nessun rendiconto estratto');
				} else 
					utilsSvc.handleHttpError(err);
			});	;		
	}
	
	
	
	vm.richiestaDettaglioTrimestre = function(idx, event) {
		$mdDialog.show({
    		targetEvent:event,
            templateUrl: 'templates/richiestaDettaglioMandatiSeda.html',
            controller: 'opzioniDettaglioCtrl',
            locals: {
            	dialogTitle:'Richiesta dettaglio mandati SEDA'
            },
            multiple: true
        }).then(function(opzioni){
        	Remuneration.GeneraRichiestaDettagliTrimestre({id:vm.records[vm.selectedIndex].idremuneration, idDettaglio: vm.detailrecords[idx].idprevisioning, all: true, tipoDettaglio:opzioni.tipologiaDettaglio,tipoRichiesta: opzioni.tipologiaRichiesta})
        		.$promise.then(function(data){
        			if (data.value=="")
        				utilsSvc.showMessage("Richiesta dettaglio mandati effettuata");
        			else
        				utilsSvc.showMessage("Si è verificato un errore durante l'esecuzione del comando: " + data.value);
        		})
        });
	}
	
	
	vm.mostraComandi = function(index, event){
		vm.getProvisioning(index, vm.records[index].idremuneration); 
		vm.selectedIndex = index;
	    $mdBottomSheet.show({
	      templateUrl: 'templates/bottom-sheet-template.html',
	      controller: 'comandiRemunerationCtrl',
	      idx: index,
	      targetEvent: event
	    }).then(function(selectedCommand) {
	      vm.executeCommand(selectedCommand.cmdIndex, selectedCommand.recordIdx, event);
	    }, 
    	function(){}
	    );
	}
	

	vm.mostraComandiDettaglio = function(index, event){
		vm.selectedDetailIndex = index;
	    $mdBottomSheet.show({
	      templateUrl: 'templates/bottom-sheet-template.html',
	      controller: 'comandiDettaglioCtrl',
	      idx: index,
	      targetEvent: event
	    }).then(function(selectedCommand) {
	      vm.executeDetailCommand(selectedCommand.cmdIndex, selectedCommand.recordIdx, event);
	    }, 
    	function(){}
	    );
	}
	

	vm.init = function() {
		vm.getCodiciSia();
		vm.getData();
	}	
	
	
	vm.executeDetailCommand = function(cmdIndex, idx, event) {
		switch(cmdIndex){
		case 0: vm.richiestaDettaglioTrimestre(idx, event); break;
		case 1: vm.richiestaDettaglioMandati(idx, event); break;
		case 2: vm.stampaRendiconto(idx, event); break;
		case 3: vm.ricalcolaQuadraturaDettaglio(event); break; 
		
		}
	}
	
	vm.executeCommand = function(cmdIndex, idx, event) {
		switch(cmdIndex){
		case 0: vm.richiestaDettaglioTuttiTrimestri(idx, event); break;
		case 1: vm.exportMessaggi(idx, event); break;
		case 2: vm.ricalcolaQuadratura(event); break;
		}
	}
	
	vm.init();

}
)
.controller('opzioniDettaglioCtrl', 
function ($scope,$mdDialog,$timeout,utilsSvc, locals) {
	

	$scope.dialogTitle = locals.dialogTitle;
	$scope.opzioni= {
			tipologiaDettaglio: 'ALL',
			tipologiaRichiesta: 'ALL'
	}
	
	$scope.confirmDialog = function() {
		$mdDialog.hide($scope.opzioni);
	}
	
	$scope.cancelDialog = function() {
    	$mdDialog.cancel();
    }
    
})
.controller('comandiRemunerationCtrl', function($scope, $mdBottomSheet, idx) {

	$scope.title = 'Comandi remuneration';
	
	$scope.items = [
	    { id:0,  name: "Dettaglio trimestri", icon: 'fa-search', visible: true },
	    { id:1,  name: "Export messaggi", icon: 'fa-file-excel-o',visible: true },
	    { id:2,  name: "Ricalc. quadratura", icon: 'fa-cogs', visible: true }
		];

	$scope.listItemClick = function($index, $event) {
	    var clickedItem = $scope.items[$index];
	    var result = {cmdIndex: $index, recordIdx: idx, event:$event}
	    $mdBottomSheet.hide(result);
	};
	  
	$scope.dismissBottomSheet = function() {
		  $mdBottomSheet.cancel();
	}
})
.controller('comandiDettaglioCtrl', function($scope, $mdBottomSheet, idx) {

	$scope.title = 'Comandi';
	
	$scope.items = [
	    { id:0,  name: "Dettaglio trimestre", icon: 'fa-arrows-alt', visible: true },
	    { id:1,  name: "Dettaglio mandati", icon: 'fa-file-o',visible: true },
	    { id:2,  name: "Stampa rendiconto", icon: 'fa-print', visible: true },
	    { id:3,  name: "Ricalc. quadratura", icon: 'fa-cogs', visible: true }
		];
	
	$scope.listItemClick = function($index, $event) {
	    var clickedItem = $scope.items[$index];
	    var result = {cmdIndex: $index, recordIdx: idx, event:$event}
	    $mdBottomSheet.hide(result);
	};
	  
	$scope.dismissBottomSheet = function() {
		  $mdBottomSheet.cancel();
	}
})
.controller('dettaglioMandatiCtrl', function($scope, $window, $mdDialog, $q, utilsSvc, Remuneration, locals) {

	$scope.dialogTitle = locals.dialogTitle;
	$scope.maxItems = locals.maxItems;
	$scope.maxDetailItems = 0;
	$scope.itemsPerPage = 500;
	$scope.id = locals.id;
	$scope.records=[];
	$scope.orderField = "idprevisioning";

	$scope.confirmDialog = function() {
		$mdDialog.hide();
	}
	
	$scope.columnWidths=[
		90,  //0
		90,  //1
		90, //2
		120, //3
		120,  //4
		110, //5this.listPromise
		90, //6
		90, //7
		80
	];
	
	$scope.setOrderField = function(field) {
		if ($scope.orderField!=field)
			$scope.orderField = field;
		else
			$scope.orderField = "-" +field;
		
		$scope.records=[];
		$scope.infiniteItems.numLoaded_ = 0;
		$scope.infiniteItems.toLoad_ = 0;
	}

	$scope.getListHeight = function() {
		return {'height':  '260px'};
//		containerHeight = ($window.innerHeight - $('#container').position().top - $('#view').position().top);
//		  return {'height':  containerHeight + 'px'};
	};
	$window.addEventListener('resize', onResize);
	function onResize() {
	  $scope.$digest();
	}
	$scope.$on('$destroy', function() {
	  $window.removeEventListener('resize', onResize);
	});

	$scope.getColumnWidth = //	              }
		function(idx) {
		return {
				'width': $scope.columnWidths[idx] + 'px', 
				'min-width':$scope.columnWidths[idx] + 'px',
				'margin-left':'8px',
				'margin-right':'8px'
		};
	}
	
	$scope.getMaxListWidth = function() {
		var res=0;
		for (var i=0;i<$scope.columnWidths.length;i++)
			res += $scope.columnWidths[i]+6+8+10;
		
		$('#container').css('width',($('#header').width()+10)+'px');
		return {'width': res+ 'px!important;'}
	}

	$scope.print = function() {
		utilsSvc.showForever('Generazione in corso...');
		Remuneration.PrintDetails({id:$scope.id}).$promise.then(function(data){
			utilsSvc.downloadFile('application/pdf',data.response,'RemunerazioneSedaDettagli.pdf');
			utilsSvc.cancelMessage();
		},function(err){
			utilsSvc.cancelMessage();
			if(err.status==404)
				utilsSvc.showMessage('Nessun rendiconto estratto');
			else
				utilsSvc.handleHttpError(err);
		})
	}	
	
	$scope.infiniteItems = {
	          numLoaded_: 0,
	          toLoad_: 0,
	          loading_:false,
	          lastStartIdx:-1,
	          listPromise:null,
	          canceler: $q.defer(),
	          // Required.
	          getItemAtIndex: function(index) {
	        	  if ($scope.maxItems==0 || index>$scope.maxItems)
	        		  return null;
	            if (index > $scope.records.length) {
	              this.fetchMoreItems_(index);
	              return null;
	            }
	            return $scope.records [index];
	          },
	          // Required.
	          // For infinite scroll behavior, we always return a slightly
				// higher
	          // number than the previously loaded items.
	          getLength: function() {
      		  return $scope.maxItems;
	        	  
	          },
	          fetchMoreItems_: function(index) {
	            if (this.toLoad_ < index) {
	              this.toLoad_ += $scope.itemsPerPage;
	              utilsSvc.showWaitMessage('Ricerca in corso...');
	              
		              this.listPromise = Remuneration.Detail({id:$scope.id, start: $scope.records.length,size:Math.max($scope.records.length+index,$scope.itemsPerPage),orderBy:$scope.orderField}).$promise;
		              var mod=this;
		              this.listPromise.then(
			              			function(data){
			              				utilsSvc.cancelWaitMessage();
			              				$scope.records = $scope.records.concat(data);
			              				mod.numLoaded_ = $scope.records.length;
			              				mod.lastStartIdx = $scope.records.length;
			              			},
			              			function(error) {
			              				utilsSvc.handleHttpError(error);
			              			}
			              	)
            
            }
	          }
	}	
	
})
;	