 // vim: sw=4:ts=4:nu:nospell:fdc=4
 /*global Ext, EQP */
 /**
 * Classe que define o painel de lista de pedido
 *
 * @author Ot�vio Augusto
 * @copyright (c) 2009, by Ot�vio Augusto
 * @company Net On - Solu��es Tecnol�gicas
 * @date 10 de Setembro 2009
 *
 */

//Define o namespace
Ext.ns('Pedido.Pedido.Orcamento');

//Cria a classe base a ser estendida
Pedido.Pedido.Orcamento = Ext.extend(Ext.Panel,{		
		
	/**
	 * Inicializa o componente
	 */
	initComponent : function(){		
		
		//Cria o datastore de or�amentos
		this.store =  new Ext.data.JsonStore({
	    	proxy: new Ext.data.HttpProxy({ 
	    		url: App.sysURL + 'preco_action/findAll/',
	    		method: 'POST'
	    	}),
		    root: 'results',
		    idProperty: 'id',  
		    totalProperty: 'total',
		    fields: ['descricao','id','quantidade','preco','total','item_id']
		});
	
		this.store.on('datachanged',this.updateValor,this);
		this.store.on('update',this.updateRow,this);
		this.store.on('load',this.updateValor,this);
		
	
		//Cria o combobox do grid de edi��o de item
		this.cmbItem = new Ext.form.ComboBox({
           typeAhead: false,
           triggerAction: 'all',
           store: this.pedido.lista.itemStore,
           displayField: 'descricao',
           valueField: 'id',	               
           mode:'local'	            
	    });
		
		//Cria o tipo de registro item
		this.parcela = Ext.data.Record.create([
	           {name: 'id', type: 'number'},
	           {name: 'prazo', type: 'number'},
	           {name: 'valor', type: 'float'}
	     ]);		 
		
		 var summary = new Ext.ux.grid.GroupSummary();		 

		//Cria a configura��o personalizada
		config = {
			height: 340,
			closable: false,
			layout: 'fit',
			tbar:{
				labelAlign: 'left',
				layout: 'column',
				bodyStyle: 'padding:4px;',
				hideLabels: true,
				items:[
        	         this.cmbFornecedor = new Ext.form.ComboBox({
        	        	 xtype: 'combo',
        	        	 emptyText: 'Prestador / Fornecedor',
        	        	 store: this.pedido.empresaStore,
        	        	 hiddenName: 'empresa_id',
        	        	 width: 400,
        	        	 valueField: 'id',
        	        	 displayField: 'razaosocial',
        	        	 triggerAction: 'all',
        	        	 mode: 'local'			    	        	        		 
        	         }),'',this.ckOrcamento = new Ext.form.Checkbox({
        	        	 xtype: 'checkbox',
        	        	 boxLabel: 'Or&ccedil;amento selecionado',
        	        	 inputValue: '1',
        	        	 style: 'margin-top: 4px;'
        	         })
				]
			},
			items:[
			       {
			    	   xtype: 'tabpanel',
			    	   activeTab: 0,
			    	   items:[
			    	          this.precoPanel = new Ext.Panel({
			    	        	  xtype: 'panel',
			    	        	  layout: 'fit',
						    	  title: 'Pre&ccedil;o (R$ 0.00)',			    	        	  
			    	        	  items:[
						 			     {
			 			 					xtype: 'editorgrid',	
			 			 					height: 200,
			 			 					store: this.store,
			 			 					columns:[
			 			 						{id: 'quantidade',header:'Quantidade',dataIndex:'quantidade',width:80},
			 			 						{id: 'item',header:'Produto / Servi&ccedil;o',dataIndex:'item_id',width:300,renderer: Ext.ux.renderer.Combo(this.cmbItem)},
			 			 						{id: 'preco',header:'Pre&ccedil;o Unit.(R$)',dataIndex:'preco',width:100,editor: new Ext.form.NumberField({allowNegative: false}),renderer: Ext.util.Format.brMoney},
			 			 						{id: 'total',header:'Pre&ccedil;o Total(R$)',dataIndex:'total',width:100,renderer: Ext.util.Format.brMoney}
			 			 					],
			 			 					autoExpandRow: 'item',			
			 			 					view : new Ext.grid.GridView({
			 			 						forceFit: true
			 			 					})
			 			 					
			 			 				}	       
			    	        	         
			    	        	  ]
			    	          }),
			    	          {
			    	        	  xtype: 'panel',
			    	        	  layout: 'fit',
						    	  title: 'Condi&ccedil;&otilde;es de pagamento',			    	        	  
			    	        	  items:[
						 			     this.condicaoPanel = new Ext.grid.EditorGridPanel({
			 			 					xtype: 'editorgrid',	
			 			 					height: 200,
			 			 					tbar:[
			 			 					      {
			 			 					    	  text: '<b>Adicionar parcela</b>',
			 			 					    	  iconCls: 'ui-add-icon',
                                                                                                  id: 'btn-add-parcela',
			 			 					    	  handler: this.addParcela,
			 			 					    	  scope: this
			 			 					      },
			 			 					      {
			 			 					    	  text: 'Remover parcela',
			 			 					    	  iconCls: 'ui-delete-icon',
                                                                                                  id: 'btn-delete-parcela',
			 			 					    	  handler: function(){
				 			 			        		var sm = this.condicaoPanel.getSelectionModel(); 
				 			 			        		this.condicaoPanel.store.remove(sm.selection.record);			 			 					    	  
			 			 					      	  },
			 			 					      	  scope: this
			 			 					      }			 			 					      
			 			 					],
			 			 					store: new Ext.data.GroupingStore({
			 			 				    	proxy: new Ext.data.HttpProxy({ 
			 			 				    		url: App.sysURL + 'parcela_action/findAll/',
			 			 				    		method: 'POST'
			 			 				    	}),
				 			 					reader: new Ext.data.JsonReader({
				 			 					    root: 'results',
				 			 						idProperty: 'id',  
				 			 					    totalProperty: 'total',
				 			 					    fields: ['prazo',{name: 'valor', type: 'float'},'id','parcela']	
				 			 				    }),			 			 					    
			 			 					    listeners:{
			 			 							'update' : this.updateParcela,
			 			 							scope: this
			 			 						},
			 			 						sortInfo: {field: 'id', direction: 'ASC'},
			 			 			            groupField: 'parcela'			 			 						
			 			 					}),
			 			 					columnLines: true,
			 			 					columns:[
			 			 						new Ext.grid.RowNumberer(),
			 			 						{id: 'prazo',header:'Prazo (dias)',dataIndex:'prazo',width:120, editor: new Ext.form.NumberField({allowBlank: false, allowNegative: false, allowDecimals: false})},
			 			 						{id: 'valor',header:'Valor (R$)',dataIndex:'valor',width:120, editor: new Ext.form.NumberField({allowBlank: false, allowNegative: false}),summaryType: 'sum',summaryRenderer: Ext.util.Format.brMoney,renderer: Ext.util.Format.brMoney},
			 			 						{id: 'parcela',header:'Parcela',dataIndex:'parcela',width:120}
			 			 					],
			 			 					plugins: summary,
			 			 					 view: new Ext.grid.GroupingView({
			 			 			            forceFit: false,
			 			 			            showGroupName: false,
			 			 			            enableNoGroups: false,
			 			 						enableGroupingMenu: false,
			 			 			            hideGroupedColumn: true,
				 			 			        groupTextTpl: 'Parcelas'
			 			 			        })
			 			 					
			 			 				})	       
			    	        	         
			    	        	  ]
			    	          }	    	          
			    	          
			    	   ]
			       }
			]
		};
		
		Ext.apply(this,config);							
		
		//Chama o initComponent da super classe
		Pedido.Pedido.Orcamento.superclass.initComponent.apply(this, arguments);	

		if (!this.data){
			//Registra evento para o componente 
			this.on('afterrender',this.loadData,this);
		}else{
			this.load();
		}
		
	},
	
	/**
	 * Carrega os dados do or�amento
	 */
	loadData : function(){
		//Cria uma c�pia do registro e o adiciona � lista do or�amento
		for (i = 0; i < this.pedido.lista.store.data.length; i++){
			var newRecord = this.pedido.lista.store.data.items[i].copy(); 

				newRecord.data['preco'] = 0;
				newRecord.data['total'] = 0;
				
				this.store.add(newRecord);
		}
				
	},
	
	/**
	 * carrega a lista de pre�os e parcelas
	 */
	load : function(){				
		Ext.getCmp('btn-add-parcela').disable();
                Ext.getCmp('btn-delete-parcela').disable();
                
                this.cmbFornecedor.setValue(this.data.empresa_id);
		
		if (this.data.selected == '1'){
			this.ckOrcamento.setValue(true);
			this.setTitle('<span style="color:green;"><b>' + this.title + '</b></span>');
			this.setIconClass('tab-selected');
		}
		this.store.load({params: {orcamento_id: this.data.id}});
		this.condicaoPanel.store.load({params:{orcamento_id: this.data.id}});
	},
	
	/**
	 * Atualiza o valor total da proposta
	 */
	updateValor : function(store){
		var total = 0;
		var valor = 0;
		var r;

		for (i = 0; i < store.data.length; i++){
			r = store.data.items[i]; 
			valor = (r.data['preco'])*r.data['quantidade'];
			if (typeof valor == 'number'){
				total += valor;
				var num = new Number(parseFloat(valor));				
				r.data['total'] = num.toFixed(2);
			}
		}
		
		
		var num = new Number(parseFloat(total));
		this.precoPanel.setTitle('Pre&ccedil;o (R$ '+ num.toFixed(2) + ')');
		this.total = num.toFixed(2);
	},
	
	/**
	 * Atualiza o valor da linha
	 */
	updateRow : function(store, record){		
		record.data['total'] = record.data['quantidade']*record.data['preco'];
		this.updateValor(store);
	},

	/**
	 * Adiciona uma parcela � condi��o de pagamento
	 */
	addParcela : function(){			
		var p = new this.parcela({
            id: '',
            prazo: 0,
            valor: 0
        });
		
        var last = this.condicaoPanel.store.getCount();
            
        this.condicaoPanel.stopEditing();
        if (this.condicaoPanel.store.getCount() > 0)
        	this.condicaoPanel.store.insert(last,p);
        else
        	this.condicaoPanel.store.add(p);
        this.condicaoPanel.startEditing(last, 0);	            
		
	},
	
	/**
	 * Atualiza o valor total da proposta
	 */
	updateParcela : function(store, record){
		var total = store.sum('valor');
				
		if (total > this.total){
			record.data['valor'] = 0;
		}
	},
	
	getValues : function(){
		var records = this.store.data.items;
		var precos = new Array();
		
		for (i = 0; i < records.length; i++){
				precos[i]= {
						'item_id':records[i].data['item_id'], 
						'preco':records[i].data['preco'],
						'quantidade': records[i].data['quantidade']
				};
				
		}
		
		try{
			var records = this.condicaoPanel.store.data.items;
			var parcelas = new Array();
	
			for (i = 0; i < records.length; i++){
				parcelas[i]= {
					'prazo':records[i].data['prazo'], 
					'valor':records[i].data['valor']					
				};
				
			}
		}catch(e){}
		
		var checkOrcamento = 0;
		if (this.ckOrcamento.checked){
			checkOrcamento = 1;
		}
		
		var item = {
				empresa_id: this.cmbFornecedor.getValue(),
				selected: checkOrcamento,
				Preco: precos,
				Parcela: parcelas
		
		};
		return item;
		
	}
	
	
	
});

//Registra o novo componente
Ext.reg('pedido-orcamento',Pedido.Pedido.Orcamento);

