FileUploadComponent.js 8.76 KB
import React, {Component} from 'react'
import {toast} from 'react-toastify';

import ReactFileReader from 'react-file-reader';

import * as SelectActionCreators from '../../actions/profilationSelect'
import uploadIcon from '../../../img/upload.svg'
import FileHelpers from '../../helpers/fileHelpers'
import camIcon from '../../../img/cam.svg'
import  LemaApi  from '../../../service/service.js';
import {connect} from 'react-redux';

import TakePicture from '../../../img/take_picture.svg'

class FileUploadComponent extends Component {

    constructor(props) {
        super(props)
        this.state = {
            stepIndex: this.props.stepIndex,
            name: this.props.name,
            
        }
        this.handleFiles = this.handleFiles.bind(this);                  
    }

    snapPhoto(){
        /*
        navigator.getMedia = ( navigator.getUserMedia || // use the proper vendor prefix
                       navigator.webkitGetUserMedia ||
                       navigator.mozGetUserMedia ||
                       navigator.msGetUserMedia);

        navigator.getMedia({video: true}, function() {
          this.props.showCamModal('CAM_MODAL', this.props.name, this.props.maxPhotos, this.state.stepIndex)
        }.bind(this), function() {
          this.props.showModal('NO_CAM_MODAL')
        }.bind(this));
        */

        try{
        navigator.mediaDevices.getUserMedia({video: true})
        .then(function(stream) {
          this.props.showCamModal('CAM_MODAL', this.props.name, this.props.maxPhotos, this.state.stepIndex)
        }.bind(this))
        .catch(function(err) {
          this.props.showModal('NO_CAM_MODAL')
        }.bind(this));

        }
        catch(err){
            this.props.showModal('NO_CAM_MODAL')
        }
        /*try{
            navigator.mediaDevices.getUserMedia({video: true}, function() {
              this.props.showCamModal('CAM_MODAL', this.props.name, this.props.maxPhotos, this.state.stepIndex)
            }.bind(this))
        }
        catch(err){
            this.props.showModal('NO_CAM_MODAL')
        }*/
    }

    handleFiles(files) {                
        let propName = this.props.name; 
        let content, idFiles = null, lenFilesAlreadyOn = 0;
        let sizeTnX, sizeTnY;     
        const lemaApi = new LemaApi();  
        const repowerCode = this.props.activationCode; 
        const billStepIndex = 1;
        var error = false
        var sizeError = false       
        var maxFiles = this.props.maxPhotos;

        /*if (this.props.activationSteps[this.state.stepIndex][this.props.name] !== '') {
            maxFiles = maxFiles - this.props.activationSteps[this.state.stepIndex][this.props.name].preview.length
        }*/
        
        if (propName == 'lightBill' || propName == 'gasBill'){
            sizeTnX = this.props.thumbNailInfo.bill_size_x;
            sizeTnY = this.props.thumbNailInfo.bill_size_y;
            idFiles = this.props.activationSteps[billStepIndex][this.props.name + "_fileId"];   
            lenFilesAlreadyOn = FileHelpers.getSplittedFileListLength(idFiles);
        }
        else{
            sizeTnX = this.props.thumbNailInfo.size_x;
            sizeTnY = this.props.thumbNailInfo.size_y;
        }

        // Ciclo sui files, li salvo e genero la preview
        for (var i = 0; (i < files.fileList.length && i < maxFiles); i++) {

            let file = files.fileList[i];
            let base64 = files.base64[i];

            if(FileHelpers.isFormatValid(FileHelpers.getFileExtension(file.name))){           
                
                let request = FileHelpers.getSaveFileRequest(file, base64, null);

                lemaApi.saveActivationFiles(repowerCode, request, FileHelpers.getFileKind(this.props.name))
                .then(
                    (response) => {

                        if (!(propName == 'lightBill' || propName == 'gasBill'))
                            idFiles = response.file_info.id.toString();
                        else
                            idFiles = FileHelpers.csvIdFilesString(idFiles, response.file_info.id).toString();
                        
                        if (idFiles.split(',').length == files.fileList.length + lenFilesAlreadyOn)
                            this.props.previewFile(file, idFiles, this.props.thumbNailInfo.outputContentType, sizeTnX, sizeTnY);                        
                    })
                    .catch((err) => {
                        toast.error("Errore salvataggio files", {position: toast.POSITION.BOTTOM_CENTER});      
                    });
            } else 
                error = true
        }

        this.props.updateStoreValue(this.props.name + '_fileNumberError', files.length > maxFiles)
        this.props.updateStoreValue(this.props.name + '_fileSizeError', sizeError)
        this.props.updateStoreValue(this.props.name + '_fileTypeError', error)
    }

    render() {

       
        return (
        
            (window.innerWidth>1024 &&
                <div className="upload-options">
                    <div className="upload-options-top">
                        <h2>Trascina file in quest'area</h2>
                        <div className="barred"><p>oppure</p></div></div>
                        <div className="upload-options-bottom">
                            <ReactFileReader multipleFiles={true}
                                            fileTypes={["image/png", "image/PNG", "image/jpg", "image/JPG", "image/jpeg", "image/JPEG", "application/pdf", "application/PDF", "application/zip"]}
                                            handleFiles={this.handleFiles}
                                            base64={true}>
                                <div className="upload-options-bottom-left">
                                    <figure className="doc-right"><img src={uploadIcon} alt=''/></figure>
                                    <p className="file-upload-link">Seleziona file</p>
                                </div>
                            </ReactFileReader>

                            <div className="upload-options-bottom-right" onClick={() => this.snapPhoto()}>
                                <figure className="doc-right">
                                    <img src={camIcon} alt=''/>
                                </figure>
                                <p className="file-upload-link">Carica foto</p>
                            </div>
                        </div>
                    </div>)
            ||
            (
                window.innerWidth <= 1024 && 
                <div className="upload-options-bottom">
                            <ReactFileReader multipleFiles={true}
                                            fileTypes={["image/png", "image/PNG", "image/jpg", "image/JPG", "image/jpeg", "image/JPEG", "application/pdf", "application/PDF", "application/zip"]}
                                            handleFiles={this.handleFiles}
                                            base64={true}>
                                <div className="upload-options-bottom-left">
                                    {/* <figure className="doc-right"><img src={uploadIcon} alt=''/></figure>
                                    <p className="file-upload-link">Seleziona file</p> */}

                                    <figure className='file-upload-link'>
                                        <img src={TakePicture} alt=''/>
                                    </figure>
                                </div>
                            </ReactFileReader>
                </div>
            )
        )
    }
}


const mapStateToProps = state => {
    return {
        activationSteps: state.ProfilationSelectReducer.activationSteps,
        thumbNailInfo:state.ProfilationSelectReducer.thumbNailInfo,
        activationCode: state.ProfilationSelectReducer.activationCode
    }
};

const mapDispatchToProps = dispatch => ({
    showModal: (modalName) =>
        dispatch(SelectActionCreators.showModal(modalName)),
    showCamModal: (modalName, docId, maxPhotos, step) =>
        dispatch(SelectActionCreators.showCamModal(modalName, docId, maxPhotos, step)),
    updatePropValue: (steps, activeStep) => dispatch(SelectActionCreators.changeValue(steps, activeStep)),
    updateActivation: (index, prop, value) => dispatch(SelectActionCreators.updateActivation(index, prop, value)),
    updateStoreValue: (prop, value) =>
        dispatch(SelectActionCreators.changeProp(prop, value)),
});

/*Profilation.propTypes = {
 steps: PropTypes.array.isRequired,
 activeStep: PropTypes.number.isRequired,
 updatePropValue: PropTypes.func.isRequired
 }*/

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