Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

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

/* eslint-disable react/prop-types */
/* eslint-disable react/jsx-key */
import React, { useEffect, useState } from "react";
import axios from "../../../../utils/axios";
import { connect } from "react-redux"
import { HiOutlineTag } from "react-icons/hi";
import { addNotification } from "../../../../redux/notification/notification.actions";

const ICON_OPTIONS = [
  <img src="/images/icons/home.png" className="img-icon lg" />,
  <img src="/images/icons/conecctions.png" className="img-icon lg" />,
  <img src="/images/icons/company.png" className="img-icon lg" />,
  <img src="/images/icons/groups.png" className="img-icon lg" />,
  <HiOutlineTag />
]

const ADD_OPTIONS = [
  <i className="fa fa-calendar img-icon lg" />,
]

const NavLinks = ({ menuData, sessionLink, addNotification }) => {

  const [menuItems, setMenuItems] = useState(menuData || [])
  const [aditionalItems, setAditionalItems] = useState([])
  const [notifications, setNotifications] = useState([])
  const [notificationsCount, setNotificationsCount] = useState(0)
  const [totalMessages, setTotalMessages] = useState(0)
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    handleNotifications()
  }, [notificationsCount])

  useEffect(() => {
    if (menuData.length > 5) {
      setMenuItems(menuData.splice(0, 5))
      setAditionalItems(menuData.splice(menuData.length - 5))
    }
  }, [])

  useEffect(() => {
    let timer;
    if (!loading) {
      timer = setTimeout(() => checkSession(), 1000);
    }
    return () => {
      clearTimeout(timer);
    };
  }, [loading])

  const checkSession = async () => {
    try {
      setLoading(true)

      const { data: response } = await axios.get(sessionLink)
      const { total_messages, total_notifications } = response.data

      if (response.success) {
        setNotificationsCount(Number(total_notifications))
        setTotalMessages(Number(total_messages))
      }

      setLoading(false)
    } catch (error) {
      console.log(error)
    }
  }

  const readNotification = (link_read, link_notification) => {
    axios.post(link_read)
      .then(({ data }) =>
        data.success
          ? window.open(link_notification, '_blank').focus()
          : addNotification({ style: 'danger', msg: data.data }))
  }

  const deleteNotification = (link_delete) => {
    axios.post(link_delete)
      .then(({ data }) => {
        !data.success && addNotification({ style: 'danger', msg: data.data })
        setNotificationsCount(prev => prev - 1)
        setNotifications(notifications.filter(notification => notification.link_delete !== link_delete))
        addNotification({ style: 'success', msg: data.data })
      })
  }

  const handleNotifications = () => {
    axios.get('/notifications/unreads')
      .then(({ data }) => {
        if (data.success) {
          let notifications = new Set(data.data.notifications)
          setNotifications([...notifications])
        }
      })
      .catch(err => {
        addNotification({
          style: "error",
          msg: 'Disculpe, ha ocurrido un error buscando notificaciones',
        })
        console.log('>>: err > ', err)
      })
  }

  return (
    <ul>
      {menuItems.map((item, index) =>
        <li key={index}>
          <a
            href={item.childs.length ? '#' : item.href}
            onClick={(e) => item.childs.length && e.preventDefault()}
          >
            {ICON_OPTIONS[index]}
            <p>{item.label}</p>
          </a>
          {!!item.childs.length &&
            <nav className='navLinkDropdown'>
              <ul>
                {item.childs.map((_element, _i) =>
                  <li key={_i}>
                    {_element.childs?.length
                      ?
                      <a href='#' onClick={(e) => e.preventDefault()}>
                        {_element.label}
                      </a>
                      : <a href={_element.href}>
                        {_element.label}
                      </a>
                    }
                    {!!_element.childs?.length &&
                      <>
                        <i className="fa fa-angle-right" />
                        <nav className='navLinkLevelThree'>
                          <ul>
                            {_element.childs?.map((levelThree, index) =>
                              <li key={index}>
                                <a
                                  href={levelThree.href}
                                >
                                  {levelThree.label}
                                </a>
                              </li>
                            )}
                          </ul>
                        </nav>
                      </>
                    }
                  </li>
                )}
              </ul>
            </nav>
          }
        </li>
      )}
      <li>
        <a href="/inmail">
          <i className="fa fa-envelope-o" />
          <p>Inmail</p>
          <span className={`badge ${totalMessages ? 'd-block' : 'd-none'}`}>
            {totalMessages}
          </span>
        </a>
      </li>
      <li className='d-md-none'>
        <a href="/chat">
          <i className="fa fa-comment-o" />
          <p>Chat</p>
          <span className="badge" />
        </a>
      </li>
      {!!aditionalItems.length &&
        <li>
          <a
            href={'#'}
            onClick={(e) => e.preventDefault()}
          >
            <i className="fa fa-inbox img-icon lg" />
            <p>Comunicación</p>
          </a>
          <div className="aditional_links">
            <ul>
              {aditionalItems.map((item, index) =>
                <li key={index}>
                  <a href={item.href}>
                    {ADD_OPTIONS[index] || null}
                    <p>{item.label}</p>
                  </a>
                </li>
              )}
              <li>
                <a href="/notifications">
                  <img src="/images/icons/bell.png" className="img-icon lg" />
                  <p>Notificaciones</p>
                  <span className={`badge ${notificationsCount ? 'd-block' : 'd-none'}`}>
                    {notificationsCount}
                  </span>
                </a>
                {!!notifications.length &&
                  <nav className='notifications-list'>
                    <ul>
                      {[...notifications].reverse().map(element => {
                        return (
                          <li key={element.message} className="d-block text-center">
                            <div className="d-inline-flex align-items-center">
                              <a
                                href={element.link}
                                onClick={(e) => {
                                  e.preventDefault()
                                  readNotification(element.link_mark_read, element.link)
                                }}
                              >
                                {element.message}
                              </a>
                              <i className="ml-3 fa fa-trash-o cursor-pointer" onClick={() => deleteNotification(element.link_delete)} />
                            </div>
                            <small style={{ fontSize: '.85rem' }}>
                              {element.time_elapsed}
                            </small>
                          </li>
                        )
                      })
                      }
                    </ul>
                  </nav>
                }
              </li>
            </ul>
          </div>
        </li>
      }
    </ul>
  );
};

const mapDispatchToProps = {
  addNotification: (notification) => addNotification(notification),
};

export default connect(null, mapDispatchToProps)(NavLinks);