Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

Ir a la última revisión | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |

import React, { useEffect, useState, useRef } from 'react'
import { axios } from '../../../utils'
import { useForm } from 'react-hook-form'
import { Button, Modal } from 'react-bootstrap'
import { useDispatch, useSelector } from 'react-redux'
import { addNotification } from '../../../redux/notification/notification.actions'

import Spinner from '../UI/Spinner'
import UbicationInput from '../../../shared/ubication-input/UbicationInput'
import FormErrorFeedback from '../UI/FormErrorFeedback'

const LocationModal = ({
  closeModal,
  isModalOpen,
  userIdEncrypted,
  setSettedAddress,
}) => {
  const [modalLoading, setModalLoading] = useState(false)
  const labels = useSelector(({ intl }) => intl.labels)
  const dispatch = useDispatch()

  const {
    register,
    errors,
    handleSubmit,
    setValue,
    clearErrors,
    getValues,
    watch,
    setError,
  } = useForm()

  const isAddressEmpty = useRef(true)
  const addressKeys = useRef([
    'address1',
    'address2',
    'country',
    'state',
    'city1',
    'city2',
    'postal_code',
    'latitude',
    'longitude',
  ])

  const handleModalOpen = (event) => {
    event && event.preventDefault()
    Object.keys(getValues()).map(([key]) => setValue(key, ''))
    closeModal()
  }

  const getAddressHandler = (addresObject) => {
    addressKeys.current.map((addressKey) => {
      setValue(addressKey, '')
    })
    const { address_components } = addresObject
    if (address_components) {
      address_components.map((address_component) => {
        const address_component_name = address_component.long_name
        const address_component_type = address_component.types[0]
        switch (address_component_type) {
          case 'route':
            setValue('address1', address_component_name)
            break
          case 'sublocality':
            setValue('address2', address_component_name)
            break
          case 'locality':
            setValue('city1', address_component_name)
            break
          case 'administrative_area_level_2':
            setValue('city2', address_component_name)
            break
          case 'administrative_area_level_1':
            setValue('state', address_component_name)
            break
          case 'country':
            setValue('country', address_component_name)
            break
          case 'postal_code':
            setValue('postal_code', address_component_name)
            break
          case 'geometry':
            setValue('latitude', address_component.latitude)
            setValue('longitude', address_component.longitude)
            break
          default:
            break
        }
      })
      isAddressEmpty.current = false
      clearErrors('formatted_address')
    } else {
      isAddressEmpty.current = true
    }
    setValue('formatted_address', addresObject.formatted_address)
  }

  const onSubmitHandler = async (data) => {
    setModalLoading(true)
    const formData = new FormData()
    Object.entries(data).map(([key, value]) => {
      formData.append(key, value)
    })
    await axios
      .post(`/profile/my-profiles/location/${userIdEncrypted}`, formData)
      .then((response) => {
        const resData = response.data
        if (resData.success) {
          setSettedAddress(resData.data.formatted_address)
          handleModalOpen()
        } else {
          const resError = resData.data
          if (resError.constructor.name === 'Object') {
            Object.entries(resError).map(([key, value]) => {
              if (key in getValues()) {
                setError(key, {
                  type: 'manual',
                  message: Array.isArray(value) ? value[0] : value,
                })
              }
            })
          } else {
            dispatch(addNotification({ style: 'danger', msg: resError }))
          }
        }
      })
    setModalLoading(false)
  }

  useEffect(() => {
    addressKeys.current.map((addressKey) => {
      register(addressKey)
    })
    register('formatted_address', {
      required: 'por favor seleccione una ubicación correcta',
    })
  }, [])

  return (
    <Modal show={isModalOpen} onHide={handleModalOpen}>
      <Modal.Header closeButton>
        <Modal.Title>{labels.location}</Modal.Title>
      </Modal.Header>
      <form onSubmit={handleSubmit(onSubmitHandler)}>
        <Modal.Body>
          <div className="form-group datefm">
            <UbicationInput
              onGetAddress={getAddressHandler}
              settedQuery={watch('formatted_address')}
            />
            <i className="fa fa-map-marker"></i>
            {errors.formatted_address && (
              <FormErrorFeedback>
                {errors.formatted_address.message}
              </FormErrorFeedback>
            )}
          </div>
        </Modal.Body>
        <Modal.Footer>
          <Button size="sm" type="submit">
            {labels.accept}
          </Button>
          <Button size="sm" variant="danger" onClick={handleModalOpen}>
            {labels.cancel}
          </Button>
        </Modal.Footer>
      </form>
      {modalLoading && <Spinner />}
    </Modal>
  )
}

export default LocationModal