<?xml version="1.0" encoding="UTF-8"?>
<panel-form xmlns="http://www.davinti.com.br/vitruvio/form/panel" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://www.davinti.com.br/vitruvio/form/panel https://bitbucket.org/davinTI/vitruvio-xds/raw/master/vitruvio-panel-form.xsd">
   <form formKey="formCadastroPadrao" height="100%" width="100%">
      <name>Formas de Pagamento</name>
      <description>Cadastro de formas de pagamento</description>
      <afterFormRenderScript language="JavaScript">
         <![CDATA[
         /*, */
            var config = { "tabela" :
                              {
                                 "conexao"     : "vitruvio",
                                 "nome"        : "forma_pagamento" ,
                                 "sequence"    : "forma_pagamento_seq" ,
                                 "idTabela"    : "CODIGO",
                                 "campos"      : ["CODIGO", "NOME" ],
                                 "camposTable" : ["CODIGO", "NOME" ]

                              },
                                 "relaciona" : [ ["CODIGO","idChave","Number"] ,
                                                 ["NOME","idDescricao","String"]                                             
                                               ] ,
                                "validacaoExclusao" : [ ["SELECT 0 AS CONTAR FROM FORMA_PAGAMENTO WHERE CODIGO = ", "Existem registros ligados a esta tabela!"],
                                						["SELECT COUNT(CHAVE_FORMA_PAGAMENTO) AS CONTAR FROM CONTROLE_DESPESAS_OPERACIONAIS WHERE CHAVE_FORMA_PAGAMENTO = ", "Existem registros ligados a esta tabela!"]
                                                      ],
                                'painel' :
                                {
                                   'titulo' : 'Cadastro de Formas de Pagamento',
                                   'icone'  : 'data:image/jpeg;base64,[encoded data, 5204 characters]'
                                }
                         };
            function run() 
            {        
               engine.setGlobalVariable('config', config);     
            }
         ]]>
         
      </afterFormRenderScript>
      <initScript language="JavaScript">
      <![CDATA[
         importClass(Packages.br.com.davinti.base.vaadin.components.icons.IconFactory);
         importClass(Packages.br.com.davinti.base.vaadin.components.resources.icons16x16.IconLibraryAPISmall);
         importClass(Packages.java.util.Calendar);
         importClass(Packages.br.com.davinti.base.vaadin.components.layout.MessageBox);
         importClass(Packages.com.vaadin.ui.Notification);  
         
         
         var getDataAtual = function() {
            var c = java.util.Calendar.getInstance();
            c.setTime(new java.util.Date());
            c.set(Calendar.HOUR_OF_DAY, 0);
            c.set(Calendar.MINUTE, 0);
            c.set(Calendar.SECOND, 0);
            c.set(Calendar.MILLISECOND, 0);
            
            return c.getTime();
         }
         
         
         var fncLimpaCampos = function(){
            var config = engine.getGlobalVariable('config');
            var lib = libService.loadScript('lib_cadastro_padrao');
            var retorno = lib.fncLimpaCampos(config);
         };
         
         var habilitaCampos = function(lHabilita){
            var botaoNovo    = engine.getWidgetController('btnNovo').getButton();
            var botaoSalvar  = engine.getWidgetController('btnSalvar').getButton();                                                                                  
            var botaoExcluir = engine.getWidgetController('btnExcluir').getButton();
            var botaoVoltar = engine.getWidgetController('btnVoltar').getButton();                                    
            
            botaoNovo.setEnabled(true);
            botaoSalvar.setEnabled(lHabilita);
            botaoExcluir.setEnabled(lHabilita);
           
            if(engine.getGlobalVariable('painelLista') == 1) {
            	botaoVoltar.setVisible(false);
            	botaoSalvar.setVisible(false);
            	botaoExcluir.setVisible(false);
            } else {
            	botaoVoltar.setVisible(true);
            	botaoSalvar.setVisible(true);
            	botaoExcluir.setVisible(true);
            }
           
            var config = engine.getGlobalVariable('config');
            var lib = libService.loadScript('lib_cadastro_padrao');
            var retorno = lib.fncHabilitaCampos(config, lHabilita);
            
            engine.getField('idChave').setEnabled(false);
            
            engine.getField('listaPrincipal').refresh();                                                
         };
         
         var novoRegistro = function() {           
            fncLimpaCampos(); 
            
            habilitaCampos(true);      
            engine.getLayout('pnlTitulo').getRootComposition().setVisible(false);
            engine.getLayout('pnlInclusao').getRootComposition().setVisible(true);           
            engine.getWidgetController('btnVoltar').getButton().setVisible(true); 
            engine.getField('idPesquisaLista')['setValue(java.lang.String)'](null);
            engine.getField('listaPrincipal').refresh();
            engine.getField('idPesquisa')['setValue(java.lang.Object)'](null);
            
            engine.getField('idChave').focus(); 
                           
         };
         
         var carregarCampos = function(id) {                         
            
            var config = engine.getGlobalVariable('config');
            var lib = libService.loadScript('lib_cadastro_padrao');
            var sql = lib.fncCarregarCampos(config, id);
            
         };
         
         var telaInicial = function() {
            engine.getLayout('pnlTitulo').getRootComposition().setVisible(true);
            engine.getLayout('pnlInclusao').getRootComposition().setVisible(false);
            var botaoNovo    = engine.getWidgetController('btnNovo').getButton();
            var botaoSalvar  = engine.getWidgetController('btnSalvar').getButton();                                                                                  
            var botaoExcluir = engine.getWidgetController('btnExcluir').getButton();
            var botaoVoltar  = engine.getWidgetController('btnVoltar').getButton();                                    
            
            botaoNovo.setVisible(true);
            botaoNovo.setEnabled(true);
            botaoSalvar.setVisible(false);
            botaoExcluir.setVisible(false);
            botaoVoltar.setVisible(false);
         
         }
         
         var deletarRegistro = function(id) {
            var config = engine.getGlobalVariable('config');
            var lib = libService.loadScript('lib_cadastro_padrao');
            var retorno = lib.fncDeletarRegistro(config, id);
            if (retorno) {           
               engine.getGlobalVariable('fncLimpaCampos')();
               engine.getGlobalVariable('habilitaCampos')(false); 
            }
         } 
         
         var validarDuplicidade = function(valor) {
         	var sql = "Select count(nome) ct from forma_pagamento where NOME = '" + valor + "'";
         	var db = libService.loadScript('db');
			var dbVitruvio = new db('vitruvio');
			var row = dbVitruvio.queryRow(sql);
			if (row.ct == 0 ) {
				return false;
			} else {
				if (engine.getField('idChave').getValue()) {
					engine.getField('idPesquisa')['setValue(java.lang.Object)'](null);
					return false;
				} else {
					return true;
				}
			}
          }     
        
         
         function run() {     
            var config = engine.getGlobalVariable('config');
            var titulo = config['painel'].titulo;
            var icone  = config['painel'].icone;
            engine.getLabel('Descricaocadastro').setValue('<p align="center"><img align="left" alt="" src="'+ icone + '" width="25" /><p align="center"><font color="Gray" face="Calibri" size="6" >&nbsp;&nbsp;' + titulo + '</font></p></p>');
            engine.getLabel('DescricaocadastroDentro').setValue('<p align="center"><img align="left" alt="" src="'+ icone + '" width="25" /><p align="center"><font color="Gray" face="Calibri" size="6" >&nbsp;&nbsp;' + titulo + '</font></p></p>');
            engine.setGlobalVariable('novoRegistro', novoRegistro);
            engine.setGlobalVariable('carregarCampos', carregarCampos);          
            engine.setGlobalVariable('habilitaCampos', habilitaCampos);          
            engine.setGlobalVariable('fncLimpaCampos', fncLimpaCampos);
            engine.setGlobalVariable('telaInicial', telaInicial); 
            engine.setGlobalVariable('deletarRegistro', deletarRegistro);
            engine.setGlobalVariable('validarDuplicidade', validarDuplicidade);
            engine.setGlobalVariable('painelLista',1);
            
            habilitaCampos(false);
            
            engine.getWidgetController('btnSalvar').getButton().setIcon(IconFactory.instance().getIconAsResource(IconLibraryAPISmall.APLICAR));
            engine.getWidgetController('btnNovo').getButton().setIcon(IconFactory.instance().getIconAsResource(IconLibraryAPISmall.CRIAR));
            engine.getWidgetController('btnExcluir').getButton().setIcon(IconFactory.instance().getIconAsResource(IconLibraryAPISmall.REMOVER));
            engine.getWidgetController('btnVoltar').getButton().setIcon(IconFactory.instance().getIconAsResource(IconLibraryAPISmall.VOLTAR));
            //engine.getFieldLocked('idAjuda', false);  // pode ser erro no componente, aberto caso Eduardo = 20108
            telaInicial(); 
                  
         }
      ]]>
      </initScript>
      <components>
         <VerticalLayout spacing="false" margin="false" height="100%" width="100%" align="TOP_LEFT" >
            <Panel width="100%" caption="" height="100%" expandRatio="1" margin="false" id="pnlTitulo" align="TOP_LEFT" >
               <VerticalLayout width="100%" expandRatio="1" margin="true">
                  <Label id="Descricaocadastro" contentMode="HTML" align="MIDDLE_CENTER" width="100%" > </Label>
                  <TextField id="idPesquisaLista" caption="Digite aqui para pesquisar:" type="string" width="100%" visible="true" immediate="true">
                     <events>
                        <valueChange>
                          <script language="JavaScript">
                              <![CDATA[
                                 function run(){
                                 	engine.getField('listaPrincipal').refresh();
                                 }
                              ]]>
                           </script>
                        </valueChange>
                     </events> 
                  </TextField>
                  <DBTable id="listaPrincipal" type="number" visible="true" width="100%" immediate="true" rows="5" selectable="false" multivalue="false" showRowCount="true">
                     <datasource>
                        <sqlBuilderDataSource connection-key="vitruvio" language="JavaScript">
                           <![CDATA[
                              
                              var getSql = function() {
                           
                              var config = { "tabela" :
                                    {
                                      "conexao"     : "vitruvio",
                                      "nome"        : "forma_pagamento" ,
                                      "sequence"    : "forma_pagamento_seq" ,
                                      "idTabela"    : "CODIGO",
                                      "campos"      : ["CODIGO", "NOME" ],
                                      "camposTable" : ["CODIGO", "NOME" ]
                                    },
                                    "relaciona" : [ ["CODIGO","idChave","Number"] ,
                                                    ["NOME","idDescricao","String"]                                             
                                                  ] ,

                                    "validacaoExclusao" : 
                                         [  ["SELECT 0 AS CONTAR FROM FORMA_PAGAMENTO WHERE CODIGO = ", "Existem registros ligados a esta tabela!"],
                                			["SELECT COUNT(CHAVE_FORMA_PAGAMENTO) AS CONTAR FROM CONTROLE_DESPESAS_OPERACIONAIS WHERE CHAVE_FORMA_PAGAMENTO = ", "Existem registros ligados a esta tabela!"]
                                        ],
                                    'painel' :
                                    {
                                       'titulo' : 'Cadastro de Combustíveis',
                                       'icone'  : 'data:image/jpeg;base64,[encoded data, 5204 characters]'
                                    }
                                        
                                       
                                };
                                 var lib = libService.loadScript('lib_cadastro_padrao');
                                 return lib.table(config, 'camposTable');
                              }
                              
                              function buildSQL(params) {
                                 var sql = getSql();
                                 if(engine) {
                                    var idPesquisaLista  = engine.getField('idPesquisaLista').getValue();
                                    if (idPesquisaLista != null) {
                                       sql = "SELECT * FROM ( " +  sql + " ) T WHERE T.NOME LIKE UPPER('%" +  idPesquisaLista + "%')";
                                    }
                                 }
                                 return sql;
                              }
                           ]]>
                        </sqlBuilderDataSource>
                        
                     </datasource>  
                     <key-field>CODIGO</key-field>
                     <columns>                                            
                        <!-- icone de edição -->
                        <generated name="Editar" align="CENTER" >
                           <scriptColumnGenerator language="JavaScript">
                              <![CDATA[
                                 importClass(Packages.br.com.davinti.base.vaadin.components.resources.icons16x16.IconLibraryAPISmall);
                                 importClass(Packages.br.com.davinti.base.vaadin.components.icons.IconFactory);   
                                 
                                 function Generator() {
                                     var comp = libService.loadScript('vaadinComponents');                                    
                                     this.generate = function (itemId, columnId, item, container) {
                                          var btn = comp.buttonIcon('editar', function () {   
                                                                               
                                          var id = itemId;
                                          engine.getField('idChave').setValue(id);
                                          
                                          if (id != null) {
                                          	 engine.setGlobalVariable('painelLista',0);                                     
                                             engine.getGlobalVariable('carregarCampos')(id);
                                             engine.getGlobalVariable('habilitaCampos')(true);   
                                             engine.getLayout('pnlInclusao').getRootComposition().setVisible(true);
                                             engine.getLayout('pnlTitulo').getRootComposition().setVisible(false);                                   
                                          }
                                                                                 
                                         }, 'pencil');                                            
                                      
                                         return btn;
                                     }
                                 }
                                 var script = new Generator();
                              ]]>
                           </scriptColumnGenerator>
                        </generated>
                        
                        <!-- icone de exclusão -->    
                        <generated name="Excluir" align="CENTER" >
                           <scriptColumnGenerator language="JavaScript">
                              <![CDATA[
                                 importClass(Packages.br.com.davinti.base.vaadin.components.layout.ConfirmationBox);
                                 importClass(Packages.br.com.davinti.base.vaadin.components.resources.icons16x16.IconLibraryAPISmall);
                                 importClass(Packages.br.com.davinti.base.vaadin.components.icons.IconFactory);                                 
                                 
                                 function Generator() {
                                     var comp = libService.loadScript('vaadinComponents');                                    
                                     this.generate = function (itemId, columnId, item, container) {
                                         var btn = comp.buttonIcon('excluir', function () {  
                                          
                                          var deletar = engine.getGlobalVariable('deletarRegistro');                                                       
                                          var registro = item.getItemProperty('CODIGO') + " - " + item.getItemProperty('NOME');                                            
                                          var msg = 'Confirma a exclusão das informações para \n'; 
                                          msg = msg.concat(registro, "?"); 
                                                                                                       
                                          ConfirmationBox.show( 'Confirmar operação'
                                                         , msg
                                                         , new ConfirmationBox.ConfirmationBoxListener() {
                                                               dialogEnd: function(context, action) {
                                                                  if(action == ConfirmationBox.Action.YES) {
                                                                     if(deletar){
                                                                     	engine.setGlobalVariable('painelLista',1);
                                                                        deletar(itemId);   
                                                                        engine.getField('listaPrincipal').refresh();                                                                        
                                                                     }
                                                                  }
                                                               }
                                                            }
                                                         ); 
                                         }, 'trash');                                          
                                      
                                         return btn;
                                     }
                                 }
                                 var script = new Generator();
                              ]]>
                           </scriptColumnGenerator>
                        </generated>                         
                        <column name="CODIGO" caption="Código"/>  
                        <column name="NOME" caption="Descrição"/>
                     </columns>
                  </DBTable>  
               </VerticalLayout>
            </Panel>
            
            <Panel width="100%" height="100%" expandRatio="1" caption="" margin="false" id="pnlInclusao">
               <VerticalLayout width="100%" margin="true">
                  <Label id="DescricaocadastroDentro" contentMode="HTML" align="MIDDLE_CENTER" width="100%" > </Label>
                  <TabLayout height="100%" width="100%">
                     <Tab caption="Dados" >
                        <VerticalLayout width="70%" margin="true" spacing="true">                     
                           <DBSearchField type="number" id="idPesquisa" expandRatio="1" caption="Pesquisar forma de pagamento" width="100%" searchCaption="Descrição da forma de pagamento" searchViewWidth="85%"	description="Selecione um fornecedor" >
								<datasource>
									<freeQuery connection-key="vitruvio">
										<![CDATA[
											SELECT * FROM forma_pagamento
										]]>
									</freeQuery>
								</datasource>
								<loadItemQuery>
									<![CDATA[
										SELECT *
											  FROM forma_pagamento
											   nome = ? ORDER BY codigo
									]]>
								</loadItemQuery>
								<key-field>CODIGO</key-field>
								<caption-field>NOME</caption-field>
								<columns>
									<column name="CODIGO" caption="Código" />
									<column name="NOME" caption="Descrição" />
								</columns>
								<filterProperties filterRequired="false">
									<value>CODIGO</value>
									<value>NOME</value>
								</filterProperties>
								<events>
									<valueChange>
										<script language="JavaScript">
											<![CDATA[
												function run() {
													//engine.getGlobalVariable('fncLimpaCampos')();
													engine.getGlobalVariable('carregarCampos')(engine.getField('idPesquisa').getValue());
												}
											]]>
										</script>
									</valueChange>
								</events>
							</DBSearchField>
							<HorizontalLayout width="100%" spacing="true">
								<TextField id="idChave" caption="Código" type="number" width="100%" expandRatio="0.08" />                              
                           		<TextField id="idDescricao" text-transform="uppercase" type="string" caption="Descrição" required="true" width="100%" expandRatio="1" /> 
							</HorizontalLayout>  
                        </VerticalLayout>  
                     </Tab>
                  </TabLayout>
               </VerticalLayout>

            </Panel>
            <Panel width="100%" margin="false" id="pnlBotoes" >
            	<VerticalLayout width="100%">
	               <HorizontalLayout margin="true" spacing="true" align="MIDDLE_CENTER" >
	                  <ButtonWidget id="btnSalvar" caption="Salvar" expandRatio="0.2" description="Salva os dados das Informações Adicionais do Cargo " align="MIDDLE_CENTER">
	                     <onClickScript language="JavaScript">
	                        <![CDATA[
	                          importClass(Packages.br.com.davinti.base.vaadin.components.layout.MessageBox);
	                           	function run() {
	                              if (engine.isValid()) {
	                              	if (engine.getGlobalVariable('validarDuplicidade')(engine.getField('idDescricao').getValue())) {
	                              		MessageBox.show(MessageBox.BoxType.INFO, 'Atenção', 'Já existe uma forma de pagamento cadastrada com esta descrição.');
	                              	} else {
		                                 var config = engine.getGlobalVariable('config');
		                                 var id     = engine.getField('idChave').getConvertedValue();
		                                 var lib = libService.loadScript('lib_cadastro_padrao');
		                                 var retorno = lib.fncGravarRegistro(config, id);
		                                
		                                 if (retorno) {
		                                    engine.getGlobalVariable('fncLimpaCampos')();
		                                 }
	                                 }
	                              }
	                           	}
	                        ]]>
	                     </onClickScript>
	                  </ButtonWidget>
	                  <ButtonWidget caption="Novo" id="btnNovo" expandRatio="0.2" description="Novo cadastro" align="MIDDLE_CENTER">
	                     <onClickScript language="JavaScript">
	                        <![CDATA[
	                           function run() {
	                              engine.setGlobalVariable('painelLista',0);
	                              engine.getGlobalVariable('novoRegistro')();
	                           }
	                        ]]>
	                     </onClickScript>
	                  </ButtonWidget>
	                  <ButtonWidget caption="Excluir" id="btnExcluir" expandRatio="0.2" description="Excluir os dados atuais" align="MIDDLE_CENTER">
	                     <onClickScript language="JavaScript">
	                        <![CDATA[
	                           importClass(Packages.br.com.davinti.base.vaadin.components.layout.MessageBox);
	                           importClass(Packages.br.com.davinti.base.vaadin.components.layout.ConfirmationBox);
	                           importClass(Packages.com.vaadin.ui.Notification);
	      
	                           function run() {
	                              if(engine.isValid()) {
	                                 var deletar = engine.getGlobalVariable('deletarRegistro');
	                                 var listener = new ConfirmationBox.ConfirmationBoxListener() {
	                                    dialogEnd: function(context, action) {
	                                       if(action == ConfirmationBox.Action.YES) {
	                                          var id = engine.getField('idChave').getConvertedValue();
	                                          if(deletar){
	                                             engine.setGlobalVariable('painelLista',0);                                       
	                                             deletar(id);
	                                          }   
	                                       }     
	                                    }
	                                 };
	                                 
	                                 ConfirmationBox.show(ConfirmationBox.DialogIcon.WARNING, 'Confirmar exclusão do registro?', 'Tem certeza de que deseja excluir o tipo de ocorrência selecionado?', listener, ConfirmationBox.ACTION_YES_CANCEL);                                   
	                              }
	                           }
	                        ]]>
	                     </onClickScript>
	                  </ButtonWidget>
	                  <ButtonWidget caption="Voltar" id="btnVoltar" expandRatio="0.2" description="Voltar a tela inicial" align="MIDDLE_CENTER">
	                     <onClickScript language="JavaScript">
	                        <![CDATA[
	                           function run() {
	                           	  engine.setGlobalVariable('painelLista',1);
	                              engine.getGlobalVariable('fncLimpaCampos')();
	                              newRecord  = false;
	                              saveStatus = false;
	                              engine.getGlobalVariable('telaInicial')();
	                              engine.getField('listaPrincipal').refresh();
	                           }
	                        ]]>
	                     </onClickScript>
	                  </ButtonWidget>
	               </HorizontalLayout>
               </VerticalLayout>
            </Panel>
         </VerticalLayout>
      </components>
   </form>
</panel-form>