// bezugsgroessenDatenGrid
// Felix Kosmalla
// 
// 
// 
// 
// 
var bezugsgroessenDatenGrid = fClass({
	
	
	
	
// ==========================
// = öffentliche Funktionen =
// ==========================	
	
	
	init:function(config){
		Ext.apply(this,config);
		
		
		this.loadComboStores();
		

		
		return this;
	},
	
	

// ==========
// = Events =
// ==========
	
	onLoadComboStores:function(){
		
	},
	
	onViewBuilt:function(){
		
	},
	
	
// =============
// = variablen =
// =============	

	view: 		null,
	grid: 		null,
	
	gridComponents: new Object(),
	
	
	
// ======================
// = private Funktionen =
// ======================	
	
	
	buildView:function(){
		
		
		this.comboStores = new Object();
		
		var aktuellesJahr = new Date().getFullYear();
		var future = 2;
		var past = 5;
		
		// "von store einrichten"
		var vonStart = aktuellesJahr - past -1;
		var vonBis = aktuellesJahr -1;
		
		var dataVon = new Array();
		for (var i=vonStart; i < vonBis; i++) {
			var tmp = new Array();
			tmp.push(i);
			dataVon.push(tmp);
		};
		
		this.comboStores.von = new Ext.data.SimpleStore({
			fields:['jahr'],
			data:dataVon
		});
		
		
		// "bis store einrichten"
		var bisStart = aktuellesJahr - past;
		var bisBis = aktuellesJahr+1;
		
		var dataBis = new Array();
		for (var i=bisStart; i < bisBis; i++) {
			var tmp = new Array();
			tmp.push(i);
			dataBis.push(tmp);
		};
		
		this.comboStores.bis = new Ext.data.SimpleStore({
			fields:['jahr'],
			data:dataBis
		});
		
		
		
		
		this.view = new Ext.Panel({
			title:'Bezugsgrößen',
			tools:[{id:'print', scope:this, handler:function(){
				if(this.requestOptions!=null){
					var ro = this.requestOptions;

					var url = cfg_backend_url + "bezugsgroessen/getPrintView/"+this.institut + "/" + this.von + "/" + this.bis;

					rcm.Application.print(url);
				}
			}},
			{id:'save', scope:this, handler:function(){
				if(this.requestOptions!=null){
					var ro = this.requestOptions;

					var url = cfg_backend_url + "bezugsgroessen/getPrintView/"+this.institut + "/" + this.von + "/" + this.bis + "/true";
					window.location.href = url;
					// rcm.Application.print(url);
				}
			}}],
			layout:'fit',
			iconCls:'winEditBezugsgroessen',
			tbar:[
			{
				text:'Jahr bearbeiten',
				id:'btEditYear',
				iconCls:'editIcon',
				scope:this,
				disabled:true,
				handler:function(){
					
					var grid = this.grid;
					
					var selModel = grid.getSelectionModel();
					
					var cell = selModel.getSelectedCell();
					
					if(cell!=null){
						this.showEditWindow(grid, cell[0], cell[1]);
					}

					
					
				}
			},
			'&nbsp;&nbsp;Institut:',
			{
				xtype:'combo',
				id:'comboInstitut',
				mode:'local',
				triggerAction:'all',
				displayField: 'name',
				valueField: 'id',
				store: this.multiStores['bcm_institute_name'],
				validateOnBlur:false,
				allowBlank:false
			},
			'&nbsp;&nbsp;',
			'Jahr&nbsp;&nbsp;von:',
			{
				xtype:'combo',
				id:'comboVon',
				mode:'local',
				triggerAction:'all',
				displayField:'jahr',
				store:this.comboStores.bis,
				allowBlank:false,
				validateOnBlur:false,
				width:100
			},
			'&nbsp;&nbsp;bis:',
			{
				xtype:'combo',
				id:'comboBis',
				mode:'local',
				triggerAction:'all',
				displayField:'jahr',
				store:this.comboStores.bis,
				allowBlank:false,
				validateOnBlur:false,
				width:100,
				validator:function(){
					if(Ext.getCmp('comboVon').getValue()>Ext.getCmp('comboBis').getValue()){
						return "Die 'von' Auswahl muss kleiner als die 'bis' Auswahl sein'";
					}else{
						return true;
					}
				}
			}
			,'&nbsp;&nbsp;',
			{
				text:'Start',
				iconCls:'startIcon',
				scope:this,
				handler:function(){
					
					if(Ext.getCmp('comboInstitut').isValid() && Ext.getCmp('comboVon').isValid() && Ext.getCmp('comboBis').isValid()){
						Ext.Msg.wait('Daten werden geladen...',false,waitDialogConfig);
						this.buildTable();
						this.requestOptions = false;
						
					}
					
					
				}
			}]
		});
		
		this.onViewBuilt();
		
		
		
		Ext.getCmp('comboInstitut').setValue(rcm.Application.state.eigenes_institut);
		Ext.getCmp('comboVon').setValue(new Date().getFullYear()-5);
		Ext.getCmp('comboBis').setValue(new Date().getFullYear());

		
	},
	
	
	showEditWindow:function(grid, rowIndex, columnIndex){
		this.von = parseInt(Ext.getCmp('comboVon').getValue());
		this.bis = parseInt(Ext.getCmp('comboBis').getValue());
		this.institut = Ext.getCmp('comboInstitut').getValue();
		
		var von = this.von;
		var bis = this.bis;
		var institut = this.institut;
		
		if(columnIndex!=0){
			var selectedYear = von + columnIndex -1;

			Ext.Ajax.request({
				url:cfg_backend_url + "bezugsgroessen/getYearValues/"+institut+"/" + selectedYear,
				method:'POST',
				scope:this,
				success:function(response){
					var werte = Ext.util.JSON.decode(response.responseText);


					// felder zusammenstellen
					var fields = new Array();

					Ext.each(werte.groessen, function(groesse){
						fields.push({
							xtype:'numberfield',
							fieldLabel:groesse.name,
							// labelWidth:300,
							name:groesse.id,
							id:'bzg_'+groesse.id,
							value:"",
							allowDecimals:false,
							decimalSeparator:',',
							decimalPrecision:0,
							plugins:[ new Ext.ux.plugins.numberFormater()],
							
							allowNegative:false,
							style:"text-align:right"
						});
					},this);




					this.editPanel = new Ext.FormPanel({
						head:false,
						items:fields,
						bodyStyle:'padding:10px',
						labelWidth:250,
						autoScroll:true
					});


					this.editWindow = new Ext.Window({
						layout:'fit',
						title:"Bezugsgrößen des Jahres <strong>" + selectedYear + "</strong> bearbeiten",
						items:this.editPanel,
						width:440,
						height:500,
						modal:true,

						buttons:[
						{
							text:'Abbrechen',
							iconCls:'cancelIcon',
							scope:this,
							handler:function(){
								this.editWindow.destroy();
							}
						},
						{
							text:'Speichern',
							iconCls:'acceptIcon',
							scope:this,
							handler:function(){
								this.editPanel.getForm().submit({
									url:cfg_backend_url + "bezugsgroessen/save/"+institut+"/"+selectedYear,
									method:"POST",
									scope:this,
									failure:function(res){

									},
									success:function(){
										this.editWindow.destroy();
										this.gridComponents.store.reload();
									}
								});
							}
						}
						]
					});

					this.editWindow.show();

					Ext.each(werte.felder, function(feld){
						Ext.getCmp('bzg_'+feld.id).setValue(feld.betrag);
						// Ext.getCmp('bzg_'+feld.id).setFormat();
					});


				}
			});						
		}



	},
	
	
	
	buildTable:function(){
		Ext.getCmp('btEditYear').enable();
		// spalten anlegen
				
				var spalten = new Array();
				
				spalten.push({
					name:'bezugsgroesse',
					type:'string'			
				});
				
				this.von = parseInt(Ext.getCmp('comboVon').getValue());
				this.bis = parseInt(Ext.getCmp('comboBis').getValue());
				this.institut = Ext.getCmp('comboInstitut').getValue();
				
				var von = this.von;
				var bis = this.bis;
				var institut = this.institut;
				
				
				// var felder = Ext.util.JSON.decode('{"felder":[{"jahr":"1999","betrag":"10","name":"Kundenvolumen"},{"jahr":"1999","betrag":"111","name":"B\u00fcrofl\u00e4che"},{"jahr":"1999","betrag":"123","name":"Depotbestand"}]}');
				
				
				
				for (var i=von; i < bis +1; i++) {
					spalten.push({
						name:i,
						type:'float'
					});
				};
				
				
				
				
				// column model anlegen
				var cols = new Array();
				cols.push({
					header:"Bezugsgrößen",
					sortable:false,
					dataIndex:'bezugsgroesse',
					width:230
				});
				
				for (var i=von; i < bis +1; i++) {
					cols.push({
						css:'text-align:right !important;',
						header:i,
						sortable:false,
						dataIndex:i,
						width:160,
						renderer:function(value){
							var parsedFloat = parseFloat(value);
							if(parsedFloat == "NaN"){
								parsedFloat = 0;
							}
							return number_format(parsedFloat, 0, ',','.');
						}
					});
				};
				
					
				
				this.gridComponents.proxy = new Ext.data.HttpProxy({
					url:cfg_backend_url + 'bezugsgroessen/getData/' + Ext.getCmp('comboInstitut').getValue() + "/" + von + "/" + bis,
					method:'post'
				});
				
				
				
				
				
				this.gridComponents.reader = new Ext.data.JsonReader({
					root:'results',
					totalProperty:'total'
				}, spalten);
				
				
				this.gridComponents.store = new Ext.data.Store({
					proxy:this.gridComponents.proxy,
					reader:this.gridComponents.reader					
				});
				
				
				
				this.gridComponents.store.on('load',function(){
					Ext.Msg.hide();
				});
				
				
				this.gridComponents.ColumnModel = new Ext.grid.ColumnModel(cols);
				// 
				
				
				this.grid = new Ext.grid.GridPanel({
					store:this.gridComponents.store,
					cm: this.gridComponents.ColumnModel,
					selModel: new Ext.grid.CellSelectionModel(),
					loadMaks:true,
					height:300,
					border:true
				});

				this.gridComponents.store.load();	
				
			
				
				if(!Ext.isEmpty(this.view.items)){
					this.view.remove(this.view.getComponent(0));
				}
				
				this.view.add(this.grid);
				this.view.doLayout();

				
				this.grid.on('celldblclick',function(grid, rowIndex, columnIndex){
					
					this.showEditWindow(grid, rowIndex, columnIndex);
					
				},this);
	},
	
	

	loadComboStores:function(){
		

		var stores = new Array();
		
		stores.push({table:'bcm_bezugsgroessen', field:'name'});
		stores.push({table:'bcm_institute', field:'name'});
		// stores.push({table:'bcm_benutzer', field:'voller_name'});
		// stores.push({table:'bcm_kostenebenen', field:'name'});
		// stores.push({table:'jahre', field:'jahr', backend:cfg_backend_url + 'spreadsheets/json/getKostenDatenYears'});
		
		this.multiStoresRaw = new Object();
		this.multiStores	= new Object();
		
		
		var counter = 0;
		
		Ext.each(stores,function(item){
			var  url = cfg_backend_url + item.table + "/" + item.field + '/ComboStore';
			
			var backend = item.backend || false;
			if(backend){
				url = backend;
			}
			
			Ext.Ajax.request({
				url: url,
				method:'POST',
				scope:this,
				success: function(response){
					
					// SimpleStore für Combobox erstellen
					var crudData = Ext.util.JSON.decode(response.responseText);

					if(!Ext.isEmpty(crudData.raw))
						this.multiStoresRaw[item.table+'_'+item.field] = crudData.raw;
					
					var simpleStore = new Ext.data.SimpleStore(crudData);				
					
					this.multiStores[item.table+'_'+item.field] = simpleStore;
					

					
					counter++;	
						
					if(stores.length == counter){
						
						
						this.onLoadComboStores();
						
						this.buildView();
						
						Ext.MessageBox.hide();
						// this.buildView();
					}
					
				}
			});
			
		},this);
		
		

		
	}

	
});


