Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

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

import React, { useRef, useState } from 'react'
import { axios } from '../../utils'
import { useDispatch, useSelector } from 'react-redux'
import { addNotification } from '../../redux/notification/notification.actions'
import styled from 'styled-components'

import Spinner from '../UI/Spinner'
import ConfirmationBox from '../UI/ConfirmBox'

import styles from './ProfileItem.module.scss'
import { Link } from 'react-router-dom'

const StyledSpinnerContainer = styled.div`
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: rgba(255, 255, 255, 0.4);
  place-items: center;
  z-index: 50;
`
const ProfileItem = ({
  image,
  name,
  email,
  network,
  status,
  fetchCallback,
  btnAcceptTitle = 'Ver perfil',
  btnCancelTitle = 'Borrar perfil',
  btnEditTitle = 'Editar perfil',
  btnLeaveTitle = 'Dejar',
  link_remove,
  link_view,
  link_edit,
  link_delete,
  link_cancel,
  link_block,
  link_reject,
  link_accept,
  link_inmail,
  link_request,
  link_unblock,
  link_unfollow,
  link_approve,
  link_leave,
  link_admin,
  link_impersonate,
  isTopData,
}) => {
  const [isShowConfirmation, setIsShowConfirmation] = useState(false)
  const [loading, setLoading] = useState(false)
  const confirmUrl = useRef('')
  const labels = useSelector(({ intl }) => intl.labels)
  const dispatch = useDispatch()

  const showConfirm = (url = '') => {
    setIsShowConfirmation(true)
    confirmUrl.current = url
  }

  const closeConfirm = (url = '') => {
    setIsShowConfirmation(false)
    confirmUrl.current = ''
  }

  const getImpersonateUrl = async (url = '') => {
    try {
      const { data } = await axios.get(url)
      if (data.success) window.location.href = data.data
    } catch (error) {
      console.log('>>: error > ', error)
    }
  }

  const onConfirm = (url) => {
    setLoading(true)

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

        if (!success) {
          const errorMessage =
            typeof data === 'string' ? data : labels.error_there_was_an_error

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

        if (fetchCallback) fetchCallback()
        dispatch(addNotification({ style: 'success', msg: data }))
      })
      .catch((err) => {
        dispatch(
          addNotification({
            style: 'error',
            msg: labels.error_there_was_an_error,
          })
        )
        throw new Error(err)
      })
      .finally(() => {
        confirmUrl.current = ''
        setLoading(false)
      })
  }

  const handleUnfollow = (link_unfollow) => {
    setLoading(true)
    axios
      .post(link_unfollow)
      .then((response) => {
        const { data, success } = response.data

        if (!success) {
          const errorMessage =
            typeof data === 'string' ? data : labels.error_there_was_an_error

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

        if (fetchCallback) fetchCallback()
        dispatch(addNotification({ style: 'success', msg: data }))
      })
      .finally(() => setLoading(false))
  }

  const getManageUrl = async () => {
    try {
      const { data } = await axios.get(link_admin)
      if (data.success) window.open(data.data, '_backend')
    } catch (error) {
      console.log('>>: error > ', error)
    }
  }

  const linksOptions = [
    {
      label: btnAcceptTitle || labels.accept,
      url: link_view,
      color: 'primary',
    },
    { label: btnEditTitle || labels.edit, url: link_edit, color: 'secondary' },
    { label: labels.approve, url: link_approve, color: 'tertiary' },
    { label: btnLeaveTitle, url: link_remove, color: 'tertiary' },
    { label: labels.accept, url: link_accept, color: 'secondary' },
    { label: labels.reject, url: link_reject, color: 'tertiary' },
    {
      label: btnCancelTitle || labels.cancel,
      url: link_delete,
      color: 'tertiary',
    },
    {
      label: labels.message || 'Mensaje',
      url: link_inmail,
      color: 'secondary',
    },
    { label: labels.administrate, url: link_admin, color: 'secondary' },
    { label: labels.unfollow, url: link_unfollow, color: 'tertiary' },
    { label: labels.block, url: link_block, color: 'tertiary' },
    { label: labels.unblock, url: link_unblock, color: 'tertiary' },
    { label: labels.connect, url: link_request, color: 'tertiary' },
    { label: labels.cancel, url: link_cancel, color: 'tertiary' },
    { label: btnLeaveTitle, url: link_leave, color: 'tertiary' },
    { label: 'Personificar', url: link_impersonate, color: 'tertiary' },
  ]

  return (
    <div className={styles.profile_item}>
      <div className={styles.profile_item_header}>
        {image && <img src={image} alt="group image" />}
        <div className={styles.profile_item_header_info}>
          <h3>{name}</h3>
          {isTopData && email && <h4>{email}</h4>}
          {network && <h4>{network}</h4>}
          {status && <h4>{status}</h4>}
          {isTopData && (
            <ul>
              {link_view && (
                <li>
                  <Link
                    to={link_view}
                    data-link={link_view}
                    className="btn btn-secondary ellipsis"
                  >
                    {btnAcceptTitle}
                  </Link>
                </li>
              )}
              {link_inmail && (
                <li>
                  <Link
                    to={link_inmail}
                    data-link={link_inmail}
                    className="btn btn-primary"
                  >
                    {labels.message}
                  </Link>
                </li>
              )}
            </ul>
          )}
        </div>
      </div>
      <hr />
      <ul className="position-relative">
        {linksOptions.map((option) => {
          const breakOptions = [link_view, link_edit, link_inmail]

          if (!option.url) {
            return null
          }

          if (option.url === link_view && isTopData) {
            return null
          }

          if (option.url === link_inmail && isTopData) {
            return null
          }

          return (
            <li key={option.label}>
              <Link
                to={option.url}
                title={option.label}
                className="position-relative"
                onClick={(e) => {
                  if (option.url === link_unfollow) {
                    e.preventDefault()
                    handleUnfollow(option.url)
                    return
                  }

                  if (option.url === link_admin) {
                    e.preventDefault()
                    getManageUrl()
                    return
                  }

                  if (option.url === link_impersonate) {
                    e.preventDefault()
                    getImpersonateUrl(option.url)
                    return
                  }

                  if (!breakOptions.includes(option.url)) {
                    e.preventDefault()
                    showConfirm(option.url)
                  }
                }}
              >
                <button className={`btn btn-${option.color}`}>
                  {option.label}
                </button>
              </Link>
            </li>
          )
        })}
        <ConfirmationBox
          show={isShowConfirmation}
          onClose={() => closeConfirm()}
          onAccept={() => onConfirm(confirmUrl.current)}
        />
      </ul>
      {loading && (
        <StyledSpinnerContainer>
          <Spinner />
        </StyledSpinnerContainer>
      )}
    </div>
  )
}

export default ProfileItem