use db_sisgesint_sc;

call spQuery_Registro_Pedidos(1, NULL, NULL, NULL,  '2011-11-15',null, 'IN', NULL, NULL);

DROP PROCEDURE IF EXISTS spQuery_Registro_Pedidos;
CREATE PROCEDURE spQuery_Registro_Pedidos( 
  varEmpresa  int,
	varVendedor int,
  varCliente  int,
  varRuta     varchar(10),
	varFechaIni date,
	varFechaFin date,
  varEstado   varchar(2),
  varField    varchar(60),
  varOrder    varchar(5)
  )
BEGIN  
  DECLARE varCadFechaIni, varCadFechaFin, varCadCliente, varCadVendedor, varCadRut TEXT DEFAULT '';
  DECLARE varCadOrd TEXT DEFAULT '';
  
  IF IFNULL(varCliente,0) <> 0 THEN
    SET varCadCliente = CONCAT(" and C.id_cliente = ", varCliente, " ");  
  END IF;
  
  IF IFNULL(varVendedor,0) <> 0 THEN
    SET varCadVendedor = CONCAT(" and C.id_trabajador = ", varVendedor, " ");  
  END IF;
  
  IF varRuta <> '' and varRuta is not null THEN
    SET varCadRut = CONCAT(" and C.id_ruta = '", varRuta, "' ");  
  END IF;
  
  IF varFechaIni IS NOT NULL THEN
    SET varCadFechaIni = CONCAT(" and C.fecha_pedido >= '", varFechaIni, "' ");
  END IF;
  
  IF varFechaFin IS NOT NULL THEN
    SET varCadFechaFin = CONCAT(" and C.fecha_pedido <= '", 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_pedido as IDE, date_format(C.fecha_pedido,'%d/%m/%Y') AS FECHA, ",
                    "C.id_tipo_doc as CTIP, T.nombre as TIPODOC, ",
                    "C.id_condicion as CCON, TC.nombre as CONDICION, ",
                    "CASE WHEN C.estado='AN' THEN 'ANULADO'   ",
                    "     WHEN C.estado='IN' THEN 'INGRESADO' ",
                    "     WHEN C.estado='FA' THEN 'FACTURADO' ",
                    "END AS ESTADO, ",                                   
                    "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, ",
                    "P.id_ruta as CRUT, R.nombre as RUTA, ", 
                    "C.id_lista as CLIS, L.nombre as LISTA, ",
                    "C.nro_pedido as PEDIDO, "
                    "C.TOTAL, ",
                    "date_format(C._date_create,'%d/%m/%Y %h:%i:%s %p') AS FECHA_CREADO, ",
                    "date_format(C._date_update,'%d/%m/%Y %h:%i:%s %p') AS FECHA_MODIFI, ",
                    "UPPER(UN.usuario) as USE