Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

Rev 7326 | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |

import React, { useEffect, useRef, useState } from 'react'
import { axios } from '../../../utils'
import { useSelector } from 'react-redux'
import { Avatar, IconButton } from '@mui/material'
import styled from 'styled-components'
import Add from '@mui/icons-material/Add'
import ArrowBackIos from '@mui/icons-material/ArrowBackIos'
import PersonRemoveIcon from '@mui/icons-material/PersonRemove'

import TextBox from './TextBox'
import ChatList from './ChatList'
import EmptySection from '../../UI/EmptySection'
import ConfirmModal from '../../modals/ConfirmModal'
import ConferenceModal from '../../modals/ConferenceModal'
import SearchInput from '../../UI/SearchInput'

const StyledShowOptions = styled.div`
  align-items: flex-start;
  display: flex;
  flex-direction: column;
  height: 342px;
  overflow-y: auto;
  ul {
    width: 100%;
  }
  &.show {
    display: flex;
  }
  &.hide {
    display: none;
  }
  .option-tab {
    align-items: center;
    border-bottom: 1px solid #e2e2e2;
    cursor: pointer;
    display: flex;
    gap: 0.5rem;
    padding: 0.5rem;
    width: 100%;
    &:hover {
      background-color: #e2e2e2;
    }
  }
  .contact-tab {
    align-items: center;
    border-bottom: 1px solid #e2e2e2;
    display: flex;
    justify-content: space-between;
    padding: 0.2rem 0.5rem;
    .info {
      display: flex;
      align-items: center;
      gap: 0.5rem;
    }
  }
`

const StyledComeBackButton = styled(IconButton)`
  border-radius: 0px !important;
  font-size: 1rem !important;
  width: -webkit-fill-available;
  justify-content: flex-start !important;
`

const OPTIONS = {
  GROUP: 'group',
  CONFERENCE: 'conference',
  ADD_CONTACTS: 'addContacts',
  LIST_CONTACTS: 'listContacts',
  INITIAL: null,
}

const PersonalChat = ({
  entity,
  onClose,
  onMinimize,
  onRead,
  not_seen_messages,
  minimized,
}) => {
  const [optionTab, setOptionTab] = useState(OPTIONS.INITIAL)
  const [availableContactsToAdd, setAvailableContactsToAdd] = useState([])
  const [groupContactsList, setGroupContactsList] = useState([])
  const [confirmModalShow, setConfirmModalShow] = useState(false)
  const [showConferenceModal, setShowConferenceModal] = useState(false)
  const [search, setSearch] = useState('')
  const [messages, setMessages] = useState([])
  const [oldMessages, setOldMessages] = useState([])
  const [currentPage, setCurrentPage] = useState(1)
  const [lastPage, setLastPage] = useState(1)
  const [loading, setLoading] = useState(false)
  const labels = useSelector(({ intl }) => intl.labels)

  const filtredGroupList = groupContactsList.filter((conversation) =>
    conversation.name.toLowerCase().includes(search.toLowerCase())
  )

  // refs
  const conversationListEl = useRef(null)
  const loader = useRef(null)
  const modalActionUrl = useRef('')

  const handleActive = () => {
    onRead(entity)
    onMinimize(entity)
  }

  const handleGetMessages = async () => {
    setLoading(true)
    const response = await axios.get(entity?.url_get_all_messages)
    const resData = response.data
    if (!resData.success) {
      return 'ha ocurrido un error'
    }
    const updatedMessages = [...resData.data.items].reverse()
    const newMessages = updatedMessages.reduce((acum, updatedMessage) => {
      if (
        messages.findIndex((message) => message.id === updatedMessage.id) === -1
      ) {
        acum = [...acum, updatedMessage]
      }
      return acum
    }, [])

    if (newMessages.length > 0) {
      setMessages([...messages, ...newMessages])
      setLoading(false)
      setLastPage(resData.data.pages)
      scrollToBottom()
    } else {
      setLoading(false)
    }
  }

  const handleLoadMore = async () => {
    await axios
      .get(`${entity?.url_get_all_messages}?page=${currentPage}`)
      .then((response) => {
        const resData = response.data
        if (resData.success) {
          if (resData.data.page > 1) {
            const updatedOldMessages = [...resData.data.items].reverse()
            setOldMessages([...updatedOldMessages, ...oldMessages])
            /* scrollDownBy(100); */
          }
        }
      })
  }

  const handleCloseChat = () => onClose(entity)

  const sendMessage = async (message) => {
    const formData = new FormData()
    formData.append('message', emojione.toShort(message))
    await axios.post(entity?.url_send, formData).then((response) => {
      const resData = response.data
      if (resData.success) {
        let newMessage = resData.data

        entity?.online
          ? (newMessage = { ...newMessage, not_received: false })
          : (newMessage = { ...newMessage, not_received: true })

        setMessages([...messages, newMessage])
      }
    })
    // await handleGetMessages()
    // setResponseMessage(null)
  }

  const showOptions = (tab = OPTIONS.INITIAL) => {
    onMinimize(entity, false)
    setOptionTab(tab)
  }

  const handleAddPersonToGroup = async (id) => {
    const formData = new FormData()
    formData.append('uid', id)
    await axios
      .post(entity?.url_add_user_to_group, formData)
      .then((response) => {
        const resData = response.data
        if (resData.success) {
          loadPersonsAvailable()
        }
      })
  }

  const handleConfirmModalAction = async () => {
    try {
      const { data } = await axios.post(modalActionUrl.current)
      if (!data.success) console.log('Error in confirm modal action')
      handleConfirmModalShow()
      onClose(entity)
      return
    } catch (error) {
      console.log(error)
    }
  }

  const handleObserver = (entities) => {
    const target = entities[0]
    if (target.isIntersecting) {
      setCurrentPage((prevState) => prevState + 1)
    }
  }

  const scrollToBottom = () => {
    if (conversationListEl.current) {
      conversationListEl.current.scrollTop =
        conversationListEl.current.scrollHeight * 9
    }
  }

  const handleConfirmModalShow = () => setConfirmModalShow(!confirmModalShow)

  const handleConfirmModalAccept = () => handleConfirmModalAction()

  /* const handleResponseMessage = (element) => {
    element.mtype === 'text'
      ? setResponseMessage(element)
      : setResponseMessage({ ...element, m: 'Archivo adjunto' })

    textAreaEl.current && textAreaEl.current.focus()
  } */

  const displayConferenceModal = () =>
    setShowConferenceModal(!showConferenceModal)

  const loadPersonsAvailable = async () => {
    await axios
      .get(entity?.url_get_contacts_availables_for_group)
      .then((response) => {
        const resData = response.data
        if (resData.success) {
          setAvailableContactsToAdd(resData.data)
        }
      })
  }

  const loadGroupContacts = async () => {
    await axios.get(entity?.url_get_contact_group_list).then((response) => {
      const resData = response.data
      if (resData.success) {
        setGroupContactsList(resData.data)
      }
    })
  }

  const handleDeletePersonFromGroup = async (urlDeletePersonFromGroup) => {
    await axios.post(urlDeletePersonFromGroup).then((response) => {
      const resData = response.data
      if (resData.success) {
        loadGroupContacts()
      }
    })
  }

  const tabsOptions = {
    group: (
      <ul>
        {entity?.url_get_contact_group_list && (
          <li>
            <button
              className="option-tab"
              onClick={() => showOptions(OPTIONS.LIST_CONTACTS)}
            >
              <i className="fa fa-group" />
              Integrantes
            </button>
          </li>
        )}
        {entity?.url_add_user_to_group && (
          <li>
            <button
              className="option-tab"
              onClick={() => showOptions(OPTIONS.ADD_CONTACTS)}
            >
              <i className="fa fa-user-plus"></i>
              {labels.add_contacts}
            </button>
          </li>
        )}
        {entity?.url_zoom && (
          <li>
            <button className="option-tab" onClick={displayConferenceModal}>
              <i className="fa fa-user-plus" />
              {labels.create_conference}
            </button>
          </li>
        )}
        {entity?.url_delete && (
          <li>
            <button
              className="option-tab"
              onClick={() => {
                handleConfirmModalShow()
                modalActionUrl.current = entity?.url_delete
              }}
            >
              <i className="fa fa-trash"></i>
              Eliminar grupo
            </button>
          </li>
        )}
        {!!entity?.url_leave && (
          <li>
            <button
              className="option-tab"
              onClick={() => {
                handleConfirmModalShow()
                modalActionUrl.current = entity?.url_leave
              }}
            >
              <PersonRemoveIcon />
              Dejar grupo
            </button>
          </li>
        )}
      </ul>
    ),
    addContacts: (
      <>
        {availableContactsToAdd.length ? (
          <ul>
            {availableContactsToAdd.map(({ image, name, id }) => (
              <li key={id}>
                <div className="contact-tab">
                  <div className="info">
                    <Avatar
                      src={image}
                      alt={`${name} profile image`}
                      sx={{
                        height: '36px',
                        width: '36px',
                      }}
                    />
                    <span>{name}</span>
                  </div>
                  <IconButton onClick={() => handleAddPersonToGroup(id)}>
                    <Add />
                  </IconButton>
                </div>
              </li>
            ))}
          </ul>
        ) : (
          <EmptySection message={labels.not_contacts} />
        )}
      </>
    ),
    listContacts: (
      <>
        <SearchInput onChange={(e) => setSearch(e.target.value)} />
        {filtredGroupList.length ? (
          <ul>
            {filtredGroupList.map(
              ({ image, name, url_remove_from_group, id }) => {
                return (
                  <li key={id}>
                    <div className="contact-tab">
                      <div className="info">
                        <Avatar
                          src={image}
                          alt={`${name} profile image`}
                          sx={{
                            height: '36px',
                            width: '36px',
                          }}
                        />
                        <span>{name}</span>
                      </div>
                      {url_remove_from_group && (
                        <IconButton
                          onClick={() =>
                            handleDeletePersonFromGroup(url_remove_from_group)
                          }
                        >
                          <PersonRemoveIcon />
                        </IconButton>
                      )}
                    </div>
                  </li>
                )
              }
            )}
          </ul>
        ) : (
          <EmptySection message={labels.not_contacts} />
        )}
      </>
    ),
  }

  // getMessageOnMaximize and subscribe to infinite Loader
  useEffect(async () => {
    const options = {
      root: null,
      rootMargin: '20px',
      treshold: 1.0,
    }
    const observer = new IntersectionObserver(handleObserver, options)
    if (!minimized) {
      await handleGetMessages()
      // loader observer
      if (loader.current) {
        observer.observe(loader.current)
      }
    }
    return () => {
      if (loader.current) {
        observer.unobserve(loader.current)
      }
    }
  }, [minimized])

  // LoadMore on change page
  useEffect(() => {
    let loadMore = () => handleLoadMore()
    loadMore()
    return () => {
      loadMore = null
    }
  }, [currentPage])

  // getMessagesInterval
  useEffect(() => {
    if (window.location.pathname === '/group/my-groups') {
      const items = document.getElementsByClassName('sc-jSgupP')
      if (items && items.length > 0) {
        items[0].style.display = 'none'
      }
    }
  }, [minimized])

  useEffect(() => {
    let timer
    if (!minimized && !loading) {
      timer = setTimeout(() => handleGetMessages(), 1000)
    }
    return () => {
      clearTimeout(timer)
    }
  }, [minimized, loading])

  // useEffect for tabs changing
  useEffect(() => {
    if (optionTab === 'addContacts') loadPersonsAvailable()
    if (optionTab === 'listContacts') loadGroupContacts()
  }, [optionTab])

  return (
    <>
      <div className="personal-chat">
        <div className={`chat-header ${not_seen_messages ? 'notify' : ''}`}>
          <Avatar
            src={entity?.image || '/images/users-group.png'}
            sx={{ width: '36px', height: '36px' }}
          />
          <div className="info-content">
            <a href={entity?.profile} target="_blank" rel="noreferrer">
              {entity?.name}
            </a>
            {entity?.type === 'user' && (
              <small className={entity?.online ? 'online' : 'offline'}>
                {entity?.online ? 'En línea' : 'Desconectado'}
              </small>
            )}
          </div>
          <div className="options ml-auto">
            <i
              className="cursor-pointer fa fa-gear"
              onClick={() =>
                showOptions(
                  entity?.type === 'user' ? OPTIONS.CONFERENCE : OPTIONS.GROUP
                )
              }
            />
            <i
              className={'cursor-pointer fa fa-minus-circle'}
              onClick={handleActive}
            />
            <i
              className="cursor-pointer fa fa-times-circle"
              onClick={handleCloseChat}
            />
          </div>
        </div>

        <div
          className="panel-body"
          style={{ display: !minimized ? 'block' : 'none' }}
        >
          {optionTab ? (
            <StyledShowOptions>
              <StyledComeBackButton
                onClick={() => showOptions(OPTIONS.INITIAL)}
              >
                <ArrowBackIos />
                {labels.back}
              </StyledComeBackButton>
              {tabsOptions[optionTab]}
            </StyledShowOptions>
          ) : (
            <>
              <ChatList
                messages={[...oldMessages, ...messages]}
                currentPage={currentPage}
                lastPage={lastPage}
                conversationList={conversationListEl}
                loader={loader}
              />
              <TextBox
                uploadUrl={entity?.url_upload}
                isNotSeen={not_seen_messages}
                markRead={() => onRead(entity)}
                onSend={sendMessage}
              />
            </>
          )}
        </div>
      </div>
      <ConfirmModal
        show={confirmModalShow}
        onClose={handleConfirmModalShow}
        onAccept={handleConfirmModalAccept}
      />
      <ConferenceModal
        show={showConferenceModal}
        zoomUrl={entity?.url_zoom}
        onClose={() => {
          showOptions()
          displayConferenceModal()
        }}
      />
    </>
  )
}

export default React.memo(PersonalChat)