app.controller('destinatariCtrl',
	
function ($scope,$http,$cookies,$window, $location,$timeout, $mdDialog, $q, $routeParams, $mdBottomSheet, 
			$mdMedia, locals, utilsSvc, Destinatari, ContiDestinatario) {
	
	var vm=this;
	
	$scope.idOrdinante = locals.ordinante.idordinante;
	$scope.ordinanti = locals.ordinanti;
	$scope.ordinante = locals.ordinante;
	
	$scope.maxItems = 0;
	$scope.itemsPerPage = 100;
	$scope.selectedIndex=-1;
	$scope.maxContiItems = 0;
	$scope.records=[];
	$scope.recordsConti=[];
	$scope.selected=[];
	$scope.filter={
		orderField:null,
		orderContiField: null
	};
	
	$scope.setSelected=function(idx) {
		$scope.selectedIndex = idx;
	}
	
	$scope.destinatarioColumnWidths=[
			230,  //0
			130
		];

	$scope.contiColumnWidths=[
		90,  //0
		90,
		120,
		80,
		250,
		100,
		250
	];

	$scope.getListHeight = function() {
		containerHeight = ($window.innerHeight - $('#container').position().top - $('#view').position().top);
		  return {'height':  containerHeight + 'px'};
	};
	
	$scope.getGridItemHeight = function() {
		return utilsSvc.getGridWithButtonHeight();
	}
	
	$window.addEventListener('resize', onResize);
	function onResize() {
	  $scope.$digest();
	}
	$scope.$on('$destroy', function() {
	  $window.removeEventListener('resize', onResize);
	});
	
	
	$scope.getDestinatarioColumnWidth = //	              }
		//        this.lastStartIdx = index;
		function(idx) {
		return {
				'width': $scope.destinatarioColumnWidths[idx] + 'px', 
				'min-width':$scope.destinatarioColumnWidths[idx] + 'px',
				'margin-left':'8px',
				'margin-right':'8px'
		};
	}

	$scope.getMaxDestinatarioListWidth = function() {
		var res=0;
		for (var i=0;i<$scope.destinatarioColumnWidths.length;i++)
			res += $scope.destinatarioColumnWidths[i]+6+8+10;
		
		$('#container').css('width',($('#header').width()+10)+'px');
		return {'width': res+ 'px!important;'}
	}

	$scope.getContiColumnWidth = //	              }
		//        this.lastStartIdx = index;
		function(idx) {
		return {
				'width': $scope.contiColumnWidths[idx] + 'px', 
				'min-width':$scope.contiColumnWidths[idx] + 'px',
				'margin-left':'8px',
				'margin-right':'8px'
		};
	}

	$scope.getMaxContiListWidth = function() {
		var res=0;
		for (var i=0;i<$scope.contiColumnWidths.length;i++)
			res += $scope.contiColumnWidths[i]+6+8+10;
		
		$('#container').css('width',($('#header').width()+10)+'px');
		return {'width': res+ 'px!important;'}
	}
	
	$scope.stampaDestinatari = function() {
		utilsSvc.showForever('Generazione in corso...');
		Destinatari.Print({idOrdinante: $scope.idOrdinante}).$promise.then(function(data){
			utilsSvc.downloadFile('application/pdf',data.response,'Destinatari.pdf');
			utilsSvc.cancelMessage();
		}).catch(function(err){
			if (err.status==404) {
				utilsSvc.cancelMessage();
				utilsSvc.showMessage('Nessun destinatario estratto');
			}
		});
	}
	
	$scope.setDestinatarioOrderField = function(field) {
		if ($scope.filter.orderField!=field)
			$scope.filter.orderField = field;
		else
			$scope.filter.orderField = "-" +field;
		
		$scope.getDestinatari();
	}

	$scope.setContiOrderField = function(field) {
		if ($scope.filter.orderContiField!=field)
			$scope.filter.orderContiField = field;
		else
			$scope.filter.orderContiField = "-" +field;
		
		$scope.getContiDestinatario();
	}

	$scope.setSelectedDestinatariIndex=function(data, $index, $event) {
		$scope.selectedIndex = $index;
		$scope.getContiDestinatario();
	}
	
	
	
	$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 (!$scope.infiniteItems.loading_)
	        		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...');
	              $scope.infiniteItems.loading_ = true;
	              
        		  this.listPromise = Destinatari.List({idOrdinante: $scope.idOrdinante, start: $scope.records.length,size:Math.max($scope.records.length+index,$scope.itemsPerPage),filter:$scope.filter.filterText,orderBy:$scope.filter.orderField}).$promise;
		              
	              var mod=this;
		              this.listPromise.then(
			              			function(data){
			              				$scope.infiniteItems.loading_ = false;
			              				$scope.infiniteItems.toLoad_=0;
			              				
			              				utilsSvc.cancelWaitMessage();
			              				$scope.records = $scope.records.concat(data);
			              				mod.numLoaded_ = $scope.records.length;
			              				mod.lastStartIdx = $scope.records.length;
			              				$scope.selected.length=$scope.records.length;
			              				if ($scope.selectedIndex==-1 && $scope.records.length>0) {
			              					$scope.selectedIndex=0;
			              					$scope.setSelectedDestinatariIndex($scope.records , 0, null);
			              				}
			              			},
			              			function(error) {
			              				$scope.infiniteItems.loading_ = false;
			              				$scope.infiniteItems.toLoad_=0;
			              				utilsSvc.handleHttpError(error);
			              			}
			              	)
            	}
          }
	}	

	$scope.contiInfiniteItems = {
	          numLoaded_: 0,
	          toLoad_: 0,
	          loading_:false,
	          lastStartIdx:-1,
	          listPromise:null,
	          canceler: $q.defer(),
	          // Required.
	          getItemAtIndex: function(index) {
	        	  if ($scope.maxContiItems==0 ||  index>$scope.maxContiItems)
	        		  return null;
	        	  if (!$scope.contiInfiniteItems.loading_)
	        		  if (index > $scope.recordsConti.length) {
	        			  this.fetchMoreItems_(index);
	        			  return null;
	        		  }
	            return $scope.recordsConti [index];
	          },
	          // Required.
	          // For infinite scroll behavior, we always return a slightly
				// higher
	          // number than the previously loaded items.
	          getLength: function() {
  		  return $scope.maxContiItems;
	        	  
	          },
	          fetchMoreItems_: function(index) {
	            if (this.toLoad_ < index) {
	              this.toLoad_ += $scope.itemsPerPage;
	              utilsSvc.showWaitMessage('Ricerca in corso...');
	              $scope.contiInfiniteItems.loading_ = true;
	              
              	this.listPromise = ContiDestinatario.List({idDestinatario: $scope.records[$scope.selectedIndex].iddestinatario, start: $scope.recordsConti.length,size:Math.max($scope.recordsConti.length+index,$scope.itemsPerPage),orderBy:$scope.filter.orderContiField}).$promise;
		              
	              var mod=this;
		              this.listPromise.then(
		            		  function(data){
		            			  	$scope.contiInfiniteItems.loading_ = false;
		            			  	$scope.contiInfiniteItems.toLoad_=0;
			              			utilsSvc.cancelWaitMessage();
			              			$scope.recordsConti = $scope.recordsConti.concat(data);
			              			mod.numLoaded_ = $scope.recordsConti.length;
			              			mod.lastStartIdx = $scope.recordsConti.length;
			              		},
			              		function(error) {
			              			$scope.contiInfiniteItems.loading_ = false;
			              			$scope.contiInfiniteItems.toLoad_=0;
			              			utilsSvc.handleHttpError(error);
			              		}
			              	)
      	}
    }
	}	

	$scope.getDestinatari = function(){
		Destinatari.Count({idOrdinante: $scope.idOrdinante, filter:$scope.filter.filterText}).$promise.then(
					function(data){
						$scope.records=[];
						$scope.maxItems = data.value;
						$scope.infiniteItems.numLoaded_ = 0;
						$scope.infiniteItems.toLoad_ = 0;
					}
				);
	}
	
	$scope.getContiDestinatario = function(){
		ContiDestinatario.Count({idDestinatario: $scope.records[$scope.selectedIndex].iddestinatario}).$promise.then(
					function(data){
						$scope.recordsConti=[];
						$scope.maxContiItems = data.value;
						$scope.contiInfiniteItems.numLoaded_ = 0;
						$scope.contiInfiniteItems.toLoad_ = 0;
					}
				);
	}
	
	$scope.nuovoDestinatario = function(event){
		Destinatari.New().$promise.then(function(data){
			data.idordinante = $scope.idOrdinante;
			$scope.records.push(data);
			$scope.editDestinatario($scope.records.length-1, event);
		});
	}
	
	$scope.editDestinatario = function(ndx, event){
		$scope.selectedIndex = ndx;
		$mdDialog.show({
            templateUrl: 'templates/destinatario.html',
            controller: 'destinatarioCtrl',
            targetEvent: event,
            locals: $scope.records[ndx],
            multiple: true
        }).then(function(data){
        	Destinatari.save(data).$promise.then(
        			function(res) {
        				utilsSvc.showMessage('Salvataggio modifiche effettuato');
        				$scope.getDestinatari();
        			}, function(err) {
        				utilsSvc.handleHttpError(err);
        				$scope.getDestinatari();
        			}
        	);
        }, 
        function(){
        	$scope.getDestinatari();
        });
	}

	$scope.eliminaDestinatario = function(ndx, event){
		utilsSvc.showConfirm("Conferma","Confermi l'eliminazione dell'elemento?")
		.then(function(res){
			Destinatari.Delete({idDestinatario: $scope.records[ndx].iddestinatario})
				.$promise.then(function(res){
					utilsSvc.showMessage("Eliminazione effettuata");
					$scope.getDestinatari();
				},
				function(err){
					utilsSvc.handleHttpError(err);
					$scope.getDestinatari();
				})
		})	
	}
	
	$scope.nuovoConto= function(event) {
		if ($scope.selectedIndex==-1) {
			utilsSvc.showMessage("Selezionare prima un destinatario");
			return;
		}

		ContiDestinatario.New().$promise.then(function(data){
			data.idordinante=$scope.idOrdinante;
			data.iddestinatario=$scope.records[$scope.selectedIndex].iddestinatario;
			$scope.recordsConti.push(data);
			$scope.editConto($scope.recordsConti.length-1, event);
		})
	}
	
	$scope.editConto = function(ndx, event){
		$mdDialog.show({
            templateUrl: 'templates/conto.html',
            controller: 'contoCtrl',
            targetEvent: event,
            locals: {conto: $scope.recordsConti[ndx], conti: $scope.recordsConti},
            multiple: true
        }).then(function(res){
        	ContiDestinatario.Save(res).$promise.then(function(resCode,p){
        		if (resCode.value=="4") 
        			utilsSvc.show("L'elemento è stato modificato da un altro utente");
        		else if (resCode.value=="5") 
        			utilsSvc.show("L'elemento è stato eliminato da un altro utente");
        		else if (resCode.value!="0")
        			utilsSvc.show(resCode.value);
        		$scope.getContiDestinatario();
        	},
        	function(err){
        		utilsSvc.handleHttpError(err);
        		$scope.getContiDestinatario();
        	});
        },
        function(){
    		
    	}
        )
	}

	$scope.eliminaConto = function(ndx, event){
		utilsSvc.showConfirm("Conferma","Confermi l'eliminazione dell'elemento?")
			.then(function(res){
				ContiDestinatario.Delete({idConto: $scope.recordsConti[ndx].id})
					.$promise.then(function(res){
						utilsSvc.showMessage("Eliminazione effettuata");
						$scope.getContiDestinatario();
					},
					function(err){
						utilsSvc.handleHttpError(err);
						$scope.getContiDestinatario();
					})
			});
	}

	$scope.getSelectedDestinatari = function(){
		var res = new Array();
		for(var i=0;i<$scope.selected.length;i++)
			if ($scope.selected[i])
				res.push($scope.records[i].iddestinatario);
		
		return res;
	}
	
	$scope.cambioSocieta=function() {
		if ($scope.getSelectedDestinatari().length==0) {
			utilsSvc.showMessage('Selezionare i destinatari interessati al cambio della società.')
		} else {
			utilsSvc.showConfirm('Conferma',"Questa funzione agisce sulle anagrafiche destinatari selezionate e permette di spostarle o duplicarle verso un altra società a seconda dell'opzione relativa.<br/>"+
					"Le anagrafiche duplicate saranno completamente indipendenti rispetto all' anagrafica di partenza.")
				.then(function(res){
					$mdDialog.show({
			            templateUrl: 'templates/cambioOrdinante.html',
			            controller: 'cambioOrdinanteCtrl',
			            targetEvent: event,
			            locals: {ordinanti: $scope.ordinanti, ordinanteOriginale: $scope.ordinante.ordinante},
			            multiple: true
			        }).then(function(data){
			        	utilsSvc.showConfirm('Conferma',"Confermi il cambio della società ordinante?")
			        		.then(function() {
			        			var opzioni = {destinatari: $scope.getSelectedDestinatari(), ordinanteDestinazione: data.ordinanteDestinazione, tipoCambio: data.tipoCambio};
			        			Destinatari.CambioOrdinanti(opzioni)
			        				.$promise.then(function(res){
			        					utilsSvc.showMessage('Operazione completata');
			        					$scope.getDestinatari();
			        				},
			        				function(err){
			        					utilsSvc.handleHttpError(err);
			        				})
			        		});
			        });	
				});
		}
			
	}
	
	$scope.cancelDialog = function(){
		$mdDialog.cancel();
	}
	
	$scope.init = function() {
		$scope.getDestinatari();
	}	
	$scope.init();

}
)

.controller('comandiDestinatariCtrl', function($scope, $mdBottomSheet, idx) {

	$scope.title = 'Comandi';
	
	$scope.items = [
	    { id:0,  name: "Anagrafica destinatari", icon: 'fa-users',visible: true },
	    { id:1,  name: "Anagrafica deleghe SEDA", icon: 'fa-refresh', 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('destinatarioCtrl',function($scope,$mdDialog,utilsSvc,locals){
	$scope.destinatario = angular.copy(locals);
	
	$scope.controllaCF=function() {
		if ($scope.destinatario.codiceFiscale==null || $scope.destinatario.codiceFiscale.length==0)
			return true;
		if ($scope.destinatario.codiceFiscale.length==16){
			if (!utilsSvc.controllaCF($scope.destinatario.codiceFiscale)){
				utilsSvc.showMessage('Codice fiscale non valido');
				return;
			}
		}
		
		if ($scope.destinatario.codiceFiscale!=null && $scope.destinatario.codiceFiscale.length==11) {
			if (!utilsSvc.controllaPIVA($scope.destinatario.codiceFiscale)){
				utilsSvc.showMessage('Partita IVA non valida');
				return;
			}
		}
		if (!($scope.destinatario.codiceFiscale.length==16 || $scope.destinatario.codiceFiscale.length==11))
			utilsSvc.showMessage('Partita IVA o codice fiscale non validi');
		
		
	}
	
	$scope.controlloIban=function(){
		if ($scope.destinatario.coordinateIbanordinante==null || $scope.destinatario.coordinateIbanordinante.trim()=='')
			return true;
		if (!utilsSvc.controlloIban($scope.destinatario.coordinateIbanordinante.replace(/\s/g, ''))) {
			utilsSvc.showMessage('Codice IBAN errato');
			return false;
		} 
		
		return true;
	}
	
	$scope.confirmDialog = function() {
		if ($scope.destinatario.destinatario==null || $scope.destinatario.destinatario.trim()=='') {
			utilsSvc.showMessage('Inserire la denominazione');
			return;
		}
		if ($scope.destinatario.codiceFiscale==null || $scope.destinatario.codiceFiscale.trim()=='') {
			utilsSvc.showMessage('Inserire il codice fiscale / partita IVA');
			return;
		}
		
		if (!$scope.controlloIban())
			return;
		
		$mdDialog.hide($scope.destinatario);
	}
	
	$scope.cancelDialog = function() {
		$mdDialog.cancel();
	}
	
})

.controller('contoCtrl',function($scope,$mdDialog,Banche, utilsSvc,locals){
	$scope.conto = angular.copy(locals.conto);
	$scope.conti = locals.conti;
	
    $scope.piazzatura = function(ev) {
    	$mdDialog.show({
    		targetEvent: ev,
            templateUrl: 'templates/ricercaFiliali.html',
            controller: 'ricercaFilialiCtrl',
            locals: {abi: $scope.conto.abi,  cab:$scope.conto.cab, istituto:$scope.conto.denominazioneBanca},
            multiple: true
        }).then(function(filiale){
        	$scope.conto.abi = filiale.abi;
        	$scope.conto.cab = filiale.cab;
        },function() {
        	
        })	
    }

	$scope.confirmDialog = function() {
		
		if ($scope.checkDati())
			$mdDialog.hide($scope.conto);
	}
	
	$scope.cancelDialog = function() {
		$mdDialog.cancel();
	}

	$scope.checkDefaultPresente= function(){
		if ($scope.conto.contoDefault) {
			var defaultPresente=false;
			for (var i=0;i<$scope.conti.length;i++) {
				if ($scope.conti[i].conto!=$scope.conto)
					if ($scope.conti[i].contoDefault) {
						$scope.conto.contoDefault = false;
						utilsSvc.showMessage('Il conto predefinito è già presente.');
						return;
					}
			}
		}
	}
	
	$scope.toUpper=function() {
		$scope.conto.conto = $scope.conto.conto.toUpperCase(); 
	}
	
	$scope.toUpperCase=function(event) {
		event.key = event.key.toUpperCase(); 
	}

	
	$scope.checkDigit=function(event, len){
		if (event.key=="Backspace" || event.key=="ArrowLeft" || event.key=="ArrowRight" || event.key=="Tab")
			return;

		if ("0123456789".indexOf(event.key)==-1 || event.target.value.length>=len)
			event.preventDefault();
	}
		
	
	$scope.controlloIban=function(){
		if ($scope.conto.coordinateIban==null || $scope.conto.coordinateIban.trim()=='')
			return true;
		if (!utilsSvc.controlloIban($scope.conto.coordinateIban.replace(/\s/g, ''))) {
			utilsSvc.showMessage('Codice IBAN errato');
			return
		} else {
		
			var iban=utilsSvc.allTrim($scope.conto.coordinateIban.toUpperCase());
		
			if (iban.substring(0,2)=='IT' || iban.substring(0,2)=='SM') {
				if (!utilsSvc.controlloCin(iban.substring(4,4+1),iban.substring(5,5+5),iban.substring(10,10+5),iban.substring(15,15+12))) {
					utilsSvc.showMessage('Codice CIN errato');
					return false;
				}
				
				if ($scope.conto.abi!=null && $scope.conto.abi!='' && $scope.conto.coordinateIban.replace(/\s/g, '').substring(5,5+5)!=$scope.conto.abi){
					 utilsSvc.showMessage('Il Codice ABI non è congruente con il codice IBAN');
					return false;				
				}
			
				var iban=$scope.conto.coordinateIban.replace(/\s/g, '');
				$scope.conto.abi = iban.substring(5,5+5);
				$scope.conto.cab = iban.substring(10,10+5);
				$scope.conto.conto = iban.substring(15,15+12);
				$scope.conto.cin = iban.substring(4,5);
				
				if ($scope.conto.abi!=null && $scope.conto.abi!='')
					Banche.GetByAbi({abi:$scope.conto.abi.trim()})
					.$promise.then(function(data){
							if (data.descri)
								$scope.conto.descrizioneBanca = data.descri.substring(0,40);
						});
			}
		}		
		return true;
	}
	
	$scope.checkDati = function() {
		if ($scope.conto.abi==null)
			$scope.conto.abi ="";
		if ($scope.conto.cab==null)
			$scope.conto.cab ="";
		
		$scope.conto.abi = $scope.conto.abi.padZero(5);
		$scope.conto.cab = $scope.conto.cab.padZero(5);
		
		if($scope.conto.conto!=null)
			$scope.conto.conto=$scope.conto.conto.toUpperCase();
		
		if ($scope.conto.coordinateIban!='' && $scope.conto.coordinateIban!=null){
			if ($scope.conto.coordinateIban.replace(/\s/g, '').substring(5,5+5)!=$scope.conto.abi){
				utilsSvc.showMessage('Il Codice ABI non è congruente con il codice IBAN');
				return false;
			}		
		}
		
		if (!$scope.controlloIban())
			return false;
		
		return true;
	}
	
})
.controller('cambioOrdinanteCtrl',function($scope, $mdDialog, utilsSvc, locals){

	$scope.ordinanti = locals.ordinanti;
	$scope.ordinanteOriginale = locals.ordinanteOriginale;
	
	$scope.res = {
			ordinanteDestinazione:0,
			tipoCambio:0
	};
	
	$scope.confirmDialog = function() {
		if ($scope.res.ordinanteDestinazione==0)
			utilsSvc.showMessage('Selezionare la società di destinazione');
		else
			$mdDialog.hide($scope.res);
	}
	
	$scope.cancelDialog = function() {
		$mdDialog.cancel();
	}
})
;	  
	