define('custom:views/campaign/record/detail',
        ['views/record/detail','collection-factory'],
        ['views/detail', 'custom:config/constants'],
        function (Dep, CollectionFactory, Constants) {

    return Dep.extend({

        contasCorrentesCollection: null,
        movimentacoesCollection: null,
    
        setup: function () {
            Dep.prototype.setup.call(this);

            this.wait(true);
            this.valorResidual = Number(this.model.get('cCValorResidual')) || 0;
            this.statusInicial = this.model.get('cNivel');

            this.model.fetch().then(() => {

                this.alocacaoNecessaria = Number(this.model.get('cCInvestimentoNecessario')) || 0;
                this.valorResidual = Number(this.model.get('cCValorResidual')) || 0;

                this.render();  // <— FORÇA NOVA RENDERIZAÇÃO COM OS VALORES CORRETOS

            }).finally(() => {
                this.addDynamicButtons();
                this.wait(false);
            });
            
            this.listenTo(this.model, 'change:cCInvestimentoNecessario', () => {
                this.alocacaoNecessaria = Number(this.model.get('cCInvestimentoNecessario')) || 0;
                this.valorResidual = Number(this.model.get('cCValorResidual')) || 0;
                this.addDynamicButtons();
            });
            
            if(Constants.ENABLE_REALOCACAO_AUTOMATICA){
                
                this.listenTo(this.model, 'change:cNivel', () => {
                    
                    this.statusAtual = this.model.get('cNivel')

                    if(this.statusAtual != this.statusInicial){
                        this.getRouter().navigate('#Campaign', { trigger: true });
                    }
                });
            }
        },
        
        afterRender: function () {
            
            Dep.prototype.afterRender.call(this); 

            
            const status = this.model.get('cNivel');

            if(status == 'Nova'){
                document.querySelector('.side').style.display = 'none'
                
            }else if(status == 'Aguardando Pagamento'){
                const el = document.querySelector('.control-label[data-name="cCInvestimentoNecessario"] .label-text');

                if(el){
                    if(this.valorResidual < 0){
                        el.textContent = "Realocação necessária";

                    }else if(this.valorResidual > 0){        
                        el.textContent = "Retorno necessário";

                    }
                }else{
                    console.warn("Não foi possivel encontrar o elemento 'cCInvestimentoNecessario'.");
                }
            }

            
        },
        addDynamicButtons: function () {
            
            const status = this.model.get('cNivel');
            

            this.removeButton('alocarInvestimento');
            this.removeButton('aprovarVerba');
            this.removeButton('reprovarVerba'); 

            this.removeButton('inserirDocumentacao');

            this.removeButton('aprovarBriefing');
            this.removeButton('reprovarBriefing');
            this.removeButton('ajustarBriefing');
            
            this.removeButton('iniciarAcao');
            
            this.removeButton('enviarArte');
            this.removeButton('aprovarArte');
            this.removeButton('reprovarArte');

            this.removeButton('compraFinalizada');

            this.removeButton('pagamentoRealizado');
            this.removeButton('realocarInvestimento');
            this.removeButton('retornarResidual');

            this.removeButton('aprovarDocumentacao');
            this.removeButton('reprovarDocumentacao');


            switch(status){

                case 'Nova':
                    
                    this.addButton({
                        name: 'iniciarAcao',
                        label: 'Iniciar Ação',
                        action: 'iniciarAcao',
                        style: 'success'
                    });

                    break;
                case 'Aprovação de Briefing':
                    this.addButton({
                        name: 'aprovarBriefing',
                        label: 'Aprovar Briefing',
                        action: 'aprovarBriefing',
                        style: 'success'
                    });

                    this.addButton({
                        name: 'reprovarBriefing',
                        label: 'Reprovar Briefing',
                        action: 'reprovarBriefing',
                        style: 'danger',
                        className: 'btn btn-danger'
                    });
                    break;
                case 'Ajuste de Briefing':

                    this.addButton({
                        name: 'ajustarBriefing',
                        label: 'Ajustar Briefing',
                        action: 'ajustarBriefing',
                        style: 'success'
                    });

                    break;
                case 'Aprovação de Verba':
                    
                    if(this.alocacaoNecessaria != null)
                    {
                        this.addButton({
                            name: 'alocarInvestimento',
                            label: 'Alocar Investimentos',
                            style: 'warning',
                            title: 'Clique para executar ação',
                            action: 'alocarInvestimento',
                            disabled: this.alocacaoNecessaria === 0
                        });

                        this.addButton({
                            name: 'aprovarVerba',
                            label: 'Aprovar Verba',
                            action: 'aprovarVerba',
                            style: 'success',
                            disabled: this.alocacaoNecessaria !== 0
                        });

                        this.addButton({
                            name: 'reprovarVerba',
                            label: 'Reprovar Verba',
                            action: 'reprovarVerba',
                            style: 'danger',
                            className: 'btn btn-danger',
                            disabled: this.alocacaoNecessaria !== 0
                        });

                    }
                    break;
                case 'Produção da Arte':                    
                        
                        this.addButton({
                            name: 'enviarArte',
                            label: 'Enviar Arte',
                            action: 'enviarArte',
                            style: 'success'
                        });

                    break;
                case 'Aprovação da Arte':
                    
                        this.addButton({
                            name: 'aprovarArte',
                            label: 'Aprovar Arte',
                            action: 'aprovarArte',
                            style: 'success'
                        });

                        this.addButton({
                            name: 'reprovarArte',
                            label: 'Reprovar Arte',
                            action: 'reprovarArte',
                            style: 'danger',
                            className: 'btn btn-danger'
                        });
                    break;
                case 'Em compras':
                        this.addButton({
                            name: 'compraFinalizada',
                            label: 'Compra finalizada',
                            action: 'compraFinalizada',
                            style: 'success'
                        });
                    break;
                case 'Em transporte':
                    break;
                case 'Aguardando Documentação':

                    this.addButton({
                        name: 'inserirDocumentacao',
                        label: 'Inserir Documentação',
                        action: 'inserirDocumentacao',
                        style: 'success'
                    });

                    break;
                case 'Aprovação da documentação':
                    this.addButton({
                        name: 'aprovarDocumentacao',
                        label: 'Aprovar Documentação',
                        action: 'aprovarDocumentacao',
                        style: 'success'
                    });

                    this.addButton({
                        name: 'reprovarDocumentacao',
                        label: 'Reprovar Documentação',
                        action: 'reprovarDocumentacao',
                        style: 'danger',
                        className: 'btn btn-danger'
                    });
                    break;
                case 'Aguardando Pagamento':

                        this.addButton({
                            name: 'pagamentoRealizado',
                            label: 'Pagamento Realizado',
                            style: 'success',
                            action: 'pagamentoRealizado',
                            disabled: this.valorResidual !== 0
                        });

                        this.addButton({
                            name: 'realocarInvestimento',
                            label: 'Realocar investimento',
                            action: 'realocarInvestimento',
                            style: 'warning',
                            disabled: this.valorResidual >= 0
                        });

                        this.addButton({
                            name: 'retornarResidual',
                            label: 'Retornar Residual',
                            action: 'retornarResidual',
                            style: 'danger',
                            className: 'btn btn-danger',
                            disabled: this.valorResidual <= 0
                        });
                    break;
                case 'Concluída':
                    break;
                case 'Cancelado':
                    break;

            }
        },
        
          //*****************//
         //       COMPRA    //
        //*****************//  

        actionCompraFinalizada: function(){

            const arquivos_compra_size = this.options.model.attributes.cCArquivosCompraIds.length;

            if(arquivos_compra_size == 0){
                    Espo.Ui.error('Nenhum Arquivo(s) da compra em anexo. Por favor verificar.');
            }else{
                try{
                                
                    this.createView('dialog', 'custom:views/campaign/modals/finalizar-compra', {
                        title: this.model.get('name'),
                        valor_alocado: this.model.get('cCValorAlocado'),  
                        valor_acao: this.model.get('budget'),
                        id_acao: this.options.model.attributes.id,
                        arquivos_ids: this.options.model.attributes.cCArquivosCompraIds, 
                        arquivos_name: this.options.model.attributes.cCArquivosCompraNames,  

                    }, view => {
                        
                        view.render();

                        this.listenToOnce(view, 'done', async response => {

                            if(response.success){
                                Espo.Ui.success(response.mensagem);
                                
                                try {
                                    
                                    await this.model.fetch();
                                    this.addDynamicButtons();

                                    // Atualiza a tela sem sumir o botão
                                    this.render();
                                    this.model.trigger('sync');

                                } catch (error) {
                                    Espo.Ui.error('Erro ao atualizar dados: ' + error.message);
                                }
                            }else{                        
                                Espo.Ui.notify(false);
                                Espo.Ui.error('Erro ao trocar de status');
                            }

                        })
                    });
                }catch(error){
                    console.error('Erro ao carregar ou exibir o modal:', error);
                    Espo.Ui.error('Falha ao carregar dados. Verifique a conexão ou logs do servidor.');
                }
                  /*          
                Espo.Ui.confirm('Deseja finalziar a compra?', {
                    title: 'Confirmação',
                    confirmText: 'Sim',
                    cancelText: 'Não'               
                    
                }).then(async () => {
                    
                        try {
                            const response = await Espo.Ajax.postRequest('Compra/action/finalizarCompra', {
                                acao_id:  this.options.model.attributes.id,
                                arquivos_ids: this.options.model.attributes.cCArquivosCompraIds, 
                                arquivos_name: this.options.model.attributes.cCArquivosCompraNames,                 
                            });

                            if (response.success) {
                                Espo.Ui.success(response.mensagem);
                                this.trigger('done', response);
                                await this.model.fetch();
                                this.addDynamicButtons();

                                // Atualiza a tela sem sumir o botão
                                this.render();
                                this.model.trigger('sync');
                            } else {
                                
                                Espo.Ui.notify(false);
                                Espo.Ui.error('Erro iniciar a ação');
                            }
                        } catch (e) {
                            Espo.Ui.error('Falha na comunicação com o servidor');
                            console.error(e);
                        }
                        
                    }).catch(() => {
                        console.log("Erro ao executar troca de status")
                    });
                    
                    
                    // Aguarda o modal renderizar e muda as cores dos botões
                    setTimeout(() => {
                        // botão "Sim"
                        const $confirm = $('.modal-footer [data-name="confirm"], .modal-footer .btn-primary');
                        $confirm.removeClass('btn-danger btn-primary').addClass('btn-success');

                    }, 4);
                    */
            }

        },

          //*****************//
         //       ARTE      //
        //*****************//  

        actionEnviarArte: function(){

            const arquivos_artes_size = this.options.model.attributes.cArquivosIds.length;

            if(arquivos_artes_size == 0){
                    Espo.Ui.error('Nenhum Arquivo(s) de arte em anexo. Por favor verificar.');
            }else{
                            
                Espo.Ui.confirm('Deseja enviar a arte?', {
                    title: 'Confirmação',
                    confirmText: 'Sim',
                    cancelText: 'Não'               
                    
                }).then(async () => {
                    
                        try {
                            const response = await Espo.Ajax.postRequest('Arte/action/enviarArte', {
                                acao_id:  this.options.model.attributes.id,
                                arquivos_ids: this.options.model.attributes.cArquivosIds, 
                                arquivos_name: this.options.model.attributes.cArquivosNames,                 
                            });

                            if (response.success) {
                                Espo.Ui.success(response.mensagem);
                                this.trigger('done', response);
                                await this.model.fetch();
                                this.addDynamicButtons();

                                // Atualiza a tela sem sumir o botão
                                this.render();
                                this.model.trigger('sync');
                            } else {
                                
                                Espo.Ui.notify(false);
                                Espo.Ui.error('Erro iniciar a ação');
                            }
                        } catch (e) {
                            Espo.Ui.error('Falha na comunicação com o servidor');
                            console.error(e);
                        }
                        
                    }).catch(() => {
                        console.log("Erro ao executar troca de status")
                    });
                    
                    
                    // Aguarda o modal renderizar e muda as cores dos botões
                    setTimeout(() => {
                        // botão "Sim"
                        const $confirm = $('.modal-footer [data-name="confirm"], .modal-footer .btn-primary');
                        $confirm.removeClass('btn-danger btn-primary').addClass('btn-success');

                    }, 4);
            }

        },
   
        actionAprovarArte: function () {
            Espo.Ui.confirm('Deseja realmente Aprovar a Arte?', {
                title: 'Confirmação',
                confirmText: 'Sim',
                cancelText: 'Não'               
                
            }).then(async () => {
                
                try {
                    const response = await Espo.Ajax.postRequest('Arte/action/aprovar', {
                        acao_id:  this.options.model.attributes.id
                    });

                    if (response.success) {
                        Espo.Ui.success(response.mensagem);
                        this.trigger('done', response);
                        await this.model.fetch();
                        this.addDynamicButtons();

                        // Atualiza a tela sem sumir o botão
                        this.render();
                        this.model.trigger('sync');
                    } else {
                        
                        Espo.Ui.notify(false);
                        Espo.Ui.error('Erro ao trocar de status');
                    }
                } catch (e) {
                    Espo.Ui.error('Falha na comunicação com o servidor');
                    console.error(e);
                }
                
            }).catch(() => {
                console.log("Erro ao executar troca de status")
            });
            
            // Aguarda o modal renderizar e muda as cores dos botões
            setTimeout(() => {
                // botão "Sim"
                const $confirm = $('.modal-footer [data-name="confirm"], .modal-footer .btn-primary');
                $confirm.removeClass('btn-danger btn-primary').addClass('btn-success');

                $('.modal-body').html('Deseja realmente <b>Aprovar a Arte</b>?');

            }, 4);
        },

        actionReprovarArte: async function() {

            try{
                            
                this.createView('dialog', 'custom:views/campaign/modals/validar-acao', {
                    title: this.model.get('name'),
                    ajustar_button: 'Reprovar Arte',
                    model: this.model,                        
                }, view => {
                    
                    view.render();

                    this.listenToOnce(view, 'done', async response => {
                        
                        if (response.success) {
                            Espo.Ui.success(response.mensagem);
                            Espo.Ui.success(response.mensagem);
                            this.trigger('done', response);
                            await this.model.fetch();
                            this.addDynamicButtons();

                            // Atualiza a tela sem sumir o botão
                            this.render();
                            this.model.trigger('sync');
                        } else {
                            
                            Espo.Ui.notify(false);
                            Espo.Ui.error('Erro reprovar Arte.');
                        }
                    })
                });
            }catch(error){
                console.error('Erro ao carregar ou exibir o modal:', error);
                Espo.Ui.error('Falha ao carregar dados. Verifique a conexão ou logs do servidor.');
            }
            
        },
          //*****************//
         //   INIT AÇÃO     //
        //*****************//  

        actionIniciarAcao: function(){
            
            Espo.Ui.confirm('Deseja dar inicio a essa ação?', {
                title: 'Confirmação',
                confirmText: 'Sim',
                cancelText: 'Não'               
                
            }).then(async () => {
                
                try {
                    const response = await Espo.Ajax.postRequest('Acao/action/iniciar', {
                        acao_id:  this.options.model.attributes.id,
                        logged_user: this.getUser().attributes.id    
                    });

                    if (response.success) {
                        Espo.Ui.success(response.mensagem);
                        this.trigger('done', response);
                        await this.model.fetch();
                        this.addDynamicButtons();

                        // Atualiza a tela sem sumir o botão
                        this.render();
                        this.model.trigger('sync');
                    } else {
                        
                        Espo.Ui.notify(false);
                        Espo.Ui.error('Erro iniciar a ação');
                    }
                } catch (e) {
                    Espo.Ui.error('Falha na comunicação com o servidor');
                    console.error(e);
                }
                
            }).catch(() => {
                console.log("Erro ao executar troca de status")
            });
            
            
            // Aguarda o modal renderizar e muda as cores dos botões
            setTimeout(() => {
                // botão "Sim"
                const $confirm = $('.modal-footer [data-name="confirm"], .modal-footer .btn-primary');
                $confirm.removeClass('btn-danger btn-primary').addClass('btn-success');

            }, 4);
        },

          //*****************//
         //   DOCUMENTAÇÃO  //
        //*****************//       
     
        actionInserirDocumentacao: async function() {

            try{
                            
                this.createView('dialog', 'custom:views/campaign/modals/inserir-docs', {
                    title: this.model.get('name'),
                    ajustar_button: 'Enviar documentação',
                    model: this.model,                        
                }, view => {
                    
                    view.render();

                    this.listenToOnce(view, 'done', async response => {

                        if(response.success){
                            Espo.Ui.success(response.mensagem);
                            
                            try {
                                
                                await this.model.fetch();
                                this.addDynamicButtons();

                                // Atualiza a tela sem sumir o botão
                                this.render();
                                this.model.trigger('sync');

                            } catch (error) {
                                Espo.Ui.error('Erro ao atualizar dados: ' + error.message);
                            }
                        }else{                        
                            Espo.Ui.notify(false);
                            Espo.Ui.error('Erro ao trocar de status');
                        }

                    })
                });
            }catch(error){
                console.error('Erro ao carregar ou exibir o modal:', error);
                Espo.Ui.error('Falha ao carregar dados. Verifique a conexão ou logs do servidor.');
            }
            
        },
          //*****************//
         //   BREAFING      //
        //*****************//

        actionAprovarBriefing: function () {
            Espo.Ui.confirm('Deseja realmente Aprovar o Briefing?', {
                title: 'Confirmação',
                confirmText: 'Sim',
                cancelText: 'Não'               
                
            }).then(async () => {
                
                try {
                    const response = await Espo.Ajax.postRequest('Briefing/action/aprovar', {
                        acao_id:  this.options.model.attributes.id
                    });

                    if (response.success) {
                        Espo.Ui.success(response.mensagem);
                        this.trigger('done', response);
                        await this.model.fetch();
                        this.addDynamicButtons();

                        // Atualiza a tela sem sumir o botão
                        this.render();
                        this.model.trigger('sync');
                    } else {
                        
                        Espo.Ui.notify(false);
                        Espo.Ui.error('Erro ao trocar de status');
                    }
                } catch (e) {
                    Espo.Ui.error('Falha na comunicação com o servidor');
                    console.error(e);
                }
                
            }).catch(() => {
                console.log("Erro ao executar troca de status")
            });
            
            // Aguarda o modal renderizar e muda as cores dos botões
            setTimeout(() => {
                // botão "Sim"
                const $confirm = $('.modal-footer [data-name="confirm"], .modal-footer .btn-primary');
                $confirm.removeClass('btn-danger btn-primary').addClass('btn-success');

                $('.modal-body').html('Deseja realmente <b>Aprovar o Briefing</b>?');

            }, 4);
        },
     
        actionReprovarBriefing: async function() {

            try{
                            
                this.createView('dialog', 'custom:views/campaign/modals/validar-acao', {
                    title: this.model.get('name'),
                    ajustar_button: 'Reprovar Briefing',
                    model: this.model,                        
                }, view => {
                    
                    view.render();

                    this.listenToOnce(view, 'done', async response => {
                        Espo.Ui.success(response.mensagem);
                        
                        try {
                            
                            await this.model.fetch();
                            this.addDynamicButtons();

                            // Atualiza a tela sem sumir o botão
                            this.render();
                            this.model.trigger('sync');

                        } catch (error) {
                            Espo.Ui.error('Erro ao atualizar dados: ' + error.message);
                        }

                    })
                });
            }catch(error){
                console.error('Erro ao carregar ou exibir o modal:', error);
                Espo.Ui.error('Falha ao carregar dados. Verifique a conexão ou logs do servidor.');
            }
            
        },

        actionAjustarBriefing: async function() {

            try{
                            
                this.createView('dialog', 'custom:views/campaign/modals/ajustar-acao', {
                    title: this.model.get('name'),
                    ajustar_button: 'Ajustar Briefing',
                    obs_field: 'Briefing atualizado',
                    model: this.model,       
                }, view => {
                    
                    view.render();

                    this.listenToOnce(view, 'done', async response => {
                        Espo.Ui.success(response.mensagem);
                        
                        try {
                            
                            await this.model.fetch();
                            this.addDynamicButtons();

                            // Atualiza a tela sem sumir o botão
                            this.render();
                            this.model.trigger('sync');

                        } catch (error) {
                            Espo.Ui.error('Erro ao atualizar dados: ' + error.message);
                        }

                    })
                });
            }catch(error){
                console.error('Erro ao carregar ou exibir o modal:', error);
                Espo.Ui.error('Falha ao carregar dados. Verifique a conexão ou logs do servidor.');
            }

        },

          //*****************//
         //   VERBA         //
        //*****************//

        actionAprovarVerba: function () {
            Espo.Ui.confirm('Deseja realmente Aprovar a Verba?', {
                title: 'Confirmação',
                confirmText: 'Sim',
                cancelText: 'Não'               
                
            }).then(async () => {
                
                try {
                    const response = await Espo.Ajax.postRequest('Verba/action/aprovar', {
                        acao_id:  this.options.model.attributes.id
                    });

                    if (response.success) {
                        Espo.Ui.success(response.mensagem);
                        this.trigger('done', response);
                        await this.model.fetch();
                        this.addDynamicButtons();

                        // Atualiza a tela sem sumir o botão
                        this.render();
                        this.model.trigger('sync');
                        
                    } else {
                        
                        Espo.Ui.notify(false);
                        Espo.Ui.error('Erro ao trocar de status');
                    }
                } catch (e) {
                    Espo.Ui.error('Falha na comunicação com o servidor');
                    console.error(e);
                }
                
            }).catch(() => {
                console.log("Erro ao executar troca de status")
            });
            
            // Aguarda o modal renderizar e muda as cores dos botões
            setTimeout(() => {
                // botão "Sim"
                const $confirm = $('.modal-footer [data-name="confirm"], .modal-footer .btn-primary');
                $confirm.removeClass('btn-danger btn-primary').addClass('btn-success');

                $('.modal-body').html('Deseja realmente <b>Aprovar a Verba</b>?');

            }, 4);
        },

        actionReprovarVerba: async function() {

            try{
                            
                this.createView('dialog', 'custom:views/campaign/modals/validar-acao', {
                    title: this.model.get('name'),
                    ajustar_button: 'Reprovar Verba',
                    model: this.model,                        
                }, view => {
                    
                    view.render();

                    this.listenToOnce(view, 'done', async response => {
                        Espo.Ui.success(response.mensagem);
                        
                        try {
                            
                            await this.model.fetch();
                            this.addDynamicButtons();

                            // Atualiza a tela sem sumir o botão
                            this.render();
                            this.model.trigger('sync');

                        } catch (error) {
                            Espo.Ui.error('Erro ao atualizar dados: ' + error.message);
                        }

                    })
                });
            }catch(error){
                console.error('Erro ao carregar ou exibir o modal:', error);
                Espo.Ui.error('Falha ao carregar dados. Verifique a conexão ou logs do servidor.');
            }
            
        },    
          //*****************//
         //  ALOCAR INVEST. //
        //*****************//

        // MÉTODO: Carrega a Coleção de Contas Correntes
        loadContasCorrentes: async function (redeId) {
            
            const entidadeContaCorrente = 'CCSoftContaCorrente'; 
            const nomeDoCampoLinkNaCC = 'account1Id';
            const gerenteMarketingId = '69153397dbca472c9';
            
            if (!this.contasCorrentesCollection) {
                //this.contasCorrentesCollection = this.getCollectionFactory().create(entidadeContaCorrente);
                this.contasCorrentesCollection = await this.getCollectionFactory().create(entidadeContaCorrente);
            }

            if (typeof this.contasCorrentesCollection.fetch !== 'function') {
                 throw new Error("A Coleção não possui o método fetch.");
            }

            const options = {
                where: [
                    {
                        type: 'equals',
                        field: nomeDoCampoLinkNaCC,   // ajuste se o nome real for outro
                        value: [redeId, gerenteMarketingId]
                    }
                ],
                select: ['id', 'name', 'saldo']
            };

            const promise = await this.contasCorrentesCollection.fetch(options);
            
            return promise;
        },

        // Método executado ao clicar no botão
        actionAlocarInvestimento: function () {
            
            const fetchAndCreateView = async () => {
                
                const redeId = this.model.get('cCCRedeAcaoId');
                
                if (!redeId) {
                    Espo.Ui.error('Nenhuma Rede associada a esta Ação. Por favor, vincule uma Rede para continuar.');
                    return;
                }

                try{
                    
                    await this.loadContasCorrentes(redeId); 
                    
                    if (!this.contasCorrentesCollection || this.contasCorrentesCollection.length === 0) {
                        Espo.Ui.error('Nenhuma Conta Corrente foi encontrada para a Rede vinculada.');
                        // Não retorna, permitindo que o modal abra, mas com a lista vazia.
                    }
                    
                    const contasCorrentesData = this.contasCorrentesCollection.models.map(model => ({
                        id: model.id,
                        nome: model.get('name'),
                        saldo: model.get('saldo'),
                        tipoConta: model.get('cSoftTipoCC')
                    }));

                    if(contasCorrentesData.length < 3)
                    {
                        throw new Error('Rede sem contas correntes suficiencias vinculadas.');
                    }

                    this.createView('dialog', 'custom:views/campaign/modals/alocar-investimentos', {
                        id: this.model.attributes.id,
                        title: this.model.get('name'),
                        saldoAcao: this.model.get('budget'),
                        model: this.model,
                        contasCorrentes: contasCorrentesData
                        
                    }, view => {
                        
                        view.render();

                        this.listenToOnce(view, 'done', async response => {
                                                     
                            
                            this.model.fetch().then(() => {
                                this.addDynamicButtons();
                                // Força recarregamento de TODAS as child views (bottom, side, relationships)
                                this.getParentView().reRender();   
                                
                                const movimentacoesView = this.getView('bottom')?.getView('cCMovimentacaos');
                                if (movimentacoesView) {
                                    movimentacoesView.collection.fetch();
                                }
                                
                                Espo.Ui.notify(false);
                            }).catch(e => {
                                Espo.Ui.notify(false);
                                Espo.Ui.error('Erro ao atualizar o saldo.');
                                console.error(e);
                            });  

                        })
                    });
                }catch(error){
                    console.error('Erro ao carregar ou exibir o modal:', error);
                    Espo.Ui.error('Falha ao carregar dados das contas correntes. Verifique a conexão ou logs do servidor.');
                }
            };

            fetchAndCreateView();
        },

          //*****************//
         // AGUARDANDO PAG. //
        //*****************//
        
        // MÉTODO: Carrega a Coleção de Contas Correntes
        loadMovimentacoes: async function (acaoId) {
            
            const entidadeMovimentacao = 'CCMovimentacao'; // ajuste se o nome real for outro
            const campoLinkCampaignId = 'campaignId';
            
            if (!this.movimentacoesCollection) {
                this.movimentacoesCollection = await this
                    .getCollectionFactory()
                    .create(entidadeMovimentacao);
            }

            if (typeof this.movimentacoesCollection.fetch !== 'function') {
                throw new Error('A coleção não possui o método fetch.');
            }

            const options = {
                where: [
                    {
                        type: 'equals',
                        field: campoLinkCampaignId,
                        value: acaoId
                    }
                ],
                select: [
                    'id',
                    'valor',
                    'cSoftTipoVerba',
                    'campaignId',
                    'softContaCorrente'
                ],
                orderBy: 'cSoftTipoVerba',
            };

            await this.movimentacoesCollection.fetch(options);

            return this.movimentacoesCollection;
        },

        actionRealocarInvestimento: async function () {

            const redeId = this.model.get('cCCRedeAcaoId');

            // Validação inicial
            if (!redeId) {
                Espo.Ui.error('Nenhuma Rede associada a esta Ação. Por favor, vincule uma Rede para continuar.');
                return;
            }

            try {
                // Loading UI
                Espo.Ui.notify('Carregando...', true);

                // 1) Carrega contas correntes
                await this.loadContasCorrentes(redeId);

                const collection = this.contasCorrentesCollection || [];
                const contasCorrentesData = collection.models.map(m => ({
                    id: m.id,
                    nome: m.get('name'),
                    saldo: m.get('saldo'),
                    tipoConta: m.get('cSoftTipoCC')
                }));

                // Validação mínima
                if (contasCorrentesData.length === 0) {
                    Espo.Ui.error('Nenhuma Conta Corrente foi encontrada para a Rede vinculada.');
                }

                if (contasCorrentesData.length < 3) {
                    throw new Error('Rede sem contas correntes suficientes vinculadas.');
                }

                Espo.Ui.notify(false);
                // 2) Cria e renderiza o modal
                const view = await this.createView(
                    'dialog',
                    'custom:views/campaign/modals/realocar-investimento',
                    {
                        id: this.model.id,
                        title: this.model.get('name'),
                        valorResidual: this.model.get('cCValorResidual'),
                        model: this.model,
                        contasCorrentes: contasCorrentesData
                    }
                );

                view.render();

                // 3) Aguarda retorno do modal
                this.listenToOnce(view, 'done', async () => {             
                        
                    this.model.fetch().then(() => {
                        //this.addDynamicButtons();
                        // Força recarregamento de TODAS as child views (bottom, side, relationships)
                        this.getParentView().reRender();   
                        
                        const movimentacoesView = this.getView('bottom')?.getView('cCMovimentacaos');
                        if (movimentacoesView) {
                            movimentacoesView.collection.fetch();
                        }
                        
                        Espo.Ui.notify(false);
                    }).catch(e => {
                        Espo.Ui.notify(false);
                        Espo.Ui.error('Erro ao atualizar o saldo.');
                        console.error(e);
                    });  
                });

            } catch (error) {
                console.error('Erro ao carregar ou exibir o modal:', error);
                Espo.Ui.error('Falha ao carregar dados das contas correntes. Verifique a conexão ou logs do servidor.');
                Espo.Ui.notify(false);
            }
        },
        
        actionRetornarResidual: async function () {

            const acaoId = this.model.get('id')

            try {
                // Loading UI
                Espo.Ui.notify('Carregando...', true);

                // 1) Carrega contas correntes
                await this.loadMovimentacoes(acaoId);

                const collection = this.movimentacoesCollection || [];
                const movimentacoesData = collection.models.map(m => ({
                    id: m.id,
                    valor: m.get('cSoftValor'),
                    cSoftTipoVerba: m.get('cSoftTipoVerba'), //Gerente, AM, AO
                    cSoftTipo: m.get('cSoftTipo'), //Debito, credito
                    softContaCorrenteId: m.get('softContaCorrenteId')
                }));

                // Validação mínima
                if (movimentacoesData.length === 0) {
                    Espo.Ui.error('Nenhuma movimentação foi encontrada para essa ação.');
                }

                const totaisPorConta  = {};

                movimentacoesData.forEach(model => {
                    const contaId = model.softContaCorrenteId;
                    const valor = parseFloat(model.valor) || 0;
                    const cSoftTipoVerba = model.cSoftTipoVerba;
                    const cSoftTipo = model.cSoftTipo;

                    if (!contaId) {
                        return; // ignora movimentações sem conta vinculada
                    }

                    if (!totaisPorConta[cSoftTipoVerba]) {
                        totaisPorConta[cSoftTipoVerba] = {
                            id: contaId,
                            total: 0
                        };
                    }

                    if(cSoftTipo == 'Crédito'){
                        totaisPorConta[cSoftTipoVerba].total -= valor;

                    }else if(cSoftTipo == 'Débito'){
                        totaisPorConta[cSoftTipoVerba].total += valor;
                    }
                });


                Espo.Ui.notify(false);
                // 2) Cria e renderiza o modal
                const view = await this.createView(
                    'dialog',
                    'custom:views/campaign/modals/retornar-investimento',
                    {
                        id: this.model.id,
                        title: this.model.get('name'),
                        valorResidual: this.model.get('cCValorResidual'),
                        movimentacoesData: totaisPorConta
                    }
                );

                view.render();

                // 3) Aguarda retorno do modal
                this.listenToOnce(view, 'done', async () => {             
                        
                    this.model.fetch().then(() => {
                        //this.addDynamicButtons();
                        // Força recarregamento de TODAS as child views (bottom, side, relationships)
                        this.getParentView().reRender();   
                        
                        const movimentacoesView = this.getView('bottom')?.getView('cCMovimentacaos');
                        if (movimentacoesView) {
                            movimentacoesView.collection.fetch();
                        }
                        
                        Espo.Ui.notify(false);
                    }).catch(e => {
                        Espo.Ui.notify(false);
                        Espo.Ui.error('Erro ao atualizar o saldo.');
                        console.error(e);
                    });  
                });

            } catch (error) {
                console.error('Erro ao carregar ou exibir o modal:', error);
                Espo.Ui.error('Falha ao carregar dados das contas correntes. Verifique a conexão ou logs do servidor.');
                Espo.Ui.notify(false);
            }
        }
    });
});