var DashTabela = SuperWidget.extend({

dados:[],
paginaAtual:1,
itensPorPagina:5,

init:function(){

var self=this;

$("#page_prev_"+this.instanceId).on("click",function(){
if(self.paginaAtual>1){
self.paginaAtual--;
self.renderPage();
}
});

$("#page_next_"+this.instanceId).on("click",function(){
var totalPaginas = self.getTotalPaginas();
if(self.paginaAtual<totalPaginas){
self.paginaAtual++;
self.renderPage();
}
});

$("#page_size_"+this.instanceId).on("change",function(){
self.itensPorPagina = parseInt($(this).val(),10) || 5;
self.paginaAtual = 1;
self.renderPage();
});

window.addEventListener("dashboardData",function(e){

self.render(e.detail || []);

});

},

render:function(dados){

this.dados = dados;
this.paginaAtual = 1;
this.renderPage();

},

renderPage:function(){

var html="";
var totalPaginas = this.getTotalPaginas();

if(this.paginaAtual > totalPaginas){
this.paginaAtual = totalPaginas;
}

var inicio = (this.paginaAtual - 1) * this.itensPorPagina;
var fim = inicio + this.itensPorPagina;
var paginaDados = this.dados.slice(inicio,fim);

paginaDados.forEach(function(item){

html+="<tr>";
html+="<td>"+esc(formataData(item.dataAuditoria))+"</td>";
html+="<td>"+esc(formataData(item.dataLimite))+"</td>";
html+="<td>"+esc(item.ciclo || "")+"</td>";
html+="<td>"+esc(item.auditor || item.usuarioRetorno)+"</td>";
html+="<td>"+esc(item.responsavelLoja)+"</td>";
html+="<td>"+esc(item.loja)+"</td>";
html+="<td>"+esc(statusResumido(item))+"</td>";
html+="</tr>";

});

if(!html){
html+="<tr><td colspan='7' class='text-center'>Sem dados para o filtro selecionado</td></tr>";
}

$("#lista_"+this.instanceId).html(html);
$("#page_info_"+this.instanceId).text("Página " + this.paginaAtual + " de " + totalPaginas + " (" + this.dados.length + " registros)");
$("#page_prev_"+this.instanceId).prop("disabled", this.paginaAtual <= 1);
$("#page_next_"+this.instanceId).prop("disabled", this.paginaAtual >= totalPaginas);

},

getTotalPaginas:function(){
if(!this.dados.length){
return 1;
}
return Math.ceil(this.dados.length / this.itensPorPagina);
}

});

function esc(v){
return String(v == null ? "" : v)
  .replace(/&/g,"&amp;")
  .replace(/</g,"&lt;")
  .replace(/>/g,"&gt;")
  .replace(/\"/g,"&quot;")
  .replace(/'/g,"&#39;");
}

function formataData(v){
var s = String(v || "").trim();
if(!s){
return "";
}
if(/^\d{4}-\d{2}-\d{2}$/.test(s)){
var p = s.split("-");
return p[2] + "/" + p[1] + "/" + p[0];
}
return s;
}

function statusResumido(item){
var s = String(item.saidaAnalise || item.status || "").trim().toUpperCase();
if(s === "CONFORME"){
return "CONFORME";
}
return "NAO_CONFORME";
}
