Untitled

mail@pastecode.io avatar
unknown
plain_text
5 months ago
62 kB
2
Indexable
({
    onInit: function(cmp, event, helper) {
    /*
        *Nao fazer query da cotação nesse componente ou inferiores!
            Se precisa que algo rode apos a cotação carregar, use os métodos: "runAfter" e cmp.get('v...').
            Se precisa fazer a quote ou outros serem recarregados, use os método: helper.dispatchEventRe...
    */

        window.addEventListener("keydown", function(event) {
            if (event.code === 'Escape') {
                cmp.set("v.isOpen", false);
            }
        }, true);

        helper.getPesoTotals(cmp, event, helper);
        // helper.recalculateDiscount(cmp, event, helper); //?removido pois ja roda ao avançar da terceira para a segunda tela
        helper.getFieldsCreditAnalysis(cmp, event, helper); 
        helper.getAcceptTerms(cmp, event, helper);
        helper.getFinancingPayment(cmp, event, helper);
        helper.getProfileName(cmp);
    },

    runAfterReloadQuote: function(cmp, event, helper){
        helper.getCanShowEsteira(cmp, event, helper); 
        helper.getDateAnalise(cmp, event, helper);
        helper.getRawQuoteDataForPromotionValidation(cmp, event, helper); 
        helper.hasShippingFee(cmp, event, helper); 
        helper.runAfterReloadQuoteData(cmp, event, helper);

        var childComponentPy = cmp.find("PaymentMethodList");
        
        if(Array.isArray(childComponentPy))
        	childComponentPy[0].runAfterReloadQuote(cmp, event, helper);
       	else  
            childComponentPy.runAfterReloadQuote(cmp, event, helper);

    },

    runAfterReloadBothQuoteAndProducts: function(cmp, event, helper){
        helper.runAfterReloadBothQuoteAndProducts(cmp, event, helper)
    },

    runAfterReloadDiscountCalculations: function(cmp, event, helper){
        helper.setProducts(cmp, event, helper); 
    },

    handleDescontoEspecificador: function(cmp, event, helper) {
        let descontoEspecificadorAtivado = cmp.get('v.descontoEspecificadorAtivado');

        helper.changeSpecifierDiscountPermission(cmp, event, helper, !descontoEspecificadorAtivado);
        cmp.set('v.descontoEspecificadorAtivado', !descontoEspecificadorAtivado);
    },

    handleConfirmDialog: function(component, event, helper) {
        component.set('v.showConfirmDialog', true);
    },

    handleErrorMessageConfirm: function(component, event, helper) {
        component.find("cupom_voucher").set("v.value", '');
        component.set('v.showAlertDialog', false);
    },

    handlerVoucherNotApplicable: function(component, event, helper) {
        component.find("cupom_voucher").set("v.value", '');
        component.set('v.showAlertNotApplicable', false);
    },

    handleConfirmDialogYes: function(component, event, helper) {
        component.set('v.showConfirmDialog', false);
        let removeQuoteReferenceFromCodigosPromocionais = component.get('c.removeQuoteReferenceFromCodigosPromocionais');
        removeQuoteReferenceFromCodigosPromocionais.setParams({
            quoteId: component.get('v.quoteId')
        });
        removeQuoteReferenceFromCodigosPromocionais.setCallback(this, function(response) {
            helper.saveDiscounts(component, event, helper);
        });
        $A.enqueueAction(removeQuoteReferenceFromCodigosPromocionais);
    },

    handleConfirmDialogNo: function(component, event, helper) {
        console.log('No');
        component.set('v.showConfirmDialog', false);
        component.find("cupom_voucher").set('v.value', '');
    },

    onToggle: function(cmp, event, helper) {
        helper.verifyDiscount(cmp, event);
        var auraId = event.getSource().getLocalId();
        var attribute = '';

        switch (auraId) {
            case 'iconPeso':
                attribute = 'v.verPeso';
                break;
            case 'iconDescontos':
                attribute = 'v.verDescontos';
                break;
            case 'iconDescontosServicos':
                attribute = 'v.verDescontosServicos';
                break;
            case 'iconFrete':
                attribute = 'v.verFrete';
                break;
            case 'iconCondicoes':
                attribute = 'v.verCondicoes';
                break;
            case 'iconCondicoesServicos':
                attribute = 'v.verCondicoesServicos';
                break;
            case 'iconObservacoes':
                attribute = 'v.verObservacoes';
                break;
            case 'iconMargem':
                attribute = 'v.verMargem';
                break;
            case 'iconNeuroTech':
                attribute = 'v.verNeuroTech';
                break;
        }

        if (cmp.get(attribute)) {
            cmp.set(attribute, false)
        } else {
            cmp.set(attribute, true)
        }
    },

    handleSuccessDiscount: function(cmp, event, helper) {
        let idsLine = cmp.get('v.updateLine');
        if (cmp.find("cupom_voucher").get('v.value') != '' && cmp.find("cupom_voucher").get('v.value') != null) {
            cmp.find("desc_adicional").set('v.value', '');
            cmp.find("desc_adicional_valor").set('v.value', '');
        }
        if (idsLine.length > 0 && cmp.find("cupom_voucher").get('v.value') == '') {
            helper.saveNegotiatedDiscount(cmp, event, helper);
        } else {
            helper.saveDiscountItemsHelper(cmp, event, helper);
        }
    },

    updateTotal: function(cmp, event, helper) {
        helper.dispatchEventReQueryQuote(cmp, event, helper, 'default');
    },

    onClickSaveServiceDiscounts: function(cmp, event, helper) {
        helper.saveServiceDiscounts(cmp, event, helper);
    },

    onClickRemoveServiceDiscounts: function(cmp, event, helper) {
        cmp.set('v.desc_service_adicional', 0);
        helper.saveServiceDiscounts(cmp, event, helper);
    },

    handleAddDiscount: function(cmp, event, helper) {
        cmp.set('v.isAddEspecDiscountVoucherLoading', true);

        let cupomVoucher = cmp.find("cupom_voucher").get("v.value");

        let hasQuoteAssociated = cmp.get('c.hasQuoteAssociated');

        hasQuoteAssociated.setParams({
            cupomCode: cupomVoucher,
            quoteId: cmp.get('v.quoteId')
        });
        hasQuoteAssociated.setCallback(this, function(response) {
            var retorno = response.getReturnValue();
            let codigoPromocional = cmp.get('v.quoteData').Codigo_Promocional__c;
            if (retorno) {
                cmp.set('v.associatedQuoteName', retorno);
                cmp.set('v.showAlertDialog', true);
                cmp.set('v.isAddEspecDiscountVoucherLoading', false);
            } else if (!retorno && codigoPromocional == cupomVoucher) {
                helper.saveDiscounts(cmp, event, helper);
            } else if (!retorno && codigoPromocional) {
                cmp.set('v.showConfirmDialog', true);
                cmp.set('v.isAddEspecDiscountVoucherLoading', false);
            } else if (!retorno && !codigoPromocional) {
                helper.saveDiscounts(cmp, event, helper);
            }
        });

        if (cupomVoucher !== '' && cmp.get('v.quoteData').RecordType.Name == 'Varejo') {

            let isPromotionApplicable = cmp.get('c.isPromotionApplicable');
            isPromotionApplicable.setParams({
                quoteData: cmp.get('v.quoteDataForPromotionValidation'),
                cupomCode: cupomVoucher
            });
            isPromotionApplicable.setCallback(this, function(response) {
                let resposta = response.getReturnValue();
                if (!resposta) {
                    cmp.set('v.showAlertNotApplicable', false);
                    $A.enqueueAction(hasQuoteAssociated);
                } else {
                    cmp.set('v.alertMessagePromotionApplicable', resposta);
                    cmp.set('v.showAlertNotApplicable', true);
                    cmp.set('v.isAddEspecDiscountVoucherLoading', false);
                }
            });
            $A.enqueueAction(isPromotionApplicable);
        } else {
            cmp.set('v.showAlertNotApplicable', false);
            $A.enqueueAction(hasQuoteAssociated);
        }
    },

    removeDiscounts: function(cmp, event, helper) {
        cmp.set('v.isVoucherFieldDisabled', false);
        cmp.set('v.isDescontoAdicionalFieldDisabled', false);
        cmp.set('v.isDescontoNegociadoFieldDisabled', false);
        cmp.set('v.isDelete', true);

        var specifierDiscountDisabled = cmp.get('v.specifierDiscountDisabled');
        if (specifierDiscountDisabled == false) {
            helper.changeSpecifierDiscountPermission(cmp, event, helper, false);
            cmp.set('v.descontoEspecificadorAtivado', false);
        }
        helper.removeDiscounts(cmp, event, helper);

        cmp.set('v.desabilitarDescontoItem', true);
        var products = cmp.get('v.quoteProducts');
        products.forEach(function(value, key) {
                cmp.set('v.desabilitarDescontoItem', false);
        });

        cmp.set('v.quoteProducts', products);

        var event = $A.get("e.c:RefreshViewEvent");
        event.fire();
    },


    handleError: function(cmp, event, helper) {
        var error = event.getParam("error");
        var errorMsg = [];

        errorMsg = error.body.output.errors.map((x) => x.message);

        var toastEvent = $A.get('e.force:showToast');
        toastEvent.setParams({
            "type": "error",
            "title": error.body.message,
            "message": errorMsg.join().replace(new RegExp(',', 'g'), '\n'),
        });

        toastEvent.fire();
    },

    //analise de crédito:

    handleErrorOnCreditAnalisy: function(cmp, event, helper){
        cmp.set('v.isCreditAnalisyLoading', false);
        cmp.handleError(cmp, event, helper);
    },

    handleSuccessOnCreditAnalisy: function(cmp, event, helper){
        cmp.set('v.isCreditAnalisyLoading', false);
        helper.dispatchEventReQueryQuote(cmp, event, helper, 'default');
    },

    //adicionar observação:

    saveObs: function(cmp, event, helper) {
        cmp.set('v.isObsLoading', true);
        cmp.find('ObsForm').submit();
    },

    handleSuccessOnSaveObs: function(cmp, event, helper){
        cmp.set('v.isObsLoading', false);
    },

    handleErrorOnSaveObs: function(cmp, event, helper){
        cmp.set('v.isObsLoading', false);
        cmp.handleError(cmp, event, helper);
    },

    //Adicionar frete:

    saveFrete: function(cmp, event, helper) {
        cmp.set('v.isFreteLoading', true);
        cmp.find('freteForm').submit();
    },

    handleSuccessOnSaveFrete: function(cmp, event, helper) {
        cmp.set('v.isFreteLoading', false);
    
        helper.dispatchEventReQueryQuote(cmp, event, helper, 'default');
        helper.dispatchEventReCalculateDiscounts(cmp, event, helper, 'default');
    },

    handleErrorOnSaveFrete: function(cmp, event, helper){
        cmp.set('v.isFreteLoading', false);
        cmp.handleError(cmp, event, helper);
    },


    onCupomChange: function(cmp, event, helper) {
        let cupomVoucher = cmp.find("cupom_voucher").get("v.value");
        cmp.set("v.cupomFieldData", cupomVoucher);
        if (cupomVoucher.length > 0) {
            cmp.find("desc_adicional").set("v.value", '');
            cmp.find("desc_adicional_valor").set("v.value", '');
            cmp.set("v.isDescontoNegociadoFieldDisabled", true);
            cmp.set("v.isDescontoAdicionalFieldDisabled", true);
        } else {
            cmp.set("v.isVoucherFieldDisabled", false);
            cmp.set("v.isDescontoNegociadoFieldDisabled", false);
            cmp.set("v.isDescontoAdicionalFieldDisabled", false);

        }
    },

    formPress: function(cmp, event, helper) {
        var input = event.getSource();
        var auraId = input.getLocalId();
        var oinput = false;

        switch (auraId) {
            case 'desc_adicional':
                let descontoAdicional = cmp.find("desc_adicional").get("v.value");
                if (descontoAdicional.length > 0) {
                    cmp.find("cupom_voucher").set("v.value", '');
                    cmp.find("desc_adicional_valor").set("v.value", '');
                    cmp.set("v.isVoucherFieldDisabled", true);
                    cmp.set("v.isDescontoAdicionalFieldDisabled", true);
                } else {
                    cmp.set("v.isVoucherFieldDisabled", false);
                    cmp.set("v.isDescontoNegociadoFieldDisabled", false);
                    cmp.set("v.isDescontoAdicionalFieldDisabled", false);
                }

                cmp.set('v.discountChanged', true);
                helper.handleDiscountNegPerFix(cmp, event);
                break;
            case 'desc_adicional_valor':
                let descontoValor = cmp.find("desc_adicional_valor").get("v.value");
                if (descontoValor.length > 0) {
                    cmp.find("cupom_voucher").set("v.value", '');
                    cmp.find("desc_adicional").set("v.value", '');
                    cmp.set("v.isVoucherFieldDisabled", true);
                    cmp.set("v.isDescontoNegociadoFieldDisabled", true);
                } else {
                    cmp.set("v.isVoucherFieldDisabled", false);
                    cmp.set("v.isDescontoAdicionalFieldDisabled", false);
                    cmp.set("v.isDescontoNegociadoFieldDisabled", false);
                }
                oinput = cmp.find("desc_adicional");
                cmp.set('v.discountChanged', true);
                break;
            case 'desc_service_adicional':
                oinput = cmp.find("desc_service_adicional_valor");
                cmp.set('v.discountChanged', true);
                break;
            case 'desc_service_adicional_valor':
                oinput = cmp.find("desc_service_adicional");
                cmp.set('v.discountChanged', true);
                break;
            default:
                alert('error');
        }

        if (oinput) {
            if (input.get('v.value') != '') {
                //oinput.set('v.disabled', true);
                oinput.set('v.value', '');
            } else {
                input.set('v.disabled', false);
                oinput.set('v.disabled', false);
            }
        }

        var products = cmp.get('v.quoteProducts');

        for (var i = 0; i < products.length; i++) {
            var product = cmp.get('v.quoteProducts')[i];
            product['descontoNegociado'] = '';
            product['descontoNegociadoPer'] = '';
        }

        cmp.set('v.quoteProducts', cmp.get('v.quoteProducts'));
    },

    percentMask: function(cmp, event, helper) {
        helper.handleDiscountNegPerFix(cmp, event);
    },

    closeModel: function(component, event, helper) {
        component.set("v.isOpen", false);
    },

    changeDiscountItem: function(component, event, helper) {
        var ctarget = event.currentTarget;
        var type = ctarget.dataset.type;
        var index = ctarget.dataset.index;
        var product = component.get('v.quoteProducts')[index];

        if (type == 'percent') {
            product['descontoNegociado'] = '';
        }

        if (type == 'value') {
            product['descontoNegociadoPer'] = '';
        }

        component.set('v.quoteProducts', component.get('v.quoteProducts'));

        if (typeof component.find("desc_adicional") !== 'undefined') {
            component.find("desc_adicional").set('v.value', '');
        }

        if (typeof component.find("desc_adicional_valor") !== 'undefined') {
            component.find("desc_adicional_valor").set('v.value', '');
        }

    },

    getCreditAnalisy: function(cmp, event, helper) {
        cmp.set('v.isCreditAnalisyLoading', true);
        helper.getFieldsCreditAnalysis(cmp);
        var event1 = $A.get("e.c:UpdateQuoteEvent");
        event1.setParams({
            "message": "updateTotal"
        });
        event1.fire();

        if(cmp.get('v.quoteData') && cmp.get('v.quoteData').SituacaoP2NeuroTech__c){
            let updateNeurotechP2Date = cmp.get('c.updateNeurotechP2Date');
            updateNeurotechP2Date.setParams({
                quoteId: cmp.get('v.quoteId')
            });
            $A.enqueueAction(updateNeurotechP2Date);
            helper.getNeurotechConsultorMetadata(cmp);
        } else {
            cmp.set('v.isCreditAnalisyLoading', false);
        }
    },

    securityMarginChange: function(cmp, evt) {
        var selected = evt.getSource().get("v.value");
        cmp.set("v.securityMargin", selected);
    },

    determinationOfConstantQuantitiesChange: function(cmp, evt) {
        var selected = evt.getSource().get("v.value");
        cmp.set("v.determinationOfConstantQuantities", selected);
    },
    handleBancoCamposEvent: function(cmp, event, helper) {
        if (event && event.getParam("campos")) {
            let campos = JSON.parse(JSON.stringify(event.getParam("campos")));
            cmp.set("v.nomeBanco", event.getParam("nomeBanco"));
            let camposFormatados = [];
            Object.keys(campos).forEach((campo, index) => {

                if((cmp.get("v.nomeBanco").toLowerCase() == 'santander' && (campo != 'currentOccupations' && campo != 'maritalStatuses' && campo != 'states')) || cmp.get("v.nomeBanco").toLowerCase() != 'santander'){

                    let mapCamposValores = campos[campo].map(conteudo => ({
                        label: conteudo.description,
                        value: conteudo.externalId
                    }));
                    let objFormatado = {
                        label: helper.getBancoCampoLabel(cmp, campo).campoLabel,
                        name: campo,
                        values: mapCamposValores,
                        value: null,
                        externalId: helper.getBancoCampoLabel(cmp, campo).externalId || null,
                        class: campo == 'states' ? 'slds-hide' : ''
                    }
                    camposFormatados.push(objFormatado);
                }
            })
            cmp.set("v.camposBanco", camposFormatados);
            if(cmp.get('v.infoCreditAnalysis') && cmp.get('v.infoCreditAnalysis').Id){
                cmp.set("v.disableEnviar", true);
                cmp.set("v.disableAtualizar", false);
            } else {
                cmp.set("v.disableEnviar", false);
                cmp.set("v.disableAtualizar", true);
            }

            let minDataVencimento = new Date(new Date().setDate(new Date().getDate() + 30)).toISOString().split('T')[0];
            let maxDataVencimento = new Date(new Date().setDate(new Date().getDate() + 90)).toISOString().split('T')[0];
            cmp.set("v.minDataVencimentoBoleto", minDataVencimento);
            cmp.set("v.maxDataVencimentoBoleto", maxDataVencimento);

            let msgDataVencimento = 'A data de vencimento deve ser entre ' + new Date(new Date().setDate(new Date().getDate() + 30)).toLocaleString().split(',')[0] +' e ' + new Date(new Date().setDate(new Date().getDate() + 90)).toLocaleString().split(',')[0];
            cmp.set("v.msgDataVencimentoBoleto", msgDataVencimento);

            let paymentPlan = null;
            if(event.getParam("paymentPlanInsert")) {
                paymentPlan = JSON.parse(JSON.stringify(event.getParam("paymentPlanInsert")));
            }
            if(paymentPlan && 
                paymentPlan.Condi_o_de_Pagamento__c && paymentPlan.Condi_o_de_Pagamento__c === '10' && 
                paymentPlan.Descricao__c && paymentPlan.Descricao__c.toLowerCase().includes('90 dias')
            ){
                cmp.set('v.disableDataVencimentoBoleto', true);
            } else {
                cmp.set('v.disableDataVencimentoBoleto', false);
            }

            cmp.set("v.verCamposBanco", true);
            helper.setCampoBanco(cmp);
            if(cmp.find('creditMat') && cmp.find('creditMat')[0] && cmp.find('creditMat')[0].get('v.msgFieldsNull')){
                cmp.set(cmp.set("v.disableEnviar", true));
            }
        }
    },

    validateShowStates: function(cmp,event,helper){
        if (event.getSource().get("v.name") == "nationalities"){
            cmp.find('campoBanco').forEach((campo) => {
                if(campo.get('v.name') == 'states' && event.getSource().get("v.value") == "BRASIL"){
                    campo.set('v.class', '');
                } else if(campo.get('v.name') == 'states' && event.getSource().get("v.value") != "BRASIL"){
                    campo.set('v.class', 'slds-hide');
                    campo.set('v.value','');
                }
            });
        }
    },

    handleRemoveBancoEvent: function(cmp, event, helper) {
        cmp.set("v.disableEnviar", false);
        if(cmp.get('v.nomeBanco') && cmp.get('v.nomeBanco') !== 'Neurotech'){
            cmp.set("v.disableAtualizar", true);
        }
        if (event) {
            cmp.set("v.verCamposBanco", false);
        }
        cmp.set("v.infoCreditAnalysis", null);
        cmp.set("v.quoteData", {});
        cmp.set("v.mensagensP2Vendedor", null);
    },

    handleEnviarAnalise: function(cmp, event, helper) {
        cmp.set('v.isCreditAnalisyLoading', true);
        let campoInvalido = false;
        let camposBanco = {};
        let camposRepresentante = {};

        if (cmp.get('v.nomeBanco') === 'Santander') {
            var action = cmp.get('c.verifyStoreEnableSantander');
            action.setCallback(this, function(response) {
                let resposta = response.getReturnValue();
                if (resposta) {
                    cmp.set('v.disableEnviar', true);
                    // Validação campos
                    if (cmp.get("v.camposBanco")) {
                        const lstCampos = cmp.find('campoBanco');
                        cmp.get("v.camposBanco").forEach(campo => {
                            if (lstCampos) {
                                const valor = lstCampos.find(c => {
                                    return c.get('v.name') === campo.name
                                })
                                if (valor && !valor.get('v.value')) {
                                    valor.setCustomValidity('Este campo deve ser preenchido.');
                                    valor.reportValidity();
                                    campoInvalido = true;
                                    cmp.set('v.disableEnviar', false);
                                cmp.set('v.isCreditAnalisyLoading', false);
                                } else {
                                    valor.setCustomValidity('');
                                    valor.reportValidity();
                                    camposBanco[campo.name] = valor.get('v.value');
                                }
                            }
                        });
                        if (cmp.find('representante')) {
                            cmp.find('representante').forEach(campo => {
                                if (!campo.get('v.value')) {
                                    campo.setCustomValidity('Este campo deve ser preenchido.');
                                    campo.reportValidity();
                                    campoInvalido = true;
                                    cmp.set('v.disableEnviar', false);
                                    cmp.set('v.isCreditAnalisyLoading', false);
                                } else {
                                    campo.setCustomValidity('');
                                    if (campo.get('v.name') === 'RepresentanteLegalCPF' && !helper.validaCPF(cmp, campo.get('v.value'))) {
                                        campo.setCustomValidity('CPF Inválido');
                                        campoInvalido = true;
                                        cmp.set('v.disableEnviar', false);
                                        cmp.set('v.isCreditAnalisyLoading', false);
                                    } else {
                                        camposRepresentante[campo.get('v.name')] = campo.get('v.value');
                                    }
                                    campo.reportValidity();
                                }
                            })
                        }
    
                        let firstInstallmentDate = cmp.find('firstInstallmentDate');
                        if (firstInstallmentDate) {
                            if (!firstInstallmentDate.get('v.value')){
                                firstInstallmentDate.setCustomValidity('Este campo deve ser preenchido.');
                                firstInstallmentDate.reportValidity();
                                campoInvalido = true;
                                cmp.set('v.disableEnviar', false);
                                cmp.set('v.showSpinner', false);
                            }
                        }
                    }
    
                    if (!campoInvalido) {
                        var sendCreditAnalysis = cmp.get('c.sendSantanderCreditAnalysis');
                        sendCreditAnalysis.setParams({
                            quote: cmp.get('v.quoteData'),
                            pickListValues: JSON.stringify(camposBanco),
                            fieldsLegalRepresentative: JSON.stringify(camposRepresentante),
                            firstInstallmentDate: cmp.find('firstInstallmentDate').get('v.value')
                        });
                        sendCreditAnalysis.setCallback(this, function(response) {
                            if (response.getReturnValue() === '202') {
                                var toastEvent = $A.get("e.force:showToast");
                                toastEvent.setParams({
                                    type: 'success',
                                    title: 'Sucesso!',
                                    message: 'Proposta enviada com sucesso'
                                });
                                cmp.set('v.disableAtualizar', false);
                                toastEvent.fire();
                            } else {
                                var toastEvent = $A.get("e.force:showToast");
                                toastEvent.setParams({
                                    type: 'error',
                                    title: 'Erro!',
                                    message: 'Erro no envio da análise. Favor, entrar em contato com o administrador.'
                                });
                                toastEvent.fire();
                            }
                        cmp.set('v.isCreditAnalisyLoading', false);
                        });
                        $A.enqueueAction(sendCreditAnalysis);
                    }
                }
            })
            $A.enqueueAction(action);
        }

        if (cmp.get('v.nomeBanco') === 'Losango') {
            var action = cmp.get('c.verifyStoreEnableLosango');
            action.setCallback(this, function(response) {
                let resposta = response.getReturnValue();
                if (resposta) {
                    cmp.set('v.disableEnviar', true);
                    // Validação campos
                    if (cmp.get("v.camposBanco")) {
                        const lstCampos = cmp.find('campoBanco');
                        let isBrazil = false;
                        cmp.get("v.camposBanco").forEach(campo => {
                            if (lstCampos) {
                                const valor = lstCampos.find(c => {
                                    if(c.get('v.name') === 'nationalities' && c.get('v.value') === 'BRASIL')
                                        isBrazil = true;
                                    return c.get('v.name') === campo.name
                                })
                                if (valor && !valor.get('v.value')) {

                                    if(valor.get('v.name') === 'states' && isBrazil){
                                        valor.setCustomValidity('Este campo deve ser preenchido.');
                                        valor.reportValidity();
                                        campoInvalido = true;
                                        cmp.set('v.disableEnviar', false);
                                        cmp.set('v.showSpinner', false);
                                    }
                                } else {
                                    valor.setCustomValidity('');
                                    valor.reportValidity();
                                    camposBanco[campo.name] = valor.get('v.value');
                                }
                            }
                        });
    
                        let assetValueField = cmp.find('assetValue');
                        if (assetValueField) {
                            if (!assetValueField.get('v.value')){
                                assetValueField.setCustomValidity('Este campo deve ser preenchido.');
                                assetValueField.reportValidity();
                                campoInvalido = true;
                                cmp.set('v.disableEnviar', false);
                                cmp.set('v.showSpinner', false);
                            }
                        }
    
                        let firstInstallmentDate = cmp.find('firstInstallmentDate');
                        if (firstInstallmentDate) {
                            if (!firstInstallmentDate.get('v.value')){
                                firstInstallmentDate.setCustomValidity('Este campo deve ser preenchido.');
                                firstInstallmentDate.reportValidity();
                                campoInvalido = true;
                                cmp.set('v.disableEnviar', false);
                                cmp.set('v.showSpinner', false);
                            }
                        }
                    }

                    if (!campoInvalido) {
                        var sendCreditAnalysis = cmp.get('c.sendLosangoCreditAnalysis');
                        sendCreditAnalysis.setParams({
                            quote: cmp.get('v.quoteData'),
                            pickListValues: JSON.stringify(camposBanco),
                            assetValue: cmp.find('assetValue').get('v.value'),
                            firstInstallmentDate: cmp.find('firstInstallmentDate').get('v.value')
                        });
                        sendCreditAnalysis.setCallback(this, function(response) {
                            if (response.getReturnValue() === '202') {
                                var toastEvent = $A.get("e.force:showToast");
                                toastEvent.setParams({
                                    type: 'success',
                                    title: 'Sucesso!',
                                    message: 'Proposta enviada com sucesso'
                                });
                                cmp.set('v.disableAtualizar', false);
                                toastEvent.fire();
                            } else {
                                var toastEvent = $A.get("e.force:showToast");
                                toastEvent.setParams({
                                    type: 'error',
                                    title: 'Erro!',
                                    message: 'Erro no envio da análise. Favor, entrar em contato com o administrador.'
                                });
                                toastEvent.fire();
                            }
                        // cmp.set('v.disableEnviar', false);
                            cmp.set('v.showSpinner', false);
                        });
                        $A.enqueueAction(sendCreditAnalysis);
                    }
                }
            })
            $A.enqueueAction(action);   
        }
    },

    handleChangeBankValues: function(cmp, event, helper) {
        let camposBancoSelecionados = cmp.get('v.camposBancoSelecionados');
        let fieldName = event.get('v.name');
        let value = event.get('v.value');
        if (fieldName) {
            campos[fieldName] = value;  
        }
        cmp.set('v.camposBancoSelecionados', camposBancoSelecionados);
    },

    getEnvironment: function(cmp, evt) {
        const env = cmp.get('v.environments');
        var envChecked = evt.getSource().get("v.value");
        let isChecked = evt.getSource().get("v.checked");
        var line = cmp.find("lineId");
        var ids = cmp.get('v.updateLine');

        var envProducts = [];
        for( var i = 0; i < env.length; i++){
            var envProdutcsL = env[i].products.length;
            for (var a = 0; a < envProdutcsL; a++) {
                envProducts.push(env[i].products[a]);
            }
        }

        for ( var i = 0; i < envProducts.length; i++){
            if((isChecked == true) && (envProducts[i].AmbienteCompleto == envChecked)){
                ids.push(line[i].get('v.value'));
                line[i].set('v.checked', true);
            }else if((isChecked == false) && (envProducts[i].AmbienteCompleto == envChecked)){
                var idx = ids.indexOf(line[i].get('v.value'));
                while (idx >= 0) {
                    ids.splice(idx, 1)

                    idx = ids.indexOf(line[i].get('v.value'));
                }
                line[i].set('v.checked', false);
            }
        }
    },

    getLineId: function(cmp, evt) {
        var chx = evt.getSource().get("v.checked");
        var line = evt.getSource().get("v.value");
        var ids = cmp.get('v.updateLine');

        if (chx == true) {
            ids.push(line);
        } else {
            var idx = ids.indexOf(line);
            while (idx >= 0) {
                ids.splice(idx, 1)

                idx = ids.indexOf(line);
            }
        }
        console.log(ids);
        cmp.set('v.updateLine', ids);
    },

    handleChangeEspec: function(cmp, event, helper) {
        let button = event.getSource();
        let auraId = event.getSource().getLocalId();

        if (button.get('v.variant') === 'neutral')
            button.set('v.variant', 'brand');

        if (auraId === 'consultEspec') {
            let other_button = cmp.find("newEspec");
            other_button.set('v.variant', 'neutral');

            cmp.set("v.disableEsp", false);
            cmp.set("v.disableEspForm", true);
            cmp.set("v.espFormStep", 0);
        } else if (auraId === 'newEspec') {
            let other_button = cmp.find("consultEspec");
            other_button.set('v.variant', 'neutral');

            cmp.set("v.disableEsp", false);
            cmp.set("v.disableEspForm", false);
            cmp.set("v.espFormStep", 1);
        }

        if ((auraId !== 'newEspec')) {
            cmp.set('v.disableAddButton', false);
            cmp.set("v.valueEsp", 'Especificador');
            cmp.set("v.espCPF", null);
            cmp.set("v.espCNPJ", null);
            cmp.set("v.valueSal", null);
            cmp.set("v.espName", null);
            cmp.set("v.espLastName", null);
            cmp.set("v.espEmail", null);
            cmp.set("v.espCelular", null);
            cmp.set("v.espCauCreaAbd", null);
            cmp.set("v.archOtherArchsOptIn", '');
            cmp.set("v.espEmailOptIn", 'Sim');
            cmp.set("v.espSMSOptIn", 'Sim');
            cmp.set("v.espCelularOptIn", 'Sim');
            cmp.set("v.espWhatsAppOptIn", 'Sim');
            cmp.set("v.espNPSOptIn", 'Sim');
        }
    },

    onChangeEspec: function(cmp, event, helper) {
        const possuiEspecificador = cmp.get('v.especificadorId');
        let reservaTecnicaSim = cmp.find('reservaTecnicaSim');
        let reservaTecnicaNao = cmp.find('reservaTecnicaNao');
        let isCorporativo = helper.verificarVendaCorporativa(cmp);

        cmp.set('v.reservaTecnica', possuiEspecificador && cmp.get('v.reservaOnLoading'));

        if (reservaTecnicaSim && !isCorporativo)
            reservaTecnicaSim.set('v.disabled', !possuiEspecificador);

        if (reservaTecnicaNao && !isCorporativo)
            reservaTecnicaNao.set('v.disabled', !possuiEspecificador);

        helper.isCpfValidado(cmp, 'v.showTooltipEspec', 'v.tooltipMessageEspec', 'v.espec');
        helper.isCnpjValidado(cmp, 'v.showTooltipEspec', 'v.tooltipMessageEspec', 'v.espec');
        helper.getAcceptTerms(cmp, event, helper);
    },

    onChangeEspecArq: function(cmp, event, helper) {
        const possuiEspecificadorArq = cmp.get('v.especArq');

        helper.isCpfValidado(cmp, 'v.showTooltipArq', 'v.tooltipMessageArq', 'v.especArq');
    },

    setClientFromEspec: function(cmp, event, helper) {
        let especificadorId = cmp.get("v.especificadorId");
        let checkBoxSamePerson = cmp.find("samePersonCheckBox").get("v.checked");

        if (checkBoxSamePerson && especificadorId) {
            cmp.set("v.clienteId", especificadorId);
        } else {
            cmp.set('v.clienteId', null);
            cmp.set('v.account', null);
        }
    },

    resetFormArch: function(component, event, helper) {
        helper.resetFormArch(component);
    },

    fetchClientOrArchData: function(component, event, helper) {
        let inputValueLength = event.getSource().get('v.value').length;
        let inputId = event.getSource().getLocalId();

        if (inputValueLength < 11) {
            if (inputId == 'espCNPJ' || inputId == 'espCPF')
                helper.resetFormArch(component);

            if (inputId == 'espCPFArq')
                helper.resetEscArqForm(component);

            if (inputId == 'clientCPF' || inputId == 'clientCNPJ')
                helper.resetFormClient(component);
        }

        if (inputValueLength >= 11) {
            let action = component.get('c.getAccountByCPFOrCNPJ');
            action.setParams({
                cpfOrCNPJ: event.getParam('value')
            });
            action.setCallback(this, function(response) {
                let state = response.getState();

                if (state == 'SUCCESS') {
                    let responseValue = response.getReturnValue();
                    console.log('responseValue: ', responseValue);

                    if (inputId == 'espCNPJ' || inputId == 'espCPF' || inputId == 'espCPFArq')
                        component.set('v.blockArch', false);

                    if (inputId == 'clientCPF' || inputId == 'clientCNPJ')
                        component.set('v.blockClient', false);

                    if (responseValue) {
                        if (inputId == 'espCNPJ' || inputId == 'espCPF') {
                            component.set('v.espName', inputId == 'espCNPJ' ? responseValue.Name : responseValue.FirstName);
                            component.set('v.accountId', responseValue.Id);
                            component.set('v.espLastName', responseValue.LastName);
                            component.set('v.valueSal', responseValue.Salutation);
                            component.set('v.espEmail', responseValue.Email__c);
                            component.set('v.espCelular', responseValue.Celular__c);
                            component.set('v.espCauCreaAbd', responseValue.CAU_CREA_ABD__c);
                            component.set('v.espEmailOptIn', helper.selectOptinValue(component, responseValue.Aceita_Notificacao_Email__c));
                            component.set('v.espSMSOptIn', helper.selectOptinValue(component, responseValue.Aceita_Notificacao_SMS__c));
                            component.set('v.espCelularOptIn', helper.selectOptinValue(component, responseValue.Aceita_Notificacao_Telefone__c));
                            component.set('v.espWhatsAppOptIn', helper.selectOptinValue(component, responseValue.Aceita_Notificacao_de_WhatsApp__c));
                            component.set('v.espNPSOptIn', helper.selectOptinValue(component, responseValue.AceitaNPS__c));

                            if (responseValue.RecordType.Name != 'Especificador' && responseValue.RecordType.Name != 'Escritório Especificador') {
                                helper.resetFormArch(component);
                                helper.showErrorToast(component, event, helper, 'O CPF/CNPJ informado já está cadastrado no sistema como outro tipo de conta.');
                                component.set('v.blockArch', true);
                                component.set('v.disableAddButton', false);
                            }
                        }

                        if (inputId == 'espCPFArq') {
                            component.set('v.especificadorArqId', responseValue.Id);
                            component.set('v.espFirstNameArq', responseValue.FirstName);
                            component.set('v.espLastNameArq', responseValue.LastName);
                            component.set('v.espvalueSalArq', responseValue.Salutation);
                            component.set('v.espEmailArq', responseValue.Email__c);
                            component.set('v.espCelularArq', responseValue.Celular__c);
                            component.set('v.espCauCreaArq', responseValue.CAU_CREA_ABD__c);
                            component.set('v.espOptinEmailArq', helper.selectOptinValue(component, responseValue.Aceita_Notificacao_Email__c));
                            component.set('v.espOptinSMSArq', helper.selectOptinValue(component, responseValue.Aceita_Notificacao_SMS__c));
                            component.set('v.espOptinLigacaoArq', helper.selectOptinValue(component, responseValue.Aceita_Notificacao_Telefone__c));
                            component.set('v.espOptinWhatsAppArq', helper.selectOptinValue(component, responseValue.Aceita_Notificacao_de_WhatsApp__c));
                            component.set('v.espOptinNPSArq', helper.selectOptinValue(component, responseValue.AceitaNPS__c));

                            if (responseValue.RecordType.Name != 'Especificador') {
                                helper.resetEscArqForm(component);
                                helper.showErrorToast(component, event, helper, 'O CPF/CNPJ informado já está cadastrado no sistema como outro tipo de conta.');
                                component.set('v.blockArch', true);
                                component.set('v.disableAddButton', false);
                            }
                        }

                        if (inputId == 'clientCPF' || inputId == 'clientCNPJ') {
                            component.find('clientBtn').set('v.label', 'Iniciar Relacionamento');
                            component.set('v.blockClient', false);
                            component.set('v.accountId', responseValue.Id);
                            component.set('v.clientName', responseValue.Name);
                            component.set('v.clientEmail', responseValue.Email__c);
                            component.set('v.clientCelular', responseValue.Celular__c);
                            component.set('v.clienteEmailOptIn', responseValue.Aceita_Notificacao_Email__c);
                            component.set('v.clienteSMSOptIn', responseValue.Aceita_Notificacao_SMS__c);
                            component.set('v.clienteCelularOptIn', responseValue.Aceita_Notificacao_Telefone__c);
                            component.set('v.clienteWhatsAppOptIn', responseValue.Aceita_Notificacao_de_WhatsApp__c);
                            component.set('v.clienteNPSOptIn', responseValue.AceitaNPS__c);

                            if (responseValue.RecordType.Name != 'Cliente PF' && responseValue.RecordType.Name != 'Cliente PJ') {
                                helper.resetFormClient(component);
                                helper.showErrorToast(component, event, helper, 'Este CPF/CNPJ já está cadastrado como Especificador.');
                                component.set('v.blockClient', true);
                            }
                        }
                    }
                }

                if (state == 'ERROR') {
                    let errors = response.getError();

                    if (errors[0] && errors[0].message) {
                        if (inputId == 'espCNPJ' || inputId == 'espCPF')
                            helper.resetFormArch(component);

                        if (inputId == 'espCPFArq')
                            helper.resetEscArqForm(component);

                        if (inputId == 'clientCPF' || inputId == 'clientCNPJ')
                            helper.resetFormClient(component);

                        if (inputValueLength)
                            helper.showErrorToast(component, event, helper, 'Ocorreu um erro na hora de buscar os valores da conta. Erro: ' + errors[0].message);
                    }
                }
            });
            $A.enqueueAction(action);
        }
    },

    phoneMask: function(cmp, event, helper) {
        let value = event.getSource().get("v.value");
        let valueClean = value.replace(/\D/g, '').substring(0, 11);
        let fieldName = event.getSource().getLocalId();
        cmp.find(fieldName).set("v.value", valueClean);

        if (valueClean.length >= 10) {
            let valueFormated = valueClean.replace(/(\d{2})(\d{5}|\d{4})(\d{4})/, "($1) $2-$3");
            let input = cmp.find(fieldName).set("v.value", valueFormated);
        }
    },

    setCauCreaAbd: function(component, event, helper) {
        let especOccupation = component.get('v.espOccupation') ? component.get('v.espOccupation') : component.get("v.archOtherArchsOptIn");
        let espCauCreaAbdField = component.find("espCauCreaAbd");

        if (especOccupation == 'Arquiteto' || especOccupation == 'Engenheiro' || 'Designer') {
            espCauCreaAbdField.set("v.disabled", false);
            component.set("v.espCauCreaAbd", '');
            component.set("v.cauCreaVisible", true);
            helper.toggleClassComponentVisible(component, "espCauCreaAbd", "slds-hide");
        }

        if (!especOccupation || especOccupation == 'Paisagista' || especOccupation == 'Construtor' || especOccupation == 'Outro') {
            espCauCreaAbdField.set("v.disabled", true);
            component.set("v.espCauCreaAbd", '0000');
            component.set("v.cauCreaVisible", false);
            helper.toggleClassComponentInvisible(component, "espCauCreaAbd", "slds-hide");
        }
    },

    checkAccount: function(component, event, helper) {
        let getSource = event.getSource();
        let auraId = getSource.getLocalId();
        let labelName = getSource.get('v.label');
        let isArchRemovingSpinner = false;

        if (labelName === 'Iniciar Relacionamento') {
            let accId = component.get('v.accountId');
            let acc = {
                Id: accId
            };
            let action = component.get('c.createAccountWithLoja');
            action.setParams({
                acc: acc,
                justCreateShopRelationship: true
            });

            action.setCallback(this, function(response) {
                let state = response.getState();

                if (state == 'SUCCESS') {
                    getSource.set('v.label', 'Cadastrar');
                } else if (state == 'ERROR') {
                    console.log('Erro ao tentar criar relacionamento com a loja.');
                    console.log('msg: ' + response.getError());
                }
            });
            $A.enqueueAction(action);
        }
        let msg = '';
        let acc;

        component.set('v.clientePreenchidoError', '');

        if (auraId == 'clientBtn') {
            let valMail = helper.validateEmail(component, event, 'clienteEmail');
            component.set("v.clientBtnDisabled", true);
            msg = 'Identificamos que já existe um cliente cadastrado com este e-mail na base de dados. Deseja atualizar suas informações?';

            if (valMail)
                acc = {
                    Email__c: component.get("v.clientEmail"),
                    RecordTypeId: component.get('v.clienteRecordType')[component.get('v.valueCliente')],
                    Loja__c: component.get('v.user').ID_Conta_Loja__c
                };
            component.set("v.clientBtnDisabled", false);

        } else if (auraId == 'espBtn') {
            let valMail = helper.validateEmail(component, event, 'espEmail');
            msg = 'Identificamos que já existe um especificador cadastrado com este e-mail na base de dados. Deseja atualizar suas informações?';
            isArchRemovingSpinner = true;

            let especificador = component.get('v.valueEsp');
            component.set('v.newClientSpinner', false);

            if (valMail)
                acc = {
                    Email__c: component.get("v.espEmail"),
                    RecordTypeId: component.get('v.clienteRecordType')[especificador],
                    Loja__c: component.get('v.user').ID_Conta_Loja__c
                };

        } else if (auraId == 'espBtnArq') {
            let salutationOptions = component.get('v.optionsSalutation');
            let occupationOptions = component.get('v.occOptions');
            let fieldErrors = [];

            if (component.get('v.espvalueSalArq') == salutationOptions[0].value)
                fieldErrors.push('Tratamento');

            if (!component.get('v.espLastNameArq'))
                fieldErrors.push('Sobrenome');

            if (component.get('v.espOccupation') == occupationOptions[0].value || !component.get('v.espOccupation'))
                fieldErrors.push('Profissão');

            if (component.get('v.cauCreaVisible') && !component.get('v.espCauCreaArq'))
                fieldErrors.push('CAU/CREA/ABD');

            if (fieldErrors.length != 0)
                helper.showErrorToast(component, event, helper, 'Os campos ' + fieldErrors + ' devem estar preenchidos para continuar.');

            if (fieldErrors.length == 0) {
                acc = {
                    Email__c: component.get("v.espEmailArq"),
                    Celular__c: component.get("v.espCelularArq"),
                    Aceita_Notificacao_Telefone__c: component.get("v.espOptinLigacaoArq"),
                    Aceita_Notificacao_Email__c: component.get("v.espOptinEmailArq"),
                    Aceita_Notificacao_SMS__c: component.get("v.espOptinSMSArq"),
                    Aceita_Notificacao_de_WhatsApp__c: component.get("v.espOptinWhatsAppArq"),
                    AceitaNPS__c: component.get("v.espOptinNPSArq"),
                    CAU_CREA_ABD__c: component.get("v.espCauCreaArq"),
                    RecordTypeId: component.get('v.clienteRecordType')[component.get('v.valueEsp')],
                    CPF__c: component.get("v.espCPFArq"),
                    FirstName: component.get('v.espFirstNameArq'),
                    LastName: component.get('v.espLastNameArq'),
                    Salutation: component.get('v.espvalueSalArq')
                };
            }
        }

        if (acc && auraId !== 'clientAdvBtn') {
            let action = component.get("c.checkEmailAccount");
            component.set('v.checkMsg', msg);
            action.setParams({
                acc: acc
            });

            action.setCallback(this, function(a) {
                let state = a.getState();

                if (state === "SUCCESS") {
                    let exists = a.getReturnValue();

                    if (exists) {
                        component.set("v.confirmType", event.getSource().getLocalId());
                        component.set("v.isOpen", true);
                    } else {
                        if (!isArchRemovingSpinner)
                            component.set("v.newClientSpinner", true);
                        helper.handleSubmitAccount(component, event, helper, '');
                    }
                } else {
                    let toastEvent = $A.get('e.force:showToast');

                    toastEvent.setParams({
                        "type": "error",
                        "message": "Erro inesperado. Por favor, entre em contato com um administrador."
                    });

                    toastEvent.fire();
                }
            });
            $A.enqueueAction(action);
        }
    },

    handleChangeEspecArq: function(cmp, event, helper) {
        let button = event.getSource();
        let auraId = event.getSource().getLocalId();

        if (button.get('v.variant') === 'neutral')
            button.set('v.variant', 'brand');

        if (auraId === 'consultEspec2') {
            let other_button = cmp.find("newEspec2");
            other_button.set('v.variant', 'neutral');

            cmp.set("v.disableEspArq", false);
            cmp.set("v.disableEspFormArq", true);
            cmp.set("v.disableCadastro", false);
            cmp.set("v.consultaSelected", true);
            cmp.set("v.novoSelected", false);
            cmp.set("v.semEspSelected", false);
        } else if (auraId === 'newEspec2') {
            let other_button = cmp.find("consultEspec2");
            other_button.set('v.variant', 'neutral');

            cmp.set("v.disableEspArq", false);
            cmp.set("v.disableEspFormArq", false);
            cmp.set("v.disableCadastro", true);
            cmp.set("v.consultaSelected", false);
            cmp.set("v.novoSelected", true);
            cmp.set("v.semEspSelected", false);
        }

        if ((auraId !== 'newEspec2')) {
            cmp.set("v.espCPFArq", null);
            cmp.set("v.espvalueSalArq", null);
            cmp.set("v.espFirstNameArq", null);
            cmp.set("v.espLastNameArq", null);
            cmp.set("v.espEmailArq", null);
            cmp.set("v.espCelularArq", null);
            cmp.set("v.espCauCreaArq", null);
            cmp.set("v.espOccupation", '');
            cmp.set("v.espOptinEmailArq", 'Sim');
            cmp.set("v.espOptinSMSArq", 'Sim');
            cmp.set("v.espOptinLigacaoArq", 'Sim');
            cmp.set("v.espOptinWhatsAppArq", 'Sim');
            cmp.set("v.espOptinNPSArq", 'Sim');
        }
    },

    nextEspForm: function(cmp, event, helper) {
        cmp.set("v.espFormStep", cmp.get("v.espFormStep") + 1);
    },

    nextArqForm: function(cmp, event, helper) {
        cmp.set("v.arqFormStep", cmp.get("v.arqFormStep") + 1);
    },

    handleCancel: function(cmp, event, helper) {
        let auraId = event.getSource().getLocalId();
        let c = undefined;

        switch (auraId) {
            case 'clienteForm':
                c = cmp.get("v.clienteFormStep");
                cmp.set("v.clienteFormStep", cmp.get("v.clienteFormStep") - 1);
                break;
            case 'espForm':
                c = cmp.get("v.espFormStep");
                cmp.set("v.espFormStep", cmp.get("v.espFormStep") - 1);
                break;
            case 'arqForm':
                c = cmp.get("v.arqFormStep");
                cmp.set("v.arqFormStep", cmp.get("v.arqFormStep") - 1);
                break;
        }
    },

    handleClickEsp: function(cmp, event, helper) {
        if (cmp.get("v.disableEspForm")) {
            cmp.set("v.disableEspForm", false);
            cmp.set("v.espFormStep", 1);
        } else {
            cmp.set("v.disableEspForm", true);
            cmp.set("v.espFormStep", 0);
        }
    },

    addEspec: function(cmp, event, helper) {
        let action = cmp.get('c.changeEspec');
        action.setParams({
            quoteId: cmp.get('v.quoteData.Id'),
            acc: cmp.get('v.espec')
        });

        action.setCallback(this, function(response) {
            let result = response.getReturnValue();

            if (result != 'Success') {
                helper.toastError(cmp, 'Não foi possível adicionar esse especificador a esse orçamento');
            } else {
                helper.saveDiscountItemsHelper(cmp, event);
                helper.toastSucesso(cmp, 'Especificador adicionado com sucesso!');
            }
            cmp.set('v.disableAddButton', true);
        });
        $A.enqueueAction(action);
    },

    remEspec: function(cmp, event, helper) {
        let action = cmp.get('c.clearEspec');
        action.setParams({
            quoteId: cmp.get('v.quoteData.Id')
        });

        action.setCallback(this, function(response) {
            let result = response.getReturnValue();

            if (result != 'Success') {
                helper.toastError(cmp, 'Não foi possível remover esse especificador desse orçamento');
            } else {
                cmp.set('v.descontoEspecificadorAtivado', false);
                cmp.set('v.disableAddButton', false);
                cmp.set('v.espec', null);
                cmp.set('v.especificadorId', null);
                helper.changeSpecifierDiscountPermission(cmp, event, helper, false);
                helper.saveDiscountItemsHelper(cmp, event);
                helper.toastSucesso(cmp, 'Especificador removido com sucesso!');
            }
        });
        $A.enqueueAction(action);
    },

    addEspecArq: function(cmp, event, helper) {
        let action = cmp.get('c.changeEspecArq');
        action.setParams({
            quoteId: cmp.get('v.quoteData.Id'),
            acc: cmp.get('v.especArq')
        });

        action.setCallback(this, function(response) {
            let result = response.getReturnValue();

            if (result != 'Success') {
                helper.toastError(cmp, 'Não foi possível adicionar esse especificador a esse orçamento');
            } else {
                helper.saveDiscountItemsHelper(cmp, event);
                helper.toastSucesso(cmp, 'Especificador adicionado com sucesso!');
            }
            cmp.set('v.disableAddButtonArq', true);
        });
        $A.enqueueAction(action);
    },

    remEspecArq: function(cmp, event, helper) {
        let action = cmp.get('c.clearEspecArq');
        action.setParams({
            quoteId: cmp.get('v.quoteData.Id')
        });

        action.setCallback(this, function(response) {
            let result = response.getReturnValue();

            if (result != 'Success') {
                helper.toastError(cmp, 'Não foi possível remover esse especificador desse orçamento');
            } else {
                cmp.set('v.descontoEspecificadorAtivado', false);
                cmp.set('v.disableAddButtonArq', false);
                cmp.set('v.especArq', null);
                
                //todo! problema: os dois abaixo disparam o requery code e calculation
                helper.changeSpecifierDiscountPermission(cmp, event, helper, false);
                helper.saveDiscountItemsHelper(cmp, event);

                helper.toastSucesso(cmp, 'Especificador removido com sucesso!');
            }
        });
        $A.enqueueAction(action);
    },

    showImageUpload: function(cmp, event) {
        if (event.getParam("acao") && event.getParam("acao") === 'add') {
            cmp.set('v.exibirUploadImagem', true);
        } else {
            cmp.set('v.exibirUploadImagem', false);
        }
    },

    handleUploadFinished: function(cmp, event) {
        let uploadedFiles = event.getParam("files");
        let fileName;
        uploadedFiles.forEach(file => fileName = file.name);
        cmp.set('v.uploadedFileName', uploadedFiles[0].name);

        var action = cmp.get('c.includeURL');
        action.setParams({
            IdQuote: cmp.get('v.quoteId'),
            nomeArquivo: fileName,
            tipoArquivo: 'imagemextra'
        });
        action.setCallback(this, function(response) {
            let valueReturn = response.getReturnValue();
        });

        $A.enqueueAction(action);
    },

    viewImage: function(cmp, event, helper) {
        var action = cmp.get('c.returnURl');
        action.setParams({
            IdQuote: cmp.get('v.quoteId'),
            tipoArquivo: 'imagemextra'
        });

        action.setCallback(this, function(response) {
            let valueReturn = response.getReturnValue();
            console.log('valueReturn', valueReturn)
            let urlEvent = $A.get("e.force:navigateToURL");
            urlEvent.setParams({
                "url": valueReturn
            });
            urlEvent.fire();
        });

        $A.enqueueAction(action);
    },

    refreshView: function(cmp, event, helper){
        console.log('teste');
    },
    
    showPopUpToken: function(cmp, event, helper) {
        let tokenField = cmp.find('tokenLosango');
        
        if (!tokenField || !tokenField.get('v.value')) {
            tokenField.setCustomValidity('Este campo deve ser preenchido.');
            tokenField.reportValidity();
            return
        }

        cmp.set('v.token', tokenField.get('v.value'))
        cmp.set('v.showPopUp', true);
    }
})
Leave a Comment