Proyectos de Subversion LeadersLinked - SPA

Rev

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

import React from 'react'
import { useForm } from 'react-hook-form'
import { styled, Typography } from '@mui/material'
import { Public, LockClock } from '@mui/icons-material'

import { axios } from '@utils'
import { updateFeed } from '@store/feed/feed.actions'
import { addNotification } from '@store/notification/notification.actions'

import styles from './survey.module.scss'
import Widget from '@components/UI/Widget'

const RadioButton = styled('div')`
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem 1rem;
  border: 2px solid var(--border-primary);
  border-radius: 50px;
  cursor: pointer;
  transition: all 200ms ease;
  position: relative;
  overflow: hidden;
  margin-bottom: 0.5rem;
  input {
    margin: 0 !important;
  }
  label {
    color: var(--font-color);
    font-weight: 500;
  }
  &::before {
    content: '';
    position: absolute;
    left: 0;
    top: 0;
    height: 100%;
    width: ${(props) => (props.porcentage ? `${props.porcentage}%` : '0%')};
    background-color: #0002;
    z-index: 4;
  }
  &:hover {
    border-color: var(--font-color);
    text-shadow: 0 0 1px var(--font-color);
  }
`

const VoteTag = styled('span')`
  position: absolute;
  bottom: 1rem;
  right: 1rem;
  color: var(--font-color) !important;
  font-weight: 600;
`

const SurveyForm = ({
  active = false,
  question = '¿Cómo consideras el ambiente laboral?',
  answers = [],
  votes = [],
  time = 0,
  voteUrl = '/feed/vote/d454717c-ba6f-485c-b94c-4fbb5f5bed94',
  resultType = 'pu'
}) => {
  const { register, handleSubmit } = useForm()

  const sendVote = handleSubmit(({ vote }) => {
    const formData = new FormData()
    formData.append('vote', vote)

    axios
      .post(voteUrl, formData)
      .then(({ data: response }) => {
        const { success, data } = response

        if (!success) {
          const errorMessage =
            typeof data === 'string'
              ? data
              : 'Error interno, por favor intente mas tarde.'
          throw new Error(errorMessage)
        }

        updateFeed({ feed: data, uuid: data.feed_uuid })
        addNotification({ style: 'success', msg: 'Voto emitido con exito' })
      })
      .catch((err) => {
        addNotification({ style: 'danger', msg: err.message })
      })
  })

  console.log({
    active,
    question,
    answers,
    votes,
    time,
    voteUrl,
    resultType
  })

  return (
    <Widget>
      <Widget.Body>
        <Typography variant='h3'>{question}</Typography>

        {resultType === 'pu' ? (
          <Typography
            variant='overline'
            title='El número de votos es visible para todos los usuarios'
          >
            <Public /> Público
          </Typography>
        ) : (
          <Typography
            variant='overline'
            title='Los resultados de la votación son privados'
          >
            <LockClock /> Privado
          </Typography>
        )}

        <form onChange={sendVote} className={styles.survey_form}>
          {answers.map((answer, index) => {
            if (answer === null) return null

            return (
              <RadioButton key={answer}>
                <input
                  type='radio'
                  name='vote'
                  ref={register({ required: true })}
                  value={index + 1}
                />
                <label htmlFor={`vote-${index + 1}`}>{answer}</label>
                {/*  {!!totalVotes && (
              <span className='mb-0'>
                {getPorcentage(votes[index], totalVotes)}%
              </span>
            )} */}
              </RadioButton>
            )
          })}
          <span>Tiempo restante: </span>
          {!active && <VoteTag>El formulario ya ha finalizado</VoteTag>}
        </form>
      </Widget.Body>
    </Widget>
  )
}

export default SurveyForm