call spQuery_Registro_Ventas(2, NULL, NULL, NULL, NULL, '2013-12-01', '2013-12-20', NULL, NULL);

DROP PROCEDURE IF EXISTS spQuery_Registro_Ventas;
CREATE PROCEDURE spQuery_Registro_Ventas(
  varEmpresa    int,
	varCliente    int, 
  varVendedor   int,
  varRuta       varchar(10),
  varTipoDoc    int,
	varFechaIni   date,
	varFechaFin   date,
  varField      varchar(60),
  varOrder      varchar(5)
  )
BEGIN  
  DECLARE varCadIni, varCadFin, varCadCli, varCadVen, varCadRut, varCadTip varchar(100) DEFAULT '';
  DECLARE varCadOrd TEXT DEFAULT '';
   
  IF IFNULL(varCliente,0) <> 0 THEN
    SET varCadCli = CONCAT(" and C.id_cliente = ", varCliente, " ");  
  END IF;
  
  IF IFNULL(varVendedor,0) <> 0 THEN
    SET varCadVen = CONCAT(" and C.id_trabajador = ", varVendedor, " ");  
  END IF;
  
  IF varRuta is not null and varRuta <> '' THEN
    SET varCadRut = CONCAT(" and C.id_ruta = '", varRuta, "' ");  
  END IF;
  
  IF varTipoDoc is not null and varTipoDoc <> ''  THEN
    SET varCadTip = CONCAT(" and C.id_tipo_doc = ", varTipoDoc, " ");  
  END IF;
  
  IF varFechaIni IS NOT NULL THEN
    SET varCadIni = CONCAT(" and C.fecha_emision >= '", varFechaIni, "' ");
  END IF;
  
  IF varFechaFin IS NOT NULL THEN
    SET varCadFin = CONCAT(" and C.fecha_emision <= '", varFechaFin, "' ");
  END IF;
  
  -- 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 C.id_venta as IDE, ",
                    "C.id_empresa as CEMP, E.nombre as EMPRESA, ",
                    "date_format(C.fecha_emision,'%d/%m/%Y') AS FECHA, ",
                    "CONCAT(T.abrev,' ', C.nro_serie, '-', C.nro_preimpreso) as DOCUMENTO, ",
                    "C.id_condicion as CCON, TC.nombre as CONDICION, ",
                    "C.ESTADO, ",
                    "C.id_tipo_doc as CTIP, ",                    
                    "C.id_cliente as CCLI, P.nombre as CLIENTE, ",
                    "C.id_trabajador as CVEN, CONCAT(V.apellido_paterno, ' ', V.apellido_materno, ' ',V.nombre) as VENDEDOR, ",
                    "C.id_ruta as CRUT, R.nombre as RUTA, ",
                    "C.id_lista as CLIS, L.nombre as LISTA, ",
                    "C.nro_pedido as PEDIDO, C.nro_guia as GUIA, "
                    "C.TOTAL, c.SALDO, ",
                    "date_format(C._date_create,'%d/%m/%Y %h:%i:%s %p') AS FECHA_CREADO, ",
                    "date_format(C._date_u