<?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);
				engine.getField('dataInicio').setValue(data);
				engine.getField('dataFinal').setValue(d);
				engine.getField('dataInicioDespesas').setValue(data);
				engine.getField('dataFinalDespesas').setValue(d);
				engine.getField('tbLancamentos').refresh();
				engine.getField('tbResultados').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" height="100%">
						<VerticalLayout width="100%" margin="true" spacing="true">
							<HorizontalLayout width="100%" spacing="true" height="100%">
						      <ImageWidget id="img1" height="75" width="441" align="TOP_LEFT">
						      		<image>
						      			<base64 extension="jpg">
						      				<![CDATA[
						      					,[encoded data, 38320 characters]
						      				]]>
						      			</base64>
						      		</image>
						      	</ImageWidget>
						      	<HorizontalLayout width="100%" expandRatio="1" spacing="true" align="BOTTOM_RIGHT">
						      		<Panel width="100%" expanRatio="0.5" caption="Período faturamento" align="TOP_RIGHT" margin="true" >
						      			<HorizontalLayout width="100%" spacing="true" >
									      	<DateField type="date" id="dataInicio" caption="Data inicial" width="100%" expandRatio="0.5" description="Data inicial da exibição" format="dd/MM/yyyy" />
											<DateField type="date" id="dataFinal" caption="Data final" width="100%" expandRatio="0.5" description="Data final da exibição" format="dd/MM/yyyy" />
										</HorizontalLayout>
									</Panel>	
									<Panel width="100%" expanRatio="0.5" caption="Período despesas" align="TOP_RIGHT" margin="true" >
										<HorizontalLayout width="100%" spacing="true" >
									      	<DateField type="date" id="dataInicioDespesas" caption="Data inicial" width="100%" expandRatio="0.5" description="Data inicial da exibição" format="dd/MM/yyyy" />
											<DateField type="date" id="dataFinalDespesas" caption="Data final" width="100%" expandRatio="0.5" description="Data final da exibição" format="dd/MM/yyyy" />
										</HorizontalLayout>
									</Panel>
									<ButtonWidget id="btnFiltrar" caption="Filtrar" description="Aplica filtro de data" width="100" >
										<onClickScript language="JavaScript">
											<![CDATA[
												function run() {
													engine.getField('tbLancamentos').refresh();
													engine.getField('tbResultados').refresh();
												}
											]]>
										</onClickScript>
									</ButtonWidget>
								</HorizontalLayout>
						    </HorizontalLayout>
						</VerticalLayout>
					</Panel>
					<Panel width="100%" margin="true" >
						<VerticalLayout width="100%" spacing="true" align="TOP_LEFT" >
							<DBTable id="tbLancamentos"  type="number" width="100%" rows="5" selectable="false" compact="true" exportXLS="true" editable="false" >
								<datasource>
									<sqlBuilderDataSource connection-key="vitruvio" language="JavaScript">
										<![CDATA[
											function buildSQL(params) {
												if(engine) {
												
													var sql = "";
													if (engine.getField('dataInicio').getValue() && engine.getField('dataFinal').getValue() && engine.getField('dataInicioDespesas').getValue() && engine.getField('dataFinalDespesas').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 cDespesas = java.util.Calendar.getInstance();
														cDespesas.setTime(engine.getField('dataInicioDespesas').getValue());
														data = cDespesas.getTime();
														var dataInicioDespesas = formatter.format(data); 
														
														var cDespesasF = java.util.Calendar.getInstance();
														cDespesasF.setTime(engine.getField('dataFinalDespesas').getValue());
														data = cDespesasF.getTime();
														var dataFinalDespesas = formatter.format(data); 
														
														sql = "Select s.nome, " +
																"case s.faturamento when 0 then 'R$ 0,00' else 'R$ ' || replace(to_char(s.faturamento,'FM999999999.00'),'.',',') end faturado, " +
																"case (s.despesa_combustivel + s.despesa_operacional) when 0 then 'R$ 0,00' else 'R$ ' || replace(to_char((s.despesa_combustivel + s.despesa_operacional),'FM999999999.00'),'.',',') end despesa, " +
																"case (s.faturamento - (s.despesa_combustivel + s.despesa_operacional)) when 0 then 'R$ 0,00' else 'R$ ' || replace(to_char(s.faturamento - (s.despesa_combustivel + s.despesa_operacional), 'FM999999999.00'),'.',',') end  liquido, " +
																"	case s.faturamento when 0 then 'R$ 0,00' else 'R$ ' || replace(to_char(((s.faturamento - (s.despesa_combustivel + s.despesa_operacional))/s.faturamento * 100),'FM999999999.00'),'.',',') end perc_lucro " +
																"     from (Select o.codigo, o.nome,  " +
																"	(Select coalesce(sum(crf.valor_liquido),0) from controle_receitas_fretes crf where crf.chave_cliente = o.codigo and crf.data between to_date('"+dataInicio+"','dd/MM/yyyy') and to_date('"+dataFinal+"','dd/MM/yyyy')) faturamento, " +
																"    (Select coalesce(sum(cdb.total_combustivel),0) from controle_despesas_combustiveis cdb where cdb.chave_cliente = o.codigo and cdb.data between to_date('"+dataInicioDespesas+"','dd/MM/yyyy') and to_date('"+dataFinalDespesas+"','dd/MM/yyyy')) despesa_combustivel, " + 
																"    (Select coalesce(sum(cdo.valor),0) from controle_despesas_operacionais cdo where cdo.chave_cliente = o.codigo and cdo.data between to_date('"+dataInicioDespesas+"','dd/MM/yyyy') and to_date('"+dataFinalDespesas+"','dd/MM/yyyy')) despesa_operacional " +
																"from clientes o) s " +
																"union all " +
																" Select 'TOTAL' nome, " +
																"case s.faturamento when 0 then 'R$ 0,00' else 'R$ ' || replace(to_char(s.faturamento,'FM999999999.00'),'.',',') end faturado, " +
																"case (s.despesa_combustivel + s.despesa_operacional) when 0 then 'R$ 0,00' else 'R$ ' || replace(to_char((s.despesa_combustivel + s.despesa_operacional),'FM999999999.00'),'.',',') end despesa, " +
																"case (s.faturamento - (s.despesa_combustivel + s.despesa_operacional)) when 0 then 'R$ 0,00' else 'R$ ' || replace(to_char(s.faturamento - (s.despesa_combustivel + s.despesa_operacional), 'FM999999999.00'),'.',',') end  liquido, " +
																"	case s.faturamento when 0 then 'R$ 0,00' else 'R$ ' || replace(to_char(((s.faturamento - (s.despesa_combustivel + s.despesa_operacional))/s.faturamento * 100),'FM999999999.00'),'.',',') end perc_lucro " +
																"     from (Select " +
																"	(Select coalesce(sum(crf.valor_liquido),0) from controle_receitas_fretes crf where crf.data between to_date('"+dataInicio+"','dd/MM/yyyy') and to_date('"+dataFinal+"','dd/MM/yyyy')) faturamento, " +
																"    (Select coalesce(sum(cdb.total_combustivel),0) from controle_despesas_combustiveis cdb where cdb.data between to_date('"+dataInicioDespesas+"','dd/MM/yyyy') and to_date('"+dataFinalDespesas+"','dd/MM/yyyy')) despesa_combustivel, " + 
																"    (Select coalesce(sum(cdo.valor),0) from controle_despesas_operacionais cdo where cdo.data between to_date('"+dataInicioDespesas+"','dd/MM/yyyy') and to_date('"+dataFinalDespesas+"','dd/MM/yyyy')) despesa_operacional) s";
														

														return sql;
													} else {
														return "select '' nome, '' faturado, '' despesa, '' liquido, '' perc_lucro";
													}	
													
												}else{
													return "select '' nome, '' faturado, '' despesa, '' liquido, '' perc_lucro";
												}
											}
										]]>
									</sqlBuilderDataSource>
								</datasource>
								<key-field>NOME</key-field>
								<columns>
									<column name="NOME" caption="Cliente" align="RIGHT" expand-ratio="0.3"/>
									<column name="FATURADO" caption="Faturamento" align="RIGHT" expand-ratio="0.1"/>
									<column name="DESPESA" caption="Despesas" align="RIGHT" expand-ratio="0.1"/>
									<column name="LIQUIDO" caption="Lucro Líquido" align="RIGHT" expand-ratio="0.1"/>
									<column name="PERC_LUCRO" caption="% Lucro" align="RIGHT" expand-ratio="0.1"/>
								</columns>
								<styleGenerator>
									<scriptGenerator language="JavaScript">
										<![CDATA[
											function getStyle(itemId, columnId, item) {
												if(item) {
													if (item.getItemProperty('NOME').getValue() == 'TOTAL') {
														return 'background-dark-gray';
													}
												}
											}
										]]>
									</scriptGenerator>
								</styleGenerator>
							</DBTable>
						</VerticalLayout>
					</Panel>
					<Panel width="100%" margin="true" expandRatio="0.8" >
						<VerticalLayout width="100%" spacing="true" align="TOP_LEFT" >
							<DBTable id="tbResultados"  type="string" expandRatio="1" compact="true" width="100%" rows="5" selectable="false" editable="false" >
								<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 cDespesas = java.util.Calendar.getInstance();
														cDespesas.setTime(engine.getField('dataInicioDespesas').getValue());
														data = cDespesas.getTime();
														var dataInicioDespesas = formatter.format(data);
														
														var fDespesas = java.util.Calendar.getInstance();
														fDespesas.setTime(engine.getField('dataFinalDespesas').getValue());
														data = fDespesas.getTime();
														var dataFinalDespesas = formatter.format(data);
														
														sql = "select fnc_dre_pivot(to_date('" + dataInicio + "','dd/MM/yyyy'),to_date('" + dataFinal + "','dd/MM/yyyy'),to_date('" + dataInicioDespesas + "','dd/MM/yyyy'),to_date('" + dataFinalDespesas + "','dd/MM/yyyy')) as sql_return";
														var ds = vQueryService.executeQuery('vitruvio', sql);
														ds.next();

														return ds.getString('sql_return');
														
													} else {
														return "select ' ' indicador, 0 total";
													}	
													
												} else {
													return "select ' ' indicador, 0 total";
												}
											}
										]]>
									</sqlBuilderDataSource>
								</datasource>
								<key-field>INDICADOR</key-field>
								<columns>
									<column name="INDICADOR" caption="Indicador" align="LEFT" expand-ratio="0.2" />
									<column name="TOTAL" caption="Total (Faturamento - Despesas)" align="RIGHT" expand-ratio="0.1" />
									<dynamicColumn matchColumnTag="C_" matchColumnBy="STARTS_WITH" align="RIGHT" expand-ratio="0.1" />
								</columns>
								<styleGenerator>
									<scriptGenerator language="JavaScript">
										<![CDATA[
											function getStyle(itemId, columnId, item) {
												if(item) {
													if (item.getItemProperty('INDICADOR').getValue() == 'FATURAMENTO BRUTO') {
														return 'background-light-green';
													}
													if (item.getItemProperty('INDICADOR').getValue() == 'DESPESAS TOTAIS') {
														return 'background-light-red';
													}
													if (item.getItemProperty('INDICADOR').getValue() == 'DESPESAS DIVERSAS') {
														return 'background-light-red';
													}
													if (item.getItemProperty('INDICADOR').getValue() == 'DESPESAS PARTICULARES') {
														return 'background-light-red';
													}
													if (item.getItemProperty('INDICADOR').getValue() == 'TOTAL') {
														return 'background-light-blue';
													}
												}
											}
										]]>
									</scriptGenerator>
								</styleGenerator>
							</DBTable>
						</VerticalLayout>
					</Panel>	
	         	</VerticalLayout>
         	</VerticalLayout>
      	</components>

   	</form>
</panel-form>