call spQuery_Almacen(NULL,NULL,'FECHA_CREADO',NULL);

DROP PROCEDURE IF EXISTS spQuery_Almacen;
CREATE PROCEDURE spQuery_Almacen(
  varCodigo   int,
	varNombre   varchar(80),
  varUsuario  int,
  varField    varchar(60),
  varOrder    varchar(5)
  )
BEGIN
  DECLARE varCadCod, varCadNom, varCadRuc  text default '';
  DECLARE varCadOrd TEXT DEFAULT '';
  
  if varCodigo is not null or varCodigo <> '' then
    set varCadCod = CONCAT(" and A.id_almacen = ", varCodigo, " ");
  end if;
  if ifnull(varNombre,'') <> '' then
    set varCadNom = CONCAT(" and A.nombre LIKE '%", varNombre, "%' ");
  end if;
  -- Para Ordenar
  IF varField is not null and varField <> '' THEN
    SET varField = CASE WHEN varField = 'FECHA_CREADO' THEN 'A._date_create'
                        WHEN varField = 'FECHA_MODIFI' THEN 'A._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 A.id_almacen AS CALM, A.nombre AS ALMACEN, A.ABREV, T.nombre as TIPO, ",
                    "A.id_empresa as CEMP, E.nombre as EMPRESA, ",
                    "A.id_agencia as CAGE, G.nombre as AGENCIA, ",
                    "A.DIRECCION, U.DEPARTAMENTO, U.PROVINCIA, U.DISTRITO, ",
                    "date_format(A._date_create,'%d/%m/%Y %h:%i:%s %p') AS FECHA_CREADO, ",
                    "date_format(A._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 _sv_almacen A ",
                    "inner join _sv_empresa E ON A.id_empresa = E.id_empresa ",
                    "inner join _sys_tipo_almacen T on A.id_tipo_almacen = T.id_tipo_almacen ",
                    "inner join _srh_agencia G on A.id_agencia = G.id_agencia ",
                    "left join _sv_ubigeo U ON A.id_ubigeo = U.id_ubigeo ",
                    "left join _sys_usuario UN ON A._user_create = UN.id_usuario ",
                    "left join _sys_usuario UU ON A._user_update = UU.id_usuario ",
                    "where A._estado='A' ",
                    "and A.id_almacen in (select id_almacen from _sys_usuario_almacen where id_usuario = ", varUsuario, ")",
	                  varCadCod, varCadNom,
                    varCadOrd);		
  PREPARE s1 FROM @sql;
  EXECUTE s1;
  DEALLOCATE PREPARE s1;
END;