Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

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

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

import FormErrorFeedback from '../UI/FormErrorFeedback'
import Spinner from '../UI/Spinner'

const KnowledgeEditModal = ({
  show,
  categories = [],
  url,
  onComplete,
  onClose,
  isEdit,
}) => {
  const [loading, setLoading] = useState(false)
  const labels = useSelector(({ intl }) => intl.labels)
  const dispatch = useDispatch()

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

  const watchDescription = watch('description', '<p></p>')

  const onSubmit = handleSubmit((data) => {
    setLoading(true)
    const formData = new FormData()
    Object.entries(data).map(([key, value]) => {
      if (['attachment', 'image'].includes(key) && value) {
        formData.append(key, value[0])
        return
      }
      formData.append(key, value)
    })

    axios
      .post(url, formData)
      .then((response) => {
        const { data, success } = response.data
        if (!success) {
          if (typeof data === 'string') {
            dispatch(addNotification({ style: 'danger', msg: data }))
            return
          }

          Object.entries(data).map(([key, value]) => {
            key in getValues() &&
              dispatch(
                addNotification({
                  style: 'danger',
                  msg: `${key}: ${Array.isArray(value) ? value[0] : value}`,
                })
              )
          })
          return
        }

        onComplete()
        onClose()
      })
      .finally(() => setLoading(false))
  })

  useEffect(() => {
    register('description', { required: true })
  }, [])

  useEffect(() => {
    if (!url || !show || !isEdit) return

    axios.get(url).then((response) => {
      const { data, success } = response.data

      if (!success) {
        const errorMessage =
          typeof data === 'string' ? data : 'Ha ocurrido un error'

        dispatch(
          addNotification({
            style: 'danger',
            msg: errorMessage,
          })
        )
        return
      }

      setValue('title', data.title)
      setValue('category_id', data.category_id)
      setValue('description', data.description)
    })
  }, [url, show, isEdit])

  useEffect(() => {
    if (!show) {
      setValue('category_id', '')
      setValue('description', '')
      setValue('title', '')
      setValue('image', '')
    }
  }, [show])

  return (
    <Modal show={show}>
      <Modal.Header className="pb-0">
        <Modal.Title>
          {isEdit ? labels.edit : labels.add} conocimiento
        </Modal.Title>
      </Modal.Header>
      <Modal.Body>
        {loading ? (
          <Spinner />
        ) : (
          <Form onSubmit={onSubmit}>
            <Form.Group>
              <Form.Label>{labels.category}</Form.Label>
              <Form.Control
                as="select"
                ref={register({ required: true })}
                name="category_id"
              >
                {categories.map(({ name, uuid }) => (
                  <option value={uuid} key={uuid}>
                    {name}
                  </option>
                ))}
              </Form.Control>
              {errors.category_id && (
                <FormErrorFeedback>
                  {labels.error_field_empty}
                </FormErrorFeedback>
              )}
            </Form.Group>

            <Form.Group>
              <Form.Label>{labels.title}</Form.Label>
              <Form.Control
                type="text"
                name="title"
                ref={register({ required: true })}
              />
              {errors.title && (
                <FormErrorFeedback>
                  {labels.error_field_empty}
                </FormErrorFeedback>
              )}
            </Form.Group>

            <CKEditor
              onChange={(e) => setValue('description', e.editor.getData())}
              initData={watchDescription}
              config={CKEDITOR_OPTIONS}
            />

            {errors.description && (
              <FormErrorFeedback>{labels.error_field_empty}</FormErrorFeedback>
            )}

            <Form.Group>
              <Form.File
                label={labels.image}
                name="image"
                ref={register({ required: true })}
              />
              {errors.image && (
                <FormErrorFeedback>
                  {labels.error_field_empty}
                </FormErrorFeedback>
              )}
            </Form.Group>

            <Form.Group>
              <Form.File
                label={labels.attachment}
                name="attachment"
                ref={register}
              />
            </Form.Group>

            <Button className="mt-3 mr-2" variant="primary" type="submit">
              {labels.accept}
            </Button>
            <Button className="btn-secondary mt-3" onClick={onClose}>
              {labels.cancel}
            </Button>
          </Form>
        )}
      </Modal.Body>
    </Modal>
  )
}

export default KnowledgeEditModal