Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
39 kB
1
Indexable
Never
import { LightningElement, api, track } from 'lwc';
import addressValidated from '@salesforce/label/c.AddressValidated';
import normalizeLabel from '@salesforce/label/c.NormalizeAddress';
import forceAddressLabel from '@salesforce/label/c.ForceAddress';
import errorCitySelect from '@salesforce/label/c.ErrorCitySelect';
import errorStreetTypeSelect from '@salesforce/label/c.ErrorStreetTypeSelect';
import findByCityName from "@salesforce/apex/AddressService.findByCityName";
import findAvailableCaps from "@salesforce/apex/CEP_LC_ProcessStartValidator.checkAvailableCaps";
import getCountry from "@salesforce/apex/AddressService.getCountry";
import checkCountry from "@salesforce/apex/AddressService.checkCountry";
import { error, warn } from "c/notificationSvc";
import { noValidCharRegEx } from 'c/cepUtilities';
import normalize from '@salesforce/apex/AddressService.normalize';
import isWind3 from '@salesforce/customPermission/NTT_isWind3';

import NumeroCivico from '@salesforce/label/c.Tooltip_NumeroCivico'; 
import EstensioneNum from '@salesforce/label/c.Tooltip_EstensioneNum'; 





export default class AddressEdit extends LightningElement {
    //CityTooltip = cityTool;
    //tooltipToponimo = toponimo;
    tooltipStreetNumExt = EstensioneNum;
    tooltipStreetNumber = NumeroCivico;
    labels = {
        addressValidated,
        normalizeLabel,
        forceAddressLabel,
        errorCitySelect,
        errorStreetTypeSelect
    };
    @api objectApiName;
    @api availableAddresses;
    @api availableAddressesUbicazione;
    @api addressPrefix;
    @api address;
    @api addressLayoutApiName;
    @api readOnly = false;
    @api disableNormalize = false;
    @api addressNormalized = false;
    @api addressForced = false;
    @api isNormalize = false;
    @api isNewRecord;
    @api formData;
    @api recordId;
    @api disableSave;
    @api showMessage = false;
    @api readOnlyButton = false;
    @track spinner = false;
    @track showAddressPicker = false;
    @track showLoadingSpinner = false;
    @track addressParts = [];
    @track value = 'N°';
    @track valueType = '';//'Via';
    @track Required__c = true;
    @track Hidden__c = false;
    @track disableNum = false;
    @track disableExt = false;
    @track countryErr;
    @track cap='';
    @track streetTypes = [];
    @track addrField = {};
    @track addr = {
        StreetType__c: this.valueType,
        StreetName__c: "",
        StreetNumberType__c: this.value,
        StreetNumber__c: "",
        StreetNumberExtn__c: "",
        PostalCode__c: "",
        City__c: "",
        IstatCode__c: "",
        Province__c: "",
        Country__c: "Italia",
        Locality__c: "",
        Building__c: "",
        Apartment__c: "",
        Staircase__c: "",
        Floor__c: "",
        At__c: "",
        AddressNormalized__c: false,
        AddressForced__c: false,
        CadastralCode__c: ""
    };
    privateChildrenRecord = {};
    fields = [];
    error;
    selectedAddress = '';
    _notRequired;
    notInizializeAddress = true;
    adrs = false;
    rdnly = false;
    formdt = false;
    errorMsg = "Seleziona un paese dall'elenco";
    changeCivico = true;
    wind3 = isWind3;


    get addressesToCopy() {
        if (!this.availableAddresses) {
            return [];
        }
        return Object.keys(this.availableAddresses).map(function (key) {
            return { key: key, values: this.availableAddresses[key] };
        }, this);
    }

    get addressesUbicazioneToCopy() {
        if (!this.availableAddressesUbicazione || this.availableAddresses) {
            return [];
        }
        return Object.keys(this.availableAddressesUbicazione).map(function (key) {
            return { key: key, values: this.availableAddressesUbicazione[key] };
        }, this);
    }

    get options() {
        return [
            { label: 'N°', value: 'N°' },
            { label: 'KM', value: 'KM' },
            { label: 'SNC', value: 'SNC' }
        ];
    }

    @api
    set notRequired(value) {
        if (value) {
            this._notRequired = value;
        }
    }
    get notRequired() {
        return this._notRequired;
    }

    connectedCallback() {
        this.wind3 = this.wind3 != true ? false : true;
        let field = ["StreetType__c", "StreetName__c", "StreetNumberType__c", "StreetNumber__c", "StreetNumberExtn__c",
            "PostalCode__c", "City__c", "IstatCode__c", "Province__c", "Country__c",
            "Locality__c", "Building__c", "Apartment__c", "Staircase__c",
            "Floor__c", "At__c", "AddressNormalized__c", "AddressForced__c", "CadastralCode__c"];
        field.forEach(str => {
            this.addrField[str] = this.addressPrefix + str;
        });
        if (this.address) {
            this.adrs = true;
        }
        if (this.readOnly) {
            this.rdnly = true;
        }
        if (this.formData) {
            this.formdt = true;
        }
        this.addr.AddressNormalized__c = this.isNormalize;
        this.addr.AddressForced__c = this.addressForced;
    }

    renderedCallback() {
        if (this.adrs) {
            this.notInizializeAddress = false;
            this.setAddress(this.address);
            this.adrs = false;
        }
        if (this.rdnly) {
            if (!this.isNormalize) {
                this.isNormalize = this.addressNormalized;
            }
            this.disableAllInputs();
            this.rdnly = false;
        }
        /* if (this.formdt) {
            this.notInizializeAddress = false;
            this.setAddress(this.formData);
            this.formdt = false;
        } */
        if(this._notRequired){
            const addrLightForm = this.template.querySelectorAll('lightning-input-field.wr-required');
            addrLightForm.forEach(obj => {
                obj.classList.remove('wr-required');
            });
            this.template.querySelector('lightning-combobox[data-id="streetNumberType"]').classList.remove('wr-required');
            this.template.querySelector('c-cep-street-type-selector').required = false;
            this.template.querySelector('c-cep-city-selector').required = false;
            this.Required__c = false;
        }
    }

    findIstatCode(event) {
        if (event) {
            this.addr.City__c = event.detail.value.city;
            this.addr.Province__c = event.detail.value.provinceAbbreviation;
            this.addr.CadastralCode__c = event.detail.value.cadastralCode;
            if (this.addr.City__c) {
                this.findIstatByCity(this.addr.City__c);
            } else {
                event.target.classList.add('slds-has-error');
            }
        }
    }

    findIstatByCity(city) {
        this.showLoadingSpinner = true;
        findByCityName({
            cityName: city
        }).then(response => {
            if (response.isError) {
                error(this, response.errorMessage);
            } else {
                if (response.data) {
                    this.addr.City__c = response.data.City__c;
                    this.addr.IstatCode__c = response.data.IstatCode__c;
                    this.addr.CadastralCode__c = response.data.CadastralCode__c;
                    this.addr.Province__c = response.data.ProvinceAbbreviation__c;
                    this.fireFoundIstatEvent(this.addr.IstatCode__c);
                }
            }
        }).catch(error => {
            console.log('error', error); 
        }).finally(() => {
            this.showLoadingSpinner = false;
        });
    }

    

    @api
    validate() {
        //LL: la validazione è composta da:
        //    boolean indirizzo normalizzato;
        //    boolean indirizzo forzato;
        //    array errori formali;
        //    array campi non compilati;
        //    se i campi sono compilati, la normalizzazione o forzatura è obbligatoria;
        const ret = {
            normalized: false,
            forced: false,
            valid: false,
            formal: [],
            required: []
        };
        let formalValid = this.formalValid();
        ret.formal = formalValid.error;

        if (!this.isValid() && !this.addressForced) {
            ret.formal.push("Hai compilato parzialmente un modulo e non hai forzato o normalizzato l'indirizzo");
        } else {
            ret.normalized = this.isNormalize;
            ret.forced = this.addressForced;
        }
        if (ret.formal.length == 0) {
            let requiredValid = this.requiredValid();
            ret.required = requiredValid.error;
        }
        new Promise((resolve) => {
            setTimeout(  
                () => {
                    this.showLoadingSpinner = false;
                }), 1000
        }); 
        ret.forced = this.addressForced;
        if ((ret.forced || ret.normalized) && ret.formal.length == 0 && ret.required.length == 0) {
            ret.valid = true;
        }
        return ret;
    }

    formalValid() {
        let formal = {
            error: [],
            isValid: false
        };
        const streetNum = this.template.querySelector("[data-id='streetNum']");
        const streetNumExt = this.template.querySelector("[data-id='streetNumExt']");
        const streetNumberType = this.template.querySelector('[data-id="streetNumberType"]');
        const addrCap = this.template.querySelector("[data-id='cap']");
        const streetType = this.template.querySelector('c-cep-street-type-selector');
        const streetName = this.template.querySelector("[data-id='streetName']");
        if (streetNumberType.value == "N°") {
            if (!/^[0-9]*$/.test(streetNum.value)) {
                formal.error.push("Il campo StreetNumber accetta solo numeri");
                streetNum.classList.add('slds-has-error');
            }
        } else if (streetNumberType.value == "KM" && streetNum.value) {
            if (!/^[1-9]\d*(,\d+)?$/.test(streetNum.value)) {
                formal.error.push("Il campo StreetNumber accetta solo numeri con la virgola");
                streetNum.classList.add('slds-has-error');
            }
        } else if (streetNumberType.value == "SNC" && streetNum.value && streetNumExt.value) {
            formal.error.push("I campi StreetNumber e StreetNumberExtension non possono essere compilati");
            streetNum.classList.add('slds-has-error');
            streetNumExt.classList.add('slds-has-error');
        }
        if (addrCap.value) {
            var reg = new RegExp(/^\d{5}$/);
            if (!reg.test(addrCap.value)) {
                formal.error.push("Il cap non è corretto");
                addrCap.classList.add('slds-has-error');
            }
        }

        console.log('before streetName.value');
        if(streetType.streetType && streetName.value){
            console.log('streetName.value = '+streetName.value);     
            let regexStreetType = new RegExp('\\b'+streetType.streetType.toLowerCase()+'\\b');       
            if(streetName.value.trim().toLowerCase().match(regexStreetType)){
                formal.error.push('Il toponimo è duplicato');
                streetName.classList.add('slds-has-error');
            }
        }

        if (formal.error.length == 0) {
            formal.isValid = true;
        }
        return formal;
    }

    @api
    requiredValid() {
        let required = {
            error: [],
            isValid: false
        };
        const streetNumberType = this.template.querySelector('[data-id="streetNumberType"]');
        const streetType = this.template.querySelector('c-cep-street-type-selector');
        const addrLightForm = this.template.querySelectorAll('lightning-input-field.wr-required');
        const addrCity = this.template.querySelector('c-cep-city-selector');
        const addrCountry = this.template.querySelector('c-input-autocomplete');
        addrLightForm.forEach(obj => {
            if (!obj.value) {
                let current = obj.fieldName.replace(this.addressPrefix, "");
                current = current.replace("__c", "");
                if (current == "StreetNumber" && streetNumberType.value == "SNC") {
                    obj.classList.remove('wr-required');
                } else {
                    required.error.push('Il campo ' + current + ' non è stato compilato');
                    obj.classList.add('slds-has-error');
                }
            }
        });
        let cityErr = this.template.querySelector("c-cep-city-selector").error;
        if (!addrCity.city) {
            required.error.push('Il campo City non è stato compilato');
            addrCity.classList.add('slds-has-error');
        } else if (cityErr) {
            required.error.push('Il campo City non è stato compilato correttamente');
        }
        if (!addrCountry.value) {
            required.error.push('Il campo Paese non è stato compilato');
            addrCountry.classList.add('slds-has-error');
        } else if (this.countryErr) {
            required.error.push('Il campo Paese non è stato compilato correttamente');
        }
        if (!streetNumberType.value) {
            required.error.push('Il campo Tipo Numero Civico non è stato compilato');
            streetNumberType.classList.add('slds-has-error');
        }
        let streetTypeErr = this.template.querySelector("c-cep-street-type-selector").error;
        if (!streetType.streetType) {
            required.error.push('Il campo Tipo Strada non è stato compilato');
            streetType.classList.add('slds-has-error');
        } else if (streetTypeErr) {
            required.error.push('Il campo Tipo Strada non è stato compilato correttamente');
        }
        if (required.error.length == 0) {
            required.isValid = true;
        }
        return required;
    }

    @api
    getValues() {
        let inputs = {};
        let targetFields = this.template.querySelectorAll("lightning-input-field");
        targetFields.forEach((currentField) => {
            if (currentField.fieldName == this.addressPrefix + "AddressNormalized__c") {
                inputs[currentField.fieldName] = this.isNormalize
            } else if (currentField.fieldName == this.addressPrefix + "AddressForced__c") {
                inputs[currentField.fieldName] = this.addressForced;
            } else {
                inputs[currentField.fieldName] = currentField.value;
            }
        });
        inputs[this.addressPrefix + "StreetNumberType__c"] = this.template.querySelector('lightning-combobox[data-id="streetNumberType"]').value;
        if(inputs[this.addressPrefix + "StreetNumberType__c"] === 'SNC'){
            inputs[this.addressPrefix + "StreetNumber__c"] = 'SNC';
        } else if(inputs[this.addressPrefix + "StreetNumberType__c"] === 'KM'){
            inputs[this.addressPrefix + "StreetNumber__c"] = 'KM ' + inputs[this.addressPrefix + "StreetNumber__c"];
        }
        inputs[this.addressPrefix + "StreetType__c"] = this.template.querySelector('c-cep-street-type-selector').streetType;
        inputs[this.addressPrefix + "City__c"] = this.template.querySelector('c-cep-city-selector').city;
        inputs[this.addressPrefix + "Country__c"] = this.template.querySelector('c-input-autocomplete').value;
        
        return inputs;
    }

    @api
    isValid() {
        if (this.readOnly && !this.addressForced) {
            this.isNormalize = true;
        }
        return this.isNormalize;
    }
    
    @api
    getIsAddressForced() {
        return this.readOnly && this.addressForced;
    }

    errorInForce() {
        let error = false;
        let cityErr = this.template.querySelector("c-cep-city-selector").error;
        if (this.countryErr || cityErr) {
            error = true
        }
        return error;
    }
    @api
    async forceAddress() {
        let formalValid = this.formalValid();
        let requiredValid = this.requiredValid();
        if (!formalValid.isValid) {
            formalValid.error.forEach((currentError) => {
                error(this, currentError);
            });
            return;
        }
        if (!requiredValid.isValid) {
            requiredValid.error.forEach((currentError) => {
                error(this, currentError);
            });
            return;
        }
        let correctCap = this.addr.PostalCode__c;
        if(correctCap==undefined || correctCap==''){
            correctCap = this.cap;
        }
        const capRes = await findAvailableCaps({
            istat:  this.addr.IstatCode__c,
            comune : this.addr.City__c,
            provincia : this.addr.Province__c,
            cap : correctCap
        });
        console.log('capRes = '+capRes);
        if (!this.errorInForce() && capRes.success==true) {
            this.addressForced = true;
            this.isNormalize = false;
            this.removeAllError(); 
            this.disableAllInputs(); 
            this.dispatchEventIstatCode();
        } else {
            if(capRes.success==false){
                error(this, capRes.messageError);
            }else{
                error(this, "Sono presenti errori nell\'indirizzo");
            }
        }
    }

    dispatchEventIstatCode(){
        if(this.addr.IstatCode__c){         
            this.dispatchEvent(new CustomEvent('istatcodeok', { detail: { data: {  istatCode: this.addr.IstatCode__c  } } }));
        }     
    }

    removeAllError() {
        this.template.querySelector('lightning-combobox[data-id="streetNumberType"]').classList.remove('slds-has-error');
        this.template.querySelector('c-cep-street-type-selector').classList.remove('slds-has-error');
        this.template.querySelector('c-cep-city-selector').classList.remove('slds-has-error');
        this.template.querySelector('c-input-autocomplete').classList.remove('slds-has-error');
        const addrLightForm = this.template.querySelectorAll('lightning-input-field');
        addrLightForm.forEach(obj => {
            obj.classList.remove('slds-has-error');
        });
    }

    @api
    disableAllInputs() {
        this.readOnly = true;
        this.disableNormalize = true;
        this.disableNum = true;
        this.disableExt = true;
        const addrStreetType = this.template.querySelector('c-cep-street-type-selector');
        addrStreetType.readOnly = true;
        const addrCity = this.template.querySelector('c-cep-city-selector');
        addrCity.readOnly = true;
        this.dispatchEvent(new CustomEvent('updateaddressnormalized', {
            detail: {
                'isnormalize': this.isNormalize,
                'addressForced': this.addressForced
            }
        })
        );
    }

    @api
    disableForm(bool) {
        if (bool) {
            this.disableAllInputs();
        } else {
            this.enableAllInputs()
        }
    }
    //NTT W3
    @api
    normalize() {
        this.addressForced = false;
        let formalValid = this.formalValid();
        let requiredValid = this.requiredValid();
        if (!formalValid.isValid) {
            formalValid.error.forEach((currentError) => {
                error(this, currentError);
            });
            return;
        }
        if (!requiredValid.isValid) {
            requiredValid.error.forEach((currentError) => {
                error(this, currentError);
            });
            return;
        }
        let addr = {};
        let inputs = this.getValues();
        for (let i in inputs) {
            let current = i.replace(this.addressPrefix, "");
            current = current.charAt(0).toLowerCase() + current.slice(1);
            current = current.replace("__c", "");
            addr[current] = inputs[i];
        }
        addr.streetNumber = addr.streetNumber.includes('KM') ? addr.streetNumber.replace('KM ', '') : addr.streetNumber;
        this.normalizeService(addr);  
        this.dispatchEventIstatCode();
    }

    normalizeService(addr) {
        this.showLoadingSpinner = true;
        normalize({
            address: addr
        }).then(response => {
            if (response.error) {
                console.log(response.errorMessage);
                console.log(response.errorStack);
                if (response.errSrv || response.errorSrv) {
                    console.log(response.errSrv);
                    console.log(response.errorSrv);
                    error(this, 'Servizio momentaneamente non disponibile. Per continuare forzare l\'indirizzo');
                }
            } else {
                const errList = JSON.parse(response.errList);
                const warList = JSON.parse(response.warList);
                if (errList.length > 0) {
                    if(this.addr.StreetNumber__c === 'SNC'){
                        this.addr.StreetNumber__c = '';
                    } else if(this.addr.StreetNumber__c.includes('KM')){
                        this.addr.StreetNumber__c = this.addr.StreetNumber__c.replace('KM ', '');
                    }
                    if(errList.indexOf('Arco non trovato per la strada') > -1 && this.addr.StreetNumberType__c !== 'SNC'){
                        let index = errList.indexOf('Arco non trovato per la strada');
                        errList[index] = 'Inserire il cap corretto';
                    }
                    errList.forEach(obj => {
                        error(this, obj);
                    });
                    if (warList.length > 0) {
                        warList.forEach(obj => {
                            warn(this, obj);
                        });
                    }
                } else if (errList.length == 0) {
                    console.log('>>> addressMap: ' + JSON.stringify(response.data));
                    this.setAddress(response.data);
                    if (this.formalValid().isValid) {
                        this.isNormalize = true;
                        this.addr.AddressNormalized__c = true;
                        this.disableAllInputs();
                        
                    } else {
                        error(this, "I seguenti caratteri non sono permessi: " + noValidCharRegEx);
                    }
                    if (warList.length > 0) {
                        warList.forEach(obj => {
                            warn(this, obj);
                        }); 
                    }
                } else if (response.status = 'list' && response.data !== undefined && response.data.length > 0) {
                    //attulmente il servizio non è predisposto per stampare la lista degli indirizzi alternativi
                    this.availableAddresses = [];
                    for (let x in response.data) {
                        if (response[x]) {
                            this.availableAddresses.push(response[x]);
                        }
                    }
                    this.showAddressPicker = true;
                }
            }
            if (!this.isNormalize) {
                this.disabledButton();
            }
        }).catch((errorMsg) => {
            error(this, errorMsg);
        }).finally(() => {
            this.showLoadingSpinner = false;
        })
    }

    closeModal() {
        this.showAddressPicker = false;
    }

    handleSelection(event) {
        this.selectedAddress = event.detail.selected;
    }

    handleChangeCivic(event) {
        if(this.changeCivico){
            this.value = event.detail.value;
            if (this.value) {
                const streetNum = this.template.querySelector("[data-id='streetNum']");
                const streetNumExt = this.template.querySelector("[data-id='streetNumExt']");
                streetNum.classList.remove('slds-has-error');
                if (this.value == "SNC") {
                    streetNum.classList.remove('wr-required');
                } else {
                    streetNum.classList.add('wr-required');
                }
                streetNum.value = "";
                streetNumExt.value = "";
                let status = {
                    "N°": {
                        disableNum: false,
                        disableExt: false
                    },
                    "KM": {
                        disableNum: false,
                        disableExt: true
                    },
                    "SNC": {
                        disableNum: true,
                        disableExt: true
                    }
                };
                this.disableExt = status[this.value].disableExt;
                this.disableNum = status[this.value].disableNum;
            } /* else {
                warn(this, "Il tipo numero civico deve essere compilato");
                event.target.value = "N°";
            } */
            event.target.classList.remove('slds-has-error');
        }
    }

    handleChangeStreet(event) {
        event.target.classList.remove('slds-has-error');
    }

    handleStreetType(event){
        this.valueType = event.detail.value.streetType;
    }

    handleBlur(event) {
        if (event.target.name.includes('City')) {
            //this.findIstatCode(event);
            this.addr.City__c = event.detail.value.city;
            this.addr.Province__c = event.detail.value.provinceAbbreviation;
            this.addr.CadastralCode__c = event.detail.value.cadastralCode;
            this.addr.IstatCode__c = event.detail.value.istatCode;
            if (event.target.value != "") {
                event.target.classList.remove('slds-has-error');
            }
        }
        if (event.target.name.includes('Country') && event.target.value != "") {
            this.countryErr = false;
            let country = event.target.value;
            if (country !== "") {
                let cntry = country.toLowerCase()
                this.showLoadingSpinner = true;
                checkCountry({
                    txt: cntry
                }).then(response => {
                    if (response) {
                        let array = response.AddressPicklistValues__r;
                        let pick = [];
                        if (array) {
                            array.forEach(obj => {
                                if (obj.MasterLabel.toLowerCase() === country.toLowerCase()) {
                                    pick.push(obj.MasterLabel);
                                }
                            });
                            if (pick.length === 1) {
                                this.addr.Country__c = pick[0];
                            }
                        } else {
                            this.countryErr = true;
                        }
                    }
                    this.showLoadingSpinner = false;
                }).catch((errorMsg) => {
                    error(this, errorMsg);
                    this.showLoadingSpinner = false;
                });
                event.target.classList.remove('slds-has-error');
            }
        }
    }

    handleChangeCountry(event) {
        this.countryErr = false;
        const txt = event.target.value;
        if (txt.length >= 2) {
            this.showLoadingSpinner = true;
            getCountry({
                txt: txt
            }).then(response => {
                if (response) {
                    this.addressParts = [];
                    let pickValues = [];
                    let array = response.AddressPicklistValues__r;
                    if (array) {
                        array.forEach(obj => {
                            pickValues.push({
                                key: obj.QualifiedApiName,
                                value: obj.MasterLabel
                            });
                        });
                        this.addressParts = pickValues;
                    }
                }
                this.showLoadingSpinner = false;
            }).catch((errorMsg) => {
                error(this, errorMsg);
                this.showLoadingSpinner = false;
            });
        } else {
            this.addressParts = [];
        }
    }

    handleChange(event) {
        let countryVal = event.detail.value;
        if (countryVal != "") {
            this.addr.Country__c = countryVal;
            event.target.classList.remove('slds-has-error');
        }
    }

    

    editAddress() {
        this.addressNormalized = false;
        this.enableAllInputs();
        this.dispatchEvent(new CustomEvent('updateaddressnormalized', {
            detail: {
                'addressNormalized': false,
                'isnormalize': this.isNormalize,
                'addressForced': this.addressForced
            }
        })
        );
    }

    @api
    enableAllInputs() {
        this.changeCivico = true;
        this.readOnly = false;
        this.addressForced = false;
        this.isNormalize = false;
        this.disableNormalize = false;
        const addrStreetType = this.template.querySelector('c-cep-street-type-selector');
        addrStreetType.readOnly = false;
        const addrCity = this.template.querySelector('c-cep-city-selector');
        const streetNumberType = this.template.querySelector('[data-id="streetNumberType"]').value;
        addrCity.readOnly = false;
        let status = {
            "N°": {
                disableNum: false,
                disableExt: false
            },
            "KM": {
                disableNum: false,
                disableExt: true
            },
            "SNC": {
                disableNum: true,
                disableExt: true
            }
        };
        this.disableExt = status[streetNumberType].disableExt;
        this.disableNum = status[streetNumberType].disableNum;
    }

    setAddressProperties(source, prefix) {
        const target = {};
        const fields = ["streetNumberType","streetNumber","streetName","streetType","apartment","building","city","country","floor","locality","postalCode","province","streetNumberExtn","staircase","istatCode","at","cadastralCode"];
        fields.forEach(f=>{
            let sourceField = prefix + f.substr(0, 1).toUpperCase() + f.substr(1) + "__c";
            target[f] = source[sourceField] === undefined ? "" : source[sourceField];
        });
        return target;
    }

    @api
    setAddress(address) {
        this.showLoadingSpinner = true;
        var addressString = JSON.stringify(address);
        if((this.addressPrefix || (!this.addressPrefix && addressString.includes("__c"))) && addressString.includes(this.addressPrefix)){
            address = this.setAddressProperties(JSON.parse(JSON.stringify(address)), this.addressPrefix);
        }
        if (address.streetName) {
            if (this.notInizializeAddress) {
                this.clearAll();
            }
            if(!address.streetNumberType){
                address = this.setNumberType(address);
            }
            if(address.streetNumberType === 'SNC'){
                this.template.querySelector('[data-id="streetNum"]').classList.remove('wr-required');
                this.disableNum = true;
                this.disableExt = true;
            } else if(address.streetNumberType === 'KM'){
                this.disableNum = false;
                this.disableExt = true;
            }
            if(address.streetNumber === 'SNC'){
                address.streetNumber = '';
            } else if(address.streetNumber.includes('KM')){
                address.streetNumber = address.streetNumber.replace('KM ', '');
            }
            //address.streetNumber = address.streetNumber === 'SNC' ? '' : address.streetNumber;
            for (let a in this.addr) {
                for (let i in address) {
                    let current = i.charAt(0).toUpperCase() + i.slice(1) + "__c";
                    if (a == current) {
                        this.addr[a] = address[i];
                    }
                }
            }

            if (this.notInizializeAddress) {
                let country = address["country"] ? address["country"] : "Italia";
                this.template.querySelector('c-input-autocomplete').value = country;
                this.template.querySelector('c-cep-city-selector').city = address["city"];
                this.template.querySelector('c-cep-street-type-selector').streetType = address["streetType"];
                this.template.querySelector('lightning-combobox[data-id="streetNumberType"]').value = address["streetNumberType"] ? address["streetNumberType"] : "N°";
                let targetFields = this.template.querySelectorAll("lightning-input-field");
                for (let add in address) {
                    targetFields.forEach((currentField) => {
                        let current2 = add.charAt(0).toUpperCase() + add.slice(1) + "__c";
                        if (this.addressPrefix + current2 == currentField.fieldName) {
                            currentField.value = address[add];
                        }
                    });
                }
            }
            this.findIstatByCity(this.addr.City__c);
            console.log(JSON.stringify(this.addr));

        }
        this.notInizializeAddress = true;
        this.showLoadingSpinner = false;
    }

    @api
    clearAll() {
        for (let a in this.addr) {
            if (a == "AddressNormalized__c" || a == "AddressForced__c") {
                this.addr[a] = false;
            } else if (a == "StreetNumberType__c") {
                if (!this.addr[a]) {
                    this.addr[a] = "N°";
                }
            } else {
                this.addr[a] = "";
            }
        }
        let targetFields = Array.from(this.template.querySelectorAll("lightning-input-field"))
            .concat(Array.from(this.template.querySelectorAll('lightning-combobox')));
        targetFields.forEach((currentField) => {
            if(currentField.name && currentField.name == 'streetNumberType'){
                currentField.value = "N°";
            } else {
                currentField.value = "";
            }
            currentField.classList.remove('slds-has-error');
        });
        let streetType = this.template.querySelector('c-cep-street-type-selector');
        streetType.streetType = "";
        streetType.classList.remove('slds-has-error');
        this.template.querySelector('c-cep-street-type-selector').error = false;
        let city = this.template.querySelector('c-cep-city-selector');
        city.city = "";
        city.classList.remove('slds-has-error');
        this.template.querySelector("c-cep-city-selector").error = false;
        this.countryErr = false;
        let country = this.template.querySelector('c-input-autocomplete');
        country.classList.remove('slds-has-error');
    }

    setNumberType(addr) {
        if (!addr.streetNumber || addr.streetNumber.includes('SNC')) {
            addr.streetNumberType = 'SNC';
        } else if (/^[0-9]+,[0-9]{1,}$/.test(addr.streetNumber) || addr.streetNumber.includes('KM')) {
            addr.streetNumberType = 'KM';
        } else if (/^[0-9]*$/.test(addr.streetNumber)) {
            addr.streetNumberType = 'N°';
        }
        return addr;
    }

    confirmAddress() {
        let addr = this.selectedAddress;
        this.countryErr = false;
        this.template.querySelector("c-cep-street-type-selector").error = false;
        this.template.querySelector("c-cep-city-selector").error = false;
        this.changeCivico = false;
        this.setAddress(addr);
        let formalValid = this.formalValid();
        let requiredValid = this.requiredValid();
        if (!formalValid.isValid) {
            formalValid.error.forEach((currentError) => {
                error(this, currentError);
            });
            return;
        }
        if (!requiredValid.isValid) {
            requiredValid.error.forEach((currentError) => {
                error(this, currentError);
            });
            return;
        }
        this.isNormalize = false;
        this.addressForced = false;
        if (addr[this.addressPrefix + "AddressNormalized__c"]) {
            this.isNormalize = true;
            this.addr.AddressNormalized__c = true;
        } else {
            this.addressForced = true;
            this.addr.AddressForced__c = true;
        }
        this.disableAllInputs();
        this.closeModal();
    }

    handleChildRegister(event) {
        event.stopPropagation();
        const item = event.detail;
        const guid = item.guid;
        this.privateChildrenRecord[guid] = item;
        this.fields.push(item.field);
        item.callbacks.registerDisconnectCallback(this.handleChildUnregister);
    }

    handleChildUnregister(event) {
        const item = event.detail;
        const guid = item.guid;
        this.privateChildrenRecord[guid] = undefined;
    }

    fireFoundIstatEvent(istateCode) {
        this.dispatchEvent(new CustomEvent('foundistat', {
            detail: {
                'istat': istateCode
            }
        }));
    }

    disabledButton() {
        this.disabledSave = false;
        this.dispatchEvent(new CustomEvent('changesavebutton', { detail: { 'disabledSave': this.disabledSave } }));
    }

    enableNormalize() {
        if (!this.disableNormalize) {
            this.disabledSave = true;
            this.isNormalize = false;
            this.dispatchEvent(new CustomEvent('changesavebutton', {
                detail: {
                    'disabledSave': this.disabledSave,
                    'isnormalize': this.isNormalize
                }
            })
            );
        }
    }

    copyFromOther() {
        this.showAddressPicker = true;
    }


    handleChangeInput(event) {
        this.enableNormalize();
        event.target.classList.remove('slds-has-error');
    }

    handleChangeCap(event) {
        this.cap = event.detail.value;
        console.log('wind3 = '+this.wind3);
        this.enableNormalize();
        event.target.classList.remove('slds-has-error');
    }



}