<?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="dashboardCaminhoes" width="100%" backgroundColor="#ffffff">
		<name>dashboardCaminhoesCusto</name>
		<description>Indicadores de Despesas - Caminhões</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 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();
				if (engine.getGlobalVariable('_mobileRender')) {
					if (!engine.getField('dataInicio').getValue()) {
						engine.getField('dataInicio').setValue(data);
						engine.getField('dataFinal').setValue(d);
					}
				} else {
					engine.getField('dataInicio').setValue(data);
					engine.getField('dataFinal').setValue(d);
				}
				
				// Registrando icones
				engine.getWidgetController('btnFiltrar').getButton().setIcon(IconFactory.instance().getIconAsResource(IconLibraryAPISmall.FILTRAR));
				engine.getGlobalVariable('tela')();
			}
		]]>
	  	</initScript>
		<components>
			<VerticalLayout width="100%" margin="false" spacing="true">
				<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%">
						      <ImageWidget id="img1" height="75" align="TOP_LEFT">
						      		<image>
						      			<base64 extension="jpg">
						      				<![CDATA[
						      					,[encoded data, 45036 characters]
						      				]]>
						      			</base64>
						      		</image>
						      	</ImageWidget>
						      	<HorizontalLayout width="600" spacing="true" align="BOTTOM_RIGHT" >
							      	<DateField type="date" id="dataInicio" caption="Data inicial" width="100%" expandRatio="0.25" description="Data inicial da exibição" format="dd/MM/yyyy" />
									<DateField type="date" id="dataFinal" caption="Data final" width="100%" expandRatio="0.25" description="Data final da exibição" format="dd/MM/yyyy" />
									<DBComboBox type="string" id="placa" width="100%" expandRatio="0.3" align="TOP_LEFT" 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>
									<ButtonWidget id="btnFiltrar" caption="Filtrar" description="Aplica filtro de data" width="100%" expandRatio="0.2">
										<onClickScript language="JavaScript">
											<![CDATA[
												function run() {
													engine.getGlobalVariable('tela')();
												}
											]]>
										</onClickScript>
									</ButtonWidget>
								</HorizontalLayout>
						    </HorizontalLayout>
						</VerticalLayout>
					</Panel>
					<ScriptWidget id="scriptTest4">
						<factory>
							<LayoutFactory type="VerticalLayout" width="100%"  />
						</factory>
						<InitScript language="JavaScript">
							<![CDATA[
								//Carregar lib externa fontawesome icons
									importClass(Packages.com.vaadin.server.FontAwesome);
									importClass(Packages.java.util.Calendar);
									
									//Carregar libs internas (tabela script_lib)		
									var chartAPI = libService.loadScript('charts');
									var vc = libService.loadScript('vaadinComponents');
									
									var corKpi = function(v1, v2) {
										var cor = '#29CBA9';
										if (v1 > v2){
											cor = '#ff0000';
										}
										return cor; 
									}
								
							    
							    var carregarInformacoesBarraProgresso = function(){
							    	root.removeAllComponents();
								    //Carregar lib externa fontawesome icons
									importClass(Packages.com.vaadin.server.FontAwesome);
									importClass(Packages.java.util.Calendar);
									
									//Carregar libs internas (tabela script_lib)		
									var chartAPI = libService.loadScript('charts');
									var vc = libService.loadScript('vaadinComponents');
									
									var corKpi = function(v1, v2) {
										var cor = '#29CBA9';
										if (v1 > v2){
											cor = '#ff0000';
										}
										return cor; 
									}
													
									var iconeKpi = function(v1, v2) {
										var icone = FontAwesome.CHEVRON_DOWN.getHtml()+' ';
										if (v1 > v2){
											icone = FontAwesome.CHEVRON_UP.getHtml()+' ';
										}
										return icone; 
									}
									
									var caminhao_inativo_b64  = ',[encoded data, 467060 characters]';
									var caminhao_vermelho_b64 = ',[encoded data, 86276 characters]';
									var caminhao_amarelo_b64  = ',[encoded data, 84300 characters]';
									var caminhao_verde_b64    = ',[encoded data, 81548 characters]';
									var caminhao_preto_b64    = ',[encoded data, 465108 characters]';
	
																
								    var getDataAtual = function() {
	                                    var c = java.util.Calendar.getInstance();
	                                      c.setTime(new java.util.Date());
	                                      c.set(Calendar.HOUR_OF_DAY, 0);
	                                      c.set(Calendar.MINUTE, 0);
	                                      c.set(Calendar.SECOND, 0);
	                                      c.set(Calendar.MILLISECOND, 0);
	                                      
	                                      return c.getTime();
	                                 }
							    
									var panel_barra = new Packages.com.vaadin.ui.VerticalLayout();
									panel_barra.setWidth("100%");
									panel_barra.setMargin(false);
									panel_barra.setSpacing(false); //voltar
								
									var grid = new Packages.com.vaadin.ui.GridLayout();
								    grid.setWidth("100%");
								    //grid.setSpacing(true);
								    //grid.setMargin(true);	//voltar						  
								    grid.setColumns(4);
								    root.addComponent(panel_barra);
								    
								    var paramsA = new java.util.ArrayList();
								    var data1 = engine.getField('dataInicio').getValue();
									if(!data1){
										var data1 = getDataAtual();
									}
									
									var data2 = engine.getField('dataFinal').getValue();
									if(!data2){
										var data2 = getDataAtual();
									}
									
									var data3 = engine.getField('dataInicio').getValue();
									if(!data3){
										var data3 = getDataAtual();
									}
									
									var data4 = engine.getField('dataFinal').getValue();
									if(!data4){
										var data4 = getDataAtual();
									}
									
									data1 = new java.sql.Timestamp(data1.getTime());
                                    data2 = new java.sql.Timestamp(data2.getTime());
                                    data3 = new java.sql.Timestamp(data3.getTime());
                                    data4 = new java.sql.Timestamp(data4.getTime());
									paramsA.add(data1);
									paramsA.add(data2);
									paramsA.add(data3);
									paramsA.add(data4);	
									
									var banco = 'vitruvio';
									/*var sql = "Select 	v.codigo," +
														" v.placa," +
														" coalesce((Select sum(cdo.valor) from controle_despesas_operacionais cdo where cdo.chave_veiculo = v.codigo group by cdo.chave_veiculo),0) valor_operacional," +
														" coalesce((Select sum(cdc.total_combustivel) from controle_despesas_combustiveis cdc where cdc.chave_veiculo = v.codigo group by cdc.chave_veiculo),0) valor_combustivel," +
														" coalesce((Select coalesce(sum(cdo.valor),0) from controle_despesas_operacionais cdo where cdo.chave_veiculo = v.codigo group by cdo.chave_veiculo),0) + coalesce((Select coalesce(sum(cdc.total_combustivel),0) from controle_despesas_combustiveis cdc where cdc.chave_veiculo = v.codigo group by cdc.chave_veiculo),0) total" +         
												 		" from veiculo v where coalesce((Select coalesce(sum(cdo.valor),0) from controle_despesas_operacionais cdo where cdo.chave_veiculo = v.codigo group by cdo.chave_veiculo),0) + coalesce((Select coalesce(sum(cdc.total_combustivel),0) from controle_despesas_combustiveis cdc where cdc.chave_veiculo = v.codigo group by cdc.chave_veiculo),0) > 0 order by 5 desc";*/
									var sql = "Select geral.codigo, geral.placa, sum(geral.valor_operacional) operacionais," +
												" sum(geral.valor_combustivel) combustiveis," +
										        " sum(geral.valor_operacional) + sum(geral.valor_combustivel) total," +
										        " sum(geral.total_litros_combutivel) litros from ( Select 	v.codigo," +
												" v.placa," +
												" coalesce((Select cdo.valor from controle_despesas_operacionais cdo where cdo.chave_veiculo = v.codigo),0) valor_operacional," +
												" coalesce((Select cdc.total_combustivel from controle_despesas_combustiveis cdc where cdc.chave_veiculo = v.codigo),0) valor_combustivel," +
										        " COALESCE((Select cdc.litros from controle_despesas_combustiveis cdc where cdc.chave_veiculo = v.codigo),0) total_litros_combutivel," +
										        " (Select cdc.data from controle_despesas_combustiveis cdc where cdc.chave_veiculo = v.codigo) cdc_data," +
										        " (Select cdo.data from controle_despesas_operacionais cdo where cdo.chave_veiculo = v.codigo) cdo_data" +
										 		" from veiculo v) geral where (cast(geral.cdo_data as date) >= ? and cast(geral.cdo_data as date) <= ?) or (cast(geral.cdc_data as date) >= ? and cast(geral.cdc_data as date) <= ?) group by geral.codigo, geral.placa order by 5 desc";
									
									engine.debug(sql);
									var dsViewDashboard = vQueryService.executeQuery(banco, sql, paramsA);					
									
									var p = new Packages.com.vaadin.ui.Panel();
									var iconeLojas = FontAwesome.TASKS.getHtml()+' ';
									p.setCaption('<span style="color: #34495E">'+iconeLojas+'<b> GASTOS POR VEÍCULOS</b></span>');
									panel_barra.addComponent(p);
									panel_barra.addComponent(grid);
									
									panel_barra.setComponentAlignment(grid, Alignment.TOP_LEFT);
									
									var tam_caminhoes_w = '120px';
									var tam_caminhoes_h = '106px'; 								
									
									var sql_mov = "Select geral.codigo, geral.placa, sum(geral.valor_operacional) valor_operacional," +
												" sum(geral.valor_combustivel) valor_combustivel," +
										        " sum(geral.valor_operacional) + sum(geral.valor_combustivel) total," +
										        " sum(geral.total_litros_combutivel) TOTAL_LITROS_COMBUSTIVEL from ( Select 	v.codigo," +
												" v.placa," +
												" coalesce((Select cdo.valor from controle_despesas_operacionais cdo where cdo.chave_veiculo = v.codigo),0) valor_operacional," +
												" coalesce((Select cdc.total_combustivel from controle_despesas_combustiveis cdc where cdc.chave_veiculo = v.codigo),0) valor_combustivel," +
										        " COALESCE((Select cdc.litros from controle_despesas_combustiveis cdc where cdc.chave_veiculo = v.codigo),0) total_litros_combutivel," +
										        " (Select cdc.data from controle_despesas_combustiveis cdc where cdc.chave_veiculo = v.codigo) cdc_data," +
										        " (Select cdo.data from controle_despesas_operacionais cdo where cdo.chave_veiculo = v.codigo) cdo_data" +
										 		" from veiculo v) geral where geral.codigo = ? and ((cast(geral.cdo_data as date) >= ? and cast(geral.cdo_data as date) <= ?) or (cast(geral.cdc_data as date) >= ? and cast(geral.cdc_data as date) <= ?)) group by geral.codigo, geral.placa";	
									
									var criarLabel = function(capt){
										var item = new Packages.com.vaadin.ui.Label(capt);
										item.addStyleName(VitruvioTheme.LABEL_SMALL);
										item.setSizeUndefined();
										//setComponentAlignment(item, Alignment.MIDDLE_RIGHT);
										return item;
									}
									
									try{
										while(dsViewDashboard.next()) {
											var chave = dsViewDashboard.getNumber("CODIGO"); 
											var placa = dsViewDashboard.getString("PLACA"); 	

											var msgRodape = null;
											var iconeRodape = FontAwesome.CHEVRON_CIRCLE_UP.getHtml()+' ';
											
											var list_mov = new Packages.com.vaadin.ui.GridLayout();
											list_mov.setWidth("100%");						  
											list_mov.setColumns(2);
											
											var params = new java.util.ArrayList();
											params.add(chave);
											params.add(data1);
											params.add(data2);
											params.add(data3);
											params.add(data4);										
											var dsViewMovimentacoes = vQueryService.executeQuery(banco, sql_mov, params);
											engine.debug(params);
										
											if(dsViewMovimentacoes.next()) {
											
												var i = criarLabel("Gastos operacionais:  ");
												list_mov.addComponent(i);
												list_mov.setComponentAlignment(i, Alignment.MIDDLE_RIGHT);
												
												var i = criarLabel(dsViewMovimentacoes.getString("VALOR_OPERACIONAL"));
												list_mov.addComponent(i);
												list_mov.setComponentAlignment(i, Alignment.MIDDLE_RIGHT);
												
												var i = criarLabel("Gastos combustíveis:  ");
												list_mov.addComponent(i);
												list_mov.setComponentAlignment(i, Alignment.MIDDLE_RIGHT);
												
												var i = criarLabel(dsViewMovimentacoes.getString("VALOR_COMBUSTIVEL"));
												list_mov.addComponent(i);
												list_mov.setComponentAlignment(i, Alignment.MIDDLE_RIGHT);
												
												var i = criarLabel("Gastos totais:  ");
												list_mov.addComponent(i);
												list_mov.setComponentAlignment(i, Alignment.MIDDLE_RIGHT);
												
												var i = criarLabel(dsViewMovimentacoes.getString("TOTAL"));
												list_mov.addComponent(i);
												list_mov.setComponentAlignment(i, Alignment.MIDDLE_RIGHT);
												
												var i = criarLabel("Litros Combustíveis:  ");
												list_mov.addComponent(i);
												list_mov.setComponentAlignment(i, Alignment.MIDDLE_RIGHT);
												
												var i = criarLabel(dsViewMovimentacoes.getString("TOTAL_LITROS_COMBUSTIVEL"));
												list_mov.addComponent(i);
												list_mov.setComponentAlignment(i, Alignment.MIDDLE_RIGHT);
											
											}
											
											var cnp_item = new Packages.com.vaadin.ui.VerticalLayout();									
											var p2 = new Packages.com.vaadin.ui.Panel();
											var iconeLojas = FontAwesome.INFO_CIRCLE.getHtml()+' ';
											p2.setCaption('<span style="color: #34495E">'+iconeLojas+'<b> Placa: '+placa  +'</b></span>');
											
											var caminhao = vc.imageFromBase64(caminhao_inativo_b64, 'png');
											
											caminhao.setWidth(tam_caminhoes_w);
											caminhao.setHeight(tam_caminhoes_h);
											
											var c = caminhao;
											cnp_item.addComponent(p2);								
											cnp_item.addComponent(c);
											cnp_item.setComponentAlignment(c, Alignment.MIDDLE_CENTER);
											
											cnp_item.addComponent(list_mov);
											grid.addComponent(cnp_item);
										}
									}catch(e){
										engine.debug('2 ' + e);
									}
									return panel_barra;							
								};
								
				
								function init(base) {
								    root = base;
								    root.setSpacing(true);
								    root.addStyleName(VitruvioTheme.LAYOUT_TINY_MARGIN);
								    
								    //bar chart
							        var chart = carregarInformacoesBarraProgresso();
							        chart.setWidth("100%");
							        //chart.setHeight("400px");
							        root.addComponent(chart);
							        carregarInformacoesBarraProgresso();
							        engine.setGlobalVariable('tela', carregarInformacoesBarraProgresso);				    
								}		    
					
							]]>
						</InitScript>
					</ScriptWidget>
			</VerticalLayout>

		</components>
	</form>
</panel-form>