call spQuery_Cuentas_Pagar(NULL, NULL,  NULL, NULL, NULL, NULL, NULL);

DROP PROCEDURE IF EXISTS spQuery_Cuentas_Pagar;
CREATE PROCEDURE spQuery_Cuentas_Pagar(	
	varEmpresa    int,
  varProveedor  int,
  varTipoDoc    int,
  varFechaIni   date,
  varFechaFin   date,
  varField      varchar(60),
  varOrder      varchar(5)
)
BEGIN 
  DECLARE varCadEmp, varCadPro, varCadTip, varCadIni, varCadFin TEXT DEFAULT '';
  DECLARE varCadOrd TEXT DEFAULT '';
  
  IF varEmpresa  <> '' and varEmpresa is not null THEN
    SET varCadEmp = CONCAT(" and V.id_empresa = ", varEmpresa);
  END IF;
  IF varProveedor  <> '' and varProveedor is not null THEN
    SET varCadPro = CONCAT(" and V.id_proveedor = ", varProveedor);
  END IF;
  IF varTipoDoc  <> '' and varTipoDoc is not null THEN
    SET varCadTip = CONCAT(" and V.id_tipo_doc = ", varTipoDoc);
  END IF;
  IF varFechaIni  <> '' and varFechaIni is not null THEN
    SET varCadIni = CONCAT(" and V.fecha_emision >= '", varFechaIni, "' ");
  END IF;
  IF varFechaFin <> '' and varFechaFin is not null THEN
    SET varCadFin = CONCAT(" and V.fecha_emision <= '", varFechaFin, "' ");
  END IF;
  
  -- Para Ordenar
  IF varField is not null and varField <> '' THEN
    SET varField = CASE WHEN varField = 'FECHA_CREADO' THEN 'V._date_create'
                        WHEN varField = 'FECHA_MODIFI' THEN 'V._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 V.id_compra as IDE, ",
                    "V.id_empresa as CEMP, E.nombre as EMPRESA, ",
                    "date_format(V.fecha_emision,'%d/%m/%Y')  as EMISION, ",                    
                    "concat(TD.abrev,' ', V.nro_documento) as DOCUMENTO, ",
                    "V.id_condicion as  CCON, TC.nombre as CONDICION, ",
                    "V.id_proveedor as CPRO, C.nombre as PROVEEDOR, C.DIRECCION, ",         
                    "V.TOTAL, V.total-V.saldo as PAGOS, V.SALDO ",                    
                    "from _sv_compra V ",
                    "inner join _sv_empresa E on V.id_empresa = E.id_empresa ",
                    "inner join _sv_proveedor C ON V.id_proveedor = C.id_proveedor ",
                    "inner join _sv_tipo_condicion TC ON V.id_condicion = TC.id_condicion ",
                    "inner join _sv_tipo_doc_compra TD ON V.id_tipo_doc = TD.id_tipo_doc ",
                    "left join _sys_usuario U ON V._user_create = U.id_usuario ",
                    "where V.estado not in ('AN','CA') ",
                    varCadEmp, varCadPro, varCadTip, varCadIni, varCadFin,
                    varCadOrd);
  PREPARE s1 FROM @sql;
  EXECUTE s1;
  DEALLOCATE PREPARE s1;
END;