Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

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

import React, { useState } from 'react'
import { useForm } from 'react-hook-form'
import { useDispatch, useSelector } from 'react-redux'
import { axios } from '../../utils'
import { addNotification } from '../../redux/notification/notification.actions'
import { Modal } from 'react-bootstrap'
import Datetime from 'react-datetime'
import FormErrorFeedback from '../UI/FormErrorFeedback'
import useFetchHelper from '../../hooks/useFetchHelper'

const ConferenceModal = ({
  show = false,
  zoomUrl = '',
  onClose = () => null,
}) => {
  const dt = new Date()
  const [date, setDate] = useState({
    year: dt.toLocaleString('default', { year: 'numeric' }),
    month: dt.toLocaleString('default', { month: '2-digit' }),
    day: dt.toLocaleString('default', { day: '2-digit' }),
  })
  const [time, setTime] = useState(
    dt.toLocaleString('es', {
      hour: 'numeric',
      minute: '2-digit',
      second: '2-digit',
    })
  )
  const { data: timezones } = useFetchHelper('timezones')
  const labels = useSelector(({ intl }) => intl.labels)
  const dispatch = useDispatch()

  const { handleSubmit, register, errors, reset, getValues } = useForm({
    mode: 'all',
  })

  const handleDateTime = (value) => {
    setDate({
      ...date,
      year: new Intl.DateTimeFormat('es', { year: 'numeric' }).format(value),
      month: new Intl.DateTimeFormat('es', { month: '2-digit' }).format(value),
      day: new Intl.DateTimeFormat('es', { day: '2-digit' }).format(value),
    })
    setTime(
      new Intl.DateTimeFormat('es', {
        hour: 'numeric',
        minute: '2-digit',
        second: 'numeric',
      }).format(value)
    )
  }

  const onSubmit = handleSubmit(async (data) => {
    try {
      const formData = new FormData()

      Object.entries(data).forEach(([key, value]) =>
        formData.append(key, value)
      )

      formData.append('date', `${date.year}-${date.month}-${date.day}`)
      formData.append('time', time)

      const { data: response } = await axios.post(zoomUrl, formData)

      if (!response.success && typeof response.data === 'string') {
        dispatch(addNotification({ msg: response.data, style: 'danger' }))
        return
      }

      if (!response.success && typeof response.data === 'object') {
        Object.entries(response.data).forEach(([key, value]) => {
          dispatch(
            addNotification({ msg: `${key}: ${value[0]}`, style: 'danger' })
          )
        })
        return
      }

      dispatch(addNotification({ msg: response.data, style: 'success' }))
      onClose()
      reset()
    } catch (error) {
      console.log(`Error: ${error}`)
      dispatch(
        addNotification({ msg: 'Ha ocurrido un error', style: 'danger' })
      )
      throw new Error(error)
    }
  })

  return (
    <Modal show={show} onHide={onClose}>
      <Modal.Header closeButton>
        <Modal.Title>{labels.create_conference}</Modal.Title>
      </Modal.Header>
      <Modal.Body>
        <form onSubmit={onSubmit} autoComplete="new-password">
          <div className="form-group">
            <label htmlFor="first_name">Título</label>
            <input
              type="text"
              name="title"
              className="form-control"
              maxLength={128}
              ref={register({ required: 'Por favor ingrese un título' })}
            />
            {errors.title && (
              <FormErrorFeedback>{errors.title.message}</FormErrorFeedback>
            )}
          </div>
          <div className="form-group">
            <label htmlFor="first_name">Descripción</label>
            <input
              type="text"
              name="description"
              className="form-control"
              ref={register({ required: 'Por favor ingrese una descripción' })}
            />
            {errors.description && (
              <FormErrorFeedback>
                {errors.description.message}
              </FormErrorFeedback>
            )}
          </div>
          <div className="form-group">
            <label htmlFor="timezone">Tipo de conferencia</label>
            <select name="type" className="form-control" ref={register}>
              <option value="i">Inmediata</option>
              <option value="s">Programada</option>
            </select>
          </div>
          {getValues('type') === 's' && (
            <div className="form-group">
              <label htmlFor="timezone">Horario</label>
              <Datetime
                dateFormat="DD-MM-YYYY"
                onChange={(e) => {
                  if (e.toDate) {
                    handleDateTime(e.toDate())
                  }
                }}
                inputProps={{ className: 'form-control' }}
                initialValue={Date.parse(new Date())}
                closeOnSelect
              />
            </div>
          )}
          <div className="form-group">
            <label htmlFor="timezone">Zona horaria</label>
            <select
              className="form-control"
              name="timezone"
              ref={register({ required: 'Por favor elige una Zona horaria' })}
            >
              <option value="" hidden>
                Zona horaria
              </option>
              {timezones.map(({ name, value }) => (
                <option value={value} key={value}>
                  {name}
                </option>
              ))}
            </select>
            {errors.timezone && (
              <FormErrorFeedback>{errors.timezone.message}</FormErrorFeedback>
            )}
          </div>
          <div className="form-group">
            <label htmlFor="timezone">Duración</label>
            <select className="form-control" name="duration" ref={register}>
              <option value={5}>5-min</option>
              <option value={10}>10-min</option>
              <option value={15}>15-min</option>
              <option value={20}>20-min</option>
              <option value={25}>25-min</option>
              <option value={30}>30-min</option>
              <option value={35}>35-min</option>
              <option value={40}>40-min</option>
              <option value={45}>45-min</option>
            </select>
          </div>
          <div className="form-group">
            <label htmlFor="first_name">Contraseña de ingreso</label>
            <input
              type="password"
              name="password"
              className="form-control"
              ref={register({
                required: 'Por favor ingrese una contraseña',
                maxLength: {
                  value: 6,
                  message: 'La contraseña debe tener al menos 6 digitos',
                },
              })}
            />
            {errors.password && (
              <FormErrorFeedback>{errors.password.message}</FormErrorFeedback>
            )}
          </div>
          <button className="btn btn-primary" type="submit">
            Crear
          </button>
        </form>
      </Modal.Body>
    </Modal>
  )
}

export default ConferenceModal