codice

mail@pastecode.io avatar
unknown
apex
2 years ago
98 kB
2
Indexable
Never
import { LightningElement, api, track, wire } from 'lwc';
import { getRecord, createRecord, updateRecord } from 'lightning/uiRecordApi';
import queryPoint from '@salesforce/apex/AdvancedSearchCnt.searchPoints';
import getOppCommodity from '@salesforce/apex/AdvancedSearchCnt.getOpportunityCommodity';
import { getObjectInfo } from 'lightning/uiObjectInfoApi';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { error } from 'c/notificationSvc';
import { labels } from 'c/labels';
import CAMBIOUSOPROCESS from '@salesforce/apex/Constants.getCambioUsoOSIProcess';
import OPPORTUNITY_SERVICE_ITEM_OBJECT from "@salesforce/schema/OpportunityServiceItem__c";
import insertOsi from "@salesforce/apex/CEP_LC_DedicatedProcessWizard.insertOsi";
import insertOsiSwitching from "@salesforce/apex/CEP_LC_DedicatedProcessWizard.insertOsiSwitching"; 
import getOsi from "@salesforce/apex/OpportunityServiceItemCnt.getOsiById";
import prescreeningCheck from "@salesforce/apex/CEP_LC_DedicatedProcessWizard.prescreening";
import processCompatibility from "@salesforce/apex/CEP_LC_DedicatedProcessWizard.checkProcessCompatibility";
import atecoTranscoding from "@salesforce/apex/CEP_LC_DedicatedProcessWizard.atecTranscode";
import OsiEdit from '@salesforce/label/c.OsiEdit'; 
import CONTACT_FIRST_NAME from '@salesforce/schema/Contact.FirstName';
import CONTACT_LAST_NAME from '@salesforce/schema/Contact.LastName'; 
import CONTACT_PHONE from '@salesforce/schema/Contact.Phone'; 
import CONTACT_MOBILE from '@salesforce/schema/Contact.MobilePhone'; 
import isLargeSmeUser from '@salesforce/customPermission/CEP_Large_Sme_Permission'; 
import isSmallBusinessUser from '@salesforce/customPermission/CEP_Small_Business_Permission';
import isAgencyReseller from '@salesforce/customPermission/CEP_CP_AgencyReseller';
import isLargeAema from '@salesforce/customPermission/CEP_Large_Aema_Permission';
import isUmbriaEnergy from '@salesforce/customPermission/CEP_isUmbriaEnergy';
import isPrescreeningEnabled from '@salesforce/apex/CEP_UTL_CervedConfiguration.IsPrescreeningEnabledService';
import updateOpportunityPrescreening from "@salesforce/apex/CEP_LC_DedicatedProcessWizard.updateOpportunityPrescreeningStatus";
import getPreviousProduct from "@salesforce/apex/CEP_LC_DedicatedProcessWizard.getPreviousProduct";
import checkDistrVat from "@salesforce/apex/CEP_LC_DedicatedProcessWizard.checkDistributorVAT";
import { isEmptyString } from 'c/cepUtilities';
//NTT W3
import getOpportunityCompanyChannel from "@salesforce/apex/NTT_RicercaAddetto.getOpportunityCompanyChannel";

import FIELD_OPP_NAME from '@salesforce/schema/Opportunity.Name';
import FIELD_OPP_SIGNDATE from '@salesforce/schema/Opportunity.SignatureDate__c';
import FIELD_OPP_SUPPLY_START from '@salesforce/schema/Opportunity.SupplyStartDate__c';
import FIELD_OPP_SUPPLY_END from '@salesforce/schema/Opportunity.SupplyEndDate__c';
import FIELD_OPP_REQUEST_TYPE from '@salesforce/schema/Opportunity.RequestType__c';
import FIELD_OPP_ANTICHURN from '@salesforce/schema/Opportunity.Antichurn__c';
import FIELD_OPP_VATNUMBER from '@salesforce/schema/Opportunity.VatNumber__c';
//NTT W3
import isWind3 from '@salesforce/customPermission/NTT_isWind3';

const DISTRIBUTOR_FIELDS = ['Account.Name', 'Account.VATNumber__c'];
const COMPANY_CHANNEL_FIELDS = ['Account.CompanyChannel__c'];

const SERVICE_POINT_FIELDS = [
    'ServicePoint__c.Account__c',
    'ServicePoint__c.PointAddressNormalized__c',
    'ServicePoint__c.PointApartment__c',
    'ServicePoint__c.PointAt__c',
    'ServicePoint__c.PointStreetName__c',
    'ServicePoint__c.PointStreetNumber__c',
    'ServicePoint__c.AvailablePower__c',
    'ServicePoint__c.PointBuilding__c',
    'ServicePoint__c.PointCity__c',
    'ServicePoint__c.PointIstatCode__c',
    'ServicePoint__c.Code__c',
    'ServicePoint__c.ContractualPower__c',
    'ServicePoint__c.ConversionFactor__c',
    'ServicePoint__c.Corrector__c',
    'ServicePoint__c.PointCountry__c',
    'ServicePoint__c.CreatedById',
    'ServicePoint__c.CurrentSupply__c',
    'ServicePoint__c.Distributor__c',
    'ServicePoint__c.DistributorName__c',
    'ServicePoint__c.DistributorVATNumber__c',
    'ServicePoint__c.EstimatedConsumption__c',
    'ServicePoint__c.PointStreetNumberExtn__c',
    'ServicePoint__c.PointFloor__c',
    'ServicePoint__c.PointStaircase__c',
    'ServicePoint__c.JointVenture__c',
    'ServicePoint__c.Key__c',
    'ServicePoint__c.LastModifiedById',
    'ServicePoint__c.PointLocality__c',
    'ServicePoint__c.Meter__c',
    'ServicePoint__c.OwnerId',
    'ServicePoint__c.PointAddress__c',
    'ServicePoint__c.PointPostalCode__c',
    'ServicePoint__c.PowerPhase__c',
    'ServicePoint__c.Pressure__c',
    'ServicePoint__c.PressureLevel__c',
    'ServicePoint__c.PointProvince__c',
    'ServicePoint__c.RecordTypeId',
    'ServicePoint__c.Name',
    'ServicePoint__c.SiteStreetName__c',
    'ServicePoint__c.SiteCity__c',
    'ServicePoint__c.SiteStreetType__c',
    'ServicePoint__c.SiteStreetNumber__c',
    'ServicePoint__c.SitePostalCode__c',
    'ServicePoint__c.SiteIstatCode__c',
    'ServicePoint__c.SiteApartment__c',
    'ServicePoint__c.SiteProvince__c',
    'ServicePoint__c.SiteLocality__c',
    'ServicePoint__c.SiteCountry__c',
    'ServicePoint__c.SiteBuilding__c',
    'ServicePoint__c.SiteFloor__c',
    'ServicePoint__c.SiteAt__c',
    'ServicePoint__c.SiteStaircase__c',
    'ServicePoint__c.PointStreetType__c',
    'ServicePoint__c.Trader__c',
    'ServicePoint__c.Voltage__c',
    'ServicePoint__c.VoltageLevel__c',
    'ServicePoint__c.CurrentAsset__r.ResidentialFlag__c',
    'ServicePoint__c.CurrentAsset__r.RequestedIndustrialSector__c',
    'ServicePoint__c.CurrentAsset__r.Usage__c',
    'ServicePoint__c.CurrentAsset__r.AvailablePower__c',
    'ServicePoint__c.IndustrialSector__c',
    'ServicePoint__c.PDRType__c',
    'ServicePoint__c.Usage__c',
    'ServicePoint__c.ExpectedAnnualWithdrawal__c',
    'ServicePoint__c.REMICode__c',
    'ServicePoint__c.TakingClass__c',
    'ServicePoint__c.TISGUseType__c',
    'ServicePoint__c.CurrentAsset__r.Account.FirstName__c',
    'ServicePoint__c.CurrentAsset__r.Account.LastName__c',
    'ServicePoint__c.CurrentAsset__r.Account.FiscalCode__c',
    'ServicePoint__c.CurrentAsset__r.Account.VATNumber__c',
    'ServicePoint__c.CurrentAsset__r.Account.CompanyName__c',
    'ServicePoint__c.CurrentAsset__r.Account.Code__c',
    'ServicePoint__c.CurrentAsset__r.VATTreatment__c',
    'ServicePoint__c.CurrentAsset__r.IPA__c',
    'ServicePoint__c.CurrentAsset__r.CIG__c',
    'ServicePoint__c.CurrentAsset__r.CUP__c',
    'ServicePoint__c.CurrentAsset__r.Account.RecordTypeDeveloperName__c',
    'ServicePoint__c.CurrentAsset__r.Account.Type',
    'ServicePoint__c.CurrentAsset__r.Excise__c',
    'ServicePoint__c.CurrentAsset__r.RegionalAdition__c',
    'ServicePoint__c.CurrentAsset__r.DailyConsumption__c'
];

const CONTESTABLE_POD_FIELDS = [
    'ContestablePod__c.City__c',
    'ContestablePod__c.StreetNumber__c',
    'ContestablePod__c.ISTATCode__c',
    'ContestablePod__c.PodCode__c',
    'ContestablePod__c.CreatedById',
    'ContestablePod__c.StreetNumberExt__c',
    'ContestablePod__c.Phase__c',
    'ContestablePod__c.Apartment__c',
    'ContestablePod__c.LastModifiedById',
    'ContestablePod__c.VoltageLevel__c',
    'ContestablePod__c.MeterSerialNumber__c',
    'ContestablePod__c.ActualMarket__c',
    'ContestablePod__c.EAMeters__c',
    'ContestablePod__c.ElectronicMeters__c',
    'ContestablePod__c.EPMeters__c',
    'ContestablePod__c.ERMeters__c',
    'ContestablePod__c.StreetName__c',
    'ContestablePod__c.OwnerId',
    'ContestablePod__c.Building__c',
    'ContestablePod__c.Floor__c',
    'ContestablePod__c.Name',
    'ContestablePod__c.PostalCode__c',
    'ContestablePod__c.ContractualPower__c',
    'ContestablePod__c.AvailablePower__c',
    'ContestablePod__c.PodPowerSetup__c',
    'ContestablePod__c.Province__c',
    'ContestablePod__c.DeliveryPoint__c',
    'ContestablePod__c.Staircase__c',
    'ContestablePod__c.CounterStatus__c',
    'ContestablePod__c.MainsVoltage__c',
    'ContestablePod__c.MetersType__c',
    'ContestablePod__c.PlaceName__c'
];


const prestazioneGasOptionList = [{ label: 'Switching Win', value: 'SWITCHING WIN' }, { label: 'Cambio Prodotto', value: 'CAMBIO PRODOTTO' },{ label: 'Cambio Prodotto Cross Brand', value: 'CAMBIO PRODOTTO CROSS BRAND' }];    
const prestazioneElectricOptionList = [{ label: 'Switching Win', value: 'SWITCHING WIN' }, { label: 'Cambio Prodotto', value: 'CAMBIO PRODOTTO' },{ label: 'Cambio Prodotto Cross Brand', value: 'CAMBIO PRODOTTO CROSS BRAND' }];  


export default class CepCommunityDedicatedProcessWizard extends LightningElement {
    labels = labels;
    @api pdcType;
    @track showEdit = false;
    @track isMondoLarge = false;
    @track _accountPrivate;
    @api
    get _account() {
        return this._accountPrivate;
    }
    set _account(value) {
        this._accountPrivate = JSON.parse(JSON.stringify(value));
        this._accountPrivate.fields = {};
        for (const key in this._accountPrivate) {
            const element = this._accountPrivate[key];
            this._accountPrivate.fields[key] = {};
            this._accountPrivate.fields[key].value = element;
        }
    }
    @track contact;
    @api isFromCommunity;
    @api interactionId;
    @api accountId;
    @api opportunityId;
    @api opportunityServiceItemId;
    @api isCambioUso = false;
    @api disabled = false;
    @api productFamily;
    @api isEditMode = false;
    @track showProcessEdit = false;
    @api hidePrescreeningSimulation = false;
    @api segmentAccount;
    @track servicePointId;
    @track osiUpdated;
    @track contestablePodId;
    @track pdaId;
    @track opportunityServiceItem;
    @track servicePoint;
    @track contestablePod;
    @track process;
    @track contractType;
    @track pod;
    @track opportunityCommodity;
    opportunityRecordType;
    @track commodity;
    @track isGas;
    @track isGasTrue;
    @track processFields;
    @track isTakeover;
    @track loadFields;
    @track showModal;
    @track showLoadingSpinner;
    @track osiFieldsToSave;
    @track hasAntichurn = false;
    @track atecoObject;
    @track toBeValuesSelected;
    isPrestazioneFormValid;
    @track prestazioneFields;
    @track prestazioni = [];
    @track distributorId;
    @track distributorName;
    @track distributorVATNumber;
    @track showSpinner;
    @track ivaCodeSelected;
    @track ivaNumberSelected;
    @track selectedProcessIncompatible = false;
    @track actualVoltageLevel;
    @track availablePowerSelected;
    @track isSaveDisabled = true;
    @track atecoManualSelection;
    currentAssetId;
    avantiButton = "avanti";
    editButton = "edit";
    @api channel;
    isServicePointOrContestable = false;
    takeOverFields;
    isContropartiCommerciali = false;
    switchingFields; 
    usageChangeFields;
    @track beneficiaryAccId;
    @track climaticZone;
    @track showNuovoPotenzaRichiesta = false;
    @track isSwitchingWin; 
    @track showCambioUso;
    @track loadSwitchingFields; 
    @track loadUsageChangeFields;
    @track isCurrentToBe; 
    @track isToBe; 
    @api primaryContactId; 
    @track isShowPreviousProduct = false;  
    @track previousProductId;  
    @track previousProduct;  
    @track showCambioProdotto = false;  
    @track previousProductName;
    @track traderPIVA;   
    @track traderName;
    @track takeOverAddressIsValid;
    @track switchingInAddressIsValid;
    @track _osiList;
    @track opportunityRecord;
    @api isMassMarket;
    wind3 = isWind3;
    compChan;

    get contractTypeValue(){
        return this.opportunityServiceItem ? this.opportunityServiceItem.ContractType__c : this._account && this._account.RecordType && this._account.RecordType.DeveloperName == 'CEP_RT_PhysicalPerson' && this.opportunityRecord && this.opportunityRecord.fields && this.opportunityRecord.fields.VatNumber__c && this.opportunityRecord.fields.VatNumber__c.value == undefined ? 'Persona fisica' : ''
    }

    cambioUsoProcess = CAMBIOUSOPROCESS;
    //NTT W3
    @wire(getOpportunityCompanyChannel, {idOpp : "$opportunityId"})
    companyChannel({error, data}) {
        console.log(data);
        if(data) {
            this.compChan = data;
        } else if(error){

        }

    };

    /* Get data needed for Switching Win date field validation logic */
    @wire(getRecord, { recordId: '$opportunityId', fields: [FIELD_OPP_VATNUMBER, FIELD_OPP_ANTICHURN, FIELD_OPP_NAME, FIELD_OPP_SIGNDATE, FIELD_OPP_SUPPLY_END, FIELD_OPP_SUPPLY_START, FIELD_OPP_REQUEST_TYPE] })
    opportunityRecord({error, data}) {
        if (data) {
            this.opportunityRecord = data;
        } else if (error) {
            this.dispatchEvent( 
                new ShowToastEvent({ 
                    title: 'Error querying Opportunity record', 
                    message: error.body.message, 
                    variant: 'error', 
                }), 
            ); 
        }
    };
    /* End of block */

    @wire(getRecord, { recordId: '$servicePointId', fields: SERVICE_POINT_FIELDS }) 
    wiredServicePoint({ error, data }) { 
        if (data) { 
            this.servicePoint = data; 
            console.log('SERVICE POINT ' + JSON.stringify(this.servicePoint)); 
            //if(data.fields.Distributor__c.value)  
            //this.loadFields = true; 
        }
        else if (error) { 
            this.dispatchEvent( 
                new ShowToastEvent({ 
                    title: 'Error querying service point', 
                    message: error.body.message, 
                    variant: 'error', 
                }), 
            ); 
 
            this.servicePoint = undefined; 
            this.loadFields = false; 
            this.loadSwitchingFields = false; 
            this.loadUsageChangeFields = false;
        }
    }

    @wire(getRecord, { recordId: '$distributorId', fields: DISTRIBUTOR_FIELDS })
    wiredDistributor({ error, data }) {
        if (data) {
            this.distributorName = data.fields.Name.value;
            this.distributorVATNumber = data.fields.VATNumber__c.value;
            console.log('distributor ' + JSON.stringify(this.distributorName));
        }
        else if (error) {
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Error querying distributor',
                    message: error.body.message,
                    variant: 'error',
                }),
            );
        }
        if (this.isEditMode)
            this.initializePrestazioneForm();
    }

    @wire(getRecord, { recordId: '$contestablePodId', fields: CONTESTABLE_POD_FIELDS })
    wiredContestablePod({ error, data }) {
        if (data) {
            this.contestablePod = data;
            console.log('contestable pod ' + JSON.stringify(this.contestablePod));
            this.initializePrestazioneForm();
            //this.loadFields = true;
            //this.setPrestazioneOptionList();
        }
        else if (error) {
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Error querying service point',
                    message: error.body.message,
                    variant: 'error',
                }),
            );

            this.servicePoint = undefined;
            //this.loadFields = false;
        }
    }

    //objectInfo;

    @wire(getObjectInfo, { objectApiName: OPPORTUNITY_SERVICE_ITEM_OBJECT.objectApiName })
    objectInfo;

    getRecordTypeId(recordTypeName) {
        let recordtypeinfo = this.objectInfo.data.recordTypeInfos;
        let recordTypeId;
        for (var eachRecordtype in recordtypeinfo) {
            if (recordtypeinfo[eachRecordtype].name === recordTypeName) {
                recordTypeId = recordtypeinfo[eachRecordtype].recordTypeId;
                break;
            }
        }
        console.log('returning -   ' + recordTypeId);
        return recordTypeId;
    }


    connectedCallback() {
        console.log('cepDedicatedProcessWizard:connectedCallback');
        this.wind3 = this.wind3 != true ? false : true;
        if (this.opportunityServiceItemId)
            this.searchOsi()
        console.log('servicePointId2021: ' + this.servicePointId);
        console.log('contestablePodId2021: ' + this.contestablePodId);
        this.setOppCommodity();
        this.isMondoLarge = isLargeSmeUser || isSmallBusinessUser || isAgencyReseller || isLargeAema || isUmbriaEnergy;
    }

    searchOsi() { 
        let qryFields = Array.from(Object.keys(this.objectInfo.data.fields)); 
        let pos; 
        for (var i = 0; i < qryFields.length; i++) { 
            if (qryFields[i] === 'CloneSourceId') { 
                pos = i; 
                break; 
            } 
        } 
        if (pos) { 
            delete qryFields[pos]; 
        } 
        let inputs = { 
            osiId: this.opportunityServiceItemId, 
            queryFields: JSON.stringify(qryFields) 
        } 
        getOsi({ 
            params: inputs 
        }) 
            .then((response) => { 
                if (response) { 
                    if (response.error) { 
                        error(this, response.errorMsg); 
                    } else { 
                        this.opportunityServiceItem = response.osi; 
                        this.servicePointId = this.opportunityServiceItem.ServicePoint__c ?  this.opportunityServiceItem.ServicePoint__c : null;
                        console.log("OpportnitySerceItemId: " + this.opportunityServiceItemId); 
                        console.log("Data 2020: " + JSON.stringify(this.opportunityServiceItem)); 
                        this.pod = this.opportunityServiceItem.ServicePointCode__c; 
                        this.process = this.opportunityServiceItem.Process__c; 
                        this.contractType = this.opportunityServiceItem.ContractType__c; 
                        this.setCommodity(); 
                        if(this.opportunityServiceItem.Process__c.toLowerCase() == "cambio prodotto"){
                            this.getPreviousProductData();
                        }else{
                            this.initializePrestazioneForm(); 
                        }
                        if (this.isTakeover) { 
                            let takeOverWizard = this.template.querySelector('[data-id="takeoverWizard"]'); 
                            if (takeOverWizard && isLargeSmeUser && !isEmptyString(this.opportunityServiceItem)) { 
                                takeOverWizard.processExternalValue('Usage__c', this.opportunityServiceItem.Usage__c); 
                            } 
                        } else { 
                            let switchingWizard = this.template.querySelector('[data-id="switchingWizard"]'); 
                            if (switchingWizard && isLargeSmeUser && !isEmptyString(this.opportunityServiceItem)) { 
                                switchingWizard.processExternalValue('Usage__c', this.opportunityServiceItem.Usage__c); 
                            } 
                        } 
                        this.showModalHandler(); 
                        if (this.isEditMode) { 
                            this.isSaveDisabled = false; 
                        } 
                    } 
                } 
            }) 
            .catch((errorMsg) => { 
                error(this, errorMsg); 
            }); 
    } 

    handleFirstFormLoaded() {
        if (this.isEditMode) {
            let prestazioneForm = this.template.querySelector('[data-id="firstForm"]');
            console.log('this process ' + this.process);
            console.log('this gas ' + this.isGas);
            if (prestazioneForm) {
                if (!this.isGas)
                    prestazioneForm.setFieldTypeAttribute('Process__c', 'options', prestazioneElectricOptionList);
                else
                    prestazioneForm.setFieldTypeAttribute('Process__c', 'options', prestazioneGasOptionList);
                if (this.process && this.process !== '')
                    console.log('settato valore')
                    prestazioneForm.setFieldValue('Process__c', this.process);
            }
        }

    }

    @api getPrescreening() {

    }

    @wire(getRecord, { recordId: '$primaryContactId', fields: [CONTACT_FIRST_NAME, CONTACT_LAST_NAME, CONTACT_PHONE, CONTACT_MOBILE] }) 
    wiredAccount({ error, data }) { 
        if (data) { 
            this.contact = data.fields; 
            console.log('Interlocutorrrr:  ' + JSON.stringify(data));
        } 
        else if (error) { 
            this.showToastMessage('Error querying Account', error.body.message, 'error'); 
        } 
    } 

    initializePrestazioneForm() {
            if(this.wind3){
                this.prestazioneFields = [
                    {
                    name: 'Service_Point_Code__c',
                    label: 'POD',
                        visible: true,
                    value: this.opportunityServiceItem ? this.opportunityServiceItem.Service_Point_Code__c : this.pod,
                        valid: true,
                        required: true,
                        disabled: true,
                        type: {
                            type: 'text'
                        }
                    },
                    {
                        name: 'Commodity__c',
                        label: 'Commodity',
                        visible: true,
                        value: this.commodity,
                        valid: true,
                        required: true,
                        disabled: true,
                        type: {
                            type: 'text'
                        }
                    },
                    {
                        name: 'ContractType__c',
                        label: 'Tipo Contratto',
                        visible: true,
                        // value: this.opportunityServiceItem ? this.opportunityServiceItem.ContractType__c : this._account && this._account.RecordType && this._account.RecordType.DeveloperName == 'CEP_RT_PhysicalPerson' && this._account.VATNumber__c == undefined ? 'Persona fisica' : '',
                        value: this.contractTypeValue,
                        valid: true,
                        required: this._account && this._account.RecordType && this._account.RecordType.DeveloperName && this._account.RecordType.DeveloperName == 'CEP_RT_PhysicalPerson',
                        disabled: this.opportunityServiceItemId || (this._account && this._account.RecordType.DeveloperName && this._account.RecordType.DeveloperName == 'CEP_RT_Organization') || (this._account && this._account.RecordType.DeveloperName == 'CEP_RT_PhysicalPerson' && this.opportunityRecord && this.opportunityRecord.fields && this.opportunityRecord.fields.VatNumber__c && this.opportunityRecord.fields.VatNumber__c.value == undefined),
                        type: {
                            type: 'picklist',
                            typeAttributes: {
                                objectName: 'OpportunityServiceItem__c',
                                fieldName: 'ContractType__c'
                            }
                        }
                    },
                    {
                        name: 'EffectiveDate__c',
                        label: 'Data decorrenza',
                    visible: this.isGasTrue,
                        value: this.opportunityServiceItem ? this.opportunityServiceItem.EffectiveDate__c : '',
                        valid: true,
                        required: false,
                        disabled: this.opportunityServiceItemId,
                        type: {
                            type: 'date',
                        }
                    },
                    {
                        name: 'PreviousProduct__c',
                        label: 'Offerta precedente',
                        visible: false,
                        value: this.previousProductName,
                        valid: true,
                        required: false,
                        disabled: true,
                        type: {
                            type: 'text',
                        }
                    },
                    {
                        name: 'PreviousProduct',
                        label: 'Ulteriori informazioni',
                        visible: false,
                        value: 'button',
                        required: false,
                        disabled: false,
                        type: {
                            type: 'button'
                        }
                    },
                    {
                        name: 'Process__c',
                        label: 'Prestazione',
                        visible: true,
                        value: this.opportunityServiceItem ? this.opportunityServiceItem.Process__c : this.process,
                        valid: true,
                        required: true,
                        disabled: this.opportunityServiceItemId,
                        type: {
                            type: 'picklist',
                            typeAttributes: {
                            options: this.prestazioni
                            //options: this.prestazioni ? this.prestazioni : (this.commodity && this.commodity === 'Gas' ? prestazioneGasOptionList : prestazioneElectricOptionList)
                            }
                        }
                    }
                ];
    
    
            }else{
                this.prestazioneFields = [
                    {
                    name: 'Service_Point_Code__c',
                    label: 'POD',
                        visible: true,
                    value: this.opportunityServiceItem ? this.opportunityServiceItem.Service_Point_Code__c : this.pod,
                        valid: true,
                        required: true,
                        disabled: true,
                        type: {
                            type: 'text'
                        }
                    },
                    {
                        name: 'Process__c',
                        label: 'Prestazione',
                        visible: true,
                    value: this.opportunityServiceItem ? this.opportunityServiceItem.Process__c : this.process,
                        valid: true,
                        required: true,
                        disabled: this.opportunityServiceItemId,
                        type: {
                            type: 'picklist',
                            typeAttributes: {
                            options: this.prestazioni
                            //options: this.prestazioni ? this.prestazioni : (this.commodity && this.commodity === 'Gas' ? prestazioneGasOptionList : prestazioneElectricOptionList)
                            }
                        }
                    },
                    {
                        name: 'Commodity__c',
                        label: 'Commodity',
                        visible: true,
                        value: this.commodity,
                        valid: true,
                        required: true,
                        disabled: true,
                        type: {
                            type: 'text'
                        }
                    },
                    {
                        name: 'ContractType__c',
                        label: 'Tipo Contratto',
                        visible: true,
                        // value: this.opportunityServiceItem ? this.opportunityServiceItem.ContractType__c : this._account && this._account.RecordType && this._account.RecordType.DeveloperName == 'CEP_RT_PhysicalPerson' && this._account.VATNumber__c == undefined ? 'Persona fisica' : '',
                        value: this.contractTypeValue,
                        valid: true,
                        required: this._account && this._account.RecordType && this._account.RecordType.DeveloperName && this._account.RecordType.DeveloperName == 'CEP_RT_PhysicalPerson',
                        disabled: this.opportunityServiceItemId || (this._account && this._account.RecordType.DeveloperName && this._account.RecordType.DeveloperName == 'CEP_RT_Organization') || (this._account && this._account.RecordType.DeveloperName == 'CEP_RT_PhysicalPerson' && this.opportunityRecord && this.opportunityRecord.fields && this.opportunityRecord.fields.VatNumber__c && this.opportunityRecord.fields.VatNumber__c.value == undefined),
                        type: {
                            type: 'picklist',
                            typeAttributes: {
                                objectName: 'OpportunityServiceItem__c',
                                fieldName: 'ContractType__c'
                            }
                        }
                    },
                    {
                        name: 'EffectiveDate__c',
                        label: 'Data decorrenza',
                    visible: this.isGasTrue,
                        value: this.opportunityServiceItem ? this.opportunityServiceItem.EffectiveDate__c : '',
                        valid: true,
                        required: false,
                        disabled: this.opportunityServiceItemId,
                        type: {
                            type: 'date',
                        }
                    },
                    {
                        name: 'PreviousProduct__c',
                        label: 'Offerta precedente',
                        visible: false,
                        value: this.previousProductName,
                        valid: true,
                        required: false,
                        disabled: true,
                        type: {
                            type: 'text',
                        }
                    },
                    {
                        name: 'PreviousProduct',
                        label: 'Ulteriori informazioni',
                        visible: false,
                        value: 'button',
                        required: false,
                        disabled: false,
                        type: {
                            type: 'button'
                        }
                    },
                    
                ];
            }
     

            
        //if (!isLargeSmeUser && !isLargeAema && !isUmbriaEnergy && !isSmallBusinessUser && !isAgencyReseller && this._account && this._account.RecordType && this._account.RecordType.DeveloperName == 'CEP_RT_PhysicalPerson' && this._account.VATNumber__c == undefined) {
        //if (!isLargeSmeUser && !isLargeAema && !isUmbriaEnergy && !isSmallBusinessUser && !isAgencyReseller &&    && this._account && this._account.RecordType && this._account.RecordType.DeveloperName == 'CEP_RT_PhysicalPerson' && this.opportunityRecord && this.opportunityRecord.fields && this.opportunityRecord.fields.VatNumber__c && this.opportunityRecord.fields.VatNumber__c.value == undefined
        if (!isLargeSmeUser && !isLargeAema && !isUmbriaEnergy && !isSmallBusinessUser && !isAgencyReseller) {
            this.contractType = this.contractTypeValue //'Persona fisica'
        }

        // if (this.isCambioUso) {
        //     // SETTARE DIRETTAMENTE NELL'ARRAY
        //     this.prestazioneFields[0].type.typeAttributes.options = ['Cambio Uso'];
        //     this.prestazioneFields[0].disabled = this.isCambioUso;
        //     this.prestazioneFields[0].value = 'Cambio Uso';
        //     this.process = 'Cambio Uso'
        // }

        // if (!this.showCambioProdotto) {
        //     // let prestazioniNew = [];
        //     // if(this.isGas)
        //     //     prestazioniNew = ;
        //     // else prestazioniNew = prestazioneElectricOptionList.slice(0, 3);
        //     this.prestazioneFields[0].type.typeAttributes.options = this.prestazioni.filter(function (obj) {
        //         return obj.label.toLowerCase() != 'cambio prodotto';
        //     });
        //     console.log("Prestazioniiii " + JSON.stringify(this.prestazioni));
        // }

        /*cambioUsoProcess().then(result=>{
            this.prestazioneFields[1].value = result;
        });*/
        //this.prestazioneFields[1].value = 'Cambio Uso';

        if (this.isEditMode) {
            this.isPrestazioneFormValid = true;
        }

    }

    setCommodity() {
        console.log("this.pod: " + this.pod);
        if (this.pod.toLowerCase().startsWith('it')) {
            this.commodity = 'Electric';
        }
        else {
            this.commodity = 'Gas';
        }
        this.isGas = this.commodity == 'Gas';
    }

    @api get account() {
        return this._account;
    }
    set account(val) {
        if (val)
            this._account = val;
    }

    @api get osiList(){
        return this._osiList;
    }

    set osiList(val){
        this._osiList = val;
        if(this._osiList)
            console.log('osiList length: '+this._osiList.length);
    }

    searchPodPdr() {
        let counter = 0;
        if(this._osiList){
            Array.from(this._osiList).forEach(element=>{
                if(element.Process__c.toUpperCase() != 'ATTIVAZIONE VAS'){
                    counter++;
                }
            })
        }
        if(!this.isMassMarket || (this.isMassMarket && counter < 5)){
        this.loadFields = false;
        this.loadSwitchingFields = false; 
        this.loadUsageChangeFields = false;
        this.servicePoint = null;
        this.servicePointId = null;
        this.takeOverFields = null;
        this.switchingFields = null; 
        this.usageChangeFields = null;
        this.isTakeover = false;
        this.isSwitchingWin = false; 
        this.showCambioUso = false;
        this.isMondoLarge = false;  
        this.isCurrentToBe = false;  
        this.isToBe = false; 
        console.log('cepDedicatedProcessWizard:searchPodPdr');
        let searchBox = this.template.querySelector('[data-id="searchBox"]');
        var serchValue = searchBox.value;
        let value = searchBox.value;
        this.pod = searchBox.value;

        if (searchBox && !this.pod || this.pod.trim() === '') {
            searchBox.classList.add('slds-has-error');
            this.loading = false;
            error(this, this.labels.requiredFields);
            return;
        }

        if (!this.validate()) {
            error(this, 'Inserire un formato POD/PDR corretto');
            return;
        }
        this.pod = this.pod.trim();
        this.setCommodity();
        console.log("this.opportunityCommodity: " + this.opportunityCommodity);
        console.log("this.commodity: " + this.commodity);

        if (isLargeSmeUser || isLargeAema || isUmbriaEnergy || isAgencyReseller || isSmallBusinessUser) {
            if (!(this.commodity == this.opportunityCommodity)) {
                error(this, 'Inserire un POD/PDR con commodity corretta');
                return;
            }
        }

        this.showLoadingSpinner = true;
        console.log('serchValue2 ' +serchValue);
        queryPoint({
            searchText: serchValue,
            accountId: this.accountId,
            opportunityId : this.opportunityId
        }).then((response) => {
            console.log('serchValue ' +serchValue);
            this.setProcess(response);
            console.log("Prestazioni: " + JSON.stringify(response.prestazioni));
            
            console.log("Query Result: " + JSON.stringify(response.isContropartiCommerciali));

            let spod = response.servicePointsPod;
            let cpod = response.contendibilePod;
            this.isServicePointOrContestable = cpod.length > 0 || spod.length > 0;
            console.log("isServicePointOrContestable: " + this.isServicePointOrContestable);
            if (response.pdaPod && response.pdaPod.length > 0) {
                var podPda = response.podPda;
                this.pdaId = podPda[0].Id;
            }
            else if (response.contendibilePod && response.contendibilePod.length > 0) {
                var podContendibile = response.contendibilePod;
                this.contestablePodId = podContendibile[0].Id;
            }
            else if (response.servicePointsPod && response.servicePointsPod.length > 0) {
                var podService = response.servicePointsPod;
                this.servicePointId = podService[0].Id;
                this.currentAssetId = podService[0].CurrentAsset__c;
            }
            if (response.distributorName) {
                this.distributorName = response.distributorName;
                this.distributorVATNumber = response.distributorVATNumber;
            }

            if (response.prestazioni) {
                 //NTT WIND3 - Caso W3
                if (response.prestazioni.toLocaleString().toUpperCase()=='ERRORE'){
                    error(this, 'Il prodotto è gia associato a W3 proseguire con il modifica offerta');
                }
                //
                
                if(!this.wind3){
                    if (response.prestazioni.toLocaleString().toUpperCase().includes('CAMBIO PRODOTTO')) {
                        if(this.opportunityRecord.fields.Antichurn__c.value){
                            this.prestazioni.push({label: 'Switching Win', value: 'Switching Win' });
                            this.hasAntichurn = true;
                        }else{
                            if(!response.isContropartiCommerciali){
                                this.prestazioni.push({label: 'Cambio Prodotto', value: 'Cambio Prodotto' });
                                this.hasAntichurn = false;
                                console.log('cambio 1');

                            }
                        }
                    }
                }
                //NTT WIND3 - Caso AE 
                if (response.prestazioni.toLocaleString().toUpperCase().includes('CAMBIO PRODOTTO CROSS BRAND')) {
                    if(this.opportunityRecord.fields.Antichurn__c.value){
                        this.prestazioni.push({label: 'Switching Win', value: 'Switching Win' });
                        this.hasAntichurn = true;
                    }else{
                        //this.prestazioni.pop();
                        this.prestazioni.push({label: 'Cambio Prodotto Cross Brand', value: 'Cambio Prodotto' });
                        this.hasAntichurn = false;
                        console.log('Cambio 2');
                    }
                }
                else if (response.prestazioni.toLocaleString().toUpperCase().includes('SWITCHING WIN')) {
                    this.prestazioni.push({label: 'Switching Win', value: 'Switching Win' });
                    this.hasAntichurn = false;
                }else{
                    error(this, 'Nessuna prestazione compatibile per il punto');
                }
                /*
                if(response.isContropartiCommerciali){
                    if(response.prestazioni.includes('Cambio Prodotto') ){
                        response.prestazioni.splice(0, 1);
                    }
                }  */

                let prestazioneForm = this.template.querySelector('[data-id="firstForm"]');
                if (prestazioneForm && this.prestazioni) {
                    prestazioneForm.setFieldTypeAttribute('UsageCategory__c', 'options', this.prestazioni);
                    //prestazioneForm.setFieldTypeAttribute('Process__c', 'options', this.prestazioni);
                }
                if(response.isContropartiCommerciali ){
                    this.isContropartiCommerciali = true;
                        if(!this.prestazioni.includes('Switching Win') ){
                            this.prestazioni.push({label: 'Switching Win', value: 'Switching Win' });
                        }
                }
                this.showLoadingSpinner = false;
            }
            if (this.pod.toLowerCase().startsWith('it')) {
                this.isGas = false;
                this.isGasTrue = false;
            }
            else {
                this.isGas = true;
                this.isGasTrue = true;
            }
            if ((response.servicePointsPod && response.servicePointsPod.length > 0) || (response.contendibilePod && response.contendibilePod.length > 0)) {
                return getPreviousProduct({
                    commodity: this.commodity,
                    accountID: this.accountId,
                    servicePointCode: this.pod
                })
            } else {
                this.showCambioProdotto = false;
                this.isGas = this.commodity == 'Gas';
                this.showModal = true;
                this.initializePrestazioneForm();
                // this.checkForProductChange();
                this.showLoadingSpinner = false;
                //this.setPrestazioneOptionList();
            }

        }).then((response2) => {
            if (response2 && response2.servicePoint) {
                this.previousProduct = response2.servicePoint;
                this.previousProductId = response2.servicePoint.CurrentAsset__r.Product2Id;
                this.previousProductName =  response2.servicePoint.CurrentAsset__r.Product2.Name;
                this.showCambioProdotto = true;
            } else {
                this.showCambioProdotto = false;
            }            
            this.isGas = this.commodity == 'Gas';
            this.showModal = true;
            this.initializePrestazioneForm();
            // this.checkForProductChange();
            this.showLoadingSpinner = false;
            //this.setPrestazioneOptionList();
        }).catch((errorMsg) => {
            console.log(JSON.stringify(errorMsg))
        });
        console.log('servicePointId2021: ' + this.servicePointId);
        console.log('contestablePodId2021: ' + this.contestablePodId);
    }else{
        let message = 'Limite massimo di richieste raggiunto :  5';
        this.dispatchEvent(
            new ShowToastEvent({
                title: 'Errore',
                message: message,
                variant: 'error',
            }),
        );
    }
   

    }

    setProcess(servicePoint, opportunityServiceItem) {
        if (servicePoint) {
            // TODO : Process default value to be defined based on the service point status
            this.process = '';
        }
        else if (opportunityServiceItem) {
            this.process = opportunityServiceItem.Process__c;
        }
    }

    handleCloseModalOsi() {
        this.resetForm();
        this.showModal = false;
        this.loadFields = false;
        this.loadSwitchingFields = false; 
        this.loadUsageChangeFields = false;
        this.showProcessEdit = false;
        this.dispatchEvent(new CustomEvent('close'));
    }

    saveOsi() {
        /*if (this.isTakeover) {
            this.createFieldObjToSave();
            let formValid = this.formValidityManager();
            let formValidAddress = this.formValidForAddress('takeover');
            if (formValid && formValidAddress) {
                //this.formValidForAddress();
                this.saveOSI();
            }
            else {
                let message = '';
                if(formValid && !formValidAddress){
                    message = 'Normalizzare o Forzare l \'indirizzo';
                }else{
                    message = 'Controllare i campi obbligatori';
                }
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Errore',
                        message: message,
                        variant: 'error',
                    }),
                );

            }
        } else*/ 
        if(this.process.toLowerCase()=='cambio prodotto cross brand'){
            console.log('chiudi modale');
            this.handleCloseModalOsi();
            return;
        }
        if (this.isSwitchingWin) { 
            this.createFieldObjToSave(); 
            let formValid = this.formValidityManager();
            if(this.process === 'Cambio Prodotto' || this.process === 'Cambio Prodotto Cross Brand'){
                console.log('this.process: '+this.process);
                if (formValid) { 
                    this.saveOSI(); 
                }else{
                    let message = 'Controllare i campi obbligatori';
                    this.dispatchEvent(
                        new ShowToastEvent({
                            title: 'Errore',
                            message: message,
                            variant: 'error',
                        }),
                    );
                }
            }else{
                let addressMandatoryFields = this.formValidForAddress('switchingIn');
                if (formValid && addressMandatoryFields && addressMandatoryFields.isValid) { 
                    this.saveOSI(); 
                } 
                else { 
                    if(formValid && !addressMandatoryFields.isValid){
                        addressMandatoryFields.error.forEach((currentError) => {
                            error(this, currentError);
                        });
                    }else{
                        error(this, 'Controllare i campi obbligatori');
                    }
                }
            }
        } 
        
    }   

    saveOSI() { 
        console.log("OSI PArams :" + JSON.stringify(this.osiFieldsToSave)); 
        if (this.osiFieldsToSave) { 
            if (this.opportunityServiceItemId) { 
                this.osiFieldsToSave.Id = this.opportunityServiceItemId; 
            } 
            if (this.isTakeover) 
                this.insertOpportunityServiceItem(); 
            else 
                this.insertOpportunityServiceItemSwitching(this.osiFieldsToSave); 
        } 
        
    } 

    checkForMissingFields(fields, objToCheck) {
        let fieldsMap = objToCheck.data.fields;
        let missingFields = [];
        Object.entries(fields).forEach(element => {
            if (element[1] == null || element[1] == undefined || element[1] == '')
                if (element[0] != "UsageCategory__c") 
                    delete this.osiFieldsToSave[element[0]]; 
            if (!fieldsMap.hasOwnProperty(element[0])) {
                missingFields.push(element[0]);
            }
        });
        return missingFields;

    }

    dispatchSaveEvent(osi) {
        this.dispatchEvent(new CustomEvent('save', {
            detail: {
                'opportunityServiceItemId': osi.id,
                'opportunityServiceItem': osi
            }

        }, { bubbles: true }));
        this.showModal = false;
    }

    async insertOpportunityServiceItem() {

        try {
            this.showSpinner = true;
            const response = await insertOsi({
                params: {
                    OSI: JSON.stringify(this.osiFieldsToSave),
                    codeAteco: this.atecoObject && this.atecoObject.Code__c ? this.atecoObject.Code__c : null,
                    actualVoltageLevel: !!this.actualVoltageLevel ? this.actualVoltageLevel : null,
                    atecoId: !!this.atecoManualSelection ? this.atecoManualSelection : null
                }
            });

            console.log('insertOpportunityServiceItem response');
            console.log(JSON.parse(JSON.stringify(response)));

            /**
             * Handle response error
             */
            if (response.error) {
                if (response.isOrdinario) {
                    this.dispatchEvent(
                        new ShowToastEvent({
                            title: 'Impossibile salvare OSI',
                            message: response.message,
                            variant: 'error',
                        }),
                    );
                } else {
                    error(this, response.errorMsg);
                }
                /** 
                 * Handle response success 
                 */ 
            } else {
                let osiId = response.osi.Id;
                if (this.isGas)
                    checkDistrVat({ params: { osiId: osiId } }).then(result => { 
                        if (result.error) 
                            error(this, result.errorMsg); 
                    });
                this.dispatchEvent(new CustomEvent('save', {
                    detail: {
                        opportunityServiceItemId: response.osi.Id,
                        opportunityServiceItem: response.osi,
                        showNuovoPotenzaRichiesta: this.showNuovoPotenzaRichiesta
                    }
                }));
                this.resetForm();
                this.showModal = false;
            }

            /**
            * Handle exception
            */
        } catch (error) {
            console.log('saveOSI catch error');
            console.log(JSON.parse(JSON.stringify(error)));
            error(this, `${errorMsg} - ${errorTrace}`);
        } finally {
            this.showSpinner = false;
        }
    }

    insertOpportunityServiceItemSwitching(recordInput) { 
        this.showSpinner = true;
        let atecoId = this.atecoManualSelection;
        let atecoCode = this.atecoObject && this.atecoObject.Code__c ? this.atecoObject.Code__c : null;
        let inputs = { 'OSI': JSON.stringify(recordInput), 'codeAteco': atecoCode, 'atecoId': atecoId, 'isFromCommunity': 'true', isMassMarket: 'true' };
        console.log('OSI JSON IN SAVING...' + JSON.stringify(recordInput));
        insertOsiSwitching({
            params: inputs
        })
            .then((response) => {
                if (response) {
                    this.showSpinner = false;
                    if (response.error) {
                        if (response.isOrdinario) {
                            this.dispatchEvent(
                                new ShowToastEvent({
                                    title: 'Impossibile salvare OSI',
                                    message: response.message,
                                    variant: 'error',
                                }),
                            );
                        }
                        else {
                            var errArray = response.errorMsg.split("FIELD_CUSTOM_VALIDATION_EXCEPTION,");
                            var err = errArray.length > 1 ? errArray[1] : errArray[0];
                            err = err.split(": []")[0];
                            error(this, err);
                        }
                    } else {
                        this.showLoadingSpinner = false;
                        console.log(JSON.stringify(response.osi));
                        this.dispatchEvent(new CustomEvent('save', {
                            detail: { opportunityServiceItemId: response.osi.Id, showNuovoPotenzaRichiesta: this.showNuovoPotenzaRichiesta }
                        }));
                        this.resetForm();
                        this.showModal = false;
                    }
                }
            })
            .catch((errorMsg) => {
                this.showSpinner = false;
                error(this, errorMsg);
            });

        /* createRecord(recordInput)
            .then(osiInserted => {
                this.showLoadingSpinner = false;
                console.log(JSON.stringify(osiInserted));
                this.dispatchSaveEvent(osiInserted);
            })
            .catch(error => {
                this.showLoadingSpinner = false;
                this.dispatchEvent(
                 new ShowToastEvent({
                        title: 'Error creating record',
                        message: error.body.message,
                        variant: 'error',
                    }),
                );

                this.showModal = false;
            });*/
    } 

    handleFieldChange(event) {
        // this.showProcessEdit = true;
        console.log(JSON.stringify(event));
        if (event.detail.source == "prestazione") {
            this.isPrestazioneFormValid = event.detail.formValid;
            switch (event.detail.field) {
                case "Process__c":
                    this.process = event.detail.value;
                    if (!this.isEditMode) {
                        this.checkProcessCompatibility();
                    }
                    let prestazioneForm = this.template.querySelector('[data-id="firstForm"]');
                    if (event.detail.value.toLowerCase() == "cambio prodotto") {
                        this.handleChangeProductSelected(prestazioneForm);
                    } else {
                        prestazioneForm.setFieldStatus("PreviousProduct__c", "visible", false);
                        prestazioneForm.setFieldStatus("PreviousProduct", "visible", false);
                    }

                    if (event.detail.value.toLowerCase() == "cambio prodotto" || event.detail.value.toLowerCase() == "switching win") {
                        prestazioneForm.setFieldStatus("EffectiveDate__c", "visible", false);
                    } else if (this.isGas){
                        prestazioneForm.setFieldStatus("EffectiveDate__c", "visible", true);
                    }

                    return;
                case "ContractType__c":
                    this.contractType = event.detail.value;
                    break;
                case "PreviousProduct":
                    this.isShowPreviousProduct = true;
            }
        }

    }

    firePrescreening() {
        //HERE THE PRESCREENING
        let avantiButton = this.template.querySelector('[data-id="avantiButton"]');
        if (avantiButton) { 
            avantiButton.disabled = true;
        }
        this.showSpinner = true;
        isPrescreeningEnabled({ channel: this.channel, performance: this.process }) 
            .then(response => { 
                if (response) { 
                    if (!response.error) { 
                        if (response.enabled) 
                            this.getPrescreeningCheck(); 
                        else { 
                            this.showSpinner = false;
                            if(this.process.toLowerCase()!='cambio prodotto'){ 
                                this.dispatchEvent( 
                                    new ShowToastEvent({ 
                                        title: 'Prescreening', 
                                        message: 'Prescreening non abilitato per canale ' + this.channel + ' e prestazione ' + this.process, 
                                        variant: 'warning', 
                                    }), 
                                ); 
                            }
                            avantiButton.disabled = false;
                        } 
                    } 
                    else { 
                        this.showSpinner = false; 
                        this.dispatchEvent( 
                            new ShowToastEvent({ 
                                title: 'Prescreening', 
                                message: response.errorMsg, 
                                variant: 'warning', 
                            }), 
                        ); 
                        avantiButton.disabled = false; 
                        updateOpportunityPrescreening({ prescreeningStatus: 'Non Previsto', oppId: this.opportunityId }).then(response => { 
                            if (response.error) { 
                                this.showSpinner = false; 
                                this.dispatchEvent( 
                                    new ShowToastEvent({ 
                                        title: 'Prescreening', 
                                        message: response.errorStacktrace, 
                                        variant: 'warning', 
                                    }), 
                                ); 
                            } 
                        }) 
                    } 
                } 
            }) 
    } 

    getPrescreeningCheck() {
        let avantiButton = this.template.querySelector('[data-id="avantiButton"]');
        prescreeningCheck({ accountId: this.accountId, oppId: this.opportunityId })
            .then((response) => {
                if (response) {
                    avantiButton.disabled = false;
                    if (response.preescreeningAlreadyRequired) { 
                        this.dispatchEvent(
                            new ShowToastEvent({
                                title: 'Prescreening',
                                message: 'Preescreening già richiesto per il cliente corrente ',
                                variant: 'warning',
                            }),
                        );
                        this.showSpinner = false;
                        return;
                    }
                    if (response.error || response.esito && response.esito.toLowerCase() === 'errore') {
                        this.dispatchEvent(
                            new ShowToastEvent({
                                title: 'Prescreening',
                                message: 'Errore tecnico, sistema non disponibile ',
                                variant: 'warning',
                            }),
                        );
                        this.showSpinner = false;
                        if (response.codiceAteco) {
                            let codiceAteco = response.codiceAteco;
                            atecoTranscoding({ codeAteco: codiceAteco, accountId: this.accountId, contractType: this.contractType }).then(result => {
                                if (result) {
                                    this.atecoObject = result.ateco;
                                    this.setAtecoField(this.atecoObject);
                                }
                            })
                        }
                        else {
                            this.setAtecoField(null);
                        }
                    } else if (response.prescreening) {
                        this.showSpinner = false;
                        this.dispatchEvent(
                            new ShowToastEvent({
                                title: 'Prescreening',
                                message: 'Prescreening recuperato in cache con esito ' + response.esito,
                                variant: response.esito.toLowerCase() == 'ko lavorabile' ? 'warning' : response.esito.toLowerCase() == 'ko non lavorabile' ? 'error' : 'success',
                            }),
                        );
                        if (response.esito.toLowerCase() == 'ko non lavorabile') {
                            this.dispatchPrescreeningEvent('Fatal');
                        }
                        if (response.esito.toLowerCase() == 'ko lavorabile') {
                            this.dispatchPrescreeningEvent('kolavorabile');
                        }
                        if (response.codiceAteco && response.atecoObj) { 
                            //let codiceAteco = response.codiceAteco; 
                            this.atecoObject = response.atecoObj; 
                            this.setAtecoField(this.atecoObject); 
                        } 
                    }
                    else {
                        this.showSpinner = false;
                        if (response.esito.toLowerCase() == 'ok') {
                            let codiceAteco = response.codiceAteco;
                            atecoTranscoding({ codeAteco: codiceAteco, accountId: this.accountId, contractType: this.contractType }).then(result => {
                                if (result) {
                                    this.atecoObject = result.ateco;
                                    this.setAtecoField(this.atecoObject);
                                    this.dispatchPrescreeningEvent('OK');
                                }
                            })
                        }
                        else if (response.esito.toLowerCase() == 'ko lavorabile') {
                            this.dispatchPrescreeningEvent('kolavorabile');
                        }
                        else if (response.esito.toLowerCase() == 'ko non lavorabile') {
                            this.dispatchPrescreeningEvent('Fatal');
                        }
                    }
                }
            })
            .catch((errorMsg) => {
                error(this, errorMsg);
                this.showSpinner = false;
                avantiButton.disabled = false;
            });
    }

    setAtecoField(value) { 
        if (this.isTakeover) { 
            let takeOverWizard = this.template.querySelector('[data-id="takeoverWizard"]'); 
            if (takeOverWizard && value) { 
                takeOverWizard.putAtecoObj(value);  
            } 
        } else {  
            let switchingWizard = this.template.querySelector('[data-id="switchingWizard"]'); 
            if (switchingWizard && value) { 
                switchingWizard.putAtecoObj(value);

            } 
        } 
    }   

    checkProcessCompatibility() {
        if (!isLargeSmeUser && !isLargeAema && !isUmbriaEnergy && !isAgencyReseller && !isSmallBusinessUser) {
            if(this.process.toLowerCase()!='cambio prodotto'){
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Prescreening',
                        message: 'In attesa prescreening...',
                        variant: 'warning',
                    }),
                );
            }
        }
        this.showSpinner = true;
        let input = {
            podPdr: this.pod, startingProcess: this.process,
            channel: this.channel ? this.channel : '*', commodity: this.commodity,
            distributor: this.servicePoint && this.distributorName ? this.distributorName : '*'
        };
        processCompatibility({ params: input }).then(response => {
            if (response) {
                if (response.error) {
                    this.showSpinner = false;
                    if (!isLargeSmeUser && !isLargeAema && !isUmbriaEnergy && !isAgencyReseller && !isSmallBusinessUser) {
                        this.firePrescreening();
                    }
                }
                else {
                    if (response.incompatibility) {
                        let msg = response.incompatibleObject ? response.incompatibleObject.toLowerCase().includes('opportunity') ? 'Opportunity' : 'Integration Case' : '';
                        let blkObj = ' bloccante : ' + response.records && response.records.length > 0 ? response.records[0].Name : '';
                        this.dispatchEvent(
                            new ShowToastEvent({
                                title: 'Processo non compatibile',
                                message: msg + blkObj,
                                variant: 'warning',
                            }),
                        );
                        let prestazioneForm = this.template.querySelector('[data-id="firstForm"]');
                        if (prestazioneForm) {
                            prestazioneForm.setFieldValue('Process__c', '');
                        }
                        this.resetForm();
                        this.showSpinner = false;
                        this.selectedProcessIncompatible = true;
                    }
                    else {
                        this.selectedProcessIncompatible = false;
                        if (!isLargeSmeUser && !isLargeAema && !isUmbriaEnergy && !isAgencyReseller && !isSmallBusinessUser) {
                            this.firePrescreening();
                        } else {
                            this.showSpinner = false;
                        }
                    }
                    //this.showSpinner = false;
                }
            }
        }).catch((errorMsg) => {
            error(this, errorMsg);
            this.showSpinner = false;
        });
    }

    simulaOKPrescreening() {
        this.dispatchPrescreeningEvent('OK');
    }

    simulaKOLavorabilePrescreening() {
        this.dispatchPrescreeningEvent('Error');
    }

    simulaKONonLavorabilePrescreening() {
        this.dispatchPrescreeningEvent('Fatal');
    }

    dispatchPrescreeningEvent(tipoEsito) {
        this.dispatchEvent(new CustomEvent('prescreeningoutcome', {
            detail: {
                'type': tipoEsito
            }

        }, { bubbles: true }));
    }
    resetForm() {
        //this.prestazioneFieldDisable(false);
        this.process = '';
        this.servicePointId = undefined;
        this.contestablePodId = undefined;
        this.contestablePod = null;
        this.servicePoint = null;
        let avantiButton = this.template.querySelector('[data-id="avantiButton"]');
        let editButton = this.template.querySelector('[data-id="editButton"]');
        if (avantiButton) { 
            avantiButton.disabled = false;
        }
        if (editButton) { 
            editButton.disabled = true;
        }
        this.showProcessEdit = false;
        this.osiFieldsToSave = null;
        this.prestazioni = [];
        this.toBeValuesSelected = null;
        this.actualVoltageLevel = null;
        this.availablePowerSelected = null;
        this.address = {};
        this.distributorVATNumber = null;
        this.distributorName = null;
        this.distributorId = null;
        this.isSaveDisabled = true;
        this.opportunityServiceItem = null;
        this.opportunityServiceItemId = null;
        this.beneficiaryAccId = null;
        this.climaticZone = null;
        if (this.template.querySelector('c-cep-takeover-wizard'))   
            this.template.querySelector('c-cep-takeover-wizard').resetForm();
        if (this.template.querySelector('c-cep-switching-win-wizard'))  
            this.template.querySelector('c-cep-switching-win-wizard').resetForm();  

        if (this.template.querySelector('c-cep-osi-referente-punto')) 
            this.template.querySelector('c-cep-osi-referente-punto').resetForm(); 

        this.atecoManualSelection = null;
        this.pod = '';
        this.loadFields = false;
        this.loadSwitchingFields = false; 
        this.loadUsageChangeFields = false;
        this.showModal = false;
    }



    prestazioneFieldDisable(isPrestazione, buttonclk) {
        let formBuilder = this.template.querySelector('[data-id="firstForm"]');
        if (formBuilder && buttonclk && buttonclk === this.editButton) {
            this.showProcessEdit = false;
            this.editButtonStatus(buttonclk);
            formBuilder.setFieldStatus('Process__c', 'disabled', isPrestazione);
            if (!isLargeSmeUser && !isLargeAema && !isUmbriaEnergy && !isAgencyReseller && !isSmallBusinessUser) {
                formBuilder.setFieldStatus('ContractType__c', 'disabled', this.opportunityServiceItemId || (this._account && this._account.RecordType.DeveloperName && this._account.RecordType.DeveloperName == 'CEP_RT_Organization') || (this._account && this._account.RecordType.DeveloperName == 'CEP_RT_PhysicalPerson' && this._account.VATNumber__c == undefined));
                formBuilder.setFieldStatus('EffectiveDate__c', 'disabled', isPrestazione);
            }
            return;
        }
        let isPrestazioneSelected = this.process && this.process !== '';
        let formBuilerCmp = this.template.querySelector('c-form-builder');
        let prestazioneIsValid = true;
        if (formBuilerCmp) { 
            prestazioneIsValid = formBuilerCmp.showFieldsErrorFocus();
        }
        if (isPrestazioneSelected && prestazioneIsValid) {
            //formBuilder.setFieldValue('Process__c', this.process);
            formBuilder.setFieldStatus('Process__c', 'disabled', isPrestazione);
            if (!isLargeSmeUser && !isLargeAema && !isUmbriaEnergy && !isAgencyReseller && !isSmallBusinessUser) {
                formBuilder.setFieldStatus('ContractType__c', 'disabled', isPrestazione);
                formBuilder.setFieldStatus('EffectiveDate__c', 'disabled', isPrestazione);
            }
            this.editButtonStatus(this.avantiButton);
            this.showModalHandler();
        }
        else { 
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Errore',
                    message: 'Seleziona un tipo di prestazione',
                    variant: 'error',
                }),
            );
        }
    }

    handleAvantiModalPrestazione() {
        console.log('this process incompatible ' + this.selectedProcessIncompatible);
        console.log('this commodity ' + this.commodity);
        console.log('this wave 1' + this.checkProcessiWave1());
        if (this.checkProcessiWave1() && !this.selectedProcessIncompatible) {
            this.prestazioneFieldDisable(true);
            //this.setPrestazioneOptionList();
        }
        else {
            if (this.selectedProcessIncompatible) {
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Errore',
                        message: 'Selezionare un processo compatibile',
                        variant: 'error',
                    }),
                );
            }
            else {
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Errore',
                        message: 'Funzionalità non disponibile per tipo di prestazione : ' + this.process,
                        variant: 'error',
                    }),
                );
            }
        }
    }
    handleEditModalPrestazione() {
        this.prestazioneFieldDisable(false, this.editButton);
        //this.setPrestazioneOptionList();
    }

    editButtonStatus(buttonClicked) {
        let avantiButton = this.template.querySelector('[data-id="avantiButton"]');
        let editButton = this.template.querySelector('[data-id="editButton"]');
        if (buttonClicked === this.avantiButton) {
            avantiButton.disabled = true;
            editButton.disabled = false;
            this.isSaveDisabled = false;
        }
        if (buttonClicked === this.editButton) {
            avantiButton.disabled = false;
            editButton.disabled = true;
            this.isSaveDisabled = true;
            let formBuilder = this.template.querySelector('[data-id="firstForm"]');
            //formBuilder.setFieldStatus('Process__c', 'disabled', false);
            //formBuilder.setFieldValue('Process__c', this.process);
        }
    }

    @track osiReferrerPointFields;
    /**
     * Handle c-cep-osi-referente-punto event
     * @param {*} event 
     */
    handleOsiReferrerPoint(event) { 
        this.osiReferrerPointFields = event.detail;
    }

    handleSelectedValue(event) {
        this.showNuovoPotenzaRichiesta = event.detail.showNuovoPotenzaRichiesta;
        let fieldSelected = event.detail.campo;
        let valueSelected = event.detail.valore;
        this.toBeValuesSelected = event.detail.allFields;
        if (fieldSelected == 'ActualVoltageLevel__c' || fieldSelected == 'VoltageLevel__c') {
            this.actualVoltageLevel = valueSelected;
        }
        if (fieldSelected == 'ContractualPower__c' || fieldSelected == 'RequestedContractualPower__c') {
            this.availablePowerSelected = this.toBeValuesSelected.AvailablePower__c;
        }
        if (this.isTakeover) { 
            let takeOverWizard = this.template.querySelector('[data-id="takeoverWizard"]'); 
            if (takeOverWizard) { 
                takeOverWizard.processExternalValue(fieldSelected, valueSelected); 
                if (isLargeSmeUser && isLargeAema && isUmbriaEnergy) { 
                    takeOverWizard.processExternalValue('Usage__c', this.opportunityServiceItem.Usage__c); 
                } 
            } 
        } else { 
            let switchingWizard = this.template.querySelector('[data-id="switchingWizard"]'); 
            if (switchingWizard) { 
                switchingWizard.processExternalValue(fieldSelected, valueSelected); 
                if (isLargeSmeUser && isLargeAema && isUmbriaEnergy)  {
                    switchingWizard.processExternalValue('Usage__c', this.opportunityServiceItem.Usage__c); 
                } 
            } 
        }

        this.isEditMode = false;
    }
    handleIvaSelected(event) {
        if (!this.isEditMode) { 
            let source = event.detail.source;
            let ivaFieldSelected = event.detail.ivaField;
            this.ivaCodeSelected = event.detail.ivaCode;
            this.ivaNumberSelected = event.detail.ivaNumber;
            if (this.isTakeover) { 
                let takeOverWizard = this.template.querySelector('[data-id="takeoverWizard"]'); 
                if (takeOverWizard && source && source.toLowerCase().includes('cepcurrenttobevalue')) { 
                    takeOverWizard.processIva(ivaFieldSelected); 
                } 
            } else { 
                let switchingWizard = this.template.querySelector('[data-id="switchingWizard"]'); 
                if (switchingWizard && source && source.toLowerCase().includes('ceptobevalue')) { 
                    switchingWizard.processIva(ivaFieldSelected); 
                } 
            }
        }
        //this.isEditMode = false;
    }
    handleTakeoverDataChange(event) { 
        let name = event.detail.name; 
        switch (name) { 
            case 'distributorselected': 
                this.handleDistributorSelected(event); 
                break; 
            case 'atecomanualselection': 
                this.handleAtecoManualSelection(event); 
                break; 
            case 'selectediva': 
                this.handleIvaSelected(event); 
                break; 
            case 'addresschanged': 
                this.handleAddressChanged(event); 
                break; 
            case 'beneficiaryselected':  
                this.handleBeneficiarySelected(event);  
                break;  
            case 'selectedclimaticzonegas':  
                this.handleSelectedClimaticZone(event);  
            default:  
                break;  
        }  
    } 

    handleSwitchingDataChange(event) { 
        let name = event.detail.name; 
        switch (name) { 
            case 'distributorselected': 
                this.handleDistributorSelected(event); 
                break; 
            case 'atecomanualselection': 
                this.handleAtecoManualSelection(event); 
                break; 
            case 'selectediva': 
                this.handleIvaSelected(event); 
                break; 
            case 'addresschanged': 
                this.handleAddressChanged(event); 
                break; 
            case 'beneficiaryselected': 
                this.handleBeneficiarySelected(event); 
                break; 
            case 'selectedclimaticzonegas': 
                this.handleSelectedClimaticZone(event); 
                break;
            case 'traderselected' : 
                this.handleSelectedTrader(event); 
                break;
            default: 
                break; 
        } 
    } 

    handleSelectedClimaticZone(event) {
        this.climaticZone = event.detail.climaticzoneCode;
    }

    handleSelectedTrader(event) {
        this.traderPIVA = event.detail.traderPIVA;
        this.traderName = event.detail.traderName;
    }

    handleDistributorSelected(event) {
        this.distributorVATNumber = event.detail.distributorVAT;
        this.distributorName = event.detail.distributorName;
    }

    handleAddressChanged(event) {
        this.isSaveDisabled = event.detail.disableSave;
    }

    createFieldObjToSave() {
        console.log('OPP OBJ :' + JSON.stringify(this.objectInfo.data.fields));
        var osiFields;
        var takeOverFields;
        var switchingFields; 
        var usageChangeFields;
        var prestazioneF;
        var toBeValueFields;
        this.isCambioUso = false;
        console.log('this.isCambioUso:' + this.isCambioUso + '   showProcessWizard:' + this.loadFields);
        let takeOver;
        let switching; 
        let usageChange;
        let prestazione;
        if (this.isCambioUso) {
            usageChange = this.template.querySelector('[data-id="usageChangeWizard"]');
            prestazione = this.template.querySelector('[data-id="firstForm"]');
            console.log('cmp: usageChange ' + takeOver);
        } else if (this.isTakeover) { 
            takeOver = this.template.querySelector('[data-id="takeoverWizard"]');
            prestazione = this.template.querySelector('[data-id="firstForm"]');
            toBeValueFields = this.toBeValuesSelected;
            console.log('cmp: takeoverWizard ' + toBeValueFields);
        } else { 
            switching = this.template.querySelector('[data-id="switchingWizard"]'); 
            prestazione = this.template.querySelector('[data-id="firstForm"]'); 
            toBeValueFields = this.toBeValuesSelected; 
            console.log('cmp: switchingWizard ' + JSON.stringify(toBeValueFields)); 
        }
        if (takeOver) {
            takeOverFields = takeOver.getOpportunityServiceItemFields();
            if (prestazione) {
                prestazioneF = prestazione.visibleFields;
            }
            if (!this.isGas)
                osiFields = {
                    ...takeOverFields,
                    ...prestazioneF,
                    ...toBeValueFields
                };
            else
                osiFields = {
                    ...takeOverFields,
                    ...prestazioneF
                };
        } else if (switching) { 
            switchingFields = switching.getOpportunityServiceItemFields(); 
            console.log('cmp: switchingWizard2 ' + JSON.stringify(switchingFields)); 
            if (prestazione) { 
                prestazioneF = prestazione.visibleFields; 
            } 
            if (!this.isGas) 
                osiFields = { 
                    ...switchingFields, 
                    ...prestazioneF, 
                    ...toBeValueFields 
                }; 
            else 
                osiFields = { 
                    ...switchingFields, 
                    ...prestazioneF 
                }; 
        } else if (usageChange) {
            usageChangeFields = usageChange.getOpportunityServiceItemFields();
            console.log('cmp: usageChangeFields2 ' + JSON.stringify(usageChangeFields));
            if (prestazione) {
                prestazioneF = prestazione.visibleFields;
            }
            osiFields = {
                ...switchingFields,
                ...prestazioneF
            }
        }
        if (osiFields) {
            osiFields.RecordTypeId = this.getRecordTypeId(this.commodity);
            osiFields.Opportunity__c = this.opportunityId;
            osiFields.ProductFamily__c = this.productFamily;
            osiFields.ServicePointCode__c = this.pod;
            osiFields.ServicePoint__c = this.servicePointId;
            osiFields.Account__c = this.accountId;
            osiFields.VATClass__c = 'Reseller' != this.segmentAccount ? this.ivaCodeSelected : 'RZ'; 
            osiFields.VATRate__c = 'Reseller' != this.segmentAccount ? this.ivaNumberSelected : '0';
            osiFields.AvailablePower__c = this.availablePowerSelected ? this.availablePowerSelected.toString().replace(',', '.') : osiFields.AvailablePower__c ? osiFields.AvailablePower__c.toString().replace(',', '.') : null;
            osiFields.ContractualPower__c = osiFields.ContractualPower__c ? osiFields.ContractualPower__c.toString().replace(',', '.') : null;
            osiFields.RequestedAvailablePower__c = osiFields.RequestedAvailablePower__c ? osiFields.RequestedAvailablePower__c.toString().replace(',', '.') : null;
            osiFields.RevenueAgencyRegistrationOngoing__c = osiFields.RevenueAgencyRegistrationOngoing__c ? (osiFields.RevenueAgencyRegistrationOngoing__c == 'SI' ? true : false) : false;
            if(osiFields.Process__c.toLowerCase() == 'cambio prodotto' && this.commodity == 'Gas'){
                if(this.servicePoint){
                    osiFields.DistributorName__c = this.servicePoint.fields && this.servicePoint.fields.DistributorName__c ? this.servicePoint.fields.DistributorName__c.value : null;
                    osiFields.DistributorVATNumber__c = this.servicePoint.fields&& this.servicePoint.fields.DistributorVATNumber__c ? this.servicePoint.fields.DistributorVATNumber__c.value : null;
                    osiFields.Distributor__c = this.servicePoint.fields&& this.servicePoint.fields.Distributor__c ? this.servicePoint.fields.Distributor__c.value : null;
                }
            }else{
                osiFields.DistributorName__c = this.distributorName;
                osiFields.DistributorVATNumber__c = this.distributorVATNumber;
                osiFields.Distributor__c = this.distributorId;
            }

            //NTT W3
            console.log('fuori cambio prodotto cross brand');
            console.log(this.compChan);
                
            if(osiFields.Process__c.toLowerCase() == 'cambio prodotto' && this.wind3 == true && this.compChan == 'AE'){
                console.log('dentro cambio prodotto cross brand');
                osiFields.Process__c = 'Cambio Prodotto Cross Brand';
            }
            //


            osiFields.PreviousProduct__c = this.previousProductId;
            let powerPhase = '';
            if (osiFields.VoltageLevel__c) {
                powerPhase = osiFields.VoltageLevel__c.toLowerCase() == 'bt monofase' ? 'Monofase' : 'Trifase';
            }
            osiFields.PowerPhase__c = powerPhase;
            if (this.isGas && osiFields.PDRType__c)
                osiFields.Usage__c = osiFields.PDRType__c;
            // if(this.atecoManualSelection)
            //     osiFields.CodeAteco__c = this.atecoManualSelection;
            osiFields.BeneficiaryAccount__c = this.beneficiaryAccId;
            osiFields.PreviousTraderVATNumber__c = this.traderPIVA;
            osiFields.PreviousTraderName__c = this.traderName;
            osiFields.ClimaticZone__c = this.climaticZone;
            osiFields.Antichurn__c = this.hasAntichurn;
            this.osiFieldsToSave = osiFields;

            //THIS DELETE NON VALUED FIELDS FROM JSON (PREVENTING TO PASS 'NULL' IN SOME DATA OR BOOLEAN FIELDS)
            this.checkForMissingFields(osiFields, this.objectInfo); 
            //console.log('FINAL OSI OBJ INM SAVING ', JSON.stringify(this.osiFieldsToSave));

            this.osiFieldsToSave = {
                ...this.osiFieldsToSave,
                ...this.osiReferrerPointFields,
            };

            console.log('+++++++++++++++++++++++++')
            console.log('createFieldObjToSave: this.osiFieldsToSave');
            console.log(JSON.parse(JSON.stringify(this.osiFieldsToSave)));
            console.log('+++++++++++++++++++++++++')


            // THIS FUNCTION HELPS TO CHECK IF THERE'S SOME MISSING FIELD IN OSI OBJECT
            /*let missingFields = this.checkForMissingFields(osiFields,this.objectInfo);
            if(missingFields.length>0){
                let missFields = '';
                missingFields.forEach(element =>{
                    missFields+= JSON.stringify(element) +'\n';
                })
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Missing Fields in ' + OPPORTUNITY_SERVICE_ITEM_OBJECT.objectApiName,
                        message: missFields,
                        variant: 'warning',
                    }),
                );
            } */
        }
    }

    formValidityManager() {
         // if (this.isEditMode)
        //     return true;
        let takeOverIsValid = true;
        let takeOverCmp = this.template.querySelector('c-cep-takeover-wizard');
        if (takeOverCmp) {
            takeOverIsValid = takeOverCmp.getFormValidity();
            console.log('takeOverIsValid: ' + takeOverIsValid);
        }
        let formBuilerCmp = this.template.querySelector('c-form-builder');
        let prestazioneIsValid = true;
        if (formBuilerCmp) { 
            prestazioneIsValid = formBuilerCmp.showFieldsErrorFocus();
        }
        if (this.isSwitchingWin) { 
            let switchingWinIsValid = true; 
            let awitchingWinCmp = this.template.querySelector('c-cep-switching-win-wizard'); 
            if (awitchingWinCmp) { 
                switchingWinIsValid = awitchingWinCmp.getFormValidity(); 
            } 
            let toBeValCmp = this.template.querySelector('c-cep-to-be-value'); 
            let toBeValValid = true; 
            if (toBeValCmp) { 
                toBeValValid = toBeValCmp.getFormValidity(); 
            } 
            // let switchingWinAddressFormCmp = this.template.querySelector('c-cep-switching-win-wizard');
            // this.switchingInAddressIsValid = true;
            // if(this.switchingWinAddressFormCmp){
            //     this.switchingInAddressIsValid = switchingWinAddressFormCmp.getAddressValidity();
            //     console.log('switchingInAddressIsValid: ' + this.switchingInAddressIsValid);
            // }
            return switchingWinIsValid && prestazioneIsValid && toBeValValid;// && switchingInAddressIsValid; 

        } else { 
            let takeOverIsValid = true; 
            let takeOverCmp = this.template.querySelector('c-cep-takeover-wizard'); 
            if (takeOverCmp) { 
                takeOverIsValid = takeOverCmp.getFormValidity(); 
            } 
            let currentValCmp = this.template.querySelector('c-cep-current-to-be-value'); 
            let tbvValid = true; 
            if (currentValCmp) { 
                tbvValid = currentValCmp.getFormValidity(); 
            } 
            // let takeOverAddressFormCmp = this.template.querySelector('c-cep-takeover-wizard');
            // this.takeOverAddressIsValid = true;
            // if(takeOverAddressFormCmp){
            //     this.takeOverAddressIsValid = takeOverCmp.getAddressValidity();
            //     console.log('takeOverAddressIsValid: ' + this.takeOverAddressIsValid);
            // }
            console.log('takeOverIsValid : ' + takeOverIsValid); 
            console.log('prestazioneIsValid : ' + takeOverIsValid); 
            console.log('currentToBeIsValid : ' + takeOverIsValid); 
 
            let osiReferrerPointCmp = this.template.querySelector('c-cep-osi-referente-punto'); 
            let osiReferrerPointValid = true; 
            if (osiReferrerPointCmp) { 
                osiReferrerPointValid = osiReferrerPointCmp.getFormValidity(); 
            }
            console.log('osiReferrerPointValid : ' + osiReferrerPointValid); 
            console.log('takeOverIsValid : ' + takeOverIsValid); 
            console.log('prestazioneIsValid : ' + takeOverIsValid); 
            console.log('currentToBeIsValid : ' + takeOverIsValid); 
            return takeOverIsValid && prestazioneIsValid && tbvValid && osiReferrerPointValid;// && takeOverAddressIsValid; 
        }
        console.log('osiReferrerPointValid : ' + osiReferrerPointValid);
        console.log('takeOverIsValid : ' + takeOverIsValid);
        console.log('prestazioneIsValid : ' + takeOverIsValid);
        console.log('currentToBeIsValid : ' + takeOverIsValid);
        return takeOverIsValid && prestazioneIsValid && tbvValid && osiReferrerPointValid;
    }

    @api showModalHandler() {
        this.showModal = true;
        if (this.process === 'SWITCHING WIN' || this.process === 'Switching Win' || this.process === 'Cambio Prodotto' || this.process === 'CAMBIO PRODOTTO' || this.process == 'Cambio Prodotto Cross Brand' || this.process == 'CAMBIO PRODOTTO CROSS BRAND') { 
            this.loadSwitchingFields = true; 
        } else if(this.process === 'Cambio Uso' || this.process === 'Cambio uso'){ 
            this.loadUsageChangeFields = true; 
        }else {
            this.loadFields = true;
        } 
        this.showProcessEdit = true;
    }

    validate() {
        const gmPatt = /^(\d{14})$/i;
        const eePatt = /^(\w{2}\d{3}\w{1}\d{8})$/i;
        //const eePattv2 = /^(\w{2}\d{3}\w{1}\d{7}\w{1})$/i;
        const eePattv2 = /^(IT\d{3}E\d{7}\w{1})$/i;
        let matchResult = gmPatt.test(this.pod);
        if (!matchResult) {
            //matchResult = eePatt.test(this.pod);
            //if (!matchResult) {
            matchResult = eePattv2.test(this.pod); 
            //}
        }
        return matchResult;
    }

    setOppCommodity() { 
        console.log("opportunityId: " + this.opportunityId);
        if (this.opportunityId) { 
            getOppCommodity({
                opportunityId: this.opportunityId
            }).then((response) => {
                console.log("opportunityCommodity: " + JSON.stringify(response));
                this.opportunityRecordType = response.recType;

                if (response.commodity == "Gas") { 
                    this.opportunityCommodity = "Gas";
                } else if (response.commodity == "Elettrico" || response.commodity == "Electric") { 
                    this.opportunityCommodity = "Electric"
                }
                console.log("this.opportunityCommodity: " + this.opportunityCommodity);

            }).catch((errorMsg) => {
                console.log(JSON.stringify(errorMsg))
            });
        }
    }


    checkProcessiWave1() {
        let valid = false;
        if (this.process) {
            if (this.commodity == 'Electric') {
                prestazioneElectricOptionList.forEach(element => {
                    console.log('process lower case '+this.process.toLowerCase());
                    console.log('element value ' + element.value.toLowerCase());
                    if (this.process.toLowerCase() == element.value.toLowerCase()) {
                        valid = true;
                    }
                    else if(this.process.toLowerCase()=='cambio prodotto cross brand' && element.value.toLowerCase()=='cambio prodotto'){
                        valid = true;
                    }
                })
            }
            if (this.commodity == 'Gas') {
                prestazioneGasOptionList.forEach(element => {
                    if (this.process.toLowerCase() == element.value.toLowerCase()) {
                        valid = true;
                    }
                    else if(this.process.toLowerCase()=='cambio prodotto cross brand' && element.value.toLowerCase()=='cambio prodotto'){
                        valid = true;
                    }
                })
            }
            return valid;
        }
        else {
            return true;
        }
    }

    handleSearchBoxInput(event) {
        let input = event.detail.value;
        if (input) {
            let searchBox = this.template.querySelector('[data-id="searchBox"]');
            if (searchBox) {
                searchBox.value = input.toUpperCase();
            }
        }
    }
    handleAtecoManualSelection(event) { 
        this.atecoManualSelection = event.detail.Id;
        if (this.isTakeover) { 
            let ctb = this.template.querySelector('c-cep-current-to-be-value'); 
            if (ctb) 
                //ctb.setRequestedIndustrialSectorFromAteco(event.detail.atecoDescription); 
                ctb.setRequestedIndustrialSectorFromAteco(event.detail.atecueDescription); 
 
        } else { 
            let tb = this.template.querySelector('c-cep-to-be-value'); 
            if (tb) 
                tb.setRequestedIndustrialSectorFromAteco(event.detail.atecueDescription); 
        } 
    }

    handleFieldInit(event) { 
        this.takeOverFields = event.detail;
        this.isCurrentToBe = !this.isGas; 
        this.isToBe = false; 
        this.isTakeover = true;
    }

    handleSwitchingFieldInit(event) { 
        this.switchingFields = event.detail; 
        this.isCurrentToBe = false; 
        this.isToBe = !this.isGas && (this.process.toLowerCase() != 'cambio prodotto' && this.process.toLowerCase() != 'cambio prodotto cross brand'); 
        this.isSwitchingWin = true; 
    } 

    handleUsageChangeFieldInit(event){
        this.usageChangeFields = event.detail;
        console.log("Dedicated Fields " + JSON.stringify(event.detail));
        this.isCurrentToBe = false;
        this.isToBe = false;
        this.showCambioUso = true;
    }

    activateSpinner(active) {
        this.showSpinner = active;
    }

    handleSpinner(event) { 
        this.activateSpinner(event.detail.active);
    }

    handleBeneficiarySelected(event) { 
        this.beneficiaryAccId = event.detail.beneficiaryId;
    }

    handleTakeOverFieldChange(event) { 
        this.isEditMode = false;
    }

    handleSwitchingFieldChange(event) { 
        this.isEditMode = false; 
    } 

    handleUsageChangeFieldChange(event) {
        this.isEditMode = false;
    }

    getPreviousProductData() {
        if ((this.servicePointId || this.contestablePodId) && this.commodity && this.accountId && this.pod) {
            getPreviousProduct({
                commodity: this.commodity,
                accountID: this.accountId,
                servicePointCode: this.pod
            }).then((response) => {
                if (response.servicePoint) {
                    this.previousProduct = response.servicePoint;
                    this.previousProductId = response.servicePoint.CurrentAsset__r.Product2Id;
                    this.previousProductName =  response.servicePoint.CurrentAsset__r.Product2.Name;
                    this.initializePrestazioneForm();
                }
            }).catch((errorMsg) => {
                console.log("Previous Product: error " + JSON.stringify(errorMsg))
                this.initializePrestazioneForm();
            });
        }
    }

    handleChangeProductSelected(prestazioneForm) {
        prestazioneForm.setFieldStatus("PreviousProduct__c", "visible", true);
        prestazioneForm.setFieldValue("PreviousProduct__c", this.previousProduct.CurrentAsset__r.Product2.Name);
        prestazioneForm.setFieldStatus("PreviousProduct", "visible", true);
        // this.servicePointId = this.previousProductId;
    }

    handleClosePreviousProductModal() {
        this.isShowPreviousProduct = false;
    }

    // handleTraderSelected(event){ 
    //     this.traderId = event.detail.traderId; 
    // } 

    formValidForAddress(type){
        //let addressIsValid = true;
        let addressMandatoryFields = {
            error: [],
            isValid: false
        };
        switch (type) {
            /*case "takeover":
                let takeOverAddressFormCmp = this.template.querySelector('c-cep-takeover-wizard');
                if(takeOverAddressFormCmp){
                    addressIsValid = takeOverAddressFormCmp.getAddressValidity() || switchingWinAddressFormCmp.getIsAddressForced();;
                    console.log('takeOverAddressIsValid: ' + addressIsValid);
                }
                break;*/
            case "switchingIn":
                let switchingWinAddressFormCmp = this.template.querySelector('c-cep-switching-win-wizard');
                if(switchingWinAddressFormCmp){
                    addressMandatoryFields = switchingWinAddressFormCmp.getAddressMandatoryFields();
                }
                break;
        }
        return addressMandatoryFields;
    }
}