<?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="sqlDespesaCategoria" language="JavaScript" workOnline="true">
               <![CDATA[
                  function buildDataSource(params) {
                     var sql =   "SELECT CDO.CHAVE_CATEGORIA ";
                     sql = sql + "      ,C.DESCRICAO AS NOME_CATEGORIA ";
                     sql = sql + "	    ,CAST(COALESCE(SUM(CDO.VALOR),0) AS NUMERIC(15,2)) AS VALOR ";
                     sql = sql + "  FROM CONTROLE_DESPESAS_OPERACIONAIS CDO ";
                     sql = sql + "  	  ,CATEGORIA C ";
                     sql = sql + " WHERE CDO.CHAVE_CATEGORIA = C.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 CDO.CHAVE_CATEGORIA ";
                     sql = sql + "         ,C.DESCRICAO ";
                     
                     sql = sql + " UNION ALL ";
                     
                     sql = sql + "SELECT CDP.CHAVE_CATEGORIA ";
                     sql = sql + "      ,C.DESCRICAO AS NOME_CATEGORIA ";
                     sql = sql + "	    ,CAST(COALESCE(SUM(CDP.VALOR),0) AS NUMERIC(15,2)) AS VALOR ";
                     sql = sql + "  FROM CONTROLE_DESPESAS_PESSOAIS CDP ";
                     sql = sql + "      ,CATEGORIA C ";
                     sql = sql + " WHERE CDP.CHAVE_CATEGORIA = C.CODIGO ";
                     sql = sql + "   AND CDP.DATA BETWEEN CAST(? AS DATE) AND CAST(? AS DATE) ";
                     sql = sql + " GROUP BY CDP.CHAVE_CATEGORIA ";
                     sql = sql + "         ,C.DESCRICAO ";
                     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);
					 }
                     prm.add(dataInicio);
                     prm.add(dataFinal);
                     
                     return vQueryService.executeQuery('vitruvio', sql, prm);
                  }
               ]]>
            </ScriptDataSource>
            
            <ScriptDataSource id="sqlDespesaCliente" language="JavaScript" workOnline="true">
               <![CDATA[
                  function buildDataSource(params) {
                    var sql = "SELECT CDO.CHAVE_CLIENTE "; 
                     sql = sql + "   ,C.NOME AS NOME_CLIENTE "; 
                     sql = sql + "   ,CAST(SUM(CDO.VALOR) + "; 
                     sql = sql + "       COALESCE((SELECT sum(CDC.total_combustivel) "; 
                     sql = sql + "      	FROM controle_despesas_combustiveis CDC ";
                     sql = sql + "       WHERE CDC.chave_cliente = CDO.chave_cliente ";
                     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 CDC.CHAVE_CLIENTE),0) ";
                     sql = sql + "       AS NUMERIC(15,2)) AS VALOR ";
                     sql = sql + "FROM CONTROLE_DESPESAS_OPERACIONAIS CDO ";
                     sql = sql + ",CLIENTES C ";
                     sql = sql + "WHERE CDO.CHAVE_CLIENTE = C.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 CDO.CHAVE_CLIENTE "; 
                     sql = sql + ",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 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>
			</DataSources>
		</ServerSide>
      
		<initScript language="JavaScript">
			<![CDATA[
				function run() {
               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="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">
               <!-- Gasto por categoria -->
               <Tab id="despesas_categoria" caption="Despesa por Categoria">
                  <DBTable type="string" id="dbDespCategoria" caption="Despesa por Categoria" editable="false" visible="true" rows="10" width="100%" requireFilter="false">
							<datasource>
								<form-datasource ref="sqlDespesaCategoria"/>
							</datasource>
							<key-field>CHAVE_CATEGORIA</key-field>
							<bind property="0" ref="dataInicioDesp" />
							<bind property="1" ref="dataFinalDesp" />
							<bind property="2" ref="frotaTerceiro" />
							<bind property="3" ref="caminhaoCarreta" />
							<columns>
                        <column name="NOME_CATEGORIA" caption="Categoria" expand-ratio="0.05" align="LEFT"/>
                        <column name="VALOR" caption="Valor" type="decimal" format="#,##0.00" decimalSeparator="," groupingSeparator="." expand-ratio="0.20"/>
 							</columns>
 						</DBTable>
					</Tab>
               
               <!-- Gasto por cliente -->
               <Tab id="despesas_cliente" caption="Despesa por Cliente">
                  <DBTable type="string" id="dbDespCliente" caption="Despesa por Cliente" editable="false" visible="true" rows="10" width="100%" requireFilter="false">
							<datasource>
								<form-datasource ref="sqlDespesaCliente"/>
							</datasource>
							<key-field>CHAVE_CLIENTE</key-field>
							<bind property="0" ref="dataInicioDesp" />
							<bind property="1" ref="dataFinalDesp" />
							<bind property="2" ref="frotaTerceiro" />
							<bind property="3" ref="caminhaoCarreta" />
							<columns>
                        <column name="NOME_CLIENTE" caption="Cliente" expand-ratio="0.05" align="LEFT"/>
                        <column name="VALOR" caption="Valor" type="decimal" format="#,##0.00" decimalSeparator="," groupingSeparator="." expand-ratio="0.20"/>
 							</columns>
 						</DBTable>
					</Tab>
				</TabLayout>
			</VerticalLayout>
		</components>
	</form>
</panel-form>