Proyectos de Subversion LeadersLinked - SPA

Rev

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

import React, { useEffect, useMemo, useRef, useState } from 'react'
import { useForm } from 'react-hook-form'
import { styled } 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'

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 = (props) => {
  const {
    active = 0,
    question = '¿Cómo consideras el ambiente laboral?',
    answers = ['Excelente', 'Regular', null, null, null],
    votes = [null, null, null, null, null],
    time = 0,
    voteUrl = '/feed/vote/d454717c-ba6f-485c-b94c-4fbb5f5bed94',
    resultType = 'pu',
    voted = 0
  } = props
  const [remainingTime, setRemainingTime] = useState('00:00:00')
  const [isActive, setIsActive] = useState(true)
  const timeRef = useRef(time)

  const { register, handleSubmit } = useForm()

  console.log(props)

  const totalVotes = useMemo(
    () =>
      votes.reduce((curr, next) => {
        if (next === null) return curr
        return curr + next
      }, 0),
    [votes]
  )

  const sendVote = handleSubmit(({ vote }) => {
    setIsActive(false)

    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) => {
        setIsActive(true)
        addNotification({ style: 'danger', msg: err.message })
      })
  })

  function getTimeDiff(segundos) {
    const currentDate = new Date()
    const futureDate = new Date(currentDate.getTime() + segundos * 1000)
    const diff = futureDate - currentDate

    const days = Math.floor(diff / (1000 * 60 * 60 * 24))
    const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
    const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))

    return `${addZero(days)}d ${addZero(hours)}h ${addZero(minutes)}m`
  }

  function addZero(unit) {
    return String(unit).padStart(2, '0')
  }

  function getPorcentage(n, total) {
    return (n / total) * 100
  }

  useEffect(() => {
    setIsActive(!!active)
  }, [active])

  return (
    <form onChange={sendVote} className={styles.survey_form}>
      <h3>{question}</h3>
      {resultType === 'pu' && (
        <span
          className='mb-2'
          title='El número de votos es visible para todos los usuarios'
        >
          <Public /> Público
        </span>
      )}
      {resultType === 'pr' && (
        <span
          className='mb-2'
          title='Los resultados de la votación son privados'
        >
          <LockClock /> Privado
        </span>
      )}
      {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>
      {!isActive && <VoteTag>Tu voto ya fue emitido</VoteTag>}
    </form>
  )
}

export default SurveyForm