call spQuery_Matriz_IP_Estructura(18);

DROP PROCEDURE IF EXISTS spQuery_Matriz_IP_Estructura;
CREATE PROCEDURE spQuery_Matriz_IP_Estructura(
  varMatriz int
  )
BEGIN
  select '<img src="../images/16x16/chart_organisation.png" >' AS IMG, 
  id_matriz as CIND, nombre as INDICADOR, NULL AS CONDICION, NULL AS PORCENTAJE, base as MONTO,-1 as NIVEL, -1 as ARBOL, NULL AS TIPONODO, NULL AS PADRE,
  100 - (select sum(porcentaje) from _sind_matriz_detalle X where id_matriz = varMatriz and X.padre = 0) as MAXPORC
  from _sind_matriz
  where id_matriz = varMatriz
  union
  select CONCAT(REPEAT('&nbsp;',(D.nivel+1)*6),
  case when D.TIPONODO = 0 
       then '<img src="../images/16x16/folder_go.png" >'
       else '<img src="../images/16x16/page.png" >'
  end
  ) AS IMG, 
  D.id_indicador as CIND, 
  I.nombre AS INDICADOR, 
  case when D.id_condicion = 0 
      then CAST(CONCAT(C.nombre, ' [', C.simbolo, ']') AS CHAR)
      else CAST(CONCAT('[', C.simbolo, ']', D.valcond) AS CHAR)
  end as CONDICION, 
  D.PORCENTAJE, D.MONTO, D.NIVEL, D.ARBOL, D.TIPONODO, D.PADRE,
  100 - IFNULL((select sum(porcentaje) from _sind_matriz_detalle X where id_matriz = varMatriz and X.padre = D.id_indicador),0) as MAXPORC
  from _sind_matriz_detalle D
  inner join _sind_indicador I ON D.id_indicador = I.id_indicador
  inner join _sind_condicion C ON D.id_condicion = C.id_condicion
  where id_matriz = varMatriz
  order by arbol;
END;

