uni-app 159发布朋友圈-实时通知

简介: uni-app 159发布朋友圈-实时通知

/pages/find/moments/moments.vue

<template>
  <view>
    <free-transparent-bar :scrollTop="scrollTop" @clickRight="clickRight"></free-transparent-bar>
    <view class="position-relative" style="height: 620rpx;">
      <image src="https://douyinzcmcss.oss-cn-shenzhen.aliyuncs.com/shengchengqi/datapic/1.jpg" mode="aspectFill" style="height: 590rpx;" class="bg-secondary w-100"></image>
      <image :src="user.avatar || '/static/images/demo/demo6.jpg'" style="width: 120rpx;height:120rpx;right: 30rpx;" mode="" class="bg-secondary rounded position-absolute bottom-0"></image>
      <text class="text-white font-md position-absolute" style="bottom: 45rpx;right: 160rpx">{{user.nickname || user.username}}</text>
    </view>
    
    <!-- 朋友圈列表样式 -->
    <free-moment-list v-for="(item,index) in list" :key='index' :item="item" :index="index" @action="doAction" @reply="replyEvent"></free-moment-list>
    
    <!-- 评论框 -->
    <free-popup ref="action" bottom transformOrigin="center bottom">
      <view style="height: 105rpx;" class="bg-light border-top flex align-center">
        <textarea fixed class="bg-white rounded p-2 font-md" style="height: 45rpx;width: 420rpx;" value="" placeholder=""  v-model="content" :focus="true"/>
        <free-icon-button @click="changeFaceModeal"><text class="iconfont font-lg">&#xe605;</text></free-icon-button>
        <free-main-button name="发送" :disabled="content.length===0" @click="send"></free-main-button>
      </view>
      
      <!-- 表情包 -->
      <scroll-view v-if="faceModal" scroll-y="true" style="height: 350rpx;" class="bg-light">
        <view class="flex flex-wrap">
          <view class="flex align-center justify-center" hover-class="bg-white" style="width:107rpx;height:107rpx;" v-for="(item,index) in faceList" :key="index" @click="addFace(item)">
            <text>{{item}}</text>
          </view>
        </view>
      </scroll-view>
    </free-popup>
    
    <!-- 上拉加载 -->
    <view class="flex align-center justify-center py-5 bg-light" v-if="list.length >= 10">
      <text class="text-muted font">{{loadmore}}</text>
    </view>
  </view>
</template>
<script>
  import freeTransparentBar from '@/components/free-ui/free-transparent-bar.vue';
  import freeMomentList from '@/components/free-ui/free-moment-list.vue';
  import freePopup from '@/components/free-ui/free-popup.vue';
  import freeIconButton from '@/components/free-ui/free-icon-button.vue';
  import freeMainButton from '@/components/free-ui/free-main-button.vue';
  import $H from '@/common/free-lib/request.js';
  import { mapState } from 'vuex';
  export default {
    components:{
      freeTransparentBar,
      freeMomentList,
      freePopup,
      freeIconButton,
      freeMainButton
    },
    data() {
      return {
        content:'',
        scrollTop:0,
        faceModal:false,
        faceList:["😀","😁","😂","😃","😄","😅","😆","😉","😊","😋","😎","😍","😘","😗","😙","😚","😇","😐","😑","😶","😏","😣","😥","😮","😯","😪","😫","😴","😌","😛","😜","😝","😒","😓","😔","😕","😲","😷","😖","😞","😟","😤","😢","😭","😦","😧","😨","😬","😰","😱","😳","😵","😡","😠"],
        commentIndex:-1,
        page:1,
        loadmore:'上拉加载更多',
        key:'moment_timeline',
        list:[],
        reply_user:false
      }
    },
    onPageScroll(e) {
      this.scrollTop = e.scrollTop;
    },
    onReachBottom() {
      if(this.loadmore !== '上拉加载更多'){
        return;
      }
      this.page += 1;
      this.loadmore = '加载中...';
      this.getData().catch(err=>{
        this.page -= 1;
        uni.showToast({
          title:'加载失败',
          icon:'none'
        });
        this.loadmore = '上拉加载更多';
      })
    },
    onLoad(e) {
      if(e.key){
        this.key  = e.key;
      }
      this.page = 1;
      this.getData();
      uni.$on('momentNotice',this.momentNotice)
    },
    destroyed() {
      uni.$off('momentNotice',this.momentNotice)
    },
    onPullDownRefresh() {
      this.page = 1;
      this.getData().then(res=>{
        uni.showToast({
          title:'刷新成功',
          icon:'none'
        });
        uni.stopPullDownRefresh();
      }).catch(err=>{
        uni.showToast({
          title:'刷新失败',
          icon:'none'
        });
        uni.stopPullDownRefresh();
      });
    },
    computed:{
      ...mapState({
        user:state=>state.user.user
      })
    },
    methods: {
      momentNotice(e){
        this.page = 1;
        this.getData().then(res=>{
          uni.showToast({
            title:'刷新成功',
            icon:'none'
          });
        });
      },
      // 点击操作菜单
      doAction(e){
        uni.showActionSheet({
          itemList: ['点赞','评论'],
          success: res => {
            if(res.tapIndex === 0){
              // 点赞
              this.doSupport(e)
            }else{
              this.content='';
              this.faceModal=false;
              this.commentIndex = e.index;
              this.reply_user = false;
              this.$refs.action.show();
              // this.doComment(e)
            }
          }
        });
      },
      // 获取数据
      getData(){
        return new Promise((result,reject)=>{
          let page = this.page;
          $H.get('/'+this.key+'/'+page).then(res=>{
            this.list = page === 1 ? res : [...this.list,...res];
            this.loadmore = this.list.length === (page * 10) ? '上拉加载更多' : '没有更多了'
            result(res);
          }).catch(err=>{
            reject(err);
          })
        })
      },
      // 点赞
      doSupport(e){
        $H.post('/moment/like',{id:e.item.moment_id}).then(res=>{
         let i = e.item.likes.findIndex(item=>item.id === this.user.id);
         if(i !== -1){
           // 取消点赞
           e.item.likes.splice(i,1);
         }else{
           // 点赞
           e.item.likes.push({
             id:this.user.id,
             name:this.user.nickname || this.user.username
           })
         }
         uni.showToast({
          title:i !== -1 ? '取消点赞成功' : '点赞成功',
        icon:'none'
         });
         
        })
      },
      // 添加表情
      addFace(item){
        this.content += item;
      },
      // 开启关闭表情包面板
      changeFaceModeal(){
        uni.hideKeyboard();
        setTimeout(()=>{
          this.faceModal = !this.faceModal;
        },100);
      },
      // 发送
      send(){
        console.log(this.reply_user);
        let item = this.list[this.commentIndex];
        $H.post('/moment/comment',{
          id:item.moment_id,
          content:this.content,
          reply_id:this.reply_user ? this.reply_user.id : 0
        }).then(res=>{
          item.comments.push({
            content:this.content,
            user:{
              id:this.user.id,
              name:this.user.nickname || this.user.username
            },
            replay:this.reply_user ? this.reply : null
          })
          uni.showToast({
            title:'评论成功',
            icon:'none'
          })
        })
        this.$refs.action.hide();
      },
      replyEvent(e){
        this.content = '';
        this.faceModal = false,
        this.commentIndex = e.index,
        this.reply_user = e.reply;
        this.$refs.action.show();
      },
      // 选择发表朋友圈类型
      clickRight(){
        let list = [{
          name:'图文',
          key:'image'
        },
        {
          name:'视频',
          key:'video'
        },
        {
          name:'文字',
          key:'content'
        }];
        uni.showActionSheet({
          itemList:list.map(v=>v.name),
          success:res=>{
            uni.navigateTo({
              url: '../add-moment/add-moment?type='+list[res.tapIndex].key,
            });
          }
        })
      }
    },
  }
</script>
<style>
</style>

/common/free-lib/chat.js

import $U from "./util.js";
import $H from './request.js';
import $store from '@/store/index.js';
class chat {
  constructor(arg) {
    this.url = arg.url
    this.isOnline = false
    this.socket = null
    // 获取当前用户相关信息
    let user = $U.getStorage('user');
    this.user = user ? JSON.parse(user) : {},
      // 初始化聊天对象
      this.TO = false;
    // 连接和监听
    if (this.user.token) {
      this.connectSocket()
    }
  }
  // 连接socket
  connectSocket() {
    console.log(this.user);
    this.socket = uni.connectSocket({
      url: this.url + '?token=' + this.user.token,
      complete: () => {}
    })
    // 监听连接成功
    this.socket.onOpen(() => this.onOpen())
    // 监听接收信息
    this.socket.onMessage((res) => this.onMessage(res))
    // 监听断开
    this.socket.onClose(() => this.onClose())
    // 监听错误
    this.socket.onError(() => this.onError())
  }
  // 监听打开
  onOpen() {
    // 用户状态上线
    this.isOnline = true;
    console.log('socket连接成功');
    // 获取用户离线消息
    this.getMessage();
  }
  // 获取离线消息
  getMessage() {
    $H.post('/chat/getmessage');
  }
  // 获取聊天记录
  getChatDetail(key = false) {
    key = key ? key : `chatDetail_${this.user.id}_${this.TO.chat_type}_${this.TO.id}`
    return this.getStorage(key)
  }
  // 监听关闭
  onClose() {
    // 用户下线
    this.isOnline = false;
    this.socket = null;
    console.log('socket连接关闭');
  }
  // 监听消息
  onMessage(data) {
    console.log('监听消息', data);
    let res = JSON.parse(data.data)
    // 错误
    switch (res.msg) {
      case 'fail':
        return uni.showToast({
          title: res.data,
          icon: 'none'
        });
        break;
      case 'recall': // 撤回消息
        this.handleOnRecall(res.data)
        break;
      case 'updateApplyList': // 新的好友申请
        $store.dispatch('getApply');
        break;
      case 'moment': // 朋友圈更新
        this.handleMoment(res.data)
        break;
      
      default:
        // 处理消息
        this.handleOnMessage(res.data)
        break;
    }
  }
  // 获取本地存储中的朋友圈动态通知
  getNotice(){
    let notice = $U.getStorage('moment_'+this.user.id);
    return notice ? JSON.parse(notice) : {
      avatar:'',
      user_id:0,
      num:0
    }
  }
  // 处理朋友圈通知
  async handleMoment(message){
    let notice = this.getNotice();
      switch(message.type){
      case 'new':
         if(message.user_id !== this.user.id){
          notice.avatar = message.avatar;
          notice.user_id = message.user_id;
          uni.showTabBarRedDot({
            index:2
          })
        }
      break;
      default:
      if(message.user_id !== this.user.id){
        notice.avatar = message.avatar
        notice.user_id = message.user_id 
        notice.num += 1
      }
      if(notice.num > 0){
        uni.setTabBarBadge({
          index:2,
          text:notice.num > 99 ? '99+' : notice.num.toString()
        })
      }else{
        uni.removeTabBarBadge({
          index:2
        })
      }
      break;
    }
    uni.$emit('momentNotice',notice);
    $U.setStorage('moment_'+this.user.id,JSON.stringify(notice));
  }
  // 读取朋友圈动态
  async readMoments(){
    let notice = {
      avatar:'',
      user_id:0,
      num:0
    };
    $U.setStorage('moment_'+this.user.id,JSON.stringify(notice));
    uni.hideTabBarRedDot({
      index:2
    })
    uni.removeTabBarBadge({
      index:2
    })
    uni.$emit('momentNotice',notice);
  }
  // 监听撤回消息处理
  async handleOnRecall(message) {
    // 通知聊天页撤回消息
    uni.$emit('onMessage', {
      ...message,
      isremove: 1
    })
    // 修改聊天记录
    let id = message.chat_type === 'group' ? message.to_id : message.from_id
    // key值:chatDetail_当前用户id_会话类型_接收人/群id
    let key = `chatDetail_${this.user.id}_${message.chat_type}_${id}`
    // 获取原来的聊天记录
    let list = this.getChatDetail(key)
    // 根据k查找对应聊天记录
    let index = list.findIndex(item => item.id === message.id)
    if (index === -1) return;
    list[index].isremove = 1
    // 存储
    this.setStorage(key, list)
    // 当前会话最后一条消息的显示
    this.updateChatItem({
      id,
      chat_type: message.chat_type
    }, (item) => {
      item.data = '对方撤回了一条消息'
      item.update_time = (new Date()).getTime()
      return item
    })
  }
  // 处理消息
  async handleOnMessage(message) {
    // 添加消息记录到本地存储中
    let {
      data
    } = this.addChatDetail(message, false)
    // 更新会话列表
    this.updateChatList(data, false)
    // 全局通知
    uni.$emit('onMessage', data)
    // 消息提示
    // this.messageNotice()
  }
  // 监听连接错误
  onError() {
    // 用户下线
    this.isOnline = false;
    this.socket = null;
    console.log('socket连接错误');
  }
  // 关闭连接
  close() {
    this.socket.close()
  }
  // 创建聊天对象
  createChatObject(detail) {
    this.TO = detail;
    console.log('创建聊天对象', this.TO)
  }
  // 销毁聊天对象
  destoryChatObject() {
    this.TO = false
  }
  // 组织发送信息格式
  formatSendData(params) {
    return {
      id: 0, // 唯一id,后端生成,用于撤回指定消息
      from_avatar: this.user.avatar, // 发送者头像
      from_name: this.user.nickname || this.user.username, // 发送者昵称
      from_id: this.user.id, // 发送者id
      to_id: params.to_id || this.TO.id, // 接收人/群 id
      to_name: params.to_name || this.TO.name, // 接收人/群 名称
      to_avatar: params.to_avatar || this.TO.avatar, // 接收人/群 头像
      chat_type: params.chat_type || this.TO.chat_type, // 接收类型
      type: params.type, // 消息类型
      data: params.data, // 消息内容
      options: params.options ? params.options : {}, // 其他参数
      create_time: (new Date()).getTime(), // 创建时间
      isremove: 0, // 是否撤回
      sendStatus: params.sendStatus ? params.sendStatus : "pending" // 发送状态,success发送成功,fail发送失败,pending发送中
    }
  }
  // 发送信息
  send(message, onProgress = false) {
    return new Promise(async (result, reject) => {
      // 添加消息历史记录
      // this.addChatDetail();
      let {
        k
      } = this.addChatDetail(message);
      // 更新会话列表 
      this.updateChatList(message);
      // 验证是否上线
      if (!this.checkOnLine()) return reject('未上线');
      // 上传文件
      let isUpload = (message.type !== 'text' && message.type !== 'emoticon' && message.type !==
        'card' && !message.data.startsWith('http://akyan.oss-cn-beijing.aliyuncs.com/'))
      let uploadResult = ''
      if (isUpload) {
        uploadResult = await $H.upload('/upload', {
          filePath: message.data
        }, onProgress);
      }
      
      // 提交到后端
      let data = isUpload ? uploadResult : message.data;
      $H.post('/chat/send', {
        to_id: this.TO.id,
        type: message.type,
        chat_type: this.TO.chat_type,
        data,
        options: JSON.stringify(message.options)
      }).then(res => {
        // 发送成功
        console.log('chat.js发送成功');
        message.id = res.id
        message.sendStatus = 'success';
        if (message.type === 'video') {
          message.data = res.data;
          message.options = res.options;
        }
        // 更新指定历史记录
        console.log('更新指定历史记录',message);
        this.updateChatDetail(message, k);
        result(res);
      }).catch(err => {
        // 发送失败
        console.log('chat.js发送失败');
        message.sendStatus = 'fail';
        // 更新指定历史记录
        this.updateChatDetail(message, k);
        // 断线重连提示
        result(err);
      });
    })
  }
  // 验证是否上线
  checkOnLine() {
    if (!this.isOnline) {
      // 断线重连提示
      this.reconnectConfirm();
      return false;
    }
    return true;
  }
  // 断线重连提示
  reconnectConfirm() {
    uni.showModal({
      title: '你已经断线,是否重新连接?',
      content: '重新连接',
      success: res => {
        if (res.confirm) {
          this.connectSocket();
        }
      },
    });
  }
  // 添加聊天记录
  addChatDetail(message, isSend = true) {
    console.log('添加到聊天记录');
    // 获取对方id
    let id = message.chat_type === 'user' ? (isSend ? message.to_id : message.from_id) : message.to_id;
    if (!id) {
      return {
        data: {},
        k: 0
      }
    }
    // key值:chatDetail_当前用户id_会话类型_接收人/群id
    let key = `chatDetail_${this.user.id}_${message.chat_type}_${id}`;
    console.log(key);
    // 获取原来的聊天记录
    let list = this.getChatdetail(key)
    console.log('获取原来的聊天记录', list);
    // 标识
    message.k = 'k' + list.length
    list.push(message)
    // 加入存储
    console.log('加入存储', message);
    this.setStorage(key, list);
    // 返回
    return {
      data: message,
      k: message.k
    }
  }
  // 删除指定聊天记录
  async deleteChatDetailItem(message,isSend = true){
    // 获取对方id
    let id = message.chat_type === 'user' ? (isSend ? message.to_id : message.from_id) : message.to_id;
    // key值:chatDetail_当前用户id_会话类型_接收人/群id
    let key = `chatDetail_${this.user.id}_${message.chat_type}_${id}`;
    // 获取原来的聊天记录
    let list = this.getChatdetail(key);
    // 根据k查找对应聊天记录
    let index = list.findIndex(item => item.k === message.k || item.id === message.id);
    if (index === -1) return;
    
    list.splice(index,1);
    // 存储
    this.setStorage(key, list);
  }
  // 更新指定历史记录
  async updateChatDetail(message, k, isSend = true) {
    // 获取对方id
    let id = message.chat_type === 'user' ? (isSend ? message.to_id : message.from_id) : message.to_id;
    // key值:chatDetail_当前用户id_会话类型_接收人/群id
    let key = `chatDetail_${this.user.id}_${message.chat_type}_${id}`;
    // 获取原来的聊天记录
    let list = this.getChatdetail(key);
    // 根据k查找对应聊天记录
    let index = list.findIndex(item => item.k === k);
    if (index === -1) return;
    list[index] = message;
    // 存储
    this.setStorage(key, list);
  }
  // 获取聊天记录
  getChatdetail(key = false) {
    key = key ? key : `chatDetail_${this.user.id}_${this.TO.chat_type}_${this.TO.id}`;
    return this.getStorage(key);
  }
  // 格式化会话最后一条消息显示
  formatChatItemData(message, isSend) {
    let data = message.data.length > 18 ? message.data.slice(0, 17) + '...' : message.data;
    switch (message.type) {
      case 'emoticon':
        data = '[表情]'
        break;
      case 'image':
        data = '[图片]'
        break;
      case 'audio':
        data = '[语音]'
        break;
      case 'video':
        data = '[视频]'
        break;
      case 'card':
        data = '[名片]'
        break;
    }
    data = isSend ? data : `${message.from_name}: ${data}`
    return data
  }
  // 更新会话列表
  updateChatList(message, isSend = true) {
    // 获取本地存储会话列表
    let list = this.getChatList()
    // 是否处于当前聊天中
    let isCurrentChat = false
    // 接收人/群 id/头像/昵称
    let id = 0
    let avatar = ''
    let name = ''
    // 判断私聊还是群聊
    if (message.chat_type === 'user') { // 私聊
      // 聊天对象是否存在
      isCurrentChat = this.TO ? (isSend ? this.TO.id === message.to_id : this.TO.id === message.from_id) :
        false
      id = isSend ? message.to_id : message.from_id
      avatar = isSend ? message.to_avatar : message.from_avatar
      name = isSend ? message.to_name : message.from_name
    } else { // 群聊
      isCurrentChat = this.TO && (this.TO.id === message.to_id)
      id = message.to_id
      avatar = message.to_avatar
      name = message.to_name
    }
    // 会话是否存在
    let index = list.findIndex(item => {
      return item.chat_type === message.chat_type && item.id === id
    })
    // 最后一条消息展现形式
    // let data = isSend ? message.data : `${message.from_name}: ${message.data}`
    let data = this.formatChatItemData(message, isSend)
    // 会话不存在,创建会话
    // 未读数是否 + 1
    let noreadnum = (isSend || isCurrentChat) ? 0 : 1
    if (index === -1) {
      let chatItem = {
        id, // 接收人/群 id
        chat_type: message.chat_type, // 接收类型 user单聊 group群聊
        avatar, // 接收人/群 头像
        name, // 接收人/群 昵称
        update_time: (new Date()).getTime(), // 最后一条消息的时间戳
        data, // 最后一条消息内容
        type: message.type, // 最后一条消息类型
        noreadnum, // 未读数
        istop: false, // 是否置顶
        shownickname: false, // 是否显示昵称
        nowarn: false, // 消息免打扰
        strongwarn: false, // 是否开启强提醒
      }
      // 群聊
      if (message.chat_type === 'group' && message.group) {
        chatItem.shownickname = true
        chatItem.name = message.to_name
        chatItem = {
          ...chatItem,
          user_id: message.group.user_id, // 群管理员id
          remark: "", // 群公告
          invite_confirm: 1, // 邀请确认
        }
      }
      list.unshift(chatItem)
    } else { // 存在,更新会话
      // 拿到当前会话
      let item = list[index]
      // 更新该会话最后一条消息时间,内容,类型
      item.update_time = (new Date()).getTime()
      item.name = message.to_name
      item.data = data
      item.type = message.type
      // 未读数更新
      item.noreadnum += noreadnum
      // 置顶会话
      list = this.listToFirst(list, index)
    }
    // 存储
    let key = `chatlist_${this.user.id}`
    this.setStorage(key, list)
    // 更新未读数
    this.updateBadge(list)
    // 通知更新vuex中的聊天会话列表
    uni.$emit('onUpdateChatList', list)
    return list
  }
  // 获取聊天记录
  getChatList() {
    let key = `chatlist_${this.user.id}`
    return this.getStorage(key)
  }
  getChatList_old(message, isSend = true) {
    // 获取本地存储会话列表
    let list = this.getChatList();
    // 是否处在当前聊天中
    let isCurrentChat = false
    // 接收人/群 id/头像/昵称
    let id = 0;
    let avatar = '';
    let name = '';
    // 判断私聊还是群聊
    if (message.chat_type === 'user') {
      // 私聊
      isCurrentChat = this.TO ? (isSend ? this.TO.id === message.to_id : message.from_id) : false;
      id = isSend ? message.to_id : message.from_id;
      avatar = isSend ? message.to_avatar : message.from_avatar
      name = isSend ? message.to_name : message.from_name
    } else {
      // 群聊
    }
    // 会话是否存在
    let index = list.findIndex(item => {
      return item.chat_type === message.chat_type && item.id === id;
    })
    // 最后一条消息展现形式
    let data = isSend ? message.data : `${message.from_name}:${message.data}`;
    // 未读数是否 +1
    let noreadnum = (isSend || isCurrentChat) ? 0 : 1;
    // 会话不存在 创建会话
    if (index === -1) {
      let chatItem = {
        id, // 接收人/群 id
        chat_type: message.chat_type, // 接收类型 user 单聊 group群聊
        name, // 接收人/群 昵称
        avatar, // 接收人/群 头像
        update_time: (new Date()).getTime(), // 最后发送的时间
        data, // 最后一条消息的内容
        type: message.type,
        noreadnum: 1, // 未读数
        istop: false, // 是否置顶
        shownickname: false, // 是否显示昵称
        nowarn: false, // 是否免打扰
        strongwarn: false, //  是否强提醒
      }
      if (message.chat_type === 'group') {
        chatItem = {
          ...chatItem,
          user_id: 0, // 管理员id
          remark: '', // 群公告
          invite_confirm: 0 // 邀请确认
        }
      }
      list.unshift(chatItem)
    } else {
      // 存在,更新会话
      // 拿到当前会话
      let item = list[index]
      // 更新改会话最后一条消息时间,内容,类型
      item.update_time = (new Date()).getTime();
      item.data = data;
      item.type = message.type;
      // 未读数更新
      item.noreadnum += noreadnum
      // 置顶会话
      list = this.listToFirst(list, index);
    }
    // 存储
    let key = `chatlist_${this.user.id}`;
    this.setStorage(key, list);
    // 更新未读数
    this.updateBadge(list);
    // 更新vuex中的聊天会话列表
    uni.$emit('onUpdateChatList', list);
    console.log('获取到的会话列表:', list)
    return list;
    /**
     * {
      id:1,  // 接收人/群 id
      chat_type:'user', // 接收类型 user 单聊 group群聊
      name:'昵称', // 接收人/群 昵称
      avatar:"/static/images/demo/demo6.jpg", // 接收人/群 头像
      type:'',// 最后一条消息类型
      update_time:1628069958, // 最后发送的时间
      data:"你好啊,哈哈哈", // 最后一条消息的内容
      noreadnum:1, // 未读数
      istop:false, // 是否置顶
      shownickname:0, // 是否显示昵称
      nowarn:0, // 是否免打扰
      strongwarn:0, //  是否强提醒
      user_id://管理员id,
      remark:'公告', // 群公告
      invite_confirm:0, // 邀请确认
     },
     **/
  }
  // 获取本地存储会话列表
  getChatList() {
    let key = `chatlist_${this.user.id}`;
    return this.getStorage(key);
  }
  // 更新指定会话
  async updateChatItem(where, data) {
    // 获取所有会话列表
    let list = this.getChatList();
    // 找到当前会话
    let index = list.findIndex(item => item.id === where.id && item.chat_type === where.chat_type);
    if (index === -1) return;
    // 更新数据
    if(typeof data === 'function'){
      list[index] = data(list[index])
    }else{
      list[index] = data
    }
    
    let key = `chatlist_${this.user.id}`;
    this.setStorage(key, list);
    // 更新会话列表状态
    uni.$emit('onUpdateChatList', list);
  }
  // 读取指定会话
  async readChatItem(id, chat_type) {
    // 获取所有会话列表
    let list = this.getChatList();
    // 找到当前会话
    let index = list.findIndex(item => item.id === id && item.chat_type === chat_type);
    if (index !== -1) {
      list[index].noreadnum = 0;
      let key = `chatlist_${this.user.id}`;
      this.setStorage(key, list);
      // 重新获取未读数
      this.updateBadge();
      // 更新会话列表状态
      uni.$emit('onUpdateChatList', list);
    }
  }
  // 删除指定会话
  async removeChatItem(id, chat_type) {
    // 获取所有会话列表
    let list = this.getChatList();
    // 找到当前会话
    let index = list.findIndex(item => item.id === id && item.chat_type === chat_type);
    if (index !== -1) {
      list.splice(index, 1);
      let key = `chatlist_${this.user.id}`;
      this.setStorage(key, list);
      // 重新获取未读数
      this.updateBadge();
      // 更新会话列表状态
      uni.$emit('onUpdateChatList', list);
    }
  }
  // 清空聊天记录
  async clearChatDetail(id, chat_type) {
    let key = `chatDetail_${this.user.id}_${chat_type}_${id}`;
    $U.removeStorage(key);
    // 获取所有会话列表
    let list = this.getChatList();
    // 找到当前会话
    let index = list.findIndex(item => item.id === id && item.chat_type === chat_type);
    if (index !== -1) {
      list[index].data = '';
      let key = `chatlist_${this.user.id}`;
      this.setStorage(key, list);
      // 更新会话列表状态
      uni.$emit('onUpdateChatList', list);
    }
  }
  /**
     {
      id:1, // 接收人/群 id
      chat_type:'user', // 接收类型 user单聊 group群聊
      avatar:'', // 接收人/群 头像
      name:'昵称', // 接收人/群 昵称
      update_time:(new Date()).getTime(), // 最后一条消息的时间戳
      data:"最后一条消息内容", // 最后一条消息内容
      type:'text',       // 最后一条消息类型
      noreadnum:0, // 未读数
      istop:false, // 是否置顶
      shownickname:0, // 是否显示昵称
      nowarn:0, // 消息免打扰
      strongwarn:0, // 是否开启强提醒
      
      user_id:0, // 群管理员id
      remark:"公告", // 群公告
      invite_confirm:0, // 邀请确认
     }
     * **/
  // 初始化会话
  initChatListItem(message) {
    // 获取本地存储会话列表
    let list = this.getChatList()
    // 会话是否存在
    let index = list.findIndex(item => {
      return item.chat_type === message.chat_type && item.id === message.to_id
    })
    // 最后一条消息展现形式
    let data = this.formatChatItemData(message, true)
    // 会话不存在,创建会话
    if (index === -1) {
      let chatItem = {
        id: message.to_id, // 接收人/群 id
        chat_type: message.chat_type, // 接收类型 user单聊 group群聊
        avatar: message.to_avatar, // 接收人/群 头像
        name: message.to_name, // 接收人/群 昵称
        update_time: (new Date()).getTime(), // 最后一条消息的时间戳
        data: message.data, // 最后一条消息内容
        type: 'system', // 最后一条消息类型
        noreadnum: 0, // 未读数
        istop: false, // 是否置顶
        shownickname: false, // 是否显示昵称
        nowarn: false, // 消息免打扰
        strongwarn: false, // 是否开启强提醒
      }
      // 群聊
      if (message.chat_type === 'group' && message.group) {
        chatItem = {
          ...chatItem,
          user_id: message.group.user_id, // 群管理员id
          remark: '', // 群公告
          invite_confirm: message.group.invite_confirm, // 邀请确认
        }
      }
      list.unshift(chatItem)
      // 存储
      let key = `chatlist_${this.user.id}`
      this.setStorage(key, list)
      // 通知更新vuex中的聊天会话列表
      uni.$emit('onUpdateChatList', list)
    }
  }
  // 获取指定会话
  getChatListItem(id, chat_type) {
    // 获取所有会话列表
    let list = this.getChatList()
    // 找到当前会话
    let index = list.findIndex(item => item.id === id && item.chat_type === chat_type)
    if (index !== -1) {
      return list[index]
    }
    return false
  }
  // 更新未读数
  async updateBadge(list = false) {
    // 获取所有会话列表
    list = list ? list : this.getChatList()
    // 统计所有未读数
    let total = 0
    list.forEach(item => {
      total += item.noreadnum
    })
    // 设置底部导航栏角标 
    if (total > 0) {
      uni.setTabBarBadge({
        index: 0,
        text: total <= 99 ? total.toString() : '99+'
      })
    } else {
      uni.removeTabBarBadge({
        index: 0
      })
    }
    uni.$emit('totalNoreadnum', total)
  }
  // 获取存储
  getStorage(key) {
    let list = $U.getStorage(key);
    return list ? JSON.parse(list) : [];
  }
  // 设置存储
  setStorage(key, value) {
    return $U.setStorage(key, JSON.stringify(value));
  }
  // 数组置顶
  listToFirst(arr, index) {
    if (index != 0) {
      arr.unshift(arr.splice(index, 1)[0]);
    }
    return arr;
  }
  // 撤回消息
  recall(message) {
    return new Promise((result, reject) => {
      $H.post('/chat/recall', {
        to_id: message.to_id,
        chat_type: message.chat_type,
        id: message.id,
      }).then(res => {
        // key值:chatDetail_当前用户id_会话类型_接收人/群id
        let key = `chatDetail_${this.user.id}_${message.chat_type}_${message.to_id}`
        // 获取原来的聊天记录
        let list = this.getChatDetail(key)
        // 根据k查找对应聊天记录
        let index = list.findIndex(item => item.id === message.id)
        if (index === -1) return;
        list[index].isremove = 1
        // 存储
        this.setStorage(key, list)
        result(res)
        // 更新会话最后一条消息显示
        this.updateChatItem({
          id: message.to_id,
          chat_type: message.chat_type
        }, (item) => {
          item.data = '你撤回了一条消息'
          item.update_time = (new Date()).getTime()
          return item
        })
      }).catch(err => {
        reject(err)
      })
    })
  }
}
export default chat

感谢大家观看,我们下次见

目录
相关文章
|
5月前
uni-app 152朋友圈动态实时通知功能
uni-app 152朋友圈动态实时通知功能
47 0
|
5月前
uni-app 134同意添加好友实时通知
uni-app 134同意添加好友实时通知
39 0
|
5月前
uni-app 100群公告推送功能(二)
uni-app 100群公告推送功能(二)
48 0
|
5月前
uni-app 155朋友圈评论功能(二)
uni-app 155朋友圈评论功能(二)
97 0
|
5月前
uni-app 120撤回消息功能(四)
uni-app 120撤回消息功能(四)
85 0
|
5月前
uni-app 99群公告推送功能(一)
uni-app 99群公告推送功能(一)
34 1
uni-app 99群公告推送功能(一)
|
5月前
uni-app 133好友申请实时通知
uni-app 133好友申请实时通知
48 5
|
5月前
uni-app 190扫一扫加入群聊功能(二)
uni-app 190扫一扫加入群聊功能(二)
58 2
|
5月前
uni-app 189扫一扫添加群聊功能(一)
uni-app 189扫一扫添加群聊功能(一)
48 1
|
5月前
uni-app 119撤回消息功能(三)
uni-app 119撤回消息功能(三)
33 1