<?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>Clientes</name>
      <description>Cadastro de Clientes</description>
      <afterFormRenderScript language="JavaScript">
         <![CDATA[
         /*, */
            var config = { "tabela" :
                              {
                                 "conexao"     : "vitruvio",
                                 "nome"        : "CLIENTES" ,
                                 "sequence"    : "CLIENTES_SEQ" ,
                                 "idTabela"    : "CODIGO",
                                 "campos"      : ["CODIGO", "NOME" ],
                                 "camposTable" : ["CODIGO", "DESCRICAO"]
                              },
                                 "relaciona" : [ ["CODIGO","idChave","Number"] ,
                                                 ["NOME","idDescricao","String"] 
                                               ] ,
                                "validacaoExclusao" : [ ["SELECT 0 AS CONTAR FROM CLIENTES WHERE CODIGO = ", "Existem registros ligados a esta tabela."],
                                						["SELECT COUNT(CHAVE_CLIENTE) AS CONTAR FROM CONTROLE_DESPESAS_OPERACIONAIS WHERE CHAVE_CLIENTE = ", "Existem registros ligados a esta tabela."],
                                						["SELECT COUNT(CHAVE_CLIENTE) AS CONTAR FROM CONTROLE_DESPESAS_COMBUSTIVEIS WHERE CHAVE_CLIENTE = ", "Existem registros ligados a esta tabela."],
                                						["SELECT COUNT(CHAVE_CLIENTE) AS CONTAR FROM CONTROLE_RECEITAS_FRETES WHERE CHAVE_CLIENTE = ", "Existem registros ligados a esta tabela."]
                                                      ],
                                'painel' :
                                {
                                   'titulo' : 'Cadastro de Clientes',
                                   'icone'  : 'data:image/jpeg;base64,/9j/4QAYRXhpZgAASUkqAAgAAAAAAAAAAAAAAP/sABFEdWNreQABAAQAAAA8AAD/4QMraHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLwA8P3hwYWNrZXQgYmVnaW49Iu+7vyI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wBbaI0R5GAUmnVqDcx9nhr59rWlXt/NlFGQM2VO073UHgFxbyxxNqcXFW8Hgkxxmmk7cl3cEF5lUghQAAgLFjtFK06avNF0oWUWSoca7aU7utQXNxzD1Bd5nO2eNgl3SK12I98NtX1OSaL09lfHU9/qUduw1Iz0qG7zwVfNO1gPHgsbgmPk7dxlrg757tiqOfEqGq7f7n/AA0h+vWrmxGZ/rlNe7/O1Q2URDcx9Tk160CdRoQkflvBpZ7iK9wNukNzVjcbZDDWvgUAFAT59Rq2s9QDQWyklu7CqyesaCXuEls0Nfvxy+H12KTgsvIMdIcHlLGZLdQzWlyRuRKdWjLqSNv7f6a51ARP9xjhXePr91LoJuofYmY7KPS7aOyvy8E6aq1p0aEI0ISLz8uMra9kK0zw7RvJVEBc+tyoLbR16KCdYn9kY11zGC4N8mJx49Sq731jsWrwm2xNtBdx2l5JfXm9Df3EiSRqWK+gRIwCCMDw2V95J1f6My3bFSA5hXE41r3pm0DADlNeKZdW6bRoQjQhGhCNCF//2Q=='
                                }
                         };
            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); 
         importClass(Packages.com.vaadin.server.FontAwesome); 
         
         
         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);
            engine.getField('percentualSocio')['setValue(java.lang.String)'](null);
            engine.getField('socios')['setValue(java.lang.Object)'](null);
            engine.getField('socioLista').getContainerDataSource().removeAllItems();
            engine.getField('socioPercentual').getContainerDataSource().removeAllItems();
            engine.getField('pracaLista').getContainerDataSource().removeAllItems();
            engine.getField('pracaPercentual').getContainerDataSource().removeAllItems();
            engine.getField('twinUsuario')["setValue(java.lang.Object)"](null);
            engine.getField('idPesquisaLista')['setValue(java.lang.String)'](null);
         };
         
         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('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 sql = "Select s.nome, os.participacao from clientes_socio os inner join clientes o on o.codigo = os.codigo_cliente inner join socios s on s.codigo = os.codigo_socio where os.codigo_cliente = " + id;
         	var db = libService.loadScript('db');
			var dbVitruvio = new db('vitruvio');
			var containerPercentual = engine.getField("socioPercentual").getContainerDataSource();
			var containerSocio = engine.getField("socioLista").getContainerDataSource();
			dbVitruvio.query(sql).each(function (r) {
				if (r.nome) {
					containerSocio.addItem(r.nome).getItemProperty("caption").setValue(r.nome);
					containerPercentual.addItem(r.nome).getItemProperty("caption").setValue(String(r.participacao));
				}	
			});
			sql = "Select codigo_usuario from clientes_usuario where codigo_cliente = " + id;
			var ids = new java.util.ArrayList();
			dbVitruvio.query(sql).each(function (r) {
				if (r.codigo_usuario) {
					ids.add(r.codigo_usuario);
				}
			});
			engine.getField('twinUsuario').setValue(ids);
			        
            var sql = "Select e.nome, os.chave_estado, os.percentual_impostos from clientes_praca os inner join estados e on e.chave_estado = os.chave_estado where os.chave_cliente = " + id;
			var containerPercentual = engine.getField("pracaPercentual").getContainerDataSource();
			var containerSocio = engine.getField("pracaLista").getContainerDataSource();
			dbVitruvio.query(sql).each(function (r) {
				if (r.nome) {
					containerSocio.addItem(r.nome).getItemProperty("caption").setValue(r.nome);
					containerPercentual.addItem(r.nome).getItemProperty("caption").setValue(String(r.percentual_impostos));
				}	
			});
         };
         
         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.getField('idChave').setValue(params.get('id'));              
               engine.getGlobalVariable('fncLimpaCampos')();
               engine.getGlobalVariable('habilitaCampos')(true); 
            }
         }  
         
         var validarDuplicidade = function(valor) {
         	var sql = "Select count(nome) ct from clientes 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="56" /><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="56" /><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);
            engine.getField('socioPercentual').setEnabled(false);
            
            //fncLimpaCampos();
            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.getWidgetController('btnPercentual').getButton().setIcon(FontAwesome.PLUS);
            engine.getWidgetController('btnRemoverPercentual').getButton().setIcon(FontAwesome.MINUS);
            engine.getWidgetController('btnPraca').getButton().setIcon(FontAwesome.PLUS);
            engine.getWidgetController('btnRemoverPraca').getButton().setIcon(FontAwesome.MINUS);
            //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"        : "clientes" ,
                                      "sequence"    : "clientes_seq" ,
                                      "idTabela"    : "CODIGO",
                                      "campos"      : ["CODIGO", "NOME"],
                                      "camposTable" : ["CODIGO", "NOME"]
                                    },
                                    "relaciona" : 
                                         [ ["CODIGO","idChave","Number"]
                                         , ["NOME","idDescricao","String"]
                                        ] ,
                                    "validacaoExclusao" : 
                                         [ ["SELECT 0 AS CONTAR FROM clientes WHERE CODIGO = ", "Existem registros ligados a esta tabela."],
                                						["SELECT COUNT(CHAVE_CLIENTE) AS CONTAR FROM CONTROLE_DESPESAS_OPERACIONAIS WHERE CHAVE_CLIENTE = ", "Existem registros ligados a esta tabela."],
                                						["SELECT COUNT(CHAVE_CLIENTE) AS CONTAR FROM CONTROLE_DESPESAS_COMBUSTIVEIS WHERE CHAVE_CLIENTE = ", "Existem registros ligados a esta tabela."],
                                						["SELECT COUNT(CHAVE_CLIENTE) AS CONTAR FROM CONTROLE_RECEITAS_FRETES WHERE CHAVE_CLIENTE = ", "Existem registros ligados a esta tabela."]
                                        ],
                                    'painel' :
                                    {
                                       'titulo' : 'Cadastro de Clientes',
                                       'icone'  : 'data:image/jpeg;base64,/9j/4QAYRXhpZgAASUkqAAgAAAAAAAAAAAAAAP/sABFEdWNreQABAAQAAAA8AAD/4QMraHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLwA8P3hwYWNrZXQgYmVnaW49Iu+7vyIgaWQ9Ilc1TTBNcENlaGlIenJlU3pOVGN6a2M5ZCI/PiA8eDp4bXBtZXRhIHhtbG5zOng9ImFkb2JlOm5zOm1ldGEvIiB4OnhtcHRrPSJBZG9iZSBYTVAgQ29yZSA1LjMtYzAxMSA2Ni4xNDU2NjEsIDIwMTIvMDIvMDYtMTQ6NTY6MjcgICAgICAgICI+IDxyZGY6UkRGIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zIyI+IDxyZGY6RGVzY3JpcHRpb24gcmRmOmFib3V0PSIiIHhtbG5zOnhtcD0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLy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yvy8E6aq1p0aEI0ISLz8uMra9kK0zw7RvJVEBc+tyoLbR16KCdYn9kY11zGC4N8mJx49Sq731jsWrwm2xNtBdx2l5JfXm9Df3EiSRqWK+gRIwCCMDw2V95J1f6My3bFSA5hXE41r3pm0DADlNeKZdW6bRoQjQhGhCNCF//2Q=='
                                    }
                                        
                                       
                                };
                                 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" expand-ratio="0.2">
                           <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" expand-ratio="0.2">
                           <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="Nome"/>
                     </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 operação" width="100%" searchCaption="Nome do operação" searchViewWidth="85%"	description="Selecione um fornecedor" >
								<datasource>
									<freeQuery connection-key="vitruvio">
										<![CDATA[
											SELECT * FROM clientes
										]]>
									</freeQuery>
								</datasource>
								<loadItemQuery>
									<![CDATA[
										SELECT *
											  FROM clientes
											   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('carregarCampos')(engine.getField('idPesquisa').getValue());
												}
											]]>
										</script>
									</valueChange>
								</events>
							</DBSearchField>
                        	<HorizontalLayout spacing="true" width="100%" >
                        		<TextField type="number" id="idChave" width="100%" caption="Código" expandRatio="0.08" />                              
                           		<TextField type="string" id="idDescricao" text-transform="uppercase" caption="Descrição" required="true" width="100%" expandRatio="1" />
                        	</HorizontalLayout>
                        	<TabLayout compact="true" width="100%">
                        		<Tab caption="Sócios">
                        			<VerticalLayout spacing="true" width="100%">
                        				<Label id="lb1" >
                        					<value>
                        					
                        					</value>
                        				</Label>
                        				<HorizontalLayout spacing="true" width="420">
	                        				<DBComboBox type="string" id="socios" caption="Sócio" width="100%" expandRatio="0.8" description="Selecione um sócio" allowNullSelection="true" searchCaption="Digite para localizar...">
	                        					<datasource>
	                        						<freeQuery connection-key="vitruvio">
	                        							<![CDATA[
	                        								Select nome from socios where codigo > 0
	                        							]]>
	                        						</freeQuery>
	                        					</datasource>
	                        					<key-field>NOME</key-field>
	                        					<caption-field>NOME</caption-field>
	                        				</DBComboBox>
	                        				<DecimalField caption="% Participação" expandRatio="0.2" maximumValue="100" maxLength="6" type="decimal" id="percentualSocio" width="100%" align="TOP_LEFT" description="Percentual de participação do sócio" />
	                        				<ButtonWidget id="btnPercentual" description="Adicionar percentual" height="25" align="BOTTOM_LEFT" >
	                        					<onClickScript language="JavaScript">
	                        						<![CDATA[
	                        							importClass(Packages.br.com.davinti.base.vaadin.components.layout.MessageBox);
	                        							
	                        							function run() {
															var containerPercentual = engine.getField("socioPercentual").getContainerDataSource();
															var containerSocio = engine.getField("socioLista").getContainerDataSource();
															var ids = engine.getField('socioLista').getContainerDataSource().getItemIds();
															var iter = ids.iterator();
															var total = 0.00;
															var definido = 0;
															while (iter.hasNext()) {
																var value = iter.next();
																if (engine.getField('socios').getValue() == value) {
																	MessageBox.show(MessageBox.BoxType.INFO, 'Atenção', 'O sócio já possui percentual definido.');
																	definido = 1;
																}
																total = parseFloat(total) + parseFloat(String(engine.getField('socioPercentual').getContainerDataSource().getItem(value)).replace(',','.'));
															}
															if (engine.getField('socioPercentual').getContainerDataSource().getItem(value)) {
																var valor = String(engine.getField('percentualSocio').getValue());
																total = (parseFloat(total) + parseFloat(engine.getField('percentualSocio').getConvertedValue()));
															} else {
																total = engine.getField('percentualSocio').getConvertedValue();
															}
															if (definido == 0) {
																if (total <= 100.00) {
																	containerSocio.addItem(engine.getField('socios').getValue()).getItemProperty("caption").setValue(engine.getField('socios').getValue());
																	containerPercentual.addItem(engine.getField('socios').getValue()).getItemProperty("caption").setValue(String(engine.getField('percentualSocio').getValue()));
																	engine.getField('percentualSocio')['setValue(java.lang.String)'](null);
            														engine.getField('socios')['setValue(java.lang.Object)'](null);
																} else {
																	MessageBox.show(MessageBox.BoxType.INFO, 'Atenção', 'Percentual não pode ultrapassar 100%.');
																}
															}
	                        							}
	                        						]]>
	                        					</onClickScript>
	                        				</ButtonWidget>
	                        				<ButtonWidget id="btnRemoverPercentual" description="Remover percentual" height="25" align="BOTTOM_LEFT" >
	                        					<onClickScript language="JavaScript">
	                        						<![CDATA[
	                        							importClass(Packages.br.com.davinti.base.vaadin.components.layout.MessageBox);
						                                function run() {
						                                	var texto = engine.getField('socioLista').getValue();
						                                	if (texto != '') {
						                                		try {
							                                		var container = engine.getField("socioLista").getContainerDataSource();
	                               									container.removeItem(texto);
	                               									var container2 = engine.getField("socioPercentual").getContainerDataSource();
	                               									container2.removeItem(texto);
	                              									} catch(e) {
	                              										MessageBox.show('Alerta', 'Dados inválidos!');
	                              									}
						                                	}
						                                };
	                        						]]>
	                        					</onClickScript>
	                        				</ButtonWidget>
                        				</HorizontalLayout>
                        				<HorizontalLayout width="420" >
                        					<ListSelect type="string" id="socioLista" readOnly="true" width="100%" expandRatio="0.8" allowNullSelection="true" rows="5">
                        						<events>
                        							<valueChange>
                        								<script language="JavaScript">
                        									<![CDATA[
                        										function run() {
                        											engine.getField('socioPercentual').setValue(engine.getField('socioLista').getValue());
                        										}
                        									]]>
                        								</script>
                        							</valueChange>
                        						</events>
                        					</ListSelect>
                        					<ListSelect type="string" id="socioPercentual"  readOnly="true"  width="100%" expandRatio="0.2"  allowNullSelection="true" rows="5">
                        						
                        					</ListSelect>
                        				</HorizontalLayout>
                        			</VerticalLayout>
                        		</Tab>
                        		<Tab caption="Usuários" visible="false">
                        			<VerticalLayout margin="false" width="100%" >
                        				<Label id="lb2">
	                        				<value>
	                        					  
	                        				</value>
	                        			</Label>
                        				<DBTwinColSelect type="number" id="twinUsuario" allowNullSelection="true" multivalue="true" width="70%" align="TOP_LEFT" >
                        					<datasource>
                        						<freeQuery connection-key="vitruvio">
                        							<![CDATA[
                        								Select usuario_id, nome from nauth.usuario where ativo = true
                        							]]>
                        						</freeQuery>
                        					</datasource>
                        					<key-field>USUARIO_ID</key-field>
                        					<caption-field>NOME</caption-field>
                        				</DBTwinColSelect>
                        			</VerticalLayout>
                        		</Tab>
                        		<Tab caption="Impostos" visible="true" >
                        			<VerticalLayout width="100%" margin="true" spacing="true" >
				                     	<HorizontalLayout width="420" spacing="true" margin="false" >
				                     		<DBComboBox type="string" id="idPraca" caption="Praça" width="100%" expandRatio="0.8" allowNullSelection="true">
				                     			<datasource>
				                     				<freeQuery connection-key="vitruvio">
				                     					<![CDATA[
				                     						Select * from estados
				                     					]]>
				                     				</freeQuery>
				                     			</datasource>
				                     			<key-field>NOME</key-field>
				                     			<caption-field>NOME</caption-field>
				                     		</DBComboBox>
				                     		<DecimalField type="decimal" id="valorImpostos" caption="% Impostos" expandRatio="0.2" width="100%" maximumValue="100" maxLength="6" />
					                     	<ButtonWidget id="btnPraca" description="Adicionar praça" height="25" align="BOTTOM_LEFT" >
		                    					<onClickScript language="JavaScript">
		                    						<![CDATA[
		                    							importClass(Packages.br.com.davinti.base.vaadin.components.layout.MessageBox);
		                    							
		                    							function run() {
															var containerPercentual = engine.getField("pracaPercentual").getContainerDataSource();
															var containerSocio = engine.getField("pracaLista").getContainerDataSource();
															var ids = engine.getField('pracaLista').getContainerDataSource().getItemIds();
															var iter = ids.iterator();
															var total = 0.00;
															var definido = 0;
															while (iter.hasNext()) {
																var value = iter.next();
																if (engine.getField('idPraca').getValue() == value) {
																	MessageBox.show(MessageBox.BoxType.INFO, 'Atenção', 'A praça já foi definida.');
																	definido = 1;
																}
																total = parseFloat(total) + parseFloat(String(engine.getField('pracaPercentual').getContainerDataSource().getItem(value)).replace(',','.'));
															}
															if (engine.getField('pracaPercentual').getContainerDataSource().getItem(value)) {
																var valor = String(engine.getField('valorImpostos').getValue());
																total = (parseFloat(total) + parseFloat(engine.getField('valorImpostos').getConvertedValue()));
															} else {
																total = engine.getField('valorImpostos').getConvertedValue();
															}
															if (definido == 0) {
																containerSocio.addItem(engine.getField('idPraca').getValue()).getItemProperty("caption").setValue(engine.getField('idPraca').getValue());
																containerPercentual.addItem(engine.getField('idPraca').getValue()).getItemProperty("caption").setValue(String(engine.getField('valorImpostos').getValue()));
																engine.getField('valorImpostos')['setValue(java.lang.String)'](null);
				       											engine.getField('idPraca')['setValue(java.lang.Object)'](null);
															}
		                    							}
		                    						]]>
		                    					</onClickScript>
		                    				</ButtonWidget>
		                    				<ButtonWidget id="btnRemoverPraca" description="Remover praça" height="25" align="BOTTOM_LEFT" >
		                    					<onClickScript language="JavaScript">
		                    						<![CDATA[
		                    							importClass(Packages.br.com.davinti.base.vaadin.components.layout.MessageBox);
						                                function run() {
						                                	var texto = engine.getField('pracaLista').getValue();
						                                	if (texto != '') {
						                                		try {
							                                		var container = engine.getField("pracaLista").getContainerDataSource();
					                           									container.removeItem(texto);
					                           									var container2 = engine.getField("pracaPercentual").getContainerDataSource();
					                           									container2.removeItem(texto);
					                          									} catch(e) {
					                          										MessageBox.show('Alerta', 'Dados inválidos!');
					                          									}
						                                	}
						                                };
		                    						]]>
		                    					</onClickScript>
		                    				</ButtonWidget>
	                    				</HorizontalLayout>
	                    				<HorizontalLayout width="420" >
	                       					<ListSelect type="string" id="pracaLista" readOnly="true" width="100%" expandRatio="0.8" allowNullSelection="true" rows="5">
	                       						<events>
	                       							<valueChange>
	                       								<script language="JavaScript">
	                       									<![CDATA[
	                       										function run() {
	                       											engine.getField('pracaPercentual').setValue(engine.getField('pracaLista').getValue());
	                       										}
	                       									]]>
	                       								</script>
	                       							</valueChange>
	                       						</events>
	                       					</ListSelect>
	                       					<ListSelect type="string" id="pracaPercentual"  readOnly="true"  width="100%" expandRatio="0.2"  allowNullSelection="true" rows="5">
	                       						
	                       					</ListSelect>
	                       				</HorizontalLayout>
                       				</VerticalLayout>
			                     </Tab>
                        	</TabLayout>                    
                        </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 um cliente cadastrado com este nome.');
	                              	} else {
	                              		// Para gravação de percentual de sócios
										var containerSocio = engine.getField("socioLista").getContainerDataSource();
										var containerPercentual = engine.getField("socioPercentual").getContainerDataSource();
										var ids = engine.getField('socioLista').getContainerDataSource().getItemIds();
										var iter = ids.iterator();
										var total = 0.00;
										while (iter.hasNext()) {
											var value = iter.next();
											total = parseFloat(total) + parseFloat(String(engine.getField('socioPercentual').getContainerDataSource().getItem(value)).replace(',','.'));
										}
										
										if (total != 100.00) {
											MessageBox.show(MessageBox.BoxType.INFO, 'Atenção', 'Percentual deve ser igual a 100%.');
										} 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);
			                                
			                                var db = libService.loadScript('db');
											var dbVitruvio = new db('vitruvio');
											var sql;
											var socio;
											var percentual;
											var iter2 = ids.iterator();
											
											dbVitruvio.transaction(function() {
												sql = "delete from clientes_socio where codigo_cliente = :cliente";
													this.update(sql, {
													cliente: Number(retorno)
												   });
									        });
											
											while (iter2.hasNext()) {
												var value = iter2.next();
												var row = dbVitruvio.queryRow("Select codigo from socios where nome = '" + String(engine.getField('socioLista').getContainerDataSource().getItem(value)) + "'");
												if (row.codigo) {
													socio = row.codigo
												}
												percentual = parseFloat(String(engine.getField('socioPercentual').getContainerDataSource().getItem(value)).replace(',','.'));
												dbVitruvio.transaction(function() {
													sql = "insert into clientes_socio (codigo,codigo_cliente,codigo_socio,participacao) values (" + dbVitruvio.getSequenceNextValSql('clientes_socios_seq') + ",:cliente,:socio,:participacao)";
												   this.update(sql, {
														cliente: Number(retorno),
														socio: Number(socio),
														participacao: percentual
												   });
										        });
										    }
										    
										    // Para gravação de praças
										    dbVitruvio.transaction(function() {
												sql = "delete from clientes_praca where chave_cliente = :cliente";
													this.update(sql, {
													cliente: Number(retorno)
												   });
									        });
									        var containerSocio = engine.getField("pracaLista").getContainerDataSource();
											var containerPercentual = engine.getField("pracaPercentual").getContainerDataSource();
											var ids = engine.getField('pracaLista').getContainerDataSource().getItemIds();
											var iter = ids.iterator();
			                                
			                                var db = libService.loadScript('db');
											var dbVitruvio = new db('vitruvio');
											var sql;
											var praca;
											var percentualPraca;
											var iter3 = ids.iterator();
												
											while (iter3.hasNext()) {
												var value = iter3.next();
												var sql = "Select chave_estado from estados where nome = '" + engine.getField('pracaLista').getContainerDataSource().getItem(value) + "'";
												var estado = dbVitruvio.queryRow(sql);	
												var praca = estado.chave_estado;
												percentualPraca = parseFloat(String(engine.getField('pracaPercentual').getContainerDataSource().getItem(value)).replace(',','.'));
												dbVitruvio.transaction(function() {
													sql = "insert into clientes_praca (chave_praca,chave_cliente,chave_estado,percentual_impostos) values (" + dbVitruvio.getSequenceNextValSql('clientes_praca_seq') + ",:cliente,:praca,:percentual)";
												   this.update(sql, {
														cliente: Number(retorno),
														praca: Number(praca),
														percentual: percentualPraca
												   });
										        });
										    }
									        
									        //*****************************
										    
										    
										    dbVitruvio.transaction(function() {
												sql = "delete from clientes_usuario where codigo_cliente = :cliente";
													this.update(sql, {
													cliente: Number(retorno)
												   });
									        });
									        
									        var u = engine.getField('twinUsuario').getValue();
									        if (u) {
										        var i = u.iterator();
										        while (i.hasNext()) {
										        	dbVitruvio.transaction(function() {
														sql = "insert into clientes_usuario (codigo,codigo_cliente,codigo_usuario) values (" + dbVitruvio.getSequenceNextValSql('clientes_usuario_seq') + ",:cliente,:usuario)";
													   this.update(sql, {
															cliente: Number(retorno),
															usuario: Number(i.next())
													   });
											        });
										        }
									        }
			                                
			                                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 cliente 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>