 // vim: sw=4:ts=4:nu:nospell:fdc=4
 /*global Ext, EQP */
 /**
 * Classe que define o painel de consolidação dos dados
 *
 * @author Otávio Augusto
 * @copyright (c) 2009, by Otávio Augusto
 * @company Net On - Soluções Tecnol?gicas
 * @date 16 de Janeiro 2009
 *
 */

//Define o namespace
Ext.ns('Financeiro.Fluxo');

//Cria a classe base a ser estendida
Financeiro.Fluxo.Consolidacao = Ext.extend(Ext.grid.GridPanel,{

	/**
	 * Inicializa o componente
	 *
	 */
	initComponent : function(){
                this.columnStore = new Ext.data.JsonStore({
                    proxy: new Ext.data.HttpProxy({
                            url: App.sysURL + 'fluxo_action/getColumns/',
                            method: 'POST'
                    }),
                    root: 'results',
                    idProperty: 'id',
                    totalProperty: 'total',
                    fields: ['id','column'],
                    listeners:{
                        'load' : this.configureColumns,
                        scope: this
                    }
                });
                
		var config = {
                    title: 'Consolida&ccedil;&atilde;o',
                    iconCls: 'tab-chart',
                    store: new Ext.data.JsonStore({
                        proxy: new Ext.data.HttpProxy({
                                url: App.sysURL + 'fluxo_action/listSaida/',
                                method: 'POST'
                        }),
                        root: 'results',
                        idProperty: 'id',
                        totalProperty: 'total',
                        fields: ['id','tipo','acumulado']
                    }),
                    colModel: new Ext.ux.grid.LockingColumnModel([
                            {id: 'vencimento',header:'&nbsp;',dataIndex:'dt_vencimento',width:250, editor: new Ext.form.DateField(),renderer: Ext.util.Format.dateRenderer('d/m/Y'), locked:true}
                    ]),
                    tbar:[
                          {
                            xtype: 'tbtext',
                            text: 'De:'
                          },
                          {
                              xtype: 'datefield',
                              id: 'dt-consolidacao-start',
                              listeners:{
                                  'select' : function(dateField, date){
                                      date.setDate(1);
                                      dateField.setValue(date);
                                  },
                                  scope: this
                              }
                          },
                          '',
                          {
                            xtype: 'tbtext',
                            text: 'At&eacute;:'
                          },
                          {
                              xtype: 'datefield',
                              id: 'dt-consolidacao-end',
                              listeners:{
                                  'select' : function(dateField, date){
                                     var d = new Date((date.getMonth() + 1) + '/' + date.getDaysInMonth() + '/' + date.getFullYear());
                                     dateField.setValue(d);
                                  },
                                  scope: this
                              }
                          },'','',
                          /*{
                            xtype: 'checkbox',
                            boxLabel: 'Considerar acumulado anterior ao período informado',
                            id: 'ac-anterior',
                            checked: true
                          },'',*/
                          '-',
                          {
                              xtype: 'button',
                              text: '<b>Aplicar</b>',
                              scope: this,
                              handler: function(button){
                                   this.loaderTarget = button;
                                   Ext.ux.Loader.start({sender: button, waitingText: 'Aplicando...'});

                                  this.columnStore.load({
                                      params:{
                                          start: Ext.getCmp('dt-consolidacao-start').getRawValue(),
                                          end: Ext.getCmp('dt-consolidacao-end').getRawValue()
                                      }
                                  })
                              }
                          }
                    ],
                    stripeRows: false,
                    trackMouseOver: false,
                    view : new Ext.ux.grid.LockingGridView({
                        selectedRowClass: 'selected',
                        getRowClass: function(record, rowIndex, rp, ds){ 
                            if(rowIndex == 6 ){
                                return 'row-saldo';
                            }
                            if (rowIndex == 5 || rowIndex == 2){
                                return 'row-total'
                            }
                        }
                    })

		};

		//Aplica as configurações ao objeto
		Ext.apply(this,config);

		//Chama o m?todo de inicialização da superclasse
		Financeiro.Fluxo.Consolidacao.superclass.initComponent.apply(this);

		this.on('show',function(){
			this.columnStore.load();
		},this);

	},

        /**
         * Reconfigura as colunas do grid de consolidação
         */
        configureColumns : function(st){
            var store = this.createNewStore(st);
            var cm = this.getNewColumnModel(st);
            
            this.reconfigure(store, cm);

            this.store.load({params:{list: false}});

            Ext.ux.Loader.stop(this.loaderTarget);
            delete(this.loaerTarget);

        },

        /**
         * Recupera o novo modelo de colunas
         */
        getNewColumnModel : function(store){
            var cm = [
                {header: '&nbsp;', dataIndex: 'tipo', width: 250, locked: true},
                {header: 'Acumulado anterior (R$)', dataIndex: 'acumulado_anterior', width: 130, locked: true, align: 'right', renderer: this.renderValor}
            ];
            
            var column = {};

            for (i = 0; i < store.data.length; i++){
                var record = store.data.items[i].data;
                column = {header: record['column'] + " (R$)", dataIndex: 'col_' + record['id'], width: 100, align:'right', renderer: this.renderValor};
                cm.push(column);
            }

            cm.push({header: '<b>ACUMULADO (R$)</b>', dataIndex: 'acumulado', width: 105, align: 'right', renderer: this.renderValor});
            
            return new Ext.ux.grid.LockingColumnModel(cm);
        },

        /**
         * Cria um novo datastore para o objeto
         */
        createNewStore : function(store){
            var fields = [
                'id',
                {name: 'tipo', type: 'string'},
                {name: 'acumulado', type: 'float'},
                {name: 'acumulado_anterior', type: 'float'}
            ];

            for (i = 0; i < store.data.length; i++){
                var record = store.data.items[i].data;
                fields.push('col_' + record['id']);
            }

            return new Ext.data.JsonStore({
                proxy: new Ext.data.HttpProxy({
                        url: App.sysURL + 'fluxo_action/listConsolidacao/',
                        method: 'POST'
                }),
                root: 'results',
                idProperty: 'id',
                totalProperty: 'total',
                fields: fields
            })

        },
        
        renderValor : function(value, metaData, record, rowIndex, colIndex){
            if (((rowIndex > 2 && rowIndex < 6) & colIndex > 0 & parseFloat(value) != 0 || value < 0)){
                return "<span class='negative-value'>(" + Ext.util.Format.number(value, '0.000,00/i') + ")</span>";
            }else
            if (colIndex > 0)
                return "<span class='positive-value'>" + Ext.util.Format.number(value, '0.000,00/i') + "</span>";
            else
                return "<span class='item-value'>"+ value + "</span>";
        }



});

//Registra o novo componente
Ext.reg('fluxo-consolidacao',Financeiro.Fluxo.Consolidacao);
