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

    return Dep.extend({

        contasCorrentesCollection: null,
/*
        setup: function () {
            // ... (código 'setup' permanece o mesmo)
            Dep.prototype.setup.call(this);   

            this.addDynamicButtons();

        },*/
    
        setup: function () {
            Dep.prototype.setup.call(this);

            this.wait(true);
            
            this.model.fetch().then(() => {

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

                this.wait(false);

            }).catch(e => {
                console.error(e);
                this.wait(false);
            });
            
            this.listenTo(this.model, 'change:cCInvestimentoNecessario', () => {
                this.alocacaoNecessaria = Number(this.model.get('cCInvestimentoNecessario')) || 0;
                this.addDynamicButtons();
            });
        },
        
        afterRender: function () {
            
            Dep.prototype.afterRender.call(this); 

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

            if(status == 'Nova'){
                document.querySelector('.side').style.display = 'none'
            }

            
        },
        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');


            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':
                    break;
                case 'Aprovação da Arte':
                    break;

                case 'Em compras':
                    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':
                    break;
                case 'Concluída':
                    break;
                case 'Cancelado':
                    break;

            }
        },
        
          //*****************//
         //   INIT AÇÃO     //
        //*****************//  

        actioniniciarAcao: function(){
            console.log("Entrei");
            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,
                        model: this.model,       
                    });

                    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")
            });
        },

          //*****************//
         //   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) {
                        
                    } 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);
        },

        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();
        },
        // Método executado ao clicar no botão
        actionAlocarInvestimento_bkp: 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{
                    // 1. Carrega as Contas Correntes e espera
                    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.
                    }
                    
                    // 2. Mapeia a coleção, extraindo nome e saldo.
                    const contasCorrentesData = this.contasCorrentesCollection.models.map(model => ({
                        id: model.id,
                        nome: model.get('name'),
                        saldo: model.get('saldo'),
                        tipoConta: model.get('cSoftTipoCC')
                    }));

                    // 3. Cria e renderiza o Modal, passando os dados
                    this.createView('dialog', 'custom:views/campaign/modals/alocar-investimentos', {
                        //id: this.model.id,
                        id: this.model.attributes.id,
                        title: this.model.get('name'),
                        saldoAcao: this.model.get('budget'), // Renomeei para evitar confusão com saldo da conta corrente
                        model: this.model,
                        // PASSANDO A LISTA DE CONTAS CORRENTES COM SALDOS
                        contasCorrentes: contasCorrentesData
                        
                    }, view => {
                        
                        view.render();

                        this.listenToOnce(view, 'done', async response => {
                            
                            this.model.fetch().then(async () => {

                                await this.model.fetch();
                                this.addDynamicButtons();

                                // Atualiza a tela sem sumir o botão
                                this.render();
                                this.model.trigger('sync');
                                Espo.Ui.notify('Atualizando dados...', 'loading');

                                const helper = this.getHelper();
                                const layoutManager = helper && helper.layoutManager;

                                if (layoutManager && typeof layoutManager.loadPanels === 'function') {
                                    //Usa o gerenciador global do layout
                                    layoutManager.loadPanels();
                                    Espo.Ui.success('Painéis recarregados com sucesso.');
                                } else {
                                    // Último fallback — força re-render da tela atual
                                    console.warn('Record.DetailView e LayoutManager não disponíveis — recarregando o registro.');
                                    const router = this.getRouter ? this.getRouter() : null;
                                    if (router) {
                                        router.navigate('#Campaign/view/' + this.model.id, { trigger: true });
                                    } else {
                                        this.reRender();
                                    }
                                }

                                Espo.Ui.notify(false);

                            });
                        })
                    });
                }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();
        }
    });
});