ProfilationStep1.js 11.1 KB
import React, { Component } from 'react';
import Select from "react-select";

import Autosuggest from 'react-autosuggest';

import { Creatable } from "react-select";
import { AsyncCreatable } from "react-select";
import  LemaApi  from '../../../service/service.js'

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

function resizable (el, factor) {
  var int = Number(factor) || 7.7;

  function resize() {
        //el.style.width = ((el.value.length+1) * int) + 'px'
        el.style.width = document.querySelector('.fakeInput').offsetWidth+4+ 'px'
    }
  var e = 'keyup,keypress,focus,blur,change'.split(',');
  for (var i in e) el.addEventListener(e[i],resize,false);
  resize();
}

// Prendo la lista dei prodotti
const getProductOptions = () => {
    return LemaApi.getProductOptions();
}

const getJobOptions = () => {
    return LemaApi.getJobsOptions();
}


function onInputKeyDown(event) {
    switch (event.keyCode) {
        case 9:   // TAB
            // Extend default TAB behavior by doing something here
            break;
        case 13: // ENTER
            // Override default ENTER behavior by doing stuff here and then preventing default

            break;
    }
}

const languages = [
  {
    name: 'C',
    year: 1972
  },
  {
    name: 'Elm',
    year: 2012
  },
];

const getSuggestions = value => {
    
  const inputValue = value.trim().toLowerCase();
  const inputLength = inputValue.length;
  const jobs = getJobOptions();

  return inputLength === 0 ? [] : jobs.filter(lang =>
    lang.value.toLowerCase().slice(0, inputLength) === inputValue
  );
};

const getSuggestionValue = suggestion => suggestion.value;

const renderSuggestion = suggestion => (
  <div>
    {suggestion.value}
  </div>
);

class ProfilationStep1 extends Component{
    constructor(props){
        super(props)
        this.state={
            value: '',
      suggestions: []
        }
        this.changeField=this.changeField.bind(this)
        this.onOptionSelected=this.onOptionSelected.bind(this)
        this.handleKeyPress=this.handleKeyPress.bind(this)
       
    }

    handleKeyPress(event){
        if(event.key=='Enter'){
            this.onChange()
        }
    }

    componentDidUpdate(){
        
        if(this.state.value!==''){

          resizable(document.querySelector('.react-autosuggest__input'),13.5);
        }
        

    }

    onOptionSelected(event, { suggestion, suggestionValue, suggestionIndex, sectionIndex, method })
    {

        
        /*this.onChange()
        resizable(document.querySelector('.react-autosuggest__input'),15);*/
       /* this.setState({
      value: suggestionValue
    });
        
        const props=this.props
    let step = {...props.step};
    step.job = suggestionValue;
    console.log('suggest',step)
    props.updatePropValue(0, step);
    //this.changeField(false,"job", event, this.props)
    */
    }

    doNothing = (event, { newValue }) => {
        this.setState({
      value: newValue
    });
        //resizable(document.querySelector('.react-autosuggest__input'),15);
    }
    /*onChange = (event, { newValue }) => {
    

   const props=this.props
    let step = {...props.step};
    step.job = newValue;
    props.updatePropValue(0, step);
    //this.changeField(false,"job", event, this.props)
  };*/



  onChange = () => {
    

   const props=this.props
    let step = {...props.step};
    step.job = this.state.value;
    
    //this.changeField(false,"job", event, this.props)
    //resizable(document.querySelector('.react-autosuggest__input'),15);

    var completed = true;
    if (this.state.value !== "") {
        for (var property in props.step) {
            if (props.step.hasOwnProperty(property)) {
                if (
                    property !== 'job' &&
                    property !== "isComplete" &&
                    property !== "isActive"
                ) {
                    completed = completed && props.step[property] !== "";
                }
            }
        }
    } else {
        completed = false;
    }
    step.isComplete = completed;
    props.updatePropValue(0, step);

    if(step.service===''){
        this.serviceInput.focus();
    }
    
    
  };

  onSuggestionsFetchRequested = ({ value }) => {

    this.setState({
      suggestions: getSuggestions(value)
    });
  };

  onSuggestionsClearRequested = () => {
    this.setState({
      suggestions: []
    });
  };

    changeField(mobile,name, event, props) {
        
    if(mobile){
        event=event.target
    }
    console.log('select',name,event,props)
    var completed = true;
    if (event !== null && event.value !== "") {
        for (var property in props.step) {
            if (props.step.hasOwnProperty(property)) {
                if (
                    property !== name &&
                    property !== "isComplete" &&
                    property !== "isActive"
                ) {
                    completed = completed && props.step[property] !== "";
                }
            }
        }
    } else {
        completed = false;
    }

    let step = {...props.step};
    step[name] = event.value;
    if(name==='service' && event.value==='light'){
        
        props.updateActivation(1,'gasVal','NotSelected')
        props.updateActivation(1,'gasBill','NoFile')
        props.updateActivation(3,'checkAcciseRidotte',{...this.props.activationSteps[3].checkAcciseRidotte,
                                                        required:false})
    }
    if(name==='service' && event.value==='gas'){
        
        props.updateActivation(1,'lightVal','NotSelected')
        props.updateActivation(1,'lightBill','NoFile')
        props.updateActivation(3,'checkAcciseRidotte',{...this.props.activationSteps[3].checkAcciseRidotte,
                                                        required:true})
    }
    if(name==='service' && event.value==='both'){
        
        props.updateActivation(1,'lightVal','')
        props.updateActivation(1,'gasVal','')
        props.updateActivation(3,'checkAcciseRidotte',{...this.props.activationSteps[3].checkAcciseRidotte,
                                                        required:true})
        
    }
    step.isComplete = completed;
    props.updatePropValue(props.index, step);


    /*if(name==='job'){
         this.serviceInput.focus();
    }*/
}

    render(){

      
        const value = this.state.value;
        const suggestions = this.state.suggestions;

         const inputProps = {

      placeholder: 'Type a programming language',
      value,
      onChange: this.doNothing,
      onBlur:this.onChange,
      onKeyPress:this.handleKeyPress
    };
        return(

                <div className="ProfilationStep ProfilationStep--one" onClick={e => this.props.activeStep(this.props.index)}>
        <p className="ProfilationStep__bold">
            Costruisci in pochi secondi la tua tariffa flat, 100% online.
        </p>

        <div className="d-flex">
        <span className='fakeInput'>{this.state.value}</span>
            <span> La mia attivit&agrave; si occupa di 
            {/*<AsyncCreatable
                openOnClick={false}
                autosize={true}
                creatable={true}
                name="job"
                placeholder="placeholder"
                value={this.props.step.job}
                onChange={e => this.changeField(false,"job", e, this.props)}
		loadOptions={getJobOptions}
                onFocus={e => this.props.activeStep(this.props.index)}
                promptTextCreator={(label) => ` ${label} `}
                className = "select-full-height select-z-index"
                onInputKeyDown={onInputKeyDown}
                
                
            />*/}

            <Autosuggest
            
	        suggestions={suggestions}
	        onSuggestionsFetchRequested={this.onSuggestionsFetchRequested}
	        onSuggestionsClearRequested={this.onSuggestionsClearRequested}
	        getSuggestionValue={getSuggestionValue}
	        renderSuggestion={renderSuggestion}
	        onSuggestionSelected={this.onOptionSelected}
	        focusInputOnSuggestionClick={false}
	        inputProps={inputProps}
            />
            

            {window.innerWidth>=768&&<br/>}ed ho bisogno di 
            
            {window.innerWidth>=0 && <Select.Async
                ref={(input) => { this.serviceInput = input; }} 
                searchable={false}
                autosize={true}
                name="service"
                placeholder="placeholder"
                value={this.props.step.service}
                onChange={e => this.changeField(false,"service", e, this.props)}
		loadOptions={getProductOptions}
                onFocus={e => this.props.activeStep(this.props.index)}
                className = "select-z-index"
                openOnFocus={true}
            />}</span> 
            {/*window.innerWidth<768 && 
                <select
                    ref={(input) => { this.serviceInput = input; }} 
                    name="service"
                    onChange={e => this.changeField(true,"service", e, this.props)}
                    value={this.props.step.service}
                    onFocus={e => this.props.activeStep(this.props.index)}
                    className='mobileSelect'
                >
                    <option value='' disabled></option>
                    <option value='light'>Elettricità</option>
                    <option value='gas'>Gas</option>
                    <option value='both'>Elettricità e Gas</option>
                </select>
            */}
        </div>
        <p tabindex="0" className="ProfilationStep__underline" onClick={() => this.props.showModal('FURNITURE_MODAL')}>
            Per il tuo business hai più sedi e forniture?
        </p>
    </div>

            )
    }
}

/*const ProfilationStep1 = props => (
	
);*/

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

export default ProfilationStep1;*/

const mapStateToProps = state => {
  return {
  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)(ProfilationStep1);