Proyectos de Subversion LeadersLinked - SPA

Rev

Rev 3173 | Rev 3175 | 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 { useDispatch, useSelector } from 'react-redux'

import { axios } from '@utils'
import { addFeed } from '@store/feed/feed.actions'
import { feedTypes } from '@store/feed/feed.types'
import { addNotification } from '@store/notification/notification.actions'
import { shareModalTypes } from '@store/share-modal/shareModal.types'
import {
  closeShareModal,
  openShareModal
} from '@store/share-modal/shareModal.actions'

import Modal from '@components/UI/modal/Modal'
import Form from '@components/common/form'
import Select from '@components/UI/inputs/Select'
import Ckeditor from '@components/UI/Ckeditor'
import DropzoneComponent from '@components/dropzone/DropzoneComponent'
import FormErrorFeedback from '@components/UI/form/FormErrorFeedback'
import ConfirmModal from './ConfirmModal'

const recomendationText = {
  [shareModalTypes.IMAGE]: 'Tamaño recomendado: 720x720',
  [shareModalTypes.FILE]: 'solo documentos PDF',
  [shareModalTypes.VIDEO]: 'Video de extensión mp4, mpeg, webm, mov'
}

const ShareModal = ({ setModalType }) => {
  const [showConfirmModal, setShowConfirmModal] = useState(false)
  const labels = useSelector(({ intl }) => intl.labels)
  const dispatch = useDispatch()

  const { isOpen, postUrl, modalType, lastModalType, feedType, feedSharedId } =
    useSelector((state) => state.shareModal)

  const {
    control,
    formState: { errors, isSubmitting },
    register,
    unregister,
    handleSubmit,
    setValue,
    getValues,
    clearErrors,
    setError,
    watch
  } = useForm({
    defaultValues: {
      description: '',
      share_width: 'p'
    }
  })

  const toggleConfirmModal = () => setShowConfirmModal(!showConfirmModal)

  const handleModalAccept = () => {
    setShowConfirmModal(false)
    setValue('description', '')
    setValue('file', '')
    clearErrors()
    dispatch(openShareModal(postUrl, modalType, feedType))
  }

  const handleModalCancel = () => {
    setShowConfirmModal(false)
    setModalType(lastModalType)
    dispatch(closeShareModal())
    dispatch(openShareModal(postUrl, lastModalType, feedType))
  }

  const onSubmit = handleSubmit((data) => {
    const form = new FormData()
    form.append(
      'posted_or_shared',
      modalType === shareModalTypes.SHARE ? 's' : 'p'
    )
    Object.entries(data).forEach(([key, value]) => form.append(key, value))

    axios
      .post(postUrl, form)
      .then((response) => {
        const { data, success } = response.data

        if (!success && typeof data !== 'string') {
          Object.entries(data).map(([key, value]) =>
            setError(key, { type: 'required', message: value[0] })
          )
          return
        }

        if (!success && typeof data === 'string') {
          throw new Error(data)
        }

        const newFeed = data

        dispatch(
          addNotification({
            style: 'success',
            msg: 'La publicación ha sido compartida'
          })
        )

        onClose()

        if (feedSharedId) {
          dispatch(addFeed(newFeed, feedSharedId))
        } else {
          dispatch(addFeed(newFeed))
        }

        setValue('description', '')
        setValue('file', '')
      })
      .catch((error) => {
        console.error(error)
        dispatch(
          addNotification({
            style: 'danger',
            msg: 'Ha ocurrido un error al publicar, intente más tarde.'
          })
        )
      })
  })

  const onUploadedHandler = (files) => {
    setValue('file', files)
    clearErrors('file')
  }

  const onClose = () => {
    clearErrors()
    dispatch(closeShareModal())
  }

  useEffect(() => {
    if (
      modalType !== shareModalTypes.POST &&
      modalType !== shareModalTypes.SHARE
    ) {
      register('file', {
        required: { value: 'true', message: 'El campo es requerido' }
      })
    } else {
      if (!getValues('file')) unregister('file')
    }

    if (getValues('file') || getValues('description')) {
      if (modalType !== lastModalType) {
        onClose()
        toggleConfirmModal()
      }
    }
  }, [modalType])

  return (
    <>
      <Modal
        show={isOpen}
        title={labels.share_a_post}
        labelAccept={labels.send}
        labelReject={labels.cancel}
        onClose={onClose}
        loading={isSubmitting}
        formId='share-form'
      >
        <Form onSubmit={onSubmit} id='share-form'>
          {feedType === feedTypes.DASHBOARD && (
            <Select
              name='shared_with'
              defaultValue='p'
              control={control}
              options={[
                { name: labels.public, value: 'p' },
                { name: labels.connections, value: 'c' }
              ]}
            />
          )}

          <Ckeditor
            name='description'
            control={control}
            rules={{ required: 'El campo es requerido' }}
            error={errors.description?.message}
          />

          {![shareModalTypes.POST, shareModalTypes.SHARE].includes(
            modalType
          ) ? (
            <DropzoneComponent
              modalType={modalType}
              onUploaded={onUploadedHandler}
              settedFile={watch('file')}
              recomendationText={recomendationText[modalType] ?? ''}
            />
          ) : null}

          {errors.file && (
            <FormErrorFeedback>{errors.file.message}</FormErrorFeedback>
          )}
        </Form>
      </Modal>
      <ConfirmModal
        show={showConfirmModal}
        onClose={handleModalCancel}
        onAccept={handleModalAccept}
        message='¿No se ha compartido tu publicación , desea descartarlo?'
      />
    </>
  )
}

export default ShareModal