<?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="formCadastro" width="100%" height="100%">
    	<name>Lançar Valor</name>
      	<description>Geral X Dia</description>
      	<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);
   			
			function fncLimpaCampos(){
				
			}
			
			function run() {
				var d = new java.util.Date();
				var c = java.util.Calendar.getInstance();
           		c.setTime(new java.util.Date());
           		c.set(Calendar.DAY_OF_MONTH, 1);
				var data = c.getTime();
				engine.setGlobalVariable('fncLimpaCampos', fncLimpaCampos);
				if (engine.getGlobalVariable('_mobileRender')) {
					if (!engine.getField('dataInicio').getValue()) {
						engine.getField('dataInicio').setValue(data);
						engine.getField('dataFinal').setValue(d);
                  if (!engine.getField('ftFrotaTerceiro').getValue()) {
                     engine.getField('ftFrotaTerceiro').setValue('A');
                  }
                  if (!engine.getField('ftCaminhaoCarreta').getValue()) {
                     engine.getField('ftCaminhaoCarreta').setValue('A');
                  }
					}
					engine.getField('tbLancamentos').refresh();
				} else {
               engine.getField('ftFrotaTerceiro').setValue('A');
               engine.getField('ftCaminhaoCarreta').setValue('A');
					engine.getField('dataInicio').setValue(data);
					engine.getField('dataFinal').setValue(d);
					engine.getField('tbLancamentos').refresh();
				}
            
				// Registrando icones
				engine.getWidgetController('btnFiltrar').getButton().setIcon(IconFactory.instance().getIconAsResource(IconLibraryAPISmall.FILTRAR));
			}
		]]>
	  	</initScript>

      	<components>
      		<VerticalLayout margin="true" width="100%" >
				<VerticalLayout spacing="true" width="100%" height="100%">
				   <Panel width="100%" expandRatio="0.1" align="TOP_LEFT" height="100%">
						<VerticalLayout width="100%" margin="true" spacing="true">
							<HorizontalLayout width="100%" spacing="true" height="100%">
						      <HorizontalLayout width="100%" expandRatio="0.35" align="TOP_LEFT">
                           <ImageWidget id="img1" height="75" align="TOP_LEFT">
						      		<image>
						      			<base64 extension="jpg">
						      				<![CDATA[
						      					,[encoded data, 7420 characters]
						      				]]>
						      			</base64>
						      		</image>
						      	</ImageWidget>
                        </HorizontalLayout>
						      	<HorizontalLayout width="100%" spacing="true" align="BOTTOM_RIGHT" expandRatio="1" >
							      	<VerticalLayout width="100%" spacing="true" expandRatio="0.8" align="TOP_LEFT">
                                 <HorizontalLayout width="100%" spacing="true" >
                                    <DateField type="date" id="dataInicio" caption="Data inicial" width="100%" expandRatio="0.30" align="TOP_RIGHT" description="Data inicial da exibição" format="dd/MM/yyyy" />
         									<DateField type="date" id="dataFinal" caption="Data final" width="100%" expandRatio="0.30" align="TOP_RIGHT" description="Data final da exibição" format="dd/MM/yyyy" />
         									<DBComboBox type="string" id="placa" width="100%" expandRatio="0.3" align="TOP_RIGHT" allowNullSelection="true" caption="Placa">
         						      		<datasource>
         						      			<freeQuery connection-key="vitruvio">
         						      				<![CDATA[
         						      					Select * from veiculo
         						      				]]>
         						      			</freeQuery>
         						      		</datasource>
         						      		<key-field>CODIGO</key-field>
         						      		<caption-field>PLACA</caption-field>
         						      	</DBComboBox>
                                 </HorizontalLayout>
                                 <OptionGroup type="string" id="ftFrotaTerceiro" disposition="horizontal" width="100%" expandRatio="0.3" align="MIDDLE_CENTER">
                                    <entry value="Ambos" key="A"/>
                                    <entry value="Frota" key="F"/>
                                    <entry value="Terceiro" key="T"/>
                                 </OptionGroup>
                                 
                                 <OptionGroup type="string" id="ftCaminhaoCarreta" disposition="horizontal" width="100%" expandRatio="0.3" align="MIDDLE_CENTER">
                                    <entry value="Todos" key="A"/>
                                    <entry value="Caminhão" key="C"/>
                                    <entry value="Carreta" key="T"/>
                                    <entry value="Outros" key="O"/>
                                 </OptionGroup>
                                 
                              </VerticalLayout>
                              <DBTwinColSelect type="number" id="ftClientes" multivalue="true" allowNullSelection="true" align="TOP_RIGHT" caption="Clientes" rows="5" width="100%" expandRatio="1">
                                 <datasource>
                                    <freeQuery connection-key="vitruvio">
                                       <![CDATA[
                                          Select codigo, nome from clientes order by nome
                                       ]]>
                                    </freeQuery>
                                 </datasource>
                                 <key-field>CODIGO</key-field>
                                 <caption-field>NOME</caption-field>
                                 <events>
                                    <valueChange>
                                       <script language="JavaScript">
                                          <![CDATA[
                                             function run() {
                                                engine.getField('clientes').setValue(engine.getField('ftClientes').getValue());
                                             }
                                          ]]>
                                       </script>
                                    </valueChange>
                                 </events>
                              </DBTwinColSelect> 
                              <TextField type="number" id="clientes" visible="false" caption="clientes" multivalue="true" />  
   									<ButtonWidget id="btnFiltrar" caption="Filtrar" description="Aplica filtro de data" width="100%" expandRatio="0.25">
   										<onClickScript language="JavaScript">
   											<![CDATA[
   												function run() {
   													engine.getField('tbLancamentos').refresh();
   												}
   											]]>
   										</onClickScript>
   									</ButtonWidget>
								</HorizontalLayout>
						    </HorizontalLayout>
						</VerticalLayout>
					</Panel>
					<Panel width="100%" margin="true" id="pnlGeral" >
						<VerticalLayout width="100%" spacing="true" align="TOP_LEFT" >
							<DBTable id="tbLancamentos"  type="number" showRowCount="true" width="100%" rows="14" selectable="false" exportXLS="true" editable="false" useGridComponent="true">
								<datasource>
									<sqlBuilderDataSource connection-key="vitruvio" language="JavaScript">
										<![CDATA[
											function buildSQL(params) {
												if(engine) {
												
											var sql = "";
											if (engine.getField('dataInicio').getValue() && engine.getField('dataFinal').getValue()) {
												var c = java.util.Calendar.getInstance();
												var formatter = new java.text.SimpleDateFormat("dd/MM/yyyy");
								           		c.setTime(engine.getField('dataInicio').getValue());
												var data = c.getTime();
												var dataInicio = formatter.format(data);
												var f = java.util.Calendar.getInstance();
												f.setTime(engine.getField('dataFinal').getValue());
												data = f.getTime();
												var dataFinal = formatter.format(data);
                                       var clientes = null;
                                       var cli = new java.util.ArrayList();
                                       if (engine.getField('clientes').getValue()) {
                                          clientes = engine.getField('clientes').getValue();
                                          
                                       } else {
                                          clientes = '[null]';
                                       }
                                       
                                       var frotaTerceiro = engine.getField('ftFrotaTerceiro').getValue();
                                       var caminhaoCarreta = engine.getField('ftCaminhaoCarreta').getValue();
                                       var placa = null;
                                       if (engine.getField('placa').getValue()) {
                                          placa = Number(engine.getField('placa').getValue());
                                       }
												sql = "select fnc_geralplaca_pivot2(to_date('"+dataInicio+"','dd/MM/yyyy'),to_date('"+dataFinal+"','dd/MM/yyyy')," + placa + ",'" + clientes + "','" + frotaTerceiro + "','" + caminhaoCarreta + "') as sql_return ";
                                    engine.debug(sql);
                                          
                                          var ds = vQueryService.executeQuery('vitruvio', sql);
														ds.next();
														return ds.getString('sql_return');
													} else {
														return "select 0 as chave, '01/01/1900' as dt, 0 as valor_frete";
													}	
													
												}else{
													return "select 0 as chave, '01/01/1900' as dt, 0 as valor_frete";
												}
											}
										]]>
									</sqlBuilderDataSource>
								</datasource>
								<key-field>CHAVE</key-field>
								<columns>
                           <column name="PLACA" caption="PLACA" align="CENTER"/>
                           <column name="QTD_FRETES" caption="QTD FRETES" align="CENTER"/>
									<column name="VALOR_FRETE" caption="VALOR DO FRETE (Líquido)" align="CENTER" format="#,##0.00" decimalSeparator="," groupingSeparator="."/>
									<dynamicColumn matchColumnTag="C_" matchColumnBy="STARTS_WITH" align="CENTER" />
                           <column name="VALOR_COMBUSTIVEL" caption="COMBUSTÍVEL" align="CENTER" format="#,##0.00" decimalSeparator="," groupingSeparator="."/>
									<column name="LIQUIDO" caption="LUCRO (Frete - Despesas)" align="CENTER" />
								</columns>
								<styleGenerator>
									<scriptGenerator language="JavaScript">
										<![CDATA[
											function getStyle(itemId, columnId, item) {
												if(item) {
													if (item.getItemProperty('CHAVE').getValue() == '-999999999999') {
														var coluna = columnId;
														if (columnId.substring(0,2) == 'C_') {
															var coluna = 'DINAMICA';
														}
														switch(coluna) {
															case 'VEICULO':
																return 'background-dark-gray';
															case 'VALOR_FRETE':
																 return 'background-light-green';
															case 'DINAMICA' :
																return 'background-light-red';
                                             case 'VALOR_COMBUSTIVEL' :
                                                return 'background-light-red';
															case 'LIQUIDO' :
																return 'background-light-blue';
														}
													}
											   }
		                           }
										]]>
									</scriptGenerator>
								</styleGenerator>
							</DBTable>
						</VerticalLayout>
					</Panel>	
	         	</VerticalLayout>
         	</VerticalLayout>
      	</components>

   	</form>
</panel-form>