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 || []);

});

$("#lista_"+this.instanceId).on("click","tr[data-process-number]",function(){
var processNumber = String($(this).attr("data-process-number") || "").trim();
var processId = String($(this).attr("data-process-id") || "").trim();
var link = buildProcessLink(processNumber, processId);
if(link){
window.open(link,"_blank");
}
});

},

render:function(dados){

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

},

renderPage:function(){

var html="";
var totalPaginas = this.getTotalPaginas();
var totalHeaders = $("#dashTabela_" + this.instanceId + " thead th").length;
var hasSolicitacaoColumn = totalHeaders >= 8;

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){
 var numeroSolicitacao = String(item.numeroSolicitacao || "").trim();
 var processId = String(item.processId || "checklist").trim();
 var clickableClass = numeroSolicitacao ? "dtb-row-link" : "";
 html+="<tr class='"+clickableClass+"' data-process-number='"+escAttr(numeroSolicitacao)+"' data-process-id='"+escAttr(processId)+"'>";
 if(hasSolicitacaoColumn){
 html+="<td>"+esc(numeroSolicitacao || "-")+"</td>";
  }
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='"+(hasSolicitacaoColumn ? 8 : 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 escAttr(v){
return esc(v).replace(/"/g,"&quot;");
}

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";
}

function buildProcessLink(numeroSolicitacao, processId){
var num = String(numeroSolicitacao || "").trim();
if(!num){
return "";
}

var pid = String(processId || "").trim() || "checklist";
var server = "";
var companyId = "";

try{
server = String(window.WCMAPI && window.WCMAPI.serverURL || "").trim();
}catch(e){}

try{
companyId = String(window.WCMAPI && window.WCMAPI.organizationId || "").trim();
}catch(e2){}

if(!server){
server = window.location.origin;
}

if(!companyId){
companyId = getCompanyIdFromDom();
}

if(!companyId){
companyId = "1";
}

return server + "/portal/p/" + companyId + "/pageworkflowview?app_ecm_workflowview_detailsProcessInstanceID=" + encodeURIComponent(num) + "&processID=" + encodeURIComponent(pid);
}

function getCompanyIdFromDom(){
var selectors = [
"input[name='WKCompany']",
"#WKCompany",
"input[name='companyId']",
"#companyId"
];

for(var i=0;i<selectors.length;i++){
try{
var value = String($(selectors[i]).val() || "").trim();
if(value) return value;
}catch(e){}
}

try{
if(window.parent && window.parent.$){
for(var j=0;j<selectors.length;j++){
var parentValue = String(window.parent.$(selectors[j]).val() || "").trim();
if(parentValue) return parentValue;
}
}
}catch(e2){}

return "";
}
