call spMante_Lista_Precios_Generar(1, 1, 'S', 'P', 50, 'Q', 1);

DROP PROCEDURE IF EXISTS spMante_Lista_Precios_Generar;
CREATE PROCEDURE spMante_Lista_Precios_Generar(
  varEmpresa  int,
  varLista    int,
  varOptPro   char(1),  /* T=Todos los productos  / S=Solo productos con Stock  */
  varMetCal   char(1),  /* U=Precio Ultima Compra / P=Precio Promedio de Compra */
  VarFactor   double,
  varOpcion   char(1),  /* Q=Consulta en Pantalla / P=Generar Procesos de Calculo */
  varUsuario  int
  )
BEGIN  
  DECLARE varSQL, varCadOpt TEXT default '';
  DECLARE varAnio, varMes varchar(4);
  
  select max(id_anio) as anio, max(id_mes) as mes
  into varAnio, varMes
  from _sv_precio_promedio_compra
  where id_anio = (select max(id_anio) from _sv_precio_promedio_compra);
  
  if varOptPro = 'S' then
    set varCadOpt = concat("and (select sum(cantidad) from _sv_kardex K where K.id_producto = P.id_producto and K.id_empresa = ", varEmpresa , ") > 0 ");
  end if;
 
  if varOpcion = 'Q' then  
    if varMetCal = "P" then
      SET @sql = CONCAT("SELECT A.CPRO, A.PRODUCTO, A.UM, A.STOCK, PPC, ",
                          "round(PPC/(1-", varFactor, "/100),5) AS PVL, ",
                          "A.STOCK*PPC AS TTC, A.STOCK*round(PPC/(1-", varFactor, "/100),5) AS TTV ",
                          "FROM ",
                          "( ",
                          "select PC.id_producto as CPRO, P.descripcion AS PRODUCTO, P.id_um_venta AS UM, ",
                          "(select sum(cantidad) from _sv_kardex K where K.id_producto = PC.id_producto and K.id_empresa =", varEmpresa, ") as STOCK, ",
                          "CASE WHEN F.operacion='*' THEN PC.precio/F.factor ELSE PC.precio*F.factor END AS PPC ",
                          "from _sv_precio_promedio_compra PC ",
                          "inner join _sv_producto P on PC.id_producto = P.id_producto ",
                          "left join _sv_factor_conv F on PC.id_um = F.id_um_origen and P.id_um_venta = F.id_um_destino ",
                          "where PC.id_anio  = '", varAnio, "' ",
                          "and PC.id_mes     = '", varMes, "' ",
                          "and PC.id_empresa = ", varEmpresa, " ",
                          varCadOpt,
                          ") A; ");
      else
        SET @sql = CONCAT("SELECT A.CPRO, A.PRODUCTO, A.UM, A.STOCK, PPC, ",
                        "round(PPC/(1-", varFactor, "/100),5) AS PVL, ",
                        "A.STOCK*PPC AS TTC, A.STOCK*round(PPC/(1-", varFactor, "/100),5) AS TTV ",
                        "FROM ",
                        "( ",
                        "select P.id_producto as CPRO, P.descripcion AS PRODUCTO, P.id_um_venta AS UM, ",
                        "(select sum(cantidad) from _sv_kardex K where K.id_producto = P.id_producto and K.id_empresa =", varEmpresa, ") as STOCK, ",
                        "CASE WHEN F.operacion='*' THEN P.precio_compra/F.factor ELSE P.precio_compra*F.factor END AS PPC ",
                        "from _sv_producto P ",
                        "left join _sv_factor_conv F on P.id_um_compra = F.id_um_origen and P.id_um_venta = F.id_um_destino ",
                        "where P._estado   = 'A' ",
                        varCadOpt,
                        ") A; ");
      end if;    
  else
    -- Eliminamos el contenido de la lista de precios
    delete from _sv_lista_producto where id_empresa = varEmpresa and id_lista = varLista;
    
    if varMetCal = "P" then
      SET @sql = CONCAT("insert into _sv_lista_producto ",
                        "SELECT ", varEmpresa, " as id_empresa, ", varLista, " as id_lista, A.id_producto, A.id_um_venta, ",
                        "round(PPC/(1-", varFactor, "/100),5) AS precio, NOW(), NOW(), ", varUsuario, ", ", varUsuario, ", 'A' ",
                        "FROM ",
                        "( ",
                        "select PC.id_producto, P.id_um_venta, ",
                        "CASE WHEN F.operacion='*' THEN PC.precio/F.factor ELSE PC.precio*F.factor END AS PPC ",
                        "from _sv_precio_promedio_compra PC ",
                        "inner join _sv_producto P on PC.id_producto = P.id_producto ",
                        "left join _sv_factor_conv F on PC.id_um = F.id_um_origen and P.id_um_venta = F.id_um_destino ",
                        "where PC.id_anio  = '", varAnio, "' ",
                        "and PC.id_mes     = '", varMes, "' ",
                        "and PC.id_empresa = ", varEmpresa, " ",
                        varCadOpt,
                        ") A; ");
    else
      SET @sql = CONCAT("insert into _sv_lista_producto ",
                        "SELECT ", varEmpresa, " as id_empresa, ", varLista, " as id_lista, A.id_producto, A.id_um_venta, ",
                        "round(PPC/(1-", varFactor, "/100),5) AS precio, NOW(), NOW(), ", varUsuario, ", ", varUsuario, ", 'A' ",
                        "FROM ",
                        "( ",
                        "select P.id_producto, P.id_um_venta, ",
                        "CASE WHEN F.operacion='*' THEN P.precio_compra/F.factor ELSE P.precio_compra*F.factor END AS PPC ",
                        "from _sv_producto P ",
                        "left join _sv_factor_conv F on P.id_um_compra = F.id_um_origen and P.id_um_venta = F.id_um_destino ",
                        "where P._estado = 'A' and P.precio_compra is not null ",
                        varCadOpt,
                        ") A; ");
    end if;
  end if;
  
  PREPARE s1 FROM @sql;
  EXECUTE s1;
  DEALLOCATE PREPARE s1; 
END;
