--
-- Finaliza outras conexoes ao banco de dados
--
select pg_terminate_backend(pg_stat_activity.pid)
from pg_stat_activity
where
    pg_stat_activity.pid <> pg_backend_pid();

select fc_en_trg(false, false);

do $$
declare
    _list refcursor;
    _item record;
    _vl_cst_med numeric;
    _vl_qtd numeric;
begin
    
    
    open _list for
        select 
            tb_nf.dt_emis,
            tb_nf.dt_op,
            tb_nf_item.id_item,
            tb_nf_item.vl_qtd_mov,
            tb_nf_item.vl_tot,
            tb_nf_item.vl_tot / tb_nf_item.vl_qtd_mov as vl_cst_rep
        from tb_nf_item
        join tb_nf on
            (tb_nf.id_emp = tb_nf_item.id_emp and
             tb_nf.id_nf = tb_nf_item.id_nf)
        where
            tb_nf.tp_emis = '[T]' and
            -- tb_nf.dt_emis >= '2020-09-01' and
            tb_nf_item.id_item in (1,2)
        order by
            tb_nf.dt_op;
            
    _vl_cst_med := 0;
      
    fetch _list into _item;
    
    while found loop
    
        if (_vl_cst_med = 0) then
            _vl_cst_med := _item.vl_cst_rep;
        else
            _vl_cst_med := (_vl_cst_med + _item.vl_cst_rep) / 2;
        end if;
        
        raise notice '% % Medio: % Reposicao: %', _item.dt_op, _item.vl_qtd_mov, _vl_cst_med, _item.vl_cst_rep;
        
        
        update tb_vnd_item set
            vl_cst_med = _vl_cst_med
        where
            id_item = _item.id_item and
            exists (select 1
                    from tb_vnd
                    where
                        tb_vnd.dt_vnd >= _item.dt_op and
                        tb_vnd.id_vnd = tb_vnd_item.id_vnd);
                                    
    
    
        fetch _list into _item;
        
    end loop;
    
    
end;
$$;

commit;

select fc_en_trg(true, true);