do $$
declare
    _item record;
    _list refcursor;
    _id_nf integer;
    _vl_max numeric;
    _vl_tot numeric;
    _id_nf_item integer;
    _id_cfop integer;
    _ver_val_max boolean;
begin
    _id_nf       := 1311;
    _vl_max      := 0;
    _vl_tot      := 0;
    _id_nf_item  := 1;
    _id_cfop     := 5928;
    _ver_val_max := false;
    
    delete from tb_nf_item where id_nf = _id_nf;
    
    open _list for
        select
            tb_item.id_item, tb_item.id_item, tb_item.descr, tb_item.id_ncm, 
            tb_item.id_und_med, tb_item.cd_bar, sum(tb_item_estq.vl_estq) * 5 as vl_estq, tb_item_emp.vl_prc_vnd
        from tb_item
        join tb_item_emp on
            (tb_item.id_item = tb_item_emp.id_item and
             tb_item_emp.id_emp = 1)
        join tb_item_estq on
            (tb_item.id_item = tb_item_estq.id_item and
             tb_item_estq.id_dep = 1)
        join tb_ncm on
            (tb_item.id_ncm = tb_ncm.id_ncm)
        where
            tb_item_estq.vl_estq > 0 and
            trim(coalesce(tb_item.id_ncm, '')) <> ''
        group by
            tb_item.id_item,
            tb_item_emp.id_item,
            tb_item_emp.id_emp
        order by id_item;
            
            
    fetch _list into _item;
        
    while found loop
        _vl_tot      := _vl_tot + (_item.vl_estq * _item.vl_prc_vnd);
        
        insert into tb_nf_item
            (id_emp, id_nf, id_nf_item, id_dep, id_item, descr_item, id_ncm, id_cfop, id_grd_estq,
             id_und_med_com, cd_bar_com, vl_qtd_com, vl_unt_com, 
             id_und_med_trib, cd_bar_trib, vl_qtd_trib, vl_unt_trib, 
             vl_seg, vl_desc, vl_frete, vl_out, vl_tot, mov_estq, tot_nf_item,
             id_grp_trib, id_trib_icms, id_trib_ipi, id_trib_pis, id_trib_cofins)
        values
            (1, _id_nf, _id_nf_item, 1, _item.id_item, _item.descr, _item.id_ncm, _id_cfop, '000',
             _item.id_und_med, '', _item.vl_estq, _item.vl_prc_vnd, 
             _item.id_und_med, '', _item.vl_estq, _item.vl_prc_vnd, 
             0, 0, 0, 0, _item.vl_estq * _item.vl_prc_vnd, false, true,
             1, '500', '99', '01', '01');
        
        _id_nf_item := _id_nf_item + 1;
        
        if (_vl_tot > _vl_max and _ver_val_max) then
            return;
        end if;
        
        fetch _list into _item;
            
    end loop;
        
end;
$$
