<?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="dashboardDespesas" width="100%" backgroundColor="#ffffff">
		<name>Indicador Controle de Gastos</name>
		<description>Indicadores Controle de Gastos</description>

		<ServerSide>
			<DataSources>
            <ScriptDataSource id="sqlDespesaVeiculos" language="JavaScript" workOnline="true">
               <![CDATA[
                  function buildDataSource(params) {
                     var sql = "SELECT V.PLACA AS DESCRICAO, cast(sum(CDC.TOTAL_COMBUSTIVEL) as numeric(15,2)) AS VALOR ";
                     sql = sql + " FROM CONTROLE_DESPESAS_COMBUSTIVEIS CDC, VEICULO V  "; 
                     sql = sql + " WHERE CDC.CHAVE_VEICULO = V.CODIGO  ";
                     sql = sql + " AND CDC.DATA BETWEEN CAST(? AS DATE) AND CAST(? AS DATE)  ";
                     if (params[3] != 'A') {
                        sql = sql + " AND CDC.FROTA_TERCEIRO = ? ";
                     }
                     if (params[4] != 'A') {
                        sql = sql + " AND CDC.CAMINHAO_CARRETA = ? ";
                     }
                     sql = sql + " AND CDC.CHAVE_CLIENTE = ?  ";
                     sql = sql + " GROUP BY V.PLACA ";
                     sql = sql + " ORDER BY 2 DESC";
                  
                     var dataInicio = params[0];
                     var dataFinal = params[1];
                     var cliente = 0;
                     if(params){
                        cliente = params[2];
                     }
                     var frotaTerceiro = "";
                     if (params[3] != "A") {
                       frotaTerceiro = params[3];
                     }
                     var caminhaoCarreta = "";
                     if (params[4] != "A") {
                       caminhaoCarreta = params[4];
                     }
                     
                     var prm = new java.util.ArrayList();
                     prm.add(dataInicio);
                     prm.add(dataFinal);
                     if (params[3] != "A") {
                        prm.add(frotaTerceiro);
                     }
                     if (params[4] != "A") {
                        prm.add(caminhaoCarreta);
                     }
      			     prm.add(cliente);
                     return vQueryService.executeQuery('vitruvio', sql, prm);
                  }
               ]]>
            </ScriptDataSource>
			</DataSources>
		</ServerSide>
      
		<initScript language="JavaScript">
			<![CDATA[
            function atualizaValores(){
               console.log("Entrou Function");
               var idCodigo = engine.getField('idCodigo').getValue();
               var dataInicioDesp = engine.getField("idDataInicio").getValue();
               var dataFinalDesp = engine.getField("idDataFim").getValue();
               var frotaTerceiro = engine.getField("idFrotaTerceiro").getValue();
               var caminhaoCarreta = engine.getField("idCaminhaoCarreta").getValue();
               
               /*Despesa Combustível*/
               vQueryService.executeDataSource("sqlDespesaVeiculos", [dataInicioDesp, dataFinalDesp, idCodigo, frotaTerceiro, caminhaoCarreta]).then(dsFaturamento=>{
                  var texto = '<p style="text-align: center;"><span style=""><strong>Despesas com Veículos<span style=""></span></strong></span></p>';
                  texto += '<table border="0" width="90%"><tbody>';
                  var total = 0;
                  var contador = 0;
                  
                  while(dsFaturamento.next()){
                     var divisao = contador / 2;
                     /*console.log("divisao: "+divisao);
                     console.log("contador: "+contador);
                     console.log("divisao%2: "+divisao%2);
                     console.log("dsFaturamento: "+dsFaturamento);*/
                     
                     if(contador%2 == 0){
                        texto += '<tr style="background-color:#FFE17D">';
                     }else{
                        texto += '<tr>';
                     }
                     
                     contador += 1;
                     
                     texto += '<td width="65%">' + dsFaturamento.getString("DESCRICAO") + '</td>';
                     texto += '<td align="left">' + 'R$ ' + accounting.formatMoney(dsFaturamento.getNumber("VALOR"), "", 2, ".", ",") + '</td>';
                     texto += '</tr>';
                     total += dsFaturamento.getNumber("VALOR");
                     /*console.log("textovalor: "+texto);*/
                     console.log("total: "+total);
                  }
                  
                  /*TOTALIZADOR*/
                  texto += '<tr style="background-color:#0A0A0A">';
                  texto += '<td style="color:#FFFFFF" width="65%">TOTAIS</td>';
                  texto += '<td style="color:#FFFFFF" align="left">' + 'R$ ' + accounting.formatMoney(total, "", 2, ".", ",") + '</td>';
                  texto += '</tr>';
                  
                  texto += '</tbody></table>';
                  
                  console.log("textototal: "+texto);
                  console.log("Fim Function");
                  engine.getLabel('lblDespVeiculos').setValue(texto);
                  console.log("Atribui label Function");
               }).catch(error=>{
               });
            }
            
				function run() {
               var paramrs = engine.getGlobalVariable('params');
               engine.getField('idCodigo').setValue(paramrs.idCodigo);
               engine.getField('idNomeCliente').setValue(paramrs.idNomeCliente);
               engine.getField('idDataInicio').setValue(paramrs.idDataInicio);
               engine.getField('idDataFim').setValue(paramrs.idDataFim);
               engine.getField('idFrotaTerceiro').setValue(paramrs.idFrotaTerceiro);
               engine.getField('idCaminhaoCarreta').setValue(paramrs.idCaminhaoCarreta);
               
               engine.getWidgetController('btnApply').getButton().setIcon("APLICAR");
               
               engine.setGlobalVariable('atualizaValores',atualizaValores);
               atualizaValores();
				}
			]]>
		</initScript>
      
		<components>
			<VerticalLayout width="100%" margin="false" spacing="true">
            <HorizontalLayout spacing="true" width="80%" align="TOP_LEFT">
               <DateField id="idDataInicio" caption="Data Início Despesa" type="date" required="false" format="dd/MM/yyyy"/>
               <DateField id="idDataFim" caption="Data Final Despesa" type="date" required="false" format="dd/MM/yyyy"/>
				</HorizontalLayout>
            
            <HorizontalLayout spacing="true" width="80%" align="TOP_LEFT">
               <OptionGroup type="string" id="idFrotaTerceiro" caption="Tipo de frota" disposition="vertical" width="100%" >
                  <entry value="Ambos" key="A"/>
                  <entry value="Frota" key="F"/>
                  <entry value="Terceiro" key="T"/>
               </OptionGroup>
               
               <OptionGroup type="string" id="idCaminhaoCarreta" caption="Tipo de transporte" disposition="vertical" width="100%">
                  <entry value="Todos" key="A"/>
                  <entry value="Caminhão" key="C"/>
                  <entry value="Carreta" key="T"/>
                  <entry value="Outros" key="O"/>
               </OptionGroup>
            </HorizontalLayout>
            
            <HorizontalLayout spacing="true" width="80%" align="TOP_LEFT">
               <TextField type="number" visible="false" caption="Pedido" id="idCodigo" readOnly="true"></TextField>
               <TextField type="string" visible="true" caption="Cliente" id="idNomeCliente" readOnly="true"></TextField>
            </HorizontalLayout>
            
            <ButtonWidget id="btnApply" visible="true" caption="Filtrar" align="CENTER" size="TINY" expandRatio="1">
               <onClickScript language="JavaScript">
                  <![CDATA[
                     function run(){
                        var atualizaValores = engine.getGlobalVariable('atualizaValores');
                        if(atualizaValores){
                           atualizaValores();
                        }
                     }
                  ]]>
               </onClickScript>
            </ButtonWidget>
            
            <HorizontalLayout width="100%" margin="false" spacing="true" >
               <Label id="lblDespVeiculos" value="" visible="true" align="CENTER"/>
            </HorizontalLayout>
			</VerticalLayout>
		</components>
	</form>
</panel-form>