﻿import React from 'react';
import AutoBind from 'react-autobind';
import toastr from 'toastr';
import { ServiceRequest } from 'Components/Request/service';
import LocalStorage from 'Components/LocalStorage';
import axios from 'axios';
import { Translate } from "react-localize-redux";
import Input from '../../../../components/UI/Input/Input';
import InputNoTranslate from '../../../../components/UI/Input/InputNoTranslate';
import Textarea from '../../../../components/UI/Textarea/Textarea';
import Button from '../../../../components/UI/Button/Button';
import Map from './Map';

class UserInfoView extends React.Component {

    signal = axios.CancelToken.source();
    // localstorage = new LocalStorage();

    constructor() {
        super();

        this.state = {
            levelNames: { NombreNivel1: '', NombreNivel2: '', NombreNivel3: '', NombreNivel4: '' },
            ubicacion_util: { Loc_Aplicada: false, Loc_Solicitud_Id: '', CC_Id: 0, Emp_id: 0, Detalle_Id: 0, Ubicacion_Id: '' },
            location: {
                Nombre: '',
                Compania: '',
                Barrio: '',
                Senas: '',
                Nivel1Nombre: '',
                Nivel2Nombre: '',
                Nivel3Nombre: '',
                Nivel4Nombre: '',
                Telefono: '',
                CodigoPostal: '',
                Principal: false,
                Latitud: 0,
                Longitud: 0
            },
            phones: [],
            btnDisabled: false,
            btnDisabled: false,
            loading: false,
            isValid:true
        }
        AutoBind(this);


    }
    componentDidMount() {
        // document.body.style.background = "url('" + baseUrl +"Public/img/bg.jpg')";
        //this.verificarSession();
        const localstorage = new LocalStorage();
        let token = this.getParameterByName('pToken')
        let id = this.getParameterByName('pId')
        
        if(token=='' || id == ''){
            toastr.error('El Registro a modificar no se encuentra disponible')
            this.setState({ isValid:false });

            return
        }

        localstorage.set('token',token);
        localstorage.set('id', id);
        this.loadLevelNames();

        this.loadBase();
    }

    componentDidCatch(error, errorInfo) {
        console.log("LoginView componentDidCatch")
    }

    componentWillUnmount() {
        //this.signal.cancel('La solicitud ha sido cancelada por el usuario.');
    }

    async verificarSession() {
        // let response = await LoginRequest.VerificarSession(this.signal.token);
        //if (response.data === "") {
        //    this.verificarParametros();
        //}                 
    }

    async verificarParametros() {

    }
     getParameterByName(name) {
        name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
        var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
        return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
    }

    async loadBase() {
        const localstorage = new LocalStorage();
        const response = await ServiceRequest.ObtenerExp_Ubicacion_Util(localstorage.get('id'), localstorage.get('token'));

        
        if (response != null) {
            let location;
            const ubicacion_util = response.data &&
            {
                Loc_Aplicada: response.data.Loc_Aplicada,
                Loc_Solicitud_Id: response.data.Loc_Solicitud_Id,
                CC_Id: response.data.CC_Id,
                Emp_id: response.data.Emp_id,
                Detalle_Id: response.data.Detalle_Id,
                Ubicacion_Id: response.data.Ubicacion_Id
            }
            localstorage.set('CC_Id', ubicacion_util.CC_Id);
            localstorage.set('Emp_id', ubicacion_util.Emp_id);



            if (ubicacion_util.Loc_Aplicada == false) {
                let localizacionResponse;
                if (ubicacion_util.Detalle_Id == 0) {
                    localizacionResponse = await ServiceRequest.ObtenerExp_Ubicacion(localstorage.get('token'), ubicacion_util.Emp_id, ubicacion_util.Ubicacion_Id);
                    
                } else {
                    localizacionResponse = await ServiceRequest.ObtenerExp_Ubicacion_Detalle(localstorage.get('token'), ubicacion_util.Emp_id, ubicacion_util.Ubicacion_Id, ubicacion_util.Detalle_Id);
                }
                if (localizacionResponse != null) {
                    location = {
                        Nombre: localizacionResponse.data.Ubicacion_Nombre,
                        Compania: '',
                        Barrio: localizacionResponse.data.Ubicacion_Barrio,
                        Senas: localizacionResponse.data.Ubicacion_Senas,
                        Nivel1Nombre: localizacionResponse.data.Nivel1Nombre,
                        Nivel2Nombre: localizacionResponse.data.Nivel2Nombre,
                        Nivel3Nombre: localizacionResponse.data.Nivel3Nombre,
                        Nivel4Nombre: localizacionResponse.data.Nivel4Nombre,
                        Telefono: localizacionResponse.data.Ubicacion_Telefono,
                        CodigoPostal: '',
                        Principal: false,
                        Latitud: localizacionResponse.data.Latitud,
                        Longitud: localizacionResponse.data.Longitud
                    }

                }

                this.setState({ location, ubicacion_util });

            } else {
                this.setState({ btnDisabled:true,isValid:false });
                toastr.error('El Registro a modificar no se encuentra disponible')
                
            }

        }
        else {
            Notification.error(response.Message);
        }
    }

    async loadLevelNames() {
        const localstorage = new LocalStorage();
        const response = await ServiceRequest.Parametro_Generales_List(localstorage.get('token'));

        
        if (response != null) {
            const levelNames = response.data ?
                {
                    NombreNivel1: response.data.Nivel1_Name,
                    NombreNivel2: response.data.Nivel2_Name,
                    NombreNivel3: response.data.Nivel3_Name,
                    NombreNivel4: response.data.Nivel4_Name
                }
                : {
                    NombreNivel1: <Translate id="general.level1" />,
                    NombreNivel2: <Translate id="general.level1" />,
                    NombreNivel3: <Translate id="general.level1" />,
                    NombreNivel4: <Translate id="general.level1" />
                };
            this.setState({ levelNames });
        }
        else {
            Notification.error(response.Message);
        }
    }


    onLevelChanged = event => {
        if (event && event.target) {
            const { value, name } = event.target;

            let location = { ...this.state.location };
            location[name] = isNaN(value) || value === '' ? value : parseInt(value);

            const levels = [{ ID: '', Nombre: <Translate id="myAccountPage.selectOption" /> }];

            switch (name) {
                case "Nivel1Id":
                    location.Nivel2Id = '';
                    location.Nivel3Id = '';
                    location.Nivel4Id = '';
                    this.setState({ location, levels2: levels, levels3: levels, levels4: levels }, () =>
                        this.loadLevels2(location.Nivel1Id)
                    );

                    break;
                case "Nivel2Id":
                    location.Nivel3Id = '';
                    location.Nivel4Id = '';
                    this.setState({ location, levels3: levels, levels4: levels }, () =>
                        this.loadLevels3(location.Nivel1Id, location.Nivel2Id)
                    );

                    break;
                case "Nivel3Id":
                    location.Nivel4Id = '';
                    this.setState({ location, levels4: levels }, () =>
                        this.loadLevels4(location.Nivel1Id, location.Nivel2Id, location.Nivel3Id)
                    );

                    break;
                case "Nivel4Id":
                    this.setState({ location });

                    break;
            }
        }
    }


    onInputChanged = event => {
        const { value, name } = event.target;

        let location = { ...this.state.location };
        location[name] = value;

        this.setState({ location });
    }


    UpdateUbicacion = async () => {
        const localstorage = new LocalStorage();
        const {  location,ubicacion_util } = this.state;
        const response = await ServiceRequest.UpdateUbicacion(localstorage.get('token'),ubicacion_util.Loc_Solicitud_Id, ubicacion_util.Ubicacion_Id,localstorage.get('Emp_id'),localstorage.get('CC_Id'),ubicacion_util.Detalle_Id,location.Latitud,location.Longitud);

        
        if (response.data == "") {
            toastr.success("Dirección Guardada Correctamente.")
            this.setState({ btnDisabled:true });

        }
        else {
            toastr.error("Error al Guardar la Dirección.");
        } 
        
        
    }

    onCheckboxChanged = event => {
        const { checked, name } = event.target;

        let location = { ...this.state.location }; 
        location[name] = checked;

        this.setState({ location });
    } 

    onPhoneNumberChanged = event => {
        const { value, name } = event.target;

        if (value === '' || !isNaN(value)) {
            let location = { ...this.state.location };
            location[name] = value;

            this.setState({ location });
        }
    }

    onChangeMyPosition = position => {
        this.setState({ location: { ...this.state.location, Latitud: position.lat, Longitud: position.lng } });
    }

    render() {
        const { levelNames, location, levels1, levels2, levels3, levels4, phones, btnDisabled, loading,isValid } = this.state;
        
        let mapControl;
        if (location.Nombre != '') {
        let currentLocation = [location.Latitud, location.Longitud];

            mapControl = <Map center={{ lat: currentLocation[0], lng: currentLocation[1] }} onChangeMyPosition={this.onChangeMyPosition} />
        }

        return (
            <React.Fragment>
                <section className="cuenta">
                    {isValid?
                    <div>
                    <div className="row">
                    <label htmlFor="txtPhone" ><Translate id="myAccountPage.infoEditAddress" /><span className="required"></span></label>
                    </div>
                    <div className="row">
                        <div className="col">
                            <h4><Translate id="myAccountPage.editAddress" /></h4>
                        </div>
                    </div>
                    <div className="row"> 
                        <div className="col-sm-12 col-sm-6">
                            <Input id="txtAddressName" value={location.Nombre} labelTextId="myAccountPage.addressName"
                                configuration={{ type: 'text', maxLength: "50", name: "Nombre", disabled: true }} 
                                onChange={this.onInputChanged}
                            />
                        </div>
                        <div className="col-sm-12 col-sm-6">
                            <label htmlFor="txtPhone" ><Translate id="myAccountPage.phone" /> <span className="required"></span></label>

                            <input type="text"
                                id="txtPhone"
                                name="Telefono"
                                className="form-control"
                                value={location.Telefono}
                                maxLength="50"
                                disabled={true}
                                onChange={this.onPhoneNumberChanged}
                                onKeyPress={this.onKeyPressHandler} />

                        </div>
                    </div>
                    <div className="row">
                        <div className="col-sm-12">
                            <Textarea id="txtAddressLine1" value={location.Barrio} labelTextId="myAccountPage.adrressLine1"
                                configuration={{ type: 'text', maxLength: "200", name: "Barrio", disabled: true }} 
                                onChange={this.onInputChanged}
                            />
                        </div>
                    </div>
                    <div className="row">
                        <div className="col-sm-12">
                            <Textarea id="txtAddressLine2" value={location.Senas} labelTextId="myAccountPage.adrressLine2"
                                configuration={{ type: 'text', maxLength: "200", name: "Senas", disabled: true }} 
                                onChange={this.onInputChanged}
                            />
                        </div>
                    </div>
                    <div className="row">
                        <div className="col-sm-12 col-sm-6">
                            {/* <Select id="ddlLevel1" name="Nivel1Id" label={levelNames.NombreNivel1} value={location.Nivel1Id} required
                                onChange={this.onLevelChanged} configuration={{ valueField: 'ID', textField: 'Nombre', options: levels1 || [] }}
                            /> */}
                            <InputNoTranslate id="ddlLevel1" value={location.Nivel1Nombre} labelTextId={levelNames.NombreNivel1}
                                configuration={{ type: 'text', maxLength: "50", name: "Nivel1", disabled: true }}
                                onChange={this.onInputChanged}
                            />
                        </div>
                        <div className="col-sm-12 col-sm-6">
                            <InputNoTranslate id="ddlLevel2" value={location.Nivel2Nombre} labelTextId={levelNames.NombreNivel2}
                                configuration={{ type: 'text', maxLength: "50", name: "Nivel2", disabled: true }}
                                onChange={this.onInputChanged}
                            />
                        </div>
                    </div>
                    <div className="row">
                        <div className="col-sm-12 col-sm-6">
                            <InputNoTranslate id="ddlLevel3" value={location.Nivel3Nombre} labelTextId={levelNames.NombreNivel3}
                                configuration={{ type: 'text', maxLength: "50", name: "Nivel3", disabled: true }}
                                onChange={this.onInputChanged}
                            />
                        </div>
                        <div className="col-sm-12 col-sm-6">
                            <InputNoTranslate id="ddlLevel4" value={location.Nivel4Nombre} labelTextId={levelNames.NombreNivel4}
                                configuration={{ type: 'text', maxLength: "50", name: "Nivel4", disabled: true }}
                                onChange={this.onInputChanged}
                            />
                        </div>
                    </div>
                    <div className="row">
       

                    </div>
                    <div className="row margin-bottom-50">

                        <div className="col-sm-12 col-sm-6 order-1 order-sm-12">
                            <div className="filtros">
                                {
                                    phones.map((phone, index) => {
                                        return <span key={index} className="selected" >{phone} <a onClick={() => this.onRemovePhoneClick(index)}>
                                            <i className="fas fa-times" />
                                        </a>
                                        </span>;
                                    })
                                }
                            </div>
                        </div>
                    </div>
                    <div className="row">
                        <div className="col-12">
                            {mapControl}
                        </div>
                    </div>
                    <div className="row">
                        <div className="col mt-3 btn-success-site">
                            <Button className="float-right margin-top-10"
                                textId={this.props.locationId === 0 ? "general.add" : "general.update"}
                                disabled={btnDisabled}
                                showLoading={loading}
                                onClick={this.UpdateUbicacion}
                            />
                        </div>
                    </div>
                    </div>
                    :
                    <div className="row">
                    <div className="col">
                        <h4 className='expirado-title'><Translate id="myAccountPage.editAddressExpired" /></h4>
                    </div>
                </div>}</section>
            </React.Fragment>
        )
    }
};
export default UserInfoView;