Rev 5478 | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |
/* eslint-disable array-callback-return */
/* eslint-disable react/prop-types */
import React, { useEffect, useRef, useState } from 'react'
import styled from 'styled-components'
import { useForm } from 'react-hook-form'
import { CKEditor } from 'ckeditor4-react'
import { useDispatch } from 'react-redux'
import { Button, Modal } from 'react-bootstrap'
import { addNotification } from '../../../redux/notification/notification.actions'
import { axios, CKEDITOR_OPTIONS } from '../../../utils'
import Spinner from '../../../shared/loading-spinner/Spinner'
import UbicationInput from '../../../shared/ubication-input/UbicationInput'
import FormErrorFeedback from '../../../shared/form-error-feedback/FormErrorFeedback'
const StyledSwitch = styled.label`
position: relative;
display: inline-block;
width: 60px;
height: 34px;
input {
opacity: 0;
width: 0;
height: 0;
}
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
-webkit-transition: 0.4s;
transition: 0.4s;
}
.slider:before {
position: absolute;
content: '';
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
-webkit-transition: 0.4s;
transition: 0.4s;
}
input:checked + .slider {
background-color: #2196f3;
}
input:focus + .slider {
box-shadow: 0 0 1px #2196f3;
}
input:checked + .slider:before {
-webkit-transform: translateX(26px);
-ms-transform: translateX(26px);
transform: translateX(26px);
}
.slider.round {
border-radius: 34px;
}
.slider.round:before {
border-radius: 50%;
}
`
const EducationModal = ({
show = false,
closeModal = () => {},
postUrl = '',
setEducations = () => {},
settedDescription = '',
degreesOptions,
}) => {
const {
register,
errors,
handleSubmit,
setValue,
clearErrors,
getValues,
watch,
} = useForm()
const [modalLoading, setModalLoading] = useState(false)
const dispatch = useDispatch()
const isAddressEmpty = useRef(true)
const addressKeys = useRef([
'address1',
'address2',
'country',
'state',
'city1',
'city2',
'postal_code',
'latitude',
'longitude',
])
const handleModalOpen = () => {
Object.keys(getValues()).map(([key]) => setValue(key, ''))
closeModal()
}
const getYears = () => {
const date = new Date()
const currentYear = date.getFullYear()
let years = []
for (let index = currentYear; index > currentYear - 100; index--) {
years = [...years, index]
}
return years
}
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
} else {
isAddressEmpty.current = true
}
setValue('formatted_address', addresObject.formatted_address)
clearErrors('formatted_address')
}
const onSubmitHandler = async (data) => {
setModalLoading(true)
const formData = new FormData()
Object.entries(data).map(([key, value]) => {
if (key === 'is_current') {
value === 'y'
? formData.append('to_year', new Date().getFullYear())
: formData.append(key, value)
}
formData.append(key, value)
})
await axios.post(postUrl, formData).then((response) => {
const resData = response.data
if (resData.success) {
setEducations(resData.data)
handleModalOpen()
} else {
const resError = resData.data
if (resError.constructor.name === 'Object') {
Object.entries(resError).map(([key, value]) => {
if (key in getValues()) {
dispatch(
addNotification({
style: 'danger',
msg: `${key}: ${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: 'Este campo es requerido',
})
register('description', { required: true })
}, [])
useEffect(async () => {
if (settedDescription) {
const { data } = await axios.get(postUrl)
if (!data.success) {
addNotification({
style: 'danger',
msg:
typeof data.data === 'string' ? data.data : 'Ha ocurrido un error',
})
setModalLoading(false)
return
}
Object.entries(data.data.education).map(([key, value]) =>
setValue(key, value)
)
Object.entries(data.data.location).map(([key, value]) =>
setValue(key, value)
)
isAddressEmpty.current = false
}
}, [show])
return (
<Modal show={show} onHide={handleModalOpen}>
<Modal.Header closeButton>
<Modal.Title>Educación</Modal.Title>
</Modal.Header>
<form onSubmit={handleSubmit(onSubmitHandler)}>
<Modal.Body>
<div className="form-group">
<select
name="degree_id"
id="degree_id"
defaultValue=""
ref={register({
required: 'este campo es requerido',
})}
>
<option value="" hidden>
Grado
</option>
{degreesOptions &&
Object.entries(degreesOptions).map(([key, value]) => (
<option value={key} key={key}>
{value}
</option>
))}
</select>
{errors.degree_id && (
<FormErrorFeedback>{errors.degree_id.message}</FormErrorFeedback>
)}
</div>
<div className="form-group">
<input
type="text"
name="university"
id="university"
placeholder="Universidad"
ref={register({
required: 'este campo es requerido',
})}
/>
{errors.university && (
<FormErrorFeedback>{errors.university.message}</FormErrorFeedback>
)}
</div>
<div className="form-group">
<input
type="text"
name="field_of_study"
id="field_of_study"
placeholder="Campo de estudio"
ref={register({
required: 'este campo es requerido',
})}
/>
{errors.field_of_study && (
<FormErrorFeedback>
{errors.field_of_study.message}
</FormErrorFeedback>
)}
</div>
<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>
<div className="form-grop">
<input
type="text"
name="grade_or_percentage"
id="grade_or_percentage"
placeholder="Grado o porcentaje"
ref={register({
required: 'este campo es requerido',
})}
/>
{errors.grade_or_percentage && (
<FormErrorFeedback>
{errors.grade_or_percentage.message}
</FormErrorFeedback>
)}
</div>
<div className="row profile-year d-flex align-items-center pt-1">
<div className="input-c p-0 pr-2">
<div className="form-group">
<select
name="from_year"
id="from_year"
defaultValue=""
ref={register({
required: 'este campo es requerido',
})}
>
<option value="">Año desde</option>
{getYears().map((year) => (
<option key={year} value={year}>
{year}
</option>
))}
</select>
{errors.from_year && (
<FormErrorFeedback>
{errors.from_year.message}
</FormErrorFeedback>
)}
</div>
</div>
{!watch('is_current') && (
<div className="input-c p-0 pr-2">
<div className="form-group">
<select
name="to_year"
id="to_year"
defaultValue=""
ref={register({
required: 'este campo es requerido',
})}
>
<option value="">Año hasta</option>
{getYears().map((year) => (
<option key={year} value={year}>
{year}
</option>
))}
</select>
{errors.to_year && (
<FormErrorFeedback>
{errors.to_year.message}
</FormErrorFeedback>
)}
</div>
</div>
)}
<div className="input-c p-0">
<label htmlFor="is_current">Educación Actual</label>
<div className="form-group">
<StyledSwitch className="switch">
<input
type="checkbox"
name="is_current"
id="is_current"
value="y"
ref={register}
/>
<span className="slider round"></span>
</StyledSwitch>
</div>
</div>
</div>
<div className="form-group">
<CKEditor
onChange={(e) => setValue('description', e.editor.getData())}
onInstanceReady={(e) => e.editor.setData(settedDescription)}
config={CKEDITOR_OPTIONS}
/>
{errors.description && (
<FormErrorFeedback>Este campo es requerido</FormErrorFeedback>
)}
</div>
</Modal.Body>
<Modal.Footer>
<Button size="sm" type="submit">
Enviar
</Button>
<Button size="sm" variant="danger" onClick={handleModalOpen}>
Cancelar
</Button>
</Modal.Footer>
</form>
{modalLoading && <Spinner />}
</Modal>
)
}
export default EducationModal