SOURCE

import React, { useEffect, useState } from 'react'
import './index.less'
import { useAppDispatch } from '@/api/hooks'
import XimSvg from '@/components/svg'
import { buttonClick } from '@/utils/types/function'
import { useNavigate } from 'react-router-dom'
import groupApi from '@/api/modules/group.api'
import SearchInput from '@/components/SearchInput'
import styles from '@/assets/styles/index.module.less'
import { Avatar, Button, Drawer, message, Modal } from 'antd'
import { OpenIM } from '@/api/im'
import { TotalUserStruct } from '@/utils/lib/types/entity'
import { pySegSort } from '@/utils/friend'
import { getNickName, tranColor } from '@/utils/avatar'
import { cveActions } from '@/store/actions'
import store from '@/store'

/**
 * 禁言
 * @constructor
 */
const DisabledChat = (props: {
  groupId?: any
  isOpen?: boolean
  groupMember?: Array<any> //已选
  onClose: buttonClick
  invitation?: boolean
}) => {
  const { groupId, isOpen, groupMember, onClose, invitation } = props
  const userID = localStorage.getItem('im_user_id')
  const userInfo = store.getState().user.userInfo
  const dispatch = useAppDispatch()
  const navigate = useNavigate()
  const [loading, setLoading] = useState<boolean>(false)
  const [groupData, setGroupData] = useState<any>()
  const [searchVal, setSearchVal] = useState('')
  const [openModal, setOpenModal] = useState<boolean | undefined>(false)
  const [friendList, setFriendList] = useState<any[]>([])
  const [friendPyList, setFriendPyList] = useState<any[]>([])
  const [selectFriendList, setSelectFriendList] = useState<any[]>([])
  const [selectUserIdList, setSelectUserIdList] = useState<any[]>([])
  const [filterFriendList, setFilterFriendList] = useState<any[]>([])

  useEffect(() => {
    setOpenModal(isOpen)
    setSelectFriendList(groupMember ? groupMember : [])
    let friendList = []
    if (!groupId && groupMember && groupMember.length > 0) {
      friendList = groupMember.map((item) => (item?.user_id ? item.user_id : item.userID))
    }
    setSelectFriendList([])
    setSelectUserIdList(friendList)
    if (isOpen) {
      getFriends()
    }
  }, [isOpen])
  /**
   * 获取好友
   */
  const getFriends = () => {
    OpenIM.getFriendList().then(({ data }) => {
      const friends: TotalUserStruct[] = JSON.parse(data as string)
      if (friends && friends.length) {
        let list = friends.filter((item) => item.friendInfo !== null).map((item) => item.friendInfo)
        if (groupId && groupMember && groupMember.length > 0) {
          const inGroup = groupMember.map((item) => (item?.userID ? item?.userID : item.user_id))
          list = list.filter((item) => inGroup.indexOf(item?.userID ? item?.userID : -1) === -1)
        }
        setSelectFriendList(list.filter((item) => selectUserIdList.indexOf(item?.userID ? item?.userID : -1) !== -1))
        setFriendList([...list])
        const friendItems = pySegSort(list)
        setFriendPyList([...friendItems])
      } else {
        setFriendList([])
      }
    })
  }
  /**
   * 好友点击
   * @param data
   */
  const friendItemClick = (data: any) => {
    if (data) {
      const userId = data.userID
      let newSelectUserIdList: Array<any> = [...selectUserIdList]
      const findIndex = newSelectUserIdList.indexOf(userId)
      if (findIndex > -1) {
        newSelectUserIdList = newSelectUserIdList.filter((s) => s !== userId)
      } else {
        newSelectUserIdList.push(userId)
      }
      setSelectUserIdList(newSelectUserIdList)
      const newFriendList = friendList.filter((item) => newSelectUserIdList.includes(item.userID))
      setSelectFriendList([...newFriendList])
    }
  }
  /**
   * 搜索内容改变
   * @param e
   */
  const searchChange = (val?: string) => {
    filterFriend(val)
    setSearchVal(val ? val : '')
  }
  /**
   * 按钮点击
   */
  const butClick = () => {
    if (selectUserIdList.length === 0) {
      message.warning('选择的好友不能为空')
      return
    }
    if (!groupId && selectUserIdList.length < 2) {
      message.warning('选择的好友不能少于两人')
      return
    }
    setLoading(true)
    if (groupId) {
      inviteUserToGroup()
    } else {
      createGroup()
    }
  }
  /**
   * 创建群聊
   */
  const createGroup = () => {
    const memberList = selectFriendList.map((s) => Number(s.userID))
    groupApi
      .createGroup({
        face_url: '',
        group_name: userInfo?.nickname ? userInfo?.nickname + '的群聊' : '',
        group_type: 0,
        introduction: '',
        notification: '',
        creator_user_id: Number(userID),
        member_list: memberList
      })
      .then((data) => {
        message.success('创建群成功')
        //创建会话
        OpenIM.getOneConversation({
          //sourceID
          sourceID: data.group_id,
          sessionType: 2
        })
          .then(({ data }) => {
            setLoading(false)
            onClose()
            dispatch(cveActions.setCurrentCve(JSON.parse(data)))
            navigate('/')
          })
          .catch((err) => {
            setLoading(false)
            message.error(err.errCode)
            console.log(err, 'openConversationErr')
          })
      })
      .catch(() => {
        setLoading(false)
      })
  }
  /**
   * 邀请用户进群
   */
  const inviteUserToGroup = () => {
    const memberList = selectFriendList.map((s) => Number(s.userID))
    groupApi
      .inviteUserToGroup({
        group_id: Number(groupId),
        invited_user_id_list: memberList,
        reason: userInfo.nickname + '邀请您加入群聊'
      })
      .then((data) => {
        message.success('邀请成功')
        //创建会话
        OpenIM.getOneConversation({
          //sourceID
          sourceID: groupId,
          sessionType: 2
        })
          .then(({ data }) => {
            onClose()
            setLoading(false)
            dispatch(cveActions.setCurrentCve(JSON.parse(data)))
            navigate('/')
          })
          .catch((err) => {
            message.error(err.errCode)
            setLoading(false)
            console.log(err, 'openConversationErr')
          })
      })
      .catch(() => {
        setLoading(false)
      })
  }
  /**
   * 好友过滤
   * @param val
   */
  const filterFriend = (val?: string) => {
    let newFriendList = []
    if (val) {
      newFriendList = friendList.filter((item: any) => item?.nickname.indexOf(val) !== -1)
      const notNickNameInFriendList = friendList.filter((item: any) => item?.nickname.indexOf(val) === -1)
      if (notNickNameInFriendList.length > 0) {
        notNickNameInFriendList.map((item: any) => {
          if (item.phoneNumber && item.phoneNumber.indexOf(val) !== -1) {
            const searchVale = item.phoneNumber.replace(val, `<span class='primary-text'>${val}</span>`)
            item['searchVale'] = searchVale
            newFriendList.push(item)
          }
        })
      }
    }
    setFilterFriendList([...newFriendList])
  }
  return (
    <Drawer
        width={320}
        closable={false}
        onClose={() => setOpenModal(false)}
        open={openModal}
      >
    <div className="create-group">
        <div className="create-group-modal">
          <div className="create-group-header">
            <div className="title">{invitation ? '添加联系人' : '创建群聊'}</div>
            <div className="close-but" onClick={() => onClose()}>
              <XimSvg name="close" />
            </div>
          </div>
          <div className="create-group-search">
            <SearchInput onChange={searchChange} />
          </div>
          {/*小头像*/}
          <div className="create-group-select">
            {selectFriendList.map((item, index) => {
              return (
                <div className="select-item" key={index}>
                  <Avatar
                    size="small"
                    style={
                      item?.faceURL
                        ? {}
                        : {
                            backgroundColor: tranColor(item?.nickname),
                            verticalAlign: 'middle'
                          }
                    }
                    src={item?.faceURL}
                  >
                    {getNickName(item?.nickname)}
                  </Avatar>
                </div>
              )
            })}
          </div>
          <div className="create-group-list">
            {!searchVal &&
              friendPyList.map((group, index) => {
                return (
                  <div className="list-group" key={index}>
                    <div className="title">{group.letter}</div>
                    <div className="friend-items">
                      {group.data?.map((item: any, index: number) => {
                        return (
                          <div className="friend-item" key={index} onClick={() => friendItemClick(item)}>
                            <div className="friend-item-radio">
                              <XimSvg name={selectUserIdList.includes(item.userID) ? 'select' : 'not-select'} />
                            </div>
                            <div className="friend-item-avatar">
                              <Avatar
                                size="large"
                                style={
                                  item?.faceURL
                                    ? {}
                                    : {
                                        backgroundColor: tranColor(item?.nickname),
                                        verticalAlign: 'middle'
                                      }
                                }
                                src={item?.faceURL}
                              >
                                {getNickName(item?.nickname)}
                              </Avatar>
                            </div>
                            <div className="friend-item-nickname">{item?.nickname}</div>
                          </div>
                        )
                      })}
                    </div>
                  </div>
                )
              })}
            {searchVal && filterFriendList.length > 0 ? (
              <div className="friend-items">
                {filterFriendList.map((item, index) => {
                  return (
                    <div className="friend-item" key={index} onClick={() => friendItemClick(item)}>
                      <div className="friend-item-radio">
                        <XimSvg name={selectUserIdList.includes(item.userID) ? 'select' : 'not-select'} />
                      </div>
                      <div className="friend-item-avatar">
                        <Avatar
                          size="large"
                          style={
                            item?.faceURL
                              ? {}
                              : {
                                  backgroundColor: tranColor(item?.nickname),
                                  verticalAlign: 'middle'
                                }
                          }
                          src={item?.faceURL}
                        >
                          {getNickName(item?.nickname)}
                        </Avatar>
                      </div>
                      <div className="friend-item-nickname">
                        {item?.nickname}
                        {item.searchVale ? (
                          <div className="friend-item-phone">
                            <div className="label">手机号:</div>
                            <div
                              className="txt"
                              dangerouslySetInnerHTML={{
                                __html: item.searchVale
                              }}
                            ></div>
                          </div>
                        ) : (
                          ''
                        )}
                      </div>
                    </div>
                  )
                })}
              </div>
            ) : searchVal ? (
              <div className="search-per-empty">
                <div className="img">
                  <XimSvg name="empty" size={86} />
                </div>
                <div className="msg">
                  没有找到
                  <span>{`"${searchVal.length > 3 ? searchVal.substring(0, 3) : searchVal}"`}</span>
                  相关的结果
                </div>
              </div>
            ) : (
              ''
            )}
          </div>
          <div className="create-group-but">
            <Button type="primary" onClick={butClick} loading={loading}>
              确认禁言({selectUserIdList.length})
            </Button>
          </div>
        </div>
      
    </div>
    </Drawer>
  )
}

export default React.memo(DisabledChat)
console 命令行工具 X clear

                    
>
console