ProfilationStep2.js 14.6 KB
import React, {Component} from "react";
import Select from "react-select";

import AutosizeInput from "react-input-autosize";

import * as SelectActionCreators from '../../actions/profilationSelect'
import { connect } from 'react-redux';

var expendOptions = [
    { value: "spendo", label: "spendo" },
    { value: "consumo", label: "consumo" }
];

var periodOptions = [
    { value: "mese", label: "mese" },
    { value: "anno", label: "anno" }
];

const yearlyMaxLightC = 150000;
const yearlyMinLightC = 3000;
const yearlyMaxLightS = 36000;
const yearlyMinLightS = 800;
const yearlyMaxGasC = 51000;
const yearlyMinGasC = 500;
const yearlyMaxGasS = 39000;
const yearlyMinGasS = 420;


function numberWithCommas(x) {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
}

class ProfilationStep2 extends Component {


    constructor(props) {
        super(props);

        this.state = {
            loading: false,
            valid: {
                gas: false,
                light: false
            },
            error: false,
            showModal: props.showModal
        };
    }
    componentWillReceiveProps(nextProps) {
        if (nextProps.isActive !== this.props.isActive && nextProps.isActive === true)
            this.setState({loading: false, error: this.getMessage()}, () => {
                let step = {...this.props.step};
                step.isComplete = false;
                this.props.updatePropValue(this.props.index, step);

            });
    }

    getMessage() {
        let error = false;
        const props = this.props;
        const previousStep = this.props.completeSteps[0];
        console.log('props', props)
        //check anno -> consumi
        if (props.step.expend === 'consumo' && props.step.period === "anno" && props.step.light.length > 0 && parseInt(props.step.light || 0) < yearlyMinLightC) {
            return <div className="error-msg">I consumi sembrano molto bassi. Se preferisci, puoi inserire i consumi mensili selezionando la voce "mese"</div>
        } else if (props.step.expend === 'consumo' && props.step.period === "anno" && props.step.gas.length > 0 && parseInt(props.step.gas || 0) < yearlyMinGasC) {
            return <div className="error-msg">I consumi sembrano molto bassi. Se preferisci, puoi inserire i consumi mensili selezionando la voce "mese"</div>
        }

        //check anno -> costi
        if (props.step.expend === 'spendo' && props.step.period === "anno" && props.step.light.length > 0 && parseInt(props.step.light || 0) < yearlyMinLightS) {
            return <div className="error-msg">I costi sembrano molto bassi. Se preferisci, puoi inserire i consumi mensili selezionando la voce "mese"</div>
        } else if (props.step.expend === 'spendo' && props.step.period === "anno" && props.step.gas.length > 0 && parseInt(props.step.gas || 0) < yearlyMinGasS) {
            return <div className="error-msg">I costi sembrano molto bassi. Se preferisci, puoi inserire i consumi mensili selezionando la voce "mese"</div>
        }

        //check mese -> consumi
        if (props.step.expend === 'consumo' && props.step.period === "mese" && props.step.light.length > 0 && parseInt(props.step.light || 0) < (yearlyMinLightC/12)) {
            return <div className="error-msg">I consumi sembrano molto bassi.</div>
        } else if (props.step.expend === 'consumo' && props.step.period === "mese" && props.step.gas.length > 0 && parseInt(props.step.gas || 0) < (yearlyMinGasC/12)) {
            return <div className="error-msg">I consumi sembrano molto bassi.</div>
        }

        //check mese -> costi
        if (props.step.expend === 'spendo' && props.step.period === "mese" && props.step.light.length > 0 && parseInt(props.step.light || 0) < (yearlyMinLightS/12)) {
            return <div className="error-msg">I costi sembrano molto bassi.</div>
        } else if (props.step.expend === 'spendo' && props.step.period === "mese" && props.step.gas.length > 0 && parseInt(props.step.gas || 0) < (yearlyMinGasS/12)) {
            return <div className="error-msg">I costi sembrano molto bassi.</div>
        }

        if (props.step.expend === 'consumo' && ((props.step.light.length > 0 && parseInt(props.step.light) >= yearlyMaxLightC) || (props.step.gas.length > 0 && parseInt(props.step.gas) >= yearlyMaxGasC))) {
            return (<div className="error-msg">
				<p>La tua attività ha delle esigenze molto specifiche.</p>
				<p>Per questo vorremmo farti contattare da uno dei nostri personal trainer dell'energia, servirti al meglio e costruire insieme a te una soluzione su misura.</p>
				<button className="button-red" onClick={() => this.state.showModal('TRAINER_MODAL')}>OK, CONTATTATEMI</button>
			</div>);
        }

        if (props.step.expend === 'spendo' && ((props.step.light.length > 0 && parseInt(props.step.light) >= yearlyMaxLightS) || (props.step.gas.length > 0 && parseInt(props.step.gas) >= yearlyMaxGasS))) {
            return (<div className="error-msg-black">
				<p>La tua attività ha delle esigenze molto specifiche.</p>
				<p>Per questo vorremmo farti contattare da uno dei nostri personal trainer dell'energia, servirti al meglio e costruire insieme a te una soluzione su misura.</p>
				<button className="button-red" onClick={() => this.state.showModal('TRAINER_MODAL')}>OK, CONTATTATEMI</button>
			</div>);
        }



        if (props.step.expend === 'spendo') {
            const toReturn = (<div className="error-msg-black">
				<p>In base alla spesa che hai indicato prevediamo un consumo stimato di circa 15.000 kWh di elettricità e 5.000 Smc di gas annui.</p>
                {(!props.step.isComplete) && <button className="button-red" onClick={this.complete}>Avanti</button>}
			</div>);
            if (previousStep.service === "both" && props.step.gas.length > 0  && props.step.light.length > 0) {
                return toReturn;
            }
            if (previousStep.service === "light" && props.step.light.length > 0) {
                return toReturn;
            }
            if (previousStep.service === "gas" && props.step.gas.length > 0) {
                return toReturn;
            }
        }

        if (props.step.expend.length > 0 && props.step.period) {

            let toReturn = <div><button  className="button-red" onClick={this.complete}>Avanti</button></div>
            if (props.step.isComplete){
                toReturn=''
            }
            console.log('return',toReturn)
            if (previousStep.service === "both" && props.step.gas.length > 0 && props.step.light.length > 0) {
                return toReturn;
            }

            if ((previousStep.service === "light" && props.step.light.length > 0) || (previousStep.service === "gas" && props.step.gas.length > 0)) {
                return toReturn;
            }
        }

        return error;
    }

    complete = () => {
        let step = {...this.props.step};
        step.isComplete = true;
        this.props.updatePropValue(this.props.index, step);
    }

    changeTextField = (name, e) => {



        //console.log('numberOnly',numberOnly(e))
		/*if(numberOnly(e))
		 {
		 this.setState({loading: true});
		 this.changeField(name, e.target);
		 }*/
		/*if(res){
		 this.setState({loading: true});
		 this.changeField(name, e.target);
		 }*/

		/*
		 codice originale
		 this.setState({loading: true});
		 this.changeField(name, e.target);*/

        //const val = (e.target.validity.valid) ? e.target.value : this.state.financialGoal;
        console.log('valid input',e.target.validity)
        if(e.target.validity.valid){

            this.setState({loading: true});
            this.changeField(name, e.target);
        }



    }

    changeField(name, event) {
        if(this.timer !== null) {
            clearTimeout(this.timer);
        }

        this.timer = setTimeout(() => {
            this.setState({loading: false, error: this.getMessage()});
        }, 3000);

        var completed = true;
        if (event !== null && event.value !== "") {
            for (var property in this.props.step) {
                if (this.props.step.hasOwnProperty(property)) {
                    if (
                        property !== name &&
                        property !== "isComplete"
                    ) {
                        completed = completed && this.props.step[property] !== "";
                        if (name === 'light' || name === 'gas') {
                            completed = completed && this.state.valid[name]
                        }
                    }
                }
            }
        } else {
            completed = false;
           
        }

        let step = {...this.props.step};

        var val=event.value;

        val=val.split('.').join("");

        step[name] = val;



        if (name === 'period') {
            step.gas = "";
            step.light = "";
            step.completed = false;
        }
        this.props.updatePropValue(this.props.index, step);

        var factor=4.17
        if(name==='gas')
            factor=1.3
        if(this.props.step.period==='mese'){
            factor=factor/12
        }
        if(name==='gas' || name==='light')
        {

            if( this.props.step.expend==='spendo')
            {

                val=Math.floor(val*factor)

            }

            this.props.updateActivation(1,name+'Val',val)
            this.props.updateStoreValue(name+'Val_tmp',val)
        }

        if(name==='expend' && event.value==='spendo' && this.props.step.expend==='consumo'){

           const newLight=Math.floor(this.props.activationSteps[1].lightVal*4.17)
            const newGas=Math.floor(this.props.activationSteps[1].gasVal*1.3)

            this.props.updateActivation(1,'lightVal',newLight)
            this.props.updateActivation(1,'gasVal',newGas)
            this.props.updateStoreValue('lightVal_tmp',newLight)
            this.props.updateStoreValue('gasVal_tmp',newGas)
        }

        if(name==='expend' && event.value==='consumo' && this.props.step.expend==='spendo'){

           const newLight=Math.floor(this.props.activationSteps[1].lightVal/4.17)
            const newGas=Math.floor(this.props.activationSteps[1].gasVal/1.3)

            this.props.updateActivation(1,'lightVal',newLight)
            this.props.updateActivation(1,'gasVal',newGas)
            this.props.updateStoreValue('lightVal_tmp',newLight)
            this.props.updateStoreValue('gasVal_tmp',newGas)
        }

        if(name==='period' && event.value==='mese'){

           const newLight=Math.floor(this.props.activationSteps[1].lightVal/12)
            const newGas=Math.floor(this.props.activationSteps[1].gasVal/12)

            this.props.updateActivation(1,'lightVal',newLight)
            this.props.updateActivation(1,'gasVal',newGas)

            this.props.updateStoreValue('lightVal_tmp',newLight)
            this.props.updateStoreValue('gasVal_tmp',newGas)
        }


    }



    render() {
        console.log('stepss',this.props.steps[1])
        const lightDots=numberWithCommas(this.props.steps[1].light)
        const gasDots=numberWithCommas(this.props.steps[1].gas)
        let props = this.props;
        
        return <div className="ProfilationStep ProfilationStep--one" onClick={e => props.activeStep(props.index)}>
			<div className="d-flex">
				<p>Per la mia attivit&agrave; </p>
				<Select
					autosize
					name="expend"
					searchable={false}
					value={props.step.expend}
					onChange={e => this.changeField("expend", e)}
					options={expendOptions}
					placeholder="placeholder"
					onFocus={e => props.activeStep(props.index)}
                    openOnFocus={true}
				/>
				<p>ogni</p>{" "}
				<Select
					autosize
					name="period"
					searchable={false}
					value={props.step.period}
					onChange={e => this.changeField("period", e)}
					options={periodOptions}
					placeholder="placeholder"
					onFocus={e => props.activeStep(props.index)}
                    openOnFocus={true}
				/>
			</div>
			<br />
            {(props.completeSteps[0].service === 'light' || props.completeSteps[0].service === 'both') && <div className="d-flex ProfilationStep__input">
				<p>circa </p>
				<AutosizeInput
					type="tel"
					name="light_val"
					value={lightDots}
					onChange={e => this.changeTextField("light", e)}
					onFocus={e => props.activeStep(props.index)}
					pattern="[0-9.]*"
					placeholder="placeh"
				/>
				<p>{props.step.expend==='consumo'? 'kWh':'€'} di elettricit&agrave; {props.completeSteps[0].service === 'both'? 'e':''} </p>
			</div>}
            {(props.completeSteps[0].service === 'gas' || props.completeSteps[0].service === 'both') && <div className="d-flex ProfilationStep__input">
				<p>circa</p>
				<AutosizeInput
					type="tel"
					name="gas_val"
					value={gasDots}
					onChange={e => this.changeTextField("gas", e)}
					onFocus={e => props.activeStep(props.index)}
					pattern="[0-9.]*"
					placeholder="placeh"
				/>
				<p>{props.step.expend==='consumo'? 'smc':'€'} di gas</p>
			</div>}
            {this.state.loading && <div><div className="validation-loader  validation-loader__little loader_spinner" ></div></div>}
            {/* {this.state.error && <div>{this.state.error}</div>} */}
            {this.props.isActive && !this.state.loading && this.state.error}
		</div>
    }
}

/*ProfilationStep2.propTypes = {
 //isComplete: PropTypes.bool.isRequired,
 //isActive: PropTypes.bool.isRequired
 step: PropTypes.object.isRequired,
 index: PropTypes.number.isRequired,
 updatePropValue: PropTypes.func.isRequired
 };

 export default ProfilationStep2;*/

const mapStateToProps = state => {
    return {
        steps:state.ProfilationSelectReducer.steps,
        activationSteps:state.ProfilationSelectReducer.activationSteps,
        //solutions:state.ProfilationSelectReducer.solutions,
        modalOpen:state.ProfilationSelectReducer.saveModalOpen
    }};

const mapDispatchToProps = dispatch => ({
	/*updatePropValue: (prop,value,index,complete) =>
	 dispatch(SelectActionCreators.changeValue(prop,value,index,complete)),*/
	 updateStoreValue: (prop,value) =>
	 dispatch(SelectActionCreators.changeProp(prop,value)),
     updateActivation: (index,prop,value) => dispatch(SelectActionCreators.updateActivation(index,prop,value)),
    showModal: (modalName) =>
        dispatch(SelectActionCreators.showModal(modalName)),
});

export default connect(mapStateToProps, mapDispatchToProps)(ProfilationStep2);