call spQuery_Sistema_Menu(2, '','',  NULL, NULL);

DROP PROCEDURE IF EXISTS spQuery_Sistema_Menu;
CREATE PROCEDURE spQuery_Sistema_Menu(
  varSistema  int,
	varCodigo   varchar(10),
	varNombre   varchar(80),
  varField    varchar(60),
  varOrder    varchar(5)
)
BEGIN
  DECLARE varCadOrd TEXT DEFAULT "order by SUBSTRING(M.id_menu,1,2), SUBSTRING(RPAD(M.id_menu,4,'0'),3,2), SUBSTRING(RPAD(M.id_menu,6,'0'),5,2), LENGTH(M.id_menu), orden";
  -- Para Ordenar
  IF varField is not null and varField <> '' THEN
    SET varField = CASE WHEN varField = 'FECHA_CREADO' THEN 'M._date_create'
                        WHEN varField = 'FECHA_MODIFI' THEN 'M._date_update'
                        ELSE varField
                   END;
    SET varCadOrd = CONCAT("ORDER BY ", varField, " ");
    IF varOrder is not null and varOrder <> '' THEN
      SET varCadOrd = CONCAT(varCadOrd, varOrder, " ");      
    END IF;
  END IF;
  
	SET @sql = CONCAT("select M.id_sistema as CSIS, M.id_menu as CMEN, M.ORDEN, M.nombre AS MENU, ",
                    "concat('<img src=\"',(select valor from _sys_config where ide='01'), img_out,'\" width=16 height=16 border=0 />') as img_out, ",
                    "concat('<img src=\"',(select valor from _sys_config where ide='01') ,img_over,'\" width=16 height=16 border=0 />') as img_over, LINK, ",
                    "date_format(M._date_create,'%d/%m/%Y %h:%i:%s %p') AS FECHA_CREADO, ",
                    "date_format(M._date_update,'%d/%m/%Y %h:%i:%s %p') AS FECHA_MODIFI, ",
                    "UPPER(UN.usuario) as USER_CREADO, ",
                    "UPPER(UU.usuario) as USER_MODIFI ",
                    "from _sys_menu M ",
                    "inner join _sys_usuario UN ON M._user_create = UN.id_usuario ",
                    "inner join _sys_usuario UU ON M._user_update = UU.id_usuario ",
                    "where M._estado = 'A' ", 
                    "and M.id_sistema = ", varSistema, " ",
                    "and M.id_menu like CONCAT('", varCodigo, "','%') ",
                    "and M.nombre like CONCAT('%','", varNombre, "','%') ",
                    varCadOrd);
  
  PREPARE s1 FROM @sql;
  EXECUTE s1;
  DEALLOCATE PREPARE s1;
END;