<?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="sqlFaturamentoDespesasTotal" language="JavaScript" workOnline="true">
               <![CDATA[
                  function buildDataSource(params) {
                     var sql =   "SELECT 0 AS CHAVE, 'Faturamento' AS DESC, CAST(COALESCE(SUM(CRF.VALOR_LIQUIDO),0) AS NUMERIC(15,2)) AS VALOR                    ";
                     sql = sql + "  FROM CONTROLE_RECEITAS_FRETES CRF                                                                     ";
                     sql = sql + " WHERE CRF.DATA BETWEEN CAST(? AS DATE) AND CAST(? AS DATE)                                             ";
                     if (params[4] != 'A') {
                       sql = sql + " AND CRF.FROTA_TERCEIRO = ? ";
                     }
                     if (params[5] != 'A') {
                       sql = sql + " AND CRF.CAMINHAO_CARRETA = ? ";
                     }
                     
                     sql = sql + " UNION ALL                                                                                              ";
                     
                     sql = sql + "SELECT 1 AS CHAVE, 'Despesas Operacionais' AS DESC, CAST(COALESCE(SUM(CDO.VALOR),0) AS NUMERIC(15,2)) AS VALOR                  ";
                     sql = sql + "  FROM CONTROLE_DESPESAS_OPERACIONAIS CDO                                                               ";
                     sql = sql + " WHERE CDO.DATA BETWEEN CAST(? AS DATE) AND CAST(? AS DATE)                                             ";
                     if (params[4] != 'A') {
                       sql = sql + " AND CDO.FROTA_TERCEIRO = ? ";
                     }
                     if (params[5] != 'A') {
                       sql = sql + " AND CDO.CAMINHAO_CARRETA = ? ";
                     }
                     
                     sql = sql + " UNION ALL                                                                                              ";
                     
                     sql = sql + "SELECT 2 AS CHAVE, 'Despesas Particulares' AS DESC, CAST(COALESCE(SUM(CDP.VALOR),0) AS NUMERIC(15,2)) AS VALOR                  ";
                     sql = sql + "  FROM CONTROLE_DESPESAS_PESSOAIS CDP                                                                   ";
                     sql = sql + " WHERE CDP.DATA BETWEEN CAST(? AS DATE) AND CAST(? AS DATE)                                             ";
                     sql = sql + " UNION ALL                                                                                              ";
                     
                     sql = sql + "SELECT 3 AS CHAVE, 'Despesas com Combustíveis' AS DESC, CAST(COALESCE(SUM(CDC.TOTAL_COMBUSTIVEL),0) AS NUMERIC(15,2)) AS VALOR  ";
                     sql = sql + "  FROM CONTROLE_DESPESAS_COMBUSTIVEIS CDC                                                               ";
                     sql = sql + " WHERE CDC.DATA BETWEEN CAST(? AS DATE) AND CAST(? AS DATE)                                             ";
                     if (params[4] != 'A') {
                        sql = sql + " AND CDC.FROTA_TERCEIRO = ? ";
                      }
                      if (params[5] != 'A') {
                        sql = sql + " AND CDC.CAMINHAO_CARRETA = ? ";
                      }
                      
                      /* */
                     
                     var fmt = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
                     var dataInicioFat = new java.sql.Date(fmt.parse(params[0]).getTime());
                     var dataFinalFat = new java.sql.Date(fmt.parse(params[1]).getTime());
                     var dataInicioDesp = new java.sql.Date(fmt.parse(params[2]).getTime());
                     var dataFinalDesp = new java.sql.Date(fmt.parse(params[3]).getTime());
                     
                     var frotaTerceiro = "";
                     if (params[4] != "A") {
                        frotaTerceiro = params[4];
                     }
                     
                     var caminhaoCarreta = "";
                     if (params[5] != "A") {
                        caminhaoCarreta = params[5];
                     }
                     
                    var frotaTerceiro2 = "";
                    if (params[4] != "A") {
                        frotaTerceiro2 = params[4];
                     }
                     
                     var caminhaoCarreta2 = "";
                     if (params[5] != "A") {
                        caminhaoCarreta2 = params[5];
                     }
                     
                     var frotaTerceiro3 = "";
                     if (params[4] != "A") {
                        frotaTerceiro2 = params[4];
                     }
                     
                     var caminhaoCarreta3 = "";
                     if (params[5] != "A") {
                        caminhaoCarreta2 = params[5];
                     }
                     
                     /* */
                     
                     var prm = new java.util.ArrayList();
                     prm.add(dataInicioFat);
                     prm.add(dataFinalFat);
                     if (params[4] != "A") {
                       prm.add(frotaTerceiro);
                     }
                      if (params[5] != "A") {
                      prm.add(caminhaoCarreta);
                     }
                     prm.add(dataInicioDesp);
                     prm.add(dataFinalDesp);
                     if (params[4] != "A") {
                       prm.add(frotaTerceiro2);
                     }
                       if (params[5] != "A") {
                       prm.add(caminhaoCarreta2);
                     }
                     prm.add(dataInicioDesp);
                     prm.add(dataFinalDesp);
                     prm.add(dataInicioDesp);
                     prm.add(dataFinalDesp);
                     if (params[4] != "A") {
                       prm.add(frotaTerceiro3);
                     }
                     if (params[5] != "A") {
                     prm.add(caminhaoCarreta3);
                     }
                     
                     return vQueryService.executeQuery('vitruvio', sql, prm);
                  }
               ]]>
            </ScriptDataSource>
            
            <ScriptDataSource id="sqlDespesaOperacional" language="JavaScript" workOnline="true">
               <![CDATA[
                  function buildDataSource(params) {
                     var sql =   "SELECT CLI.NOME AS DESCRICAO ";
                     sql = sql + "      ,CAST(SUM(CDO.VALOR) AS NUMERIC(15,2)) AS VALOR ";
                     sql = sql + "  FROM CONTROLE_DESPESAS_OPERACIONAIS CDO ";
                     sql = sql + "      ,CLIENTES CLI ";
                     sql = sql + " WHERE CDO.CHAVE_CLIENTE = CLI.CODIGO ";
                     sql = sql + "   AND CDO.DATA BETWEEN CAST(? AS DATE) AND CAST(? AS DATE) ";
                     if (params[2] != 'A') {
                       sql = sql + " AND CDO.FROTA_TERCEIRO = ? ";
                     }
                     if (params[3] != 'A') {
                       sql = sql + " AND CDO.CAMINHAO_CARRETA = ? ";
                     }
                     sql = sql + " GROUP BY CLI.NOME ";
                     sql = sql + " ORDER BY 2 DESC ";
                     
                     var fmt = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
                     var dataInicio = new java.sql.Date(fmt.parse(params[0]).getTime());
                     var dataFinal = new java.sql.Date(fmt.parse(params[1]).getTime());
                     var frotaTerceiro = "";
                     if (params[2] != "A") {
                     frotaTerceiro = params[2];
                     }
                     var caminhaoCarreta = "";
                     if (params[3] != "A") {
                     caminhaoCarreta = params[3];
                     }
                     
                     var prm = new java.util.ArrayList();
                     prm.add(dataInicio);
                     prm.add(dataFinal);
                     if (params[2] != "A") {
                     prm.add(frotaTerceiro);
                     }
                     if (params[3] != "A") {
                     prm.add(caminhaoCarreta);
                     }
                     
                     return vQueryService.executeQuery('vitruvio', sql, prm);
                  }
               ]]>
            </ScriptDataSource>
            
            <ScriptDataSource id="sqlDespesaParticular" language="JavaScript" workOnline="true">
               <![CDATA[
                  function buildDataSource(params) {
                     var sql =   "SELECT S.NOME AS DESCRICAO ";
                     sql = sql + "      ,CAST(SUM(CDP.VALOR) AS NUMERIC(15,2)) AS VALOR ";
                     sql = sql + "  FROM CONTROLE_DESPESAS_PESSOAIS CDP ";
                     sql = sql + "      ,SOCIOS S ";
                     sql = sql + " WHERE CDP.CHAVE_RESPONSAVEL = S.CODIGO ";
                     sql = sql + "   AND CDP.DATA BETWEEN CAST(? AS DATE) AND CAST(? AS DATE) ";
                     sql = sql + " GROUP BY S.NOME ";
                     sql = sql + " ORDER BY 2 DESC ";
                     
                     var fmt = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
                     var dataInicio = new java.sql.Date(fmt.parse(params[0]).getTime());
                     var dataFinal = new java.sql.Date(fmt.parse(params[1]).getTime());
                     var prm = new java.util.ArrayList();
                     prm.add(dataInicio);
                     prm.add(dataFinal);
                     return vQueryService.executeQuery('vitruvio', sql, prm);
                  }
               ]]>
            </ScriptDataSource>
            
            <ScriptDataSource id="sqlDespesaCombustivel" language="JavaScript" workOnline="true">
               <![CDATA[
                  function buildDataSource(params) {
                     var sql =   "SELECT C.CODIGO, C.NOME AS DESCRICAO ";
                     sql = sql + "      ,CAST(SUM(CDC.TOTAL_COMBUSTIVEL) AS NUMERIC(15,2)) AS VALOR ";
                     sql = sql + "  FROM CONTROLE_DESPESAS_COMBUSTIVEIS CDC ";
                     sql = sql + "      ,CLIENTES C ";
                     sql = sql + " WHERE CDC.CHAVE_CLIENTE = C.CODIGO ";
                     sql = sql + "   AND CDC.DATA BETWEEN CAST(? AS DATE) AND CAST(? AS DATE) ";
                     if (params[2] != 'A') {
                       sql = sql + " AND CDC.FROTA_TERCEIRO = ? ";
                     }
                     if (params[3] != 'A') {
                       sql = sql + " AND CDC.CAMINHAO_CARRETA = ? ";
                     }
                     sql = sql + " GROUP BY C.CODIGO, C.NOME ";
                     sql = sql + " ORDER BY 3 DESC ";
                     
                     var fmt = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
                     var dataInicio = new java.sql.Date(fmt.parse(params[0]).getTime());
                     var dataFinal = new java.sql.Date(fmt.parse(params[1]).getTime());
                     var frotaTerceiro = "";
                      if (params[2] != "A") {
                        frotaTerceiro = params[2];
                      }
                      var caminhaoCarreta = "";
                      if (params[3] != "A") {
                        caminhaoCarreta = params[3];
                      }
                     
                     var prm = new java.util.ArrayList();
                     prm.add(dataInicio);
                     prm.add(dataFinal);
                     if (params[2] != "A") {
                        prm.add(frotaTerceiro);
                     }
                     if (params[3] != "A") {
                        prm.add(caminhaoCarreta);
                     }
                     return vQueryService.executeQuery('vitruvio', sql, prm);
                  }
               ]]>
            </ScriptDataSource>
            
            <ScriptDataSource id="sqlFaturamento" language="JavaScript" workOnline="true">
               <![CDATA[
                  function buildDataSource(params) {
                     var sql =   "SELECT C.NOME AS DESCRICAO ";
                     sql = sql + "      ,CAST(SUM(CDF.VALOR_LIQUIDO) AS NUMERIC(15,2)) AS VALOR ";
                     sql = sql + "  FROM CONTROLE_RECEITAS_FRETES CDF ";
                     sql = sql + "      ,CLIENTES C ";
                     sql = sql + " WHERE CDF.CHAVE_CLIENTE = C.CODIGO ";
                     sql = sql + "   AND CDF.DATA BETWEEN CAST(? AS DATE) AND CAST(? AS DATE) ";
                     if (params[2] != 'A') {
                        sql = sql + " AND CDF.FROTA_TERCEIRO = ? ";
                      }
                      if (params[3] != 'A') {
                        sql = sql + " AND CDF.CAMINHAO_CARRETA = ? ";
                      }
                     sql = sql + " GROUP BY C.NOME ";
                     sql = sql + " ORDER BY 2 DESC ";
                     
                     var fmt = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
                     var dataInicio = new java.sql.Date(fmt.parse(params[0]).getTime());
                     var dataFinal = new java.sql.Date(fmt.parse(params[1]).getTime());
                     var frotaTerceiro = "";
                     if (params[2] != "A") {
                        frotaTerceiro = params[2];
                     }
                     var caminhaoCarreta = "";
                     if (params[3] != "A") {
                        caminhaoCarreta = params[3];
                     }
                     
                     var prm = new java.util.ArrayList();
                     prm.add(dataInicio);
                     prm.add(dataFinal);
                     if (params[2] != "A") {
                        prm.add(frotaTerceiro);
                     }
                     if (params[3] != "A") {
                        prm.add(caminhaoCarreta);
                     }
                     return vQueryService.executeQuery('vitruvio', sql, prm);
                  }
               ]]>
            </ScriptDataSource>
            
            <ScriptDataSource id="sqlDespesaVeiculos" language="JavaScript" workOnline="true">
               <![CDATA[
                  function buildDataSource(params) {
                     var sql =   "SELECT 'PLACA: '||V.PLACA AS DESCRICAO ";
                     sql = sql + "      ,CAST(SUM(CDC.TOTAL_COMBUSTIVEL) AS NUMERIC(15,2)) + CAST(SUM(CDO.VALOR) AS NUMERIC(15,2)) AS VALOR ";
                     sql = sql + "  FROM CONTROLE_DESPESAS_COMBUSTIVEIS CDC ";
					      sql = sql + "      ,CONTROLE_DESPESAS_OPERACIONAIS CDO ";
                     sql = sql + "      ,VEICULO V ";
                     sql = sql + " WHERE CDC.CHAVE_VEICULO = V.CODIGO ";
					      sql = sql + "   AND CDO.CHAVE_VEICULO = V.CODIGO ";
                     sql = sql + "   AND CDC.DATA BETWEEN CAST(? AS DATE) AND CAST(? AS DATE) ";
                     if (params[2] != 'A') {
                        sql = sql + " AND CDC.FROTA_TERCEIRO = ?";
                     }
                     if (params[3] != 'A') {
                        sql = sql + " AND CDC.CAMINHAO_CARRETA = ?";
                     }
					      sql = sql + "   AND CDO.DATA BETWEEN CAST(? AS DATE) AND CAST(? AS DATE) ";
                     if (params[2] != 'A') {
                        sql = sql + " AND CDO.FROTA_TERCEIRO = ? ";
                     }
                     if (params[3] != 'A') {
                        sql = sql + " AND CDO.CAMINHAO_CARRETA = ? ";
                     }
                     sql = sql + " GROUP BY V.MARCA, V.PLACA ";
                     sql = sql + " ORDER BY 2 DESC ";
                     
                     var fmt = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
                     var dataInicio = new java.sql.Date(fmt.parse(params[0]).getTime());
                     var dataFinal = new java.sql.Date(fmt.parse(params[1]).getTime());
                     var frotaTerceiro = "";
                      if (params[2] != "A") {
                        frotaTerceiro = params[2];
                      }
                      var caminhaoCarreta = "";
                      if (params[3] != "A") {
                        caminhaoCarreta = params[3];
                      }
                      var frotaTerceiro2 = "";
                      if (params[2] != "A") {
                        frotaTerceiro2 = params[2];
                      }
                      var caminhaoCarreta2 = "";
                      if (params[3] != "A") {
                        caminhaoCarreta2 = params[3];
                      }
                     
                     var prm = new java.util.ArrayList();
                     prm.add(dataInicio);
                     prm.add(dataFinal);
                     if (params[2] != "A") {
                        prm.add(frotaTerceiro);
                      }
                      if (params[3] != "A") {
                        prm.add(caminhaoCarreta)
                      }
					      prm.add(dataInicio);
                     prm.add(dataFinal);
                     if (params[2] != "A") {
                        prm.add(frotaTerceiro2);
                      }
                      if (params[3] != "A") {
                        prm.add(caminhaoCarreta2);
                      }
                     
                     return vQueryService.executeQuery('vitruvio', sql, prm);
                  }
               ]]>
            </ScriptDataSource>
            
            <ScriptDataSource id="sqlDespesaVeiculosBarra" language="JavaScript" workOnline="true">
               <![CDATA[
                  function buildDataSource(params) {
                     var sql =   "SELECT * FROM (SELECT * ";
                     sql = sql + "  FROM (SELECT V.PLACA ";
                     sql = sql + "              ,CAST(COALESCE((SELECT SUM(CDF.VALOR_LIQUIDO) ";
                     sql = sql + "                  FROM CONTROLE_RECEITAS_FRETES CDF ";
                     sql = sql + "                 WHERE CDF.CHAVE_VEICULO = V.CODIGO ";
                     sql = sql + "                   AND CDF.DATA BETWEEN CAST(? AS DATE) AND CAST(? AS DATE) ";
                     if (params[4] != 'A') {
                        sql = sql + " AND CDF.FROTA_TERCEIRO = ? ";
                      }
                      if (params[5] != 'A') {
                        sql = sql + " AND CDF.CAMINHAO_CARRETA = ? ";
                      }
                     sql = sql + " ),0) AS NUMERIC(15, 2)) AS FATURAMENTO ";
                     
                     sql = sql + "              ,CAST(COALESCE((SELECT SUM(CDC.TOTAL_COMBUSTIVEL)";
                     sql = sql + "                  FROM CONTROLE_DESPESAS_COMBUSTIVEIS CDC ";
                     sql = sql + "                 WHERE CDC.CHAVE_VEICULO = V.CODIGO ";
                     sql = sql + "                   AND CDC.DATA BETWEEN CAST(? AS DATE) AND CAST(? AS DATE) ";
                     if (params[4] != 'A') {
                        sql = sql + " AND CDC.FROTA_TERCEIRO = ? ";
                      }
                      if (params[5] != 'A') {
                        sql = sql + " AND CDC.CAMINHAO_CARRETA = ? ";
                      }
                     sql = sql + " ),0)";
                     
                     
					      sql = sql + "				+ COALESCE((SELECT SUM(CDO.VALOR)";
                     sql = sql + "                  FROM CONTROLE_DESPESAS_OPERACIONAIS CDO ";
                     sql = sql + "                 WHERE CDO.CHAVE_VEICULO = V.CODIGO ";
                     sql = sql + "                   AND CDO.DATA BETWEEN CAST(? AS DATE) AND CAST(? AS DATE) ";
                     if (params[4] != 'A') {
                        sql = sql + " AND CDO.FROTA_TERCEIRO = ? ";
                      }
                      if (params[5] != 'A') {
                        sql = sql + " AND CDO.CAMINHAO_CARRETA = ? ";
                      }
                     sql = sql + " ),0) AS NUMERIC(15, 2)) AS DESPESA ";
                     
                     
                     sql = sql + "          FROM VEICULO V) V ";
                     sql = sql + " WHERE ((V.FATURAMENTO > 0) OR (V.DESPESA > 0)) ORDER BY 2 DESC) A ORDER BY 2 ASC";
                     
                     var fmt = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
                     var dataInicioFat = new java.sql.Date(fmt.parse(params[0]).getTime());
                     var dataFinalFat = new java.sql.Date(fmt.parse(params[1]).getTime());
                     var dataInicioDesp = new java.sql.Date(fmt.parse(params[2]).getTime());
                     var dataFinalDesp = new java.sql.Date(fmt.parse(params[3]).getTime());
                     var frotaTerceiro = "";
                      if (params[4] != "A") {
                        frotaTerceiro = params[4];
                      }
                      var caminhaoCarreta = "";
                      if (params[5] != "A") {
                        caminhaoCarreta = params[5];
                      }
                      var frotaTerceiro2 = "";
                      if (params[4] != "A") {
                        frotaTerceiro2 = params[4];
                      }
                      var caminhaoCarreta2 = "";
                      if (params[5] != "A") {
                        caminhaoCarreta2 = params[5];
                      }
                      var frotaTerceiro3 = "";
                      if (params[4] != "A") {
                        frotaTerceiro3 = params[4];
                      }
                      var caminhaoCarreta3 = "";
                      if (params[5] != "A") {
                        caminhaoCarreta3 = params[5];
                      }
                     
                     var prm = new java.util.ArrayList();
                     prm.add(dataInicioFat);
                     prm.add(dataFinalFat);
                     if (params[4] != "A") {
                        prm.add(frotaTerceiro);
                      }
                      if (params[5] != "A") {
                         prm.add(caminhaoCarreta);
                      }
                     
                     prm.add(dataInicioDesp);
                     prm.add(dataFinalDesp);
                     if (params[4] != "A") {
                         prm.add(frotaTerceiro2);
                      }
                      if (params[5] != "A") {
                         prm.add(caminhaoCarreta2);
                      }
                     
      				   prm.add(dataInicioDesp);
      				   prm.add(dataFinalDesp);
                     if (params[4] != "A") {
                         prm.add(frotaTerceiro3);
                      }
                      if (params[5] != "A") {
                        prm.add(caminhaoCarreta3);
                      }
                     
                     return vQueryService.executeQuery('vitruvio', sql, prm);
                  }
               ]]>
            </ScriptDataSource>
			</DataSources>
		</ServerSide>
      
		<initScript language="JavaScript">
			<![CDATA[
				function run() {
               engine.getComponent('scpFaturamentoCliente').setVisible(false);
               /*engine.getComponent('scpFaturamentoPlaca').setVisible(false);*/
               
               engine.getField('frotaTerceiro').setValue("A");
               engine.getField('caminhaoCarreta').setValue("A");
				}
			]]>
		</initScript>
      
		<components>
			<VerticalLayout width="100%" margin="false" spacing="true">
            <HorizontalLayout spacing="true" width="80%" align="TOP_LEFT">
               <DateField id="dataInicioFat" caption="Início faturamento" type="date" required="false" format="dd/MM/yyyy"/>
               <DateField id="dataFinalFat" caption="Final faturamento" type="date" required="false" format="dd/MM/yyyy"/>
				</HorizontalLayout>
            
            <HorizontalLayout spacing="true" width="80%" align="TOP_LEFT">
               <DateField id="dataInicioDesp" caption="Início despesa" type="date" required="false" format="dd/MM/yyyy"/>
               <DateField id="dataFinalDesp" caption="Final despesa" type="date" required="false" format="dd/MM/yyyy"/>
				</HorizontalLayout>
            
            <HorizontalLayout spacing="true" width="80%" align="TOP_LEFT">
               <OptionGroup type="string" id="frotaTerceiro" 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="caminhaoCarreta" 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>
            
            <TabLayout id="tabLayout" width="100%" framed="true">
					<!-- Faturamento Geral -->
					<Tab id="faturamento_despesas" caption="Gráfico Faturamento x Despesas">
                  <ScriptWidget id="scpFaturamentoGeral">
							<factory>
								<LayoutFactory type="VerticalLayout" width="100%" />
							</factory>
							<InitScript language="JavaScript">
								<![CDATA[
                     			function chartFaturamentoDespesas(periodo, callback) {
										var arrayLegenda = [];
										var arrayDados = [];
										var vendaLoja = 0;
                              
										vQueryService.executeDataSource("sqlFaturamentoDespesasTotal", periodo).then(dsFaturamento=>{
											while (dsFaturamento.next()) {
												vendaLoja = (dsFaturamento.getNumber("VALOR"));
												
												var legenda = "" + dsFaturamento.getString("DESC") + ' - ' + accounting.formatMoney(vendaLoja, "", 2, ".", ",");
												arrayLegenda.push(legenda);
												arrayDados.push({
													value: vendaLoja,
													name: legenda
													}
												);
											}									
										    var json = chartAPI.pie({
										        legend: {
										        	orient: 'horizontal',
										        	data: arrayLegenda
										        },
										        data: arrayDados
										   	}, "highcharts");										    
											callback(json, null);
										}).catch(error=>{
											callback(null, error);
										});
									}
                        
									function init(base) {
                              var dataInicioFat = engine.getField("dataInicioFat").getValue();
										var dataFinalFat = engine.getField("dataFinalFat").getValue();
                              var dataInicioDesp = engine.getField("dataInicioDesp").getValue();
										var dataFinalDesp = engine.getField("dataFinalDesp").getValue();
                              var frotaTerceiro = engine.getField("frotaTerceiro").getValue();
                              var caminhaoCarreta = engine.getField("caminhaoCarreta").getValue();
                              
                              chartFaturamentoDespesas([dataInicioFat, dataFinalFat, dataInicioDesp, dataFinalDesp, frotaTerceiro, caminhaoCarreta], function(chart,error){
                                 if(!error){
                                    chart.setWidth("100%");
                                    chart.setHeight("610px");
                                    chart.setCaption("Totais");
                                    chart.id = "chartKpiOrcadoRealizado"+new Date().getTime();
                                    if(base.components.length == 0){
                                       base.addComponent(chart);
                                    }else{
                                       base.components[0] = chart;
                                    }
                                 }
                              });
									}
								]]>
							</InitScript>
						</ScriptWidget>
					</Tab>
               
               <!-- Faturamento Geral -->
					<Tab id="faturamento_despesas" caption="Gráfico por placas">
                  <ScriptWidget id="scpFaturamentoGeral">
							<factory>
								<LayoutFactory type="VerticalLayout" width="100%" height="5000px" />
							</factory>
							<InitScript language="JavaScript">
								<![CDATA[
                           function chartBarraPlaca(periodo, callback) {
                              var arrayLegenda = ['Faturamento', 'Despesas'];
                              var arrayLabel = [];
                              var arrayFaturamento = [];
                              var arrayDepesas = [];
                              
                              var faturamento = 0;
                              var despesas = 0;
                              
                              vQueryService.executeDataSource("sqlDespesaVeiculosBarra", periodo).then(dsFaturamento=>{
                                 while (dsFaturamento.next()) {
                                    faturamento = dsFaturamento.getNumber("FATURAMENTO");
                                    despesas = dsFaturamento.getNumber("DESPESA");
                                    
                                    var label = dsFaturamento.getString("PLACA");
                                    arrayLabel.push(label);
                                    arrayFaturamento.push(faturamento);
                                    arrayDepesas.push(despesas);
                                 }
                                 var json = chartAPI.bar({
                                    orientation: 'horizontal',
                                    color: ['#228B22', '#FF0000'],
                                    legend: arrayLegenda,
                                    labels: arrayLabel,
                                    data: [
                                       { name: 'Faturamento', data: arrayFaturamento },
                                       { name: 'Despesas', data: arrayDepesas }
                                    ]
                                 });                                                           
                                 callback(json, null);
                              }).catch(error=>{
                                 callback(null, error);
                              });
                           }
                        
							        function init(base) {
                   			      var dataInicioFat = engine.getField("dataInicioFat").getValue();
								         var dataFinalFat = engine.getField("dataFinalFat").getValue();
                                 var dataInicioDesp = engine.getField("dataInicioDesp").getValue();
								         var dataFinalDesp = engine.getField("dataFinalDesp").getValue();
                                 var frotaTerceiro = engine.getField("frotaTerceiro").getValue();
                                 var caminhaoCarreta = engine.getField("caminhaoCarreta").getValue();
                            
	                            chartBarraPlaca([dataInicioFat, dataFinalFat, dataInicioDesp, dataFinalDesp, frotaTerceiro, caminhaoCarreta], function(chart,error){
	                                 if(!error){
	                                    chart.setWidth("100%");
	                                    chart.setHeight("5000px"); /* era 650 */
	                                    chart.setCaption("Faturamento x Depesas placas");
	                                    chart.id = "chartBarraPlaca"+new Date().getTime();
	                                    if(base.components.length == 0){
	                                       base.addComponent(chart);
	                                    }else{
	                                       base.components[0] = chart;
	                                    }
	                                    base.addComponent(chart);
	                                 }
	                            });
							}
								]]>
							</InitScript>
						</ScriptWidget>
					</Tab>
               
               <!-- Faturamento Geral por cliente -->
               <Tab id="faturamento_despesas_cliente" caption="Filtro por cliente">
                  <ScriptWidget id="scpFaturamentoCliente">
							<factory>
								<LayoutFactory type="VerticalLayout" width="100%" />
							</factory>
							<InitScript language="JavaScript">
								<![CDATA[
									function init(base) {
                              var dataInicioFat = engine.getField("dataInicioFat").getValue();
										var dataFinalFat = engine.getField("dataFinalFat").getValue();
                              var dataInicioDesp = engine.getField("dataInicioDesp").getValue();
										var dataFinalDesp = engine.getField("dataFinalDesp").getValue();
                              var frotaTerceiro = engine.getField("frotaTerceiro").getValue();
                              var caminhaoCarreta = engine.getField("caminhaoCarreta").getValue();
                              var exibeLabel = false;
                              
                              /*Valor Faturamento Geral*/
                              vQueryService.executeDataSource("sqlFaturamentoDespesasTotal", [dataInicioFat, dataFinalFat, dataInicioDesp, dataFinalDesp, frotaTerceiro, caminhaoCarreta]).then(dsFaturamento=>{
                                 var texto = '<p style="text-align: center;"><span style=""><strong>Totais<span style=""></span></strong></span></p>';
                                 
                                 texto += '<table border="0" width="90%"><tbody>';
                                 while(dsFaturamento.next()){
                                    texto += '<tr>';
                                    texto += '<td width="65%">' + dsFaturamento.getString("DESC") + '</td>';
                                    texto += '<td align="left">' + 'R$ ' + accounting.formatMoney(dsFaturamento.getNumber("VALOR"), "", 2, ".", ",") + '</td>';
                                    texto += '</tr>';
                                 }
                                 texto += '</tbody></table>';
                                 
                                 engine.getLabel('lblFaturamentoGeralCli').setValue(texto);
                              }).catch(error=>{
                              });
                              
                              /*Faturamento*/
                              vQueryService.executeDataSource("sqlFaturamento", [dataInicioFat, dataFinalFat, frotaTerceiro, caminhaoCarreta]).then(dsFaturamento=>{
                                 var texto = '<p style="text-align: center;"><span style=""><strong>Faturamento<span style=""></span></strong></span></p>';
                                 exibeLabel = false;
                                 texto += '<table border="0" width="90%"><tbody>';
                                 while(dsFaturamento.next()){
                                    if(dsFaturamento.getNumber("VALOR") > 0){
                                       exibeLabel = true;
                                    }
                                    texto += '<tr>';
                                    texto += '<td width="65%">' + dsFaturamento.getString("DESCRICAO") + '</td>';
                                    texto += '<td align="left">' + 'R$ ' + accounting.formatMoney(dsFaturamento.getNumber("VALOR"), "", 2, ".", ",") + '</td>';
                                    texto += '</tr>';
                                 }
                                 texto += '</tbody></table>';
                                 engine.getLabel('lblFaturamento').setValue(texto);
                                 engine.getLabel('lblFaturamento').setVisible(exibeLabel);
                              }).catch(error=>{
                              });
                              
                              /*Despesa Operacional*/
                              vQueryService.executeDataSource("sqlDespesaOperacional", [dataInicioDesp, dataFinalDesp, frotaTerceiro, caminhaoCarreta]).then(dsFaturamento=>{
                                 var texto = '<p style="text-align: center;"><span style=""><strong>Despesas Operacionais<span style=""></span></strong></span></p>';
                                 exibeLabel = false;
                                 texto += '<table border="0" width="90%"><tbody>';
                                 while(dsFaturamento.next()){
                                    if(dsFaturamento.getNumber("VALOR") > 0){
                                       exibeLabel = true;
                                    }
                                    texto += '<tr>';
                                    texto += '<td width="65%">' + dsFaturamento.getString("DESCRICAO") + '</td>';
                                    texto += '<td align="left">' + 'R$ ' + accounting.formatMoney(dsFaturamento.getNumber("VALOR"), "", 2, ".", ",") + '</td>';
                                    texto += '</tr>';
                                 }
                                 texto += '</tbody></table>';
                                 engine.getLabel('lblDespOperacional').setValue(texto);
                                 engine.getLabel('lblDespOperacional').setVisible(exibeLabel);
                              }).catch(error=>{
                              });
                              
                              /*Despesa Particular*/
                              vQueryService.executeDataSource("sqlDespesaParticular", [dataInicioDesp, dataFinalDesp, frotaTerceiro, caminhaoCarreta]).then(dsFaturamento=>{
                                 var texto = '<p style="text-align: center;"><span style=""><strong>Despesas Particulares<span style=""></span></strong></span></p>';
                                 exibeLabel = false;
                                 texto += '<table border="0" width="90%"><tbody>';
                                 while(dsFaturamento.next()){
                                    if(dsFaturamento.getNumber("VALOR") > 0){
                                       exibeLabel = true;
                                    }
                                    texto += '<tr>';
                                    texto += '<td width="65%">' + dsFaturamento.getString("DESCRICAO") + '</td>';
                                    texto += '<td align="left">' + 'R$ ' + accounting.formatMoney(dsFaturamento.getNumber("VALOR"), "", 2, ".", ",") + '</td>';
                                    texto += '</tr>';
                                 }
                                 texto += '</tbody></table>';
                                 engine.getLabel('lblDespParticular').setValue(texto);
                                 engine.getLabel('lblDespParticular').setVisible(exibeLabel);
                              }).catch(error=>{
                              });
                              
                              var texto = '<p style="text-align: center;"><span style=""><strong>Despesas por Combustíveis<span style=""></span></strong></span></p>';
                              engine.getLabel('lblDespCombustivel').setValue(texto);
									}
								]]>
							</InitScript>
						</ScriptWidget>
                  
                  <VerticalLayout width="100%" margin="false" spacing="true">
                     <HorizontalLayout width="100%" margin="false" spacing="true" >
                        <Label id="lblFaturamentoGeralCli" value="" visible="true" align="CENTER"/>
                     </HorizontalLayout>
                     
                     <HorizontalLayout width="100%" margin="false" spacing="true" caption="Faturamento">
                        <Label id="lblFaturamento" value="" visible="true" align="CENTER"/>
                     </HorizontalLayout>
                     
                     <HorizontalLayout width="100%" margin="false" spacing="true" caption="Despesas Operacionais">
                        <Label id="lblDespOperacional" value="" visible="true" align="CENTER"/>
                     </HorizontalLayout>
                     
                     <HorizontalLayout width="100%" margin="false" spacing="true" caption="Despesas Particulares">
                        <Label id="lblDespParticular" value="" visible="true" align="CENTER"/>
                     </HorizontalLayout>
                     
                     <Label id="lblDespCombustivel" value="" visible="true" align="CENTER"/>
                     
                     <!-- Gasto por cliente dos combustíveis-->
                     <Tab id="despesas_cliente" caption="">
                        <DBTable type="string" id="dbDespCliente" caption="" editable="false" visible="true" rows="10" width="100%" requireFilter="false">
                           <datasource>
                              <form-datasource ref="sqlDespesaCombustivel"/>
                           </datasource>
                           <key-field>CODIGO</key-field>
                           <bind property="0" ref="dataInicioDesp" />
                           <bind property="1" ref="dataFinalDesp" />
                           <bind property="3" ref="frotaTerceiro" />
                           <bind property="4" ref="caminhaoCarreta" />
                           <columns>
                              <column name="DESCRICAO" caption="Nome" expand-ratio="0.05" align="LEFT"/>
                              <column name="VALOR" caption="Valor" type="decimal" format="#,##0.00" decimalSeparator="," groupingSeparator="." expand-ratio="0.20"/>
                           </columns>
                           <styleGenerator>
                              <scriptGenerator language="JavaScript">
                                 <![CDATA[
                                    function getStyle(itemId, columnId, item) {
                                       if(columnId == 'DESCRICAO'){
                                          return {'text-decoration': 'underline', 'color' : 'blue'};
                                       }
                                    }
                                 ]]>
                              </scriptGenerator>
                           </styleGenerator>
                           <events>
                              <columnClick>
                                 <script language="JavaScript">
                                    <![CDATA[
                                       function run(event) {
                                          var item = event.item;
                                          var column = event.column;
                                          if(column.name == "DESCRICAO"){
                                             var dataInicioParam = engine.getField("dataInicioDesp").getValue();
                                             var dataFinalParm = engine.getField("dataFinalDesp").getValue();
                                             var frotaTerceiroParam = engine.getField("frotaTerceiro").getValue();
                                             var caminhaoCarretaParam = engine.getField("caminhaoCarreta").getValue();
                                             engine.openPanel("faturamento_despesas_detalhes",{idCodigo: item['CODIGO'], idNomeCliente: item['DESCRICAO'], idDataInicio: dataInicioParam, idDataFim: dataFinalParm, idFrotaTerceiro: frotaTerceiroParam, idCaminhaoCarreta: caminhaoCarretaParam});
                                          }
                                       }
                                    ]]>
                                 </script>
                              </columnClick>
                           </events>
                        </DBTable>
                     </Tab>
                  </VerticalLayout>
					</Tab>
				</TabLayout>
			</VerticalLayout>
		</components>
	</form>
</panel-form>