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

import AutosizeInput from "react-input-autosize";

import data from '../data.json'

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

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
            },
            editing:false,
            error: false,
            showModal: props.showModal,
            messageConsumptionEstimate: '',
            valueConsumptionEstimate: '',
            ee_estimate: 0,
            gas_estimate:0
        };

        this.handleFocus=this.handleFocus.bind(this)
    }

    handleFocus(index){
        this.props.activeStep(this.props.index)

        this.props.updateStoreValue('tabIndex',index)
    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.isActive !== this.props.isActive && nextProps.isActive === true)
            
            this.setState({loading: false, error: this.getMessage()}, () => {
                let step = {...this.props.step};
                
                this.props.updateStoreValue('profilationStepTwoError',(this.getMessage()!==false))
                this.props.updatePropValue(this.props.index, step);
            });
    }

    componentDidMount(){
    if(window.innerWidth>1024 && this.props.isActive){
        
            if(this.props.steps[0].service!=='gas'){
                
                this.lightInput.focus();
            else
                this.gasInput.focus();            
        }
        const lightEl=document.querySelector('[name="light_val"]')
        const gasEl=document.querySelector('[name="gas_val"]')
        setTimeout(function(){
            if(this.props.steps[0].service!=='gas'&&document.activeElement!==lightEl){
                this.lightInput.focus()
            }
            else if(this.props.steps[0].service==='gas'&&document.activeElement!==gasEl){
                this.gasInput.focus()
            }
        
    }.bind(this),500)
        
    }

    getMessage() {
        let error = false;
        const props = this.props;
        const previousStep = this.props.completeSteps[0];

        const lemaApi = new LemaApi();
        var ee_amount = props.step.light != 0 ? props.step.light : null;
        var gas_amount = props.step.gas != 0 ? props.step.gas : null;
        var period = (props.step.period == "anno") ? "yearly" : (props.step.period == "mese") ? "monthly" : "";
        
        lemaApi.getConsumptionEstimate(ee_amount, gas_amount, period, props.step.expend)
            .then(response => {
                this.setState({messageConsumptionEstimate:(<div></div>)});
                
                var type = response.data.consumption_info.type;
                
                if(type == 2 || type == 6 || type == 3 || type == 7)
                {                 
                    if(period == "yearly")
                        this.setState({messageConsumptionEstimate:<div className="error-msg">I consumi sembrano molto bassi. Se preferisci, puoi inserire i consumi mensili selezionando la voce "mese".</div>});
                    else if(period == "monthly")
                        this.setState({messageConsumptionEstimate:<div className="error-msg">I consumi sembrano molto bassi.</div>});
                }
                if(type == 4 || type == 8)
                {
                    this.setState({messageConsumptionEstimate:(<div className="error-msg">				
                    <p className="isRed">La tua attività ha delle esigenze molto specifiche. 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(type == 5 || type == 9)
                {
                    this.setState({messageConsumptionEstimate:(<div className="error-msg-black">
	
                    <p className="isRed">La tua attività ha delle esigenze molto specifiche. 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>)});
                }

                this.setState({valueConsumptionEstimate:(<div></div>)});
                if(props.step.expend === 'spendo')
                {
                    if(props.steps[0].service==='both')
                    {
                        this.props.updateActivation(1, 'lightVal', response.data.consumption_info.ee_Kwh);
                        this.props.updateStoreValue('lightVal_tmp', response.data.consumption_info.ee_Kwh);
                        this.props.updateActivation(1, 'gasVal', response.data.consumption_info.gas_Smc);
                        this.props.updateStoreValue('gasVal_tmp', response.data.consumption_info.gas_Smc);

                        this.setState({valueConsumptionEstimate:(<div className="error-msg-black">
                        <p>In base alla spesa che hai indicato prevediamo un consumo stimato di circa {numberWithCommas(this.props.lightVal_tmp)} kWh di elettricità e {numberWithCommas(this.props.gasVal_tmp)} Smc di gas annui.</p>
                        {(!props.step.isComplete && this.state.editing) && <button className="button-red" tabIndex={8} onClick={this.complete}>Avanti</button>}
                        </div>)});
                    }

                    if(props.steps[0].service==='light')
                    {                  
                        this.props.updateActivation(1, 'lightVal', response.data.consumption_info.ee_Kwh)
                        this.props.updateStoreValue('lightVal_tmp', response.data.consumption_info.ee_Kwh)
                        
                        this.setState({valueConsumptionEstimate:(<div className="error-msg-black">
                        <p>In base alla spesa che hai indicato prevediamo un consumo stimato di circa {numberWithCommas(this.props.lightVal_tmp)} kWh di elettricità annui.</p>
                        {(!props.step.isComplete && this.state.editing) && <button className="button-red" tabIndex={8} onClick={this.complete}>Avanti</button>}
                        </div>)});
                    }

                    if(props.steps[0].service==='gas'){
                        this.props.updateActivation(1, 'gasVal',response.data.consumption_info.gas_Smc)
                        this.props.updateStoreValue('gasVal_tmp', response.data.consumption_info.gas_Smc)

                        this.setState({valueConsumptionEstimate:(<div className="error-msg-black">
                        <p>In base alla spesa che hai indicato prevediamo un consumo stimato di circa {numberWithCommas(this.props.gasVal_tmp)} Smc di gas annui.</p>
                        {(!props.step.isComplete && this.state.editing) && <button className="button-red" tabIndex={8} onClick={this.complete}>Avanti</button>}
                        </div>)});
                   }
                }
                else if(props.step.expend.length > 0 && props.step.period)
                {
                    this.setState({valueConsumptionEstimate:<div><button  className="button-red"  tabIndex={8} onClick={this.complete}>Avanti</button></div>});
                }

            })
            .catch(response => {
                this.setState({messageConsumptionEstimate:(<div></div>)});
                this.setState({valueConsumptionEstimate:(<div></div>)});
            });

        return error;
    }

    complete = () => {
        let step = {...this.props.step};
        step.isComplete = true;
        this.setState({
            ...this.state,
            editing:false
        })
        this.props.activeStep(this.props.index+1)
        this.props.updateStoreValue('profilationStepTwoError', false);
        this.props.updatePropValue(this.props.index, step);
    }

    changeTextField = (name, e) => {

        if(e.target.validity.valid){
            this.props.updatePropValue(this.props.index, {
                ...this.props.step,
                isComplete:false
            });
            this.setState({
                ...this.state,
                editing:true,
                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()});
        }, 1000);

        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;

        step.isComplete = 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!==this.props.step.expend){
            
            step.gas = "";
            step.light = "";
            step.completed = false;
        
            this.props.updatePropValue(this.props.index, step);

            const newLight=''
            const newGas=''

            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!==this.props.step.period){

            step.gas = "";
            step.light = "";
            step.completed = false;
        
            this.props.updatePropValue(this.props.index, step);

            const newLight=''
            const newGas=''

            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() {
        
        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>{data.profilationSteps[1].intro} </p>
				<Select
					autosize
					name="expend"
					searchable={false}
					value={props.step.expend}
					onChange={e => this.changeField("expend", e)}
					options={expendOptions}
					placeholder="placeholder"
					onFocus={() => this.handleFocus(4)}
                    openOnFocus={true}
                   tabIndex={'4'}
				/>
				<p>{data.profilationSteps[1].when}</p>{" "}
				<Select
					autosize
					name="period"
					searchable={false}
					value={props.step.period}
					onChange={e => this.changeField("period", e)}
					options={periodOptions}
					placeholder="placeholder"
					onFocus={() => this.handleFocus(5)}
                    openOnFocus={true}
                    tabIndex={'5'}
				/>
			</div>
			<br />
            {(props.completeSteps[0].service === 'light' || props.completeSteps[0].service === 'both') && <div className="d-flex d-flex__smaller ProfilationStep__input">
				<p>{data.profilationSteps[1].howMuch} </p>
				<AutosizeInput
                    ref={(input) => { this.lightInput = input; }} 
					type="tel"
					name="light_val"
					value={lightDots}
					onChange={e => this.changeTextField("light", e)}
					onFocus={() => this.handleFocus(6)}
					pattern="[0-9.]*"
					placeholder="placeh"
                    tabIndex={6}
				/>
				<p>{props.step.expend==='consumo'? 'kWh':'€'} {data.profilationSteps[1].light}{props.completeSteps[0].service === 'both'? data.profilationSteps[1].and:data.profilationSteps[1].dot} </p>
			</div>}
            {(props.completeSteps[0].service === 'gas' || props.completeSteps[0].service === 'both') && <div className="d-flex ProfilationStep__input">
				<p>{data.profilationSteps[1].howMuch}</p>
				<AutosizeInput
                    ref={(input) => { this.gasInput = input; }} 
					type="tel"
					name="gas_val"
					value={gasDots}
					onChange={e => this.changeTextField("gas", e)}
					onFocus={() => this.handleFocus(7)}
					pattern="[0-9.]*"
					placeholder="placeh"
                    tabIndex={7}
				/>
				<p>{props.step.expend==='consumo'? 'smc':'€'} {data.profilationSteps[1].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}
            {this.state.messageConsumptionEstimate}
            
            {(this.state.messageConsumptionEstimate.props != undefined && this.state.messageConsumptionEstimate.props.children == undefined) && this.state.valueConsumptionEstimate}
		</div>
    }
}

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

const mapDispatchToProps = dispatch => ({
	 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);