chat.nvue 59.8 KB
Newer Older
DCloud_JSON's avatar
DCloud_JSON 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
<template>
  <!-- 设置导航栏标题,如与谁对话,群人数为几人等。注意:部分平台page-meta必须为第一个节点 -->
  <!-- #ifndef H5 -->
  <page-meta>
     <navigation-bar :title="navTitle" background-color="#f8f8f8" front-color="#000000" />
  </page-meta>
  <!-- #endif -->
  
  <!-- #ifdef H5 -->
  <view v-if="isWidescreen">
    <text style="position: absolute;z-index: 9;top: -45px;left: 15px;" :selectable="true">{{navTitle}}</text>
  </view>
  <page-meta v-else>
     <navigation-bar :title="navTitle" background-color="#f8f8f8" front-color="#000000" />
  </page-meta>
  <!-- #endif -->
 
  
  <view class="page" id="uni-im-chat">
    <!-- #ifdef H5 -->
    <!-- H5端 左上角显示未读消息数 ,nvue端使用setTitleNViewButtonBadge设置-->
    <view @click="tapUnreadCount" class="unread_count" v-if="unread_count != 0">
      {{ unread_count > 99 ? '99+' : unread_count }}
    </view>
    <!-- #endif -->

    <uni-im-msg-list v-if="conversation.id" :conversationId="conversation.id" ref="msg-list" @showControl="showControl" @chatInputContentAddcallUser="setCallAboutUidBefore"
      @retriesSendMsg="retriesSendMsg" :paddingBottom="msgListPaddingBottom + 'px'" class="msg-list"
      @clickItem="hideKeyboard" @putChatInputContent="putChatInputContent" :chooseMore="chooseMoreMsg"
      :checkedMsgList.sync="checkedMsgList"
    ></uni-im-msg-list>

    <!-- 聊天数据输入框 键盘弹出后要抬高底部内边距 全面屏的安全距离 -->
    <text v-if="conversation.leave" class="disable-input">- 你不是此群成员 -</text>
    <text v-else-if="conversation.isMuteAllMembers" class="disable-input">-  全群禁言禁止输入 -</text>
    <view v-else class="chat-foot">
      <!-- pc宽屏(width>960px)的输入框 -->
      <!-- #ifdef H5 -->
      <view v-if="isWidescreen" class="pc">
        <view class="tool-bar">
          <view class="icons">
            <uni-im-icons v-for="(item,index) in menuList" :key="index" @click.native.stop="clickMenu(index,$event)"
              :code="item.iconCode" size="24" color="#666666" :title.native="`选择${item.title},并发送`"></uni-im-icons>
          </view>
          <template v-for="item in inputMsgToolBar" :key="item.component.name">
            <component :is="item.component" v-bind="item.props" @beforeSendMsg="beforeSendMsg" @sendMsg="sendMsg" @updateMsg="updateMsg" />
          </template>
        </view>
        <view class="answer-msg" v-if="answerMsg !== false">
          <text class="answer-msg-text">{{getNicknameByUid(answerMsg.from_uid)}}:{{trAnswerMsg(answerMsg)}}</text>
          <uni-icons @click="answerMsg = false" type="clear" color="#aaa" size="16px"></uni-icons>
        </view>
        <uni-im-chat-input ref="chat-input" class="textarea" @input="onInput" :maxlength="50000"
          v-model="chatInputContent" @focus="onChatInputFocus" @blur="onChatInputBlur" :focus="isFocus"
          placeholder="请输入消息" placeholder-style="color:#bbb;" @confirm="chatInputConfirm"
        ></uni-im-chat-input>
        <view class="send-btn-box">
          <text class="send-btn-tip">↵ 发送 / shift + ↵ 换行</text>
          <button @click="chatInputConfirm" :disabled="!canSend" class="send" type="primary">发送</button>
        </view>
      </view>
      <!-- #endif -->

      <!-- 非pc宽屏(width<960px)的输入框 -->
      <template v-if="!isWidescreen">
        <view v-if="showInputBox" class="input-box">
          <!-- 切换为语音模式 -->
68
          <!-- #ifdef H5 -->
DCloud_JSON's avatar
DCloud_JSON 已提交
69
          <view class="camera-filled-box" @click="chooseFileSendMsg('image')">
70
            <uni-icons type="camera-filled" size="20px" color="#FFF"></uni-icons>
DCloud_JSON's avatar
DCloud_JSON 已提交
71
          </view>
72 73
          <!-- #endif -->
          <!-- #ifndef H5 -->
DCloud_JSON's avatar
DCloud_JSON 已提交
74 75
          <uni-im-icons @click="changeSoundIsShow" :code="soundIsShow?'e69f':'e684'" size="30"
            class="icon"></uni-im-icons>
76
          <!-- #endif -->
DCloud_JSON's avatar
DCloud_JSON 已提交
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606
          <view class="input-box-conetnt">
            <view class="textarea-box">
              <textarea :cursor="inputCursor" v-model="chatInputContent" @input="onInput" @confirm="beforeSendMsg()"
                @linechange="linechange" :flex="true" :style="{ height: textareaHeight + 'px' }"
                :disable-default-padding="false" :hold-keyboard="true" :confirm-hold="true" :auto-blur="false"
                confirm-type="send" :show-confirm-bar="false" :cursor-spacing="20" maxlength="50000" :focus="systemInfo.uniPlatform === 'app'?'':isFocus"
                @focus="onChatInputFocus" @blur="onChatInputBlur" :fixed="true" :adjust-position="false"
                class="textarea" ref="chat-input" />
            </view>
            <view class="answer-msg" v-if="answerMsg !== false">
              <text class="answer-msg-text">{{getNicknameByUid(answerMsg.from_uid)}}:{{trAnswerMsg(answerMsg)}}</text>
              <uni-icons @click="answerMsg = false" type="clear" color="#aaa" size="16"></uni-icons>
            </view>
            <uni-im-sound class="uni-im-sound" v-if="soundIsShow" @success="sendSound"></uni-im-sound>
          </view>
          <uni-im-icons @click.native.stop="changeEmojiIsShow" :code="emojiIsShow?'e69f':'e646'" size="30"
            class="icon"></uni-im-icons>
          <text v-if="!soundIsShow&&chatInputContent" @click.prevent="beforeSendMsg()" class="icon beforeSendMsg">发送</text>
          <uni-im-icons v-else @click.native.stop="changeMenuIsShow" code="e75a" size="30" class="icon"></uni-im-icons>
        </view>

        <view v-if="menuIsShow||emojiIsShow" class="media-box" :style="{height:keyboardMaxHeight+'px'}">
          <view v-if="menuIsShow" class="menu" :style="{height:keyboardMaxHeight+'px'}">
            <view class="menu-item" v-for="(item,index) in menuList" :key="index" @click.stop="clickMenu(index,$event)">
              <view class="menu-item-icon">
                <uni-im-icons :code="item.iconCode" size="26"></uni-im-icons>
              </view>
              <text class="menu-item-text">{{item.title}}</text>
            </view>
          </view>
          <scroll-view :scroll-y="true" v-if="emojiIsShow" class="emojiListBox"
            :style="{height:keyboardMaxHeight+'px'}">
            <text v-for="(uniCodeEmoji,index) in emojiCodes" :key="index"
              @click.stop="clickEmojiItem(uniCodeEmoji,$event)" class="emoji-item">{{uniCodeEmoji}}</text>
          </scroll-view>
        </view>
        <!-- #ifndef H5 -->
        <!-- 调整输入框的位置,占位专用:键盘高度 或 全面屏底部不可用区域高度 -->
        <view v-else :style="{height: (keyboardHeight || phoneBH) +'px'}"></view>
        <!-- #endif -->
      </template>
    </view>

    <msg-popup-control ref="msg-popup-control" @answer="setAnswerMsg" @share="shareMsg" @chooseMore="chooseMoreMsg = true;checkedMsgList = $event"></msg-popup-control>

    <template v-if="showAboutUidBox && memberList.length != 0">
      <view class="member-list-mark" @click.stop="showAboutUidBox = false"></view>
      <scroll-view scroll-y="true" class="member-list" :scroll-top="memberListScrollTop">
        <view v-for="(item,index) in memberList" :key="item._id" class="member-list-item"
          :class="{'member-list-item-active':callAboutUid == item.users._id}" @mouseover="callAboutUid = item.users._id"
          @click="setCallAboutUid(item.users._id)" :id="'a'+item.users._id">
          {{item.users.nickname}}
        </view>
      </scroll-view>
    </template>


    <!-- #ifdef H5 -->
    <uni-im-share-msg id="uni-im-share-msg" ref="share-msg"></uni-im-share-msg>
    <!-- #endif -->
    
    
    <view style="position: fixed;top: 200px;left: 0;background-color: #FFFFFF;">
     <!-- showAboutUidBox:{{showAboutUidBox}}-
      aboutUserKeyword:{{aboutUserKeyword}}-
			conversation.leave:{{conversation.leave}}
      msgListPaddingBottom:{{msgListPaddingBottom}}
			keyboardHeight:{{keyboardHeight}}
			keyboardMaxHeight:{{keyboardMaxHeight}}
			systemInfo.osName:{{systemInfo.osName}}
      chooseMoreMsg:{{chooseMoreMsg}}
      checkedMsgList:{{checkedMsgList}} -->
		</view>
    
    <view v-if="chooseMoreMsg" class="toolbar" @click="chooseMoreMsg = false">
      <view class="item" @click="shareMsg(checkedMsgList)">
        <view class="icons-box">
          <uni-icons size="35" type="redo"></uni-icons>
        </view>
        <text class="title">逐条转发</text>
      </view>
      <view class="item" @click="shareMsg(checkedMsgList,true)">
        <view class="icons-box">
          <uni-icons size="35" type="paperplane"></uni-icons>
        </view>
        <text class="title">合并转发</text>
      </view>
      <view class="item" @click="toolBarNext">
        <view class="icons-box">
          <uni-icons size="35" type="folder-add"></uni-icons>
        </view>
        <text class="title">收藏</text>
      </view>
      <view class="item" @click="toolBarNext">
        <view class="icons-box">
          <uni-icons size="35" type="download"></uni-icons>
        </view>
        <text class="title">保存至电脑</text>
      </view>
      <view class="item" @click="toolBarNext">
        <view class="icons-box">
          <uni-icons size="35" type="trash"></uni-icons>
        </view>
        <text class="title">删除</text>
      </view>
      <uni-icons @click="chooseMoreMsg = false" color="#999" size="35" type="closeempty"></uni-icons>
    </view>
  </view>
</template>

<script>
  import uniIm from '@/uni_modules/uni-im/sdk/index.js';
  import msgPopupControl from '@/uni_modules/uni-im/components/uni-im-msg/popup-control.vue';
  import {markRaw} from "vue";

  // #ifdef APP-NVUE
  // 定义weex的dom模块(https://doc.weex.io/zh/docs/modules/dom.html#scrolltoelement)
  const dom = weex.requireModule('dom') || {};
  // #endif

  import {
    store as uniIdStore
  } from '@/uni_modules/uni-id-pages/common/store';
  import emojiCodes from './emojiCodes.js';

  let shiftKeyPressed = false;
  let lastKeyDown = ""
  let currentCursor = ''

/**
 * chat 组件,渲染一个完整的会话,包括头部、消息列表、输入区。
 * 
 * @module
 * 
 * @see 用于渲染消息列表的组件 {@link module:uni-im-msg-list}
 */
  export default {
    components: {
      msgPopupControl
    },
    data() {
      return {
        inputMsgToolBar:[],
        // 当前会话对象
        conversation: {
          id: false,
          leave:false
        },
        //聊天输入框高度
        textareaHeight: 26,
        menuIsShow: false,
        emojiIsShow: false,
        soundIsShow: false,
        menuList: [{
            "title": "图片",
            "iconCode": "e7be"
          },
          {
            "title": "视频",
            "iconCode": "e690"
          },
          {
            "title": "文件",
            "iconCode": "e69e"
          }
        ],
        navTitle:"",//导航栏标题
        keyboardHeight: 0,
        keyboardMaxHeight: 260,
        emojiCodes: emojiCodes,
        isFocus: false,
        answerMsg: false,
        callAboutUid: false,
        showAboutUidBox: false,
        inputCursor: '',
        // @用户时的搜索词
        aboutUserKeyword: '',
        memberListScrollTop: 0,
        chooseMoreMsg: false,
        checkedMsgList: []
      };
    },
    props: {
      // #ifdef VUE3
      conversation_id: {
        default: ''
      }
      // #endif
    },
    computed: {
      ...uniIm.mapState(['currentConversationId', 'conversationDatas', 'isWidescreen', 'systemInfo']),
      unread_count() {
        // 所有会话的未读消息数
        const unreadCount = uniIm.conversation.unreadCount()

        // #ifdef APP-PLUS
        // 给标题栏返回按钮添加数字角标,表示有几条其他会话的未读消息数
        plus.webview.currentWebview().setTitleNViewButtonBadge({
          index: 0,
          text: unreadCount
        })
        // #endif

        return unreadCount
      },
      isSafariPc() {
        return this.systemInfo.browserName == 'safari' && this.isWidescreen
      },
      group_member() {
        let group_member = this.conversation.group_member
        if (!this.callAboutUid && typeof group_member == 'object') {
          this.callAboutUid = Object.keys(this.conversation.group_member)[0]
        }
        return group_member
      },
      memberList() {
        // 当前输入框已经@了的用户id 要过滤掉 
        let callUidList = this.getCallUid(this.chatInputContent)
        
        let group_member = this.group_member || {}
        let memberList = []
        for (let key in group_member) {
          let member = group_member[key]
          if(member.users.nickname){
            let nickname = member.users.nickname.toLowerCase()
            if (nickname.indexOf(this.aboutUserKeyword.toLowerCase()) != -1 && !callUidList.includes(member.users._id)) {
              memberList.push(member)
            }
          }
        }
        if (memberList.length) {
          let has = memberList.find(member => member.users._id == this.callAboutUid)
          if (!has) {
            this.callAboutUid = memberList[0].users._id
          }
        } else {
          // 没有数据时也不隐藏,因为用户可能回删@用户的关键词
          // this.showAboutUidBox = (memberList.length != 0)
        }
        // 按昵称排序
        return memberList.sort((a, b) => {
          return a.users.nickname.localeCompare(b.users.nickname)
        })
      },
      //聊天数据
      //当前会话的聊天框文字内容
      chatInputContent: {
        get() {
          // console.log('this.conversation',this.conversation);
          return this.conversation?.chatInputContent || '';
        },
        set(chatInputContent) {
          // #ifdef APP-NVUE
          if(this.nvueSetChatInputContent){
            clearTimeout(this.nvueSetChatInputContent)
          }
          this.nvueSetChatInputContent = setTimeout(()=>this.conversation.chatInputContent = chatInputContent,1000)
          // #endif
          // #ifndef APP-NVUE
          this.conversation.chatInputContent = chatInputContent
          // #endif
        }
      },
      canSend() {
        if(typeof this.chatInputContent === 'string'){
          return this.chatInputContent.trim() != ''
        }else{
          return this.chatInputContent.html.length != 0
        }
      },
      //当前用户自己的uid
      current_uid() {
        return uniIdStore.userInfo._id;
      },
      phoneBH() {
         // #ifdef H5
        return 0
        // #endif
        
       // #ifndef H5
        return this.systemInfo.safeAreaInsets.bottom
        // #endif
      },
      msgListPaddingBottom() {
        // #ifdef H5
        // 是否为pc宽屏(width>960px)
        if (this.isWidescreen) {
          return 0
        }else{
          return 56
        }
        // #endif

        let msgListPaddingBottom = this.textareaHeight + 30
        if (this.keyboardHeight || this.menuIsShow || this.emojiIsShow) {
          msgListPaddingBottom += this.keyboardMaxHeight
        }
        if (!this.keyboardHeight) {
          msgListPaddingBottom += this.phoneBH
        }
        return msgListPaddingBottom
      },
      // 临时方案 修复(兼容)微信小程序框架的bug:iOS端textarea组件 在 iOS 真机下 无法动态切换绑定 onInput 事件
      // 大家可以一起顶帖 链接地址:https://developers.weixin.qq.com/community/develop/doc/0002a02800cd90b9632efeab55b000
      showInputBox() {
        // #ifndef MP-WEIXIN
        return true
        // #endif
        // #ifdef MP-WEIXIN
        return this.conversation.id
        // #endif
      }
    },
    created() {
      // 监听推送消息
      this.onImMsg = (res) => {
        if(uniIm.isDisabled){
          return console.log('uniIm isDisabled')
        }
        //获取透传内容
        const {
          type,
          data
        } = res.data.payload;
        //判断消息类型是否为im,且为当前页面对应会话消息
        if (
          type == "uni-im" 
          && data.conversation_id == this.currentConversationId 
          && data.from_uid != this.current_uid 
          && uniIm.utils.isReadableMsg(data)
        ) {
          // 已经打开相应会话时,收到消息,则设置此会话为已读。注意无需判断,本地会话未读数是否为0,因为云端可能不为0
          this.conversation.clearUnreadCount();
          console.log('聊天页面-收到消息: ', JSON.stringify(res));
          // 需要重新设置滚动条的高,以至于用户可以立即看到(即:滚动到最后一条消息)
          // console.log(66666);

          // 注:为兼容web-PC端这里必须使用setTimeout 0
          setTimeout(() => {
            this.$refs['msg-list']?.notifyNewMsg()
          }, 0);
        }
      }
      uniIm.onMsg(this.onImMsg);

      // #ifdef H5
      //通过监听窗口变化 获取键盘弹出或收起事件
      window.addEventListener('resize', () => {
        if (this.currentConversationId) {
          this.showLast(0);
          this.soundIsShow = false
        }
      })
      // #endif

      this.onKeyboardHeightChange = ({
        height
      }) => {
        this.keyboardHeight = height
        // console.log('height',height)
        if (height) {
          this.keyboardMaxHeight = height
        }
        this.$nextTick(() => {
          this.showLast();
          // 临时方案:解决部分情况下 web-pc nvue 平台下不能滚动到最后一条消息的问题
          setTimeout(() => {
            this.showLast()
          }, 800)
        });
      }
      // #ifndef H5
      // 监听键盘高度变化显示最后一条消息
      uni.onKeyboardHeightChange(this.onKeyboardHeightChange);
      // #endif
      
      // #ifdef H5
      const oldWindowHeight = window.innerHeight;
      window.onresize = ()=>{
        this.onKeyboardHeightChange({"height": oldWindowHeight - window.innerHeight})
      }
      // #endif
    },
    mounted() {
      // #ifdef H5
      // 以下为实现拖拽或粘贴图片至聊天页面,直接发送的逻辑
      const chatBodyDom = document.getElementById("uni-im-chat")
      // 阻止默认事件
      chatBodyDom.addEventListener(
        'dragover',
        function(event) {
          event.preventDefault();
        },
        false
      );
      // 拖拽结束时触发
      chatBodyDom.addEventListener(
        'drop',
        e => {
          //取消默认浏览器拖拽效果
          e.preventDefault();
          //获取文件对象
          let fileList = e.dataTransfer.files;
          if (fileList.length == 0) {
            return false;
          }
          const [file] = fileList
          let fileType = file.type.split('/')[0] || 'file'
          if (fileList === 'image') {
            let blobUrl = window.URL.createObjectURL(file);
            if(this.chatInputContent === ''){
              this.$refs["chat-input"]?.setHtml(`<img src="${blobUrl}" />`)
            }else{
              this.$refs["chat-input"]?.addHtmlToCursor(`<img src="${blobUrl}" />`)
            }
            return false; // 拖拽图片内容进入输入框先不发送
          }
          
          let {
            name,
            size
          } = file
          // console.log(78979798,fileList);
          const blobUrl = window.URL.createObjectURL(file);
          this.uploadFileAndSendMsg({
              tempFiles:[{
                size,
                name,
                path:blobUrl,
                fileType
              }]
          })
        },
        false
      );

      const chatInput = document.querySelector('.pc .textarea');
      if (chatInput) {
        //键盘按下时
        let oldValue = ''
        chatInput.addEventListener('keydown',async e => {
          if (this.showAboutUidBox) {
            if(e.key == 'Enter'){
              if(this.memberList.length){
                console.log('选中要@的人')
                this.setCallAboutUid(this.callAboutUid)
              }
            }else if(["ArrowUp", "ArrowDown"].includes(e.key)){
              console.log('上下箭头选择@谁')
              let index = this.memberList.findIndex(i => i.users._id == this.callAboutUid)
              // console.log('index',index);
              if (e.key == "ArrowUp") {
                index--
              } else {
                index++
              }
              if (index < 0 || index > this.memberList.length - 1) {
                index = 0
              }
              this.callAboutUid = this.memberList[index].users._id
              // 防止选中的成员看不到,触发滚动
              this.memberListScrollTop = (index - 3) * 50
              // console.log('this.memberListScrollTop',this.memberListScrollTop);
              e.preventDefault();
            }else if(["ArrowLeft", "ArrowRight"].includes(e.key)){
              this.showAboutUidBox = false
            }else if(e.key == 'Backspace'){
              setTimeout(() => {
                // 获取e.target 元素内不包含在标签内的文字内容
                let newValue = e.target.innerText
                console.log('删除键',newValue,oldValue);
                // 拿到newValue 和 oldValue 中 包含的@字符的个数
                let newAtN = newValue.replace(/[^@]/g, "").length
                let oldAtN = oldValue.replace(/[^@]/g, "").length
                if(newAtN === 0 || newAtN < oldAtN){
                  console.log('删除了@成员的昵称');
                  this.showAboutUidBox = false
                }
                oldValue = newValue
              }, 0);
            }
          }else{
            // console.log('键盘按下时',e.key);
            if(e.key == '@'){
              this.showAboutUidBox = true
            }
          }
        })
      }
      
      // #endif
    },
    onShow() {
      if (this.conversation.id) {
        // 用于打开会话窗口后,切换到后台,再切回时设置当前会话id。
        uniIm.currentConversationId = this.conversation.id

        // 用于从后台切到前台时,设置当前会话为已读
        this.clearConversationUnreadCount()
      }
    },
    onUnload() {
      // console.log('onUnload');

      // 关闭监听消息推送事件
      uniIm.offMsg(this.onImMsg);

      // #ifndef H5
      uni.offKeyboardHeightChange(this.onKeyboardHeightChange)
      // #endif

      //页面销毁之前销毁 全局变量 正在聊天的用户的id
      uniIm.currentConversationId = false
      // console.log('beforeDestroy');
      // 关闭sound播放
      uniIm.audioContext.stop()
    },
    beforeDestroy() {
      //页面销毁之前销毁 全局变量 正在聊天的用户的id
      uniIm.currentConversationId = false
      // console.log('beforeDestroy');
      // 关闭sound播放
      uniIm.audioContext.stop()
    },
    onHide() {
      uniIm.currentConversationId = false
      // 关闭sound播放
      uniIm.audioContext.stop()
    },
    async onLoad(param) {
607 608 609 610 611
      for (const key in param) {
        try{
          param[key] = JSON.parse(param[key])
        }catch(_){}
      }
DCloud_JSON's avatar
DCloud_JSON 已提交
612 613 614 615 616 617 618 619 620
      //调用load方法,因为pc宽屏时本页面是以组件形式展示。如$refs.chatView.loadconversation_id()执行
      await this.load(param);
    },
    watch: {
      async chatInputContent(newValue, oldValue) {
        // #ifndef APP-NVUE
        if(this.isWidescreen || this.watchChatInputContentDisabled === true){
          return
        }
DCloud_JSON's avatar
DCloud_JSON 已提交
621
        // console.log('chatInputContent',newValue,oldValue);
DCloud_JSON's avatar
DCloud_JSON 已提交
622 623 624 625 626
        // 截流调用 chatInputContentAfter 方法
        if(this.doChatInputContentAfter){
          clearTimeout(this.doChatInputContentAfter)
        }
        this.doChatInputContentAfter = setTimeout(() => {
DCloud_JSON's avatar
DCloud_JSON 已提交
627
          // console.error('chatInputContent#6');
DCloud_JSON's avatar
DCloud_JSON 已提交
628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706
          this.lockDoChatInputContentAfter = false
          this.chatInputContentAfter(newValue, oldValue)
        }, 300);
        // #endif
      },
      // 监听群昵称变化
      'conversation.title':{
        handler(){
          this.updateNavTitle()
        }
      },
      // 监听群成员数变化
      'conversation.group_member':{
        handler(){
          this.updateNavTitle()
        },
        deep:true,
        immediate:true
      },
      // 兼容nvue下不能通过isFocus控制聚焦
      // #ifdef APP-NVUE
      isFocus(newValue){
        console.log("this.$refs['chat-input'].focus",this.$refs["chat-input"].attr.focus)
        if(newValue){
          this.$refs["chat-input"].focus()
        }else{
          this.$refs["chat-input"].blur()
        }
      },
      // #endif
    },
    methods: {
      async load(param) {
        this.answerMsg = false
        // conversation_id = "single_eff0518ad35e16a8a025cc8af03e0388"

        // console.log('conversation_id',conversation_id);
        this.conversation = await uniIm.conversation.get(param)
        // this.conversation.call_list = []
        // console.log('this.conversation',this.conversation)
        
        // 调用扩展点,扩展程序可以在消息输入框新增一个工具类的项
        this.inputMsgToolBar = uniIm.extensions
          .invokeExts("input-msg-tool-bar",this.conversation)
          .filter((result) => result && result.component)
          .map((result) => {
            return {
              component: markRaw(result.component),
              props: result.props||{}
            };
          });

        //设置全局的app当前正在聊天的会话id(注:本页面可能是直达页)
        uniIm.currentConversationId = this.conversation.id
        this.$nextTick(() => {
          this.$refs['msg-list'].init()
        })

        // console.log('this.conversation',this.conversation);
        
        //debug用模拟一次性自动发送100条数据
        // for (var i = 0; i < 20; i++) {
        // 	this.chatInputContent = '这是第'+i+'条消息'
        // 	this.beforeSendMsg()
        // }*/
        
        // 清除当前会话未读数
        this.clearConversationUnreadCount()
        
        // #ifdef H5
        if(this.isWidescreen){
          // 切换到新的会话后把输入焦点设置到输入框(考虑到可能有草稿文字,需延迟设置)
          setTimeout(() => {
            this.$refs["chat-input"].focusToLast?.()
          }, 100)
        }
        // #endif
      },
      chatInputContentAfter(newValue, oldValue){
DCloud_JSON's avatar
DCloud_JSON 已提交
707
        // console.log('chatInputContentAfter',newValue,oldValue);
DCloud_JSON's avatar
DCloud_JSON 已提交
708 709 710 711 712 713 714 715 716 717 718 719 720 721
        currentCursor = -1
        // 先找到字符不同的位置,即为光标操作时的位置
        for (let i = 0; i < newValue.length; i++) {
          if (newValue[i] !== oldValue[i]) {
            currentCursor = i
            break
          }
        }
        if(currentCursor == -1){
          currentCursor = newValue.length
        }
        // console.log('cursor光标的位置',currentCursor,newValue,'newValue');
        let isAdd = newValue.length > oldValue.length
        let changeValue = isAdd ? newValue[currentCursor] : oldValue[currentCursor]
DCloud_JSON's avatar
DCloud_JSON 已提交
722
        // console.log('changeValue变化的内容',changeValue);
DCloud_JSON's avatar
DCloud_JSON 已提交
723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234
        if(changeValue == '@'){
          this.showAboutUidBox = isAdd
          if(isAdd){
            // 增加了@符号,显示@成员列表
            this.memberListScrollTop = 0
            if (this.memberList.length) {
              this.callAboutUid = this.memberList[0].users._id
            }
          }
        }
        // 删除了  \u200b@\u200b${nickname}\u2009
        if(!isAdd){
          if(changeValue === '\u2009'){
            // console.log('删除了 u2009 符号');
            // 找到从光标位置到\u200b@\u200b符号的最左边的位置
            let leftIndex = newValue.slice(0,currentCursor).lastIndexOf('\u200b@\u200b')
            // console.log('leftIndex',leftIndex);
            // 删除从leftIndex到光标之间的字符
            const newchatInputContent = newValue.slice(0,leftIndex) + newValue.slice(currentCursor)
            this.setChatInputContent(newchatInputContent,leftIndex)
          }else if(changeValue === '\u200b'){
            // console.log('删除了 u200b 符号');
            // 找到从光标位置到\u2009符号的最左边的位置
            let leftIndex = newValue.slice(currentCursor).indexOf('\u2009') + currentCursor + 1
            // console.log('leftIndex~~',leftIndex,newValue.slice(leftIndex));
            // 删除从光标到leftIndex之间的字符
            const newchatInputContent = newValue.slice(0,currentCursor) + newValue.slice(leftIndex)
            this.setChatInputContent(newchatInputContent,currentCursor)
          }else{
            // 判断被删的字符是否在\u200b@\u200b${nickname}\u2009中
            let leftIndex = newValue.slice(0,currentCursor).lastIndexOf('\u200b@\u200b')
            let rightIndex = newValue.slice(currentCursor).indexOf('\u2009') + currentCursor + 1
            if(leftIndex != -1 && rightIndex != currentCursor){
              // console.log('删除了@成员的昵称');
              // 删除从leftIndex到rightIndex之间的字符
              const newchatInputContent = newValue.slice(0,leftIndex) + newValue.slice(rightIndex)
              this.setChatInputContent(newchatInputContent,leftIndex)
            }
          }
        }
      },
      clearConversationUnreadCount(){
        if(this.conversation.unread_count){
          this.conversation.clearUnreadCount();
        }
      },
      putChatInputContent(value){
        if(this.isWidescreen){
          this.$refs["chat-input"]?.setContent(value)
        }else{
          if(typeof value === 'string'){
            this.setChatInputContent(value)
          }else{
            uni.showToast({
              title: '移动端暂不支持编辑富文本消息',
              icon: 'none'
            });
          }
        }
      },
      // 通过setChatInputContent设置chatInputContent时,不再触发watchchatInputContent,并可以设置光标位置
      setChatInputContent(value,cursor){
        this.watchChatInputContentDisabled = true
        this.chatInputContent = value
        this.$nextTick(() => {
          this.watchChatInputContentDisabled = false
          // 光标被重新定位到当前位置
          setTimeout(() => {
            this.inputCursor = cursor
          }, 300);
        })
      },
      getNicknameByUid(uid) {
        let users = uniIm.users[uid]
        if (users) {
          return users.nickname
        } else {
          return ''
        }
      },
      trAnswerMsg(answerMsg) {
        return uniIm.utils.getMsgNote(answerMsg)
      },
      onChatInputFocus() {
        // console.log('onChatInputFocus');
        this.isFocus = true;
        this.$nextTick(() => {
          this.menuIsShow = false
          this.emojiIsShow = false
        })
      },
      onChatInputBlur() {
        // console.log('onChatInputBlur');
        this.isFocus = false;
      },
      changeSoundIsShow() {
        this.soundIsShow = !this.soundIsShow
        if (this.soundIsShow) {
          // 将输入框高度记录,并设置为26
          this.oldTextareaHeight = this.textareaHeight
          this.textareaHeight = 26

          uni.hideKeyboard();
        } else {
          // 恢复切换之前的输入框高度
          this.textareaHeight = this.oldTextareaHeight
          this.isFocus = true
        }
        uni.$emit('changeSoundIsShow');
        this.$nextTick(() => {
          this.menuIsShow = false
          this.emojiIsShow = false
        })
      },
      changeMenuIsShow(e) {
        if (this.keyboardHeight) {
          this.menuIsShow = true
          uni.hideKeyboard()
        } else {
          this.menuIsShow = !this.menuIsShow
        }
        this.emojiIsShow = false;
        this.showLast(0)
        e.stopPropagation()
      },
      changeEmojiIsShow(e) {
        this.soundIsShow = false

        if (this.keyboardHeight) {
          this.emojiIsShow = true
          uni.hideKeyboard()
        } else {
          this.emojiIsShow = !this.emojiIsShow
        }
        this.menuIsShow = false
        this.showLast(0)
        e.stopPropagation()
      },
      uploadFileAndSendMsg({tempFiles}){
        // console.log(res, 'image');
        // console.log('this.uploadFileAndSendMsg res',res);
        tempFiles.forEach(async tempFile => {
          // console.log('tempFile~',tempFile);
          let {
            path:url,
            name,
            size
          } = tempFile;
          
          let {fileType} = tempFile
          if (!['image', 'video'].includes(fileType)) {
            fileType = 'file'
          }
          // console.log('fileType===>', fileType);
          // console.error('tempFile~~~~~~~~~', tempFile,size/1000/1024+'mb');
          const sizeMB = size/1000/1024
          if(fileType == 'image' && sizeMB > 2){
            return uni.showToast({
              title: '图片大小不能超过2mb',
              icon: 'none'
            });
          } else if(sizeMB > 100){
            return uni.showToast({
              title: '文件大小不能超过100mb',
              icon: 'none'
            });
          }
          
          let data = {};
          data[fileType] = {
            url,
            size,
            name
          };
          
          let msg = await this.beforeSendMsg(data,false)
          // console.log('~~~beforeSendMsg',msg);
          try{
            const result = await uniCloud.uploadFile({
              filePath: tempFile.path,
              cloudPath: Date.now() + uniCloud.getCurrentUserInfo().uid + '.' + name.split('.').pop(),
            });
            // console.log('result.fileID',result.fileID);
            msg.body.url = result.fileID
            await this.updateMsg(msg)
            this.sendMsg(msg)
          }catch(e){
            console.error(777,e)
          }
          
        });
      },
      async chooseFileSendMsg(type,_config={}) {
        // console.log('type',type);
        //先创建发送消息的
        let objFn = {
          'image':()=>{
            uni.chooseImage({
            	// count:9,
              crop:{
                "quality":100,
                "width":800,
                "height":800
              },
            	// sourceType,
            	// extension,
            	success:res=> beforeUploadFileAndSendMsg(res,'image'),
            	"fail":alertFail
            });
          },
          'video':()=>{
            uni.chooseVideo({
              sourceType: ['camera', 'album'],
              success:res=> beforeUploadFileAndSendMsg(res,'video'),
              "fail":alertFail
            });
          },
          'all':()=>{
            let chooseFile = uni.chooseFile;
            // #ifdef MP-WEIXIN
            chooseFile = wx.chooseMedia;
            // #endif
            chooseFile({
            	type: 'all',
            	// count:10,
              sourceType:['album','camera'],
            	"success":this.uploadFileAndSendMsg,
            	"fail":alertFail
            })
          }
        };
        objFn[type]();
        
        const _this = this;
        function beforeUploadFileAndSendMsg(res,fileType){
          // console.log(111,res)
          // 视频只能选择单文件,为了参数统一,这里转成数组
          if(fileType == 'video'){
            // #ifndef H5
            res.tempFile = {
              size: res.size,
              width: res.width,
              height: res.height
            }
            // #endif
            res.tempFile.path = res.tempFilePath
            res.tempFiles = [res.tempFile]
          }
          res.tempFiles.forEach(item=>{
            //如果没有type,默认为:用户选择的类型
            if(!item.fileType){
              item.fileType = fileType
            }
            // 如果没有name,默认为:用户id+随机数+时间戳生成一个
            if(!item.name){
             item.name = _this.current_uid + Math.random().toString(36).substr(2) + Date.now()
            }
          })
          // console.log(222,res)
          _this.uploadFileAndSendMsg(res)
        }
        function alertFail(res){
          console.error('res',res);
          // uni.showModal({
          //   content: JSON.stringify(res),
          //   showCancel: false
          // });
        }
        
      },
      hideKeyboard() {
        // console.log('hideKeyboard');
        uni.hideKeyboard();
        this.$nextTick(() => {
          this.menuIsShow = false
          this.emojiIsShow = false
          this.isFocus = false
        })
      },
      onInput(e) {
        // console.log('onInput',e);
        // 记录按下@之后的内容
        const enterText = this.isWidescreen ? e.data : e.detail.value[e.detail.cursor - 1]
        // console.log('enterText',enterText);
        if(this.showAboutUidBox && enterText && enterText != '@'){
          setTimeout(()=>{
            // 输入法正在输入中
            let isComposing = false
            // #ifdef H5
            isComposing = this.isWidescreen ? document.querySelector('#uni-im-chat-input').isComposing : e.isComposing
            // #endif
            if (isComposing) {
              console.log('输入法正在输入中')
            }else{
              this.aboutUserKeyword += enterText
            }
          },0)
        }else{
          this.aboutUserKeyword = ""
        }
        
        // 非宽屏设备 && 非Android端 一旦输入换行符直接发送消息
        if (!this.isWidescreen && this.systemInfo.platform != 'android' && this.chatInputContent && this.chatInputContent.indexOf('\n') >= 0) {
          e.preventDefault() // 阻止换行,TODO:视乎并没有阻止住
          // console.log("有\n",this.chatInputContent, this.chatInputContent.length);
          this.beforeSendMsg()
        }
      },
      sendSound(e) {
        // console.log('sendSound',e);
        this.beforeSendMsg({
          sound: e
        })
      },
      async setAnswerMsg(msgId) {
        this.answerMsg = this.conversation.msgList.find(msg => msg._id == msgId)
        this.isFocus = true
      },
      async chatInputConfirm() {
        if(this.showAboutUidBox && this.memberList.length){
          console.log('正在执行选中要@的人,不发送数据')
          return
        }
        if (typeof this.chatInputContent == 'object'){
          // 富文本(图文混排、@某人)消息
          
          // 把字符串中带url的链接转为html的a标签的形式。1.将字符串,按是否为标签,切割为数组
          const htmlStr = this.chatInputContent.html.split(/(<[^>]+>)/)
                  // 2.找到不以<开头的字符串内的url并替换为 html的a
                  .map(str=>str.startsWith('<') ? str : uniIm.utils.replaceUrlToLink(str))
                  .join(' ')
          
          // 先插到消息列表
          let msg = await this.beforeSendMsg({
            "rich-text":uniIm.utils.parseHtml(htmlStr)
          },false)
          
          // 上传消息中的图片
          let promiseArr = []
          msg.body.forEach(async item=>{
            if(item.type === 'text'){
              item.text = item.text.trim();
            }else if(item.name === 'img' && item.attrs.src.indexOf('data:image/png;base64,') === 0){
              promiseArr.push(new Promise((resolve,reject)=>{
                uniCloud.uploadFile({
                  filePath: item.attrs.src,
                  cloudPath: Date.now() + uniCloud.getCurrentUserInfo().uid + '.' + name.split('.').pop(),
                }).then(res=>{
                  item.attrs.src = res.fileID
                  // console.log('上传成功',res);
                  resolve()
                }).catch(e=>{
                  console.error(777,e,item.attrs.src);
                  reject()
                })
              }))
            }
          })
          await Promise.all(promiseArr)
          
          // console.log('msg',msg);
          
          // 传完更新
          await this.updateMsg(msg)
          // 执行发送
          this.sendMsg(msg)
        }else{
          // 把this.chatInputContent中的&nbsp;变成空格,再把头尾的空格去掉
          this.chatInputContent = this.chatInputContent.replace(/&nbsp;/g, ' ').trim()
          // 普通消息
          await this.beforeSendMsg()
        }
      },
      async beforeSendMsg(param = {},_continue = true) {
        // console.log('beforeSendMsg',{param});
        let msg = {
          type: 'text',
          to_uid: this.conversation.friend_uid,
          conversation_id: this.conversation.id,
          group_id: this.conversation.group_id,
          client_create_time: Date.now(),
          from_uid: uniCloud.getCurrentUserInfo().uid,
          state: 0,
          body: this.chatInputContent
        }
        // 根据传入的参数设置消息类型和内容
        for (let key in param) {
          if (param[key]) {
            msg.type = key
            msg.body = JSON.parse(JSON.stringify(param[key]))
          }
        }
        // 如果是文本类型需要做一些处理
        if (msg.type === 'text') {
          //清除空格
          msg.body = msg.body.trim();
          // 阻止发送空消息
          if (!msg.body.length) {
            this.$nextTick(() => {
              this.chatInputContent = '';
              this.textareaHeight = 26;
            });
            return uni.showToast({
              title: '不能发送空消息',
              icon: 'none'
            });
          }
          
          // 如果包含\u200b@\u200b 则转为富文本消息
          if (msg.body.includes('\u200b@\u200b')) {
            msg.type = 'rich-text'
            // 把msg.body转成富文本消息;tmpBody按照\u200b@\u200b分割成数组,再按照\u2009分割成数组
            let tmpBody = msg.body
            msg.body = []
            tmpBody.split('\u200b@').forEach(str => {
              str.split('\u2009').forEach(item=>{
                if(item.includes('\u200b')){
                  const nickname = item.replace('\u200b','')
                  let user_id = false
                  for (let uid in this.group_member) {
                    if(this.group_member[uid].users.nickname == nickname){
                      user_id = uid
                      break
                    }
                  }
                  msg.body.push({
                      "name": "span",
                      "attrs": {
                        "class": "nickname",
                        user_id,
                      }
                  })
                }else{
                  msg.body.push({
                    type: 'text',
                    text: item
                  })
                }
              })
            })
          }
        }
        
        this.$nextTick(e => {
          this.chatInputContent = '';
          this.textareaHeight = 26;
          this.answerMsg = false
        });

        //如果是回复某一条消息,需要带上相关id
        if (this.answerMsg !== false) {
          msg.about_msg_id = this.answerMsg._id
        }

        // 消息列表追加此消息。此时消息状态值为0,表示发送中
        let resMsg = this.conversation.msgList.push(msg)

        this.$nextTick(() => {
          this.showLast()
          // #ifdef APP-NVUE
          // 临时方案:解决偶发nvue下不能滚动到最后一条消息的问题
          setTimeout(() => {
            this.showLast()
          }, 800)
          // #endif
        })
        msg.state = 0
        // console.error('sendMsg-sendMsg-sendMsg', msg);
        // 存到本地数据库
        await this.conversation.msgManager.localMsg.add(msg)
        // console.log('msg被localMsg.add引用 会新增一个unique_id',msg)
        if(_continue){
          this.sendMsg(msg);
        }else{
          return msg;
        }
      },
      getCallUid(param){
        let aboutNicknameList = []
        if( this.isWidescreen){
          // #ifdef H5
          if(typeof param === 'object'){
            let tmpDom = document.createElement('div')
            tmpDom.innerHTML = param.html
            let nicknameDomList = tmpDom.querySelectorAll('.nickname');
            for (let i = 0; i < nicknameDomList.length; i++) {
              aboutNicknameList.push(nicknameDomList[i].innerText.substring(1))
            }
          }
          // #endif
        }else{
          // 获取所有@的用户昵称
          aboutNicknameList = param.split('\u200b@\u200b').filter(str => str.includes('\u2009')).map(
            str => {
              let index = str.indexOf('\u2009')
              return str.slice(0, index)
            })
        }
        // console.log('aboutNicknameList',aboutNicknameList);
        
        let ids = []
        aboutNicknameList.forEach(nickname => {
          for (let uid in this.group_member) {
            if (this.group_member[uid].users.nickname == nickname) {
              ids.push(uid)
            }
          }
        })
        // console.log('ids',ids);
        return ids
      },
      sendMsg(msg, callback) {
1235 1236 1237 1238
        if(this.conversation.source){
          msg.chat_source = this.conversation.source
        }
        
DCloud_JSON's avatar
DCloud_JSON 已提交
1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853
        // console.log('sendMsg-sendMsg-sendMsg', msg);
        const uniImCo = uniCloud.importObject('uni-im-co', {
          customUI: true
        });
        // 接收消息的appId,默认为当前应用的appId。如果你是2个不同appId的应用相互发,请修改此值为相对的appId
        msg.appId = this.systemInfo.appId
        // 拿到当前消息的索引值
        let index = this.conversation.msgList.findIndex(i => i.unique_id == msg.unique_id)
        // 生成新对象,否则不触发更新
        msg = Object.assign({}, msg)
        uniImCo.sendMsg(msg)
          .then(async e => {
            // console.log('uniImCo.sendMsg',{e,msg});
            msg.state = e.errCode === 0 ? 100 : -100;
            msg.create_time = e.data.create_time;
            msg._id = e.data._id;
            await this.updateMsg(msg)
          })
          .catch(async e => {
            uni.showModal({
              content: e.message,
              showCancel: false,
              confirmText: '关闭',
            });
            console.error('uniImCo.sendMsg error:', e.errCode, e.message);
            // 必须要有create_time的值,否则indexDB通过创建时间索引找不到数据
            msg.create_time = Date.now();
            msg.state = -200;
            await this.updateMsg(msg)
          })
          .finally(e => {
            if (callback) {
              callback(e);
            }
          });
      },
      // 更新消息
      async updateMsg(msg){
        if(!msg.conversation_id){
          throw 'msg.conversation_id不能为空'
        }
        if(!msg.unique_id){
          throw 'msg.unique_id不能为空'
        }
        let conversation = await uniIm.conversation.get(msg.conversation_id)
        let index = conversation.msgList.findIndex(_msg => _msg.unique_id == msg.unique_id)
        if(index === -1){
          throw 'updateMsg msg 不存在'
        }

        /* TODO: splice 更新方式会把原本的 msg 对象从数组中踢出,导致已经渲染的消息组件无法响应后续的变更(比如 read_msg),
          所以这里使用 merge 更新方式,虽然此方式在 vue2 中有问题。*/
        let oldMsg = conversation.msgList[index]
        Object.assign(oldMsg, msg)
        // conversation.msgList.splice(index, 1, msg)

        conversation.msgManager.localMsg.update(msg.unique_id, msg)
        // console.log('change after',conversation.msgList[index]);
      },
      retriesSendMsg(msg) {
        uni.showLoading({
          mask: true
        });
        // console.log('retriesSendMsg', msg);
        msg.isRetries = true
        this.sendMsg(msg, e => {
          uni.hideLoading();
        });
      },
      showLast(duration = 300) {
        let msgListRef = this.$refs['msg-list']
        if (msgListRef) {
          msgListRef.showLast(duration)
        }
      },
      setCallAboutUidBefore(uid){
        // 当前输入框已经@了的用户id 要过滤掉
        let callUidList = this.getCallUid(this.chatInputContent)
        if(callUidList.includes(uid)){
          console.log('此用户id已经@过');
          uni.showToast({
            title: '此用户已经@过',
            icon: 'none'
          });
        }else{
          this.setCallAboutUid(uid)
        }
      },
      setCallAboutUid(uid) {
        // 替换光标位置到左边最后一个@符号数据 为: \u200b@\u200b + nickname
        // 光标位置到左边最后一个@符号的位置
        const nickname = this.group_member[uid].users.nickname
        if(this.isWidescreen){
          // #ifdef H5
          // web 宽屏设备
          const callString = `<span class="nickname" user_id="${uid}" contenteditable="false">@${nickname}</span>\u2009`
          if(this.showAboutUidBox){
            this.$refs["chat-input"]?.deleteLeftChar(1 + this.aboutUserKeyword.length)
          }
          // 在光标位置插入@昵称
          this.$refs["chat-input"]?.addHtmlToCursor(callString)
          // TODO:解决在消息列表中的@昵称点击事件,确弹出了选择@成员列表的问题
          this.$nextTick(()=>this.showAboutUidBox = false)
          // #endif
        }else{
          // 窄屏设备
          const callString = `\u200b@\u200b${nickname}\u2009`
          // 找到从光标位置到左边的@符号的位置
          const atCharIndex = this.chatInputContent.slice(0,currentCursor+1).lastIndexOf('@')
          // console.log('this.chatInputContent.slice(0,currentCursor)',this.chatInputContent.slice(0,currentCursor+1))
          // console.log('atCharIndex',atCharIndex);
          // console.log('this.chatInputContent',this.chatInputContent);
          if(atCharIndex == -1){
            console.error('没有找到@符号');
          }
          // 获取焦点
          this.isFocus = true
          // 删除在选用户时敲的字符和@符号
          const newchatInputContent = this.chatInputContent.slice(0, atCharIndex) + callString + this.chatInputContent.slice(currentCursor+1)
          // 光标位置移到@昵称的后面
          const newCursor = atCharIndex + callString.length
          // console.log('newchatInputContent',newchatInputContent);
          // console.log('newCursor',newCursor);
          this.setChatInputContent(newchatInputContent,newCursor)
        }
        // 关闭@成员列表
        this.showAboutUidBox = false
      },
      linechange(e) {
        //console.log(e.detail);
        let {
          height,
          lineCount
        } = e.detail;
        // console.log(height,lineCount);
        if (lineCount === 1) {
          this.textareaHeight = 26;
        } else if (height <= 100) {
          this.textareaHeight = height - 2;
        }
      },
      async showControl({
        msgId,
        msgContentDomInfo
      }) {
        const msg = this.conversation.msgList.find(msg => msg._id === msgId)
        let isSelf = msg.from_uid == uniCloud.getCurrentUserInfo().uid
        this.$refs['msg-popup-control'].show({isSelf,msg,msgContentDomInfo})
        
        /*
        let controlData = {
          msg,
          isInTop: false
        };

        let metrics = uniIm.utils.getScreenMetrics()
        if (isSelf) {
          controlData.left = 'unset'
          controlData.right = metrics.pageWidth - msgContentDomInfo.right
        } else {
          controlData.left = msgContentDomInfo.left + msgContentDomInfo.width / 2
          controlData.right = 'unset'
        }
        
        controlData.isInTop = msgContentDomInfo.top > 60
        
        if (controlData.isInTop) {
          // #ifdef H5
          let n = -20
          // #endif
          // #ifndef H5
          let n = -65
          // #endif
          controlData.top = msgContentDomInfo.top + n
        } else {
          // #ifdef APP
          let n = 8
          // #endif
          // #ifdef H5
          let n = 55
          // #endif
          // #ifdef MP
          let n = 10
          // #endif
          controlData.top = msgContentDomInfo.bottom + n
        }
        
        console.log('msgContentDomInfo',msgContentDomInfo)
        controlData.msgWidth = msgContentDomInfo.width
        this.$refs['msg-popup-control'].show(controlData)
        */
      },
      shareMsg(msgList,merge = false) {
        this.$refs['share-msg'].open(msgList,merge)
      },
      toolBarNext(){
        uni.showToast({
          title: '暂不支持',
          icon: 'none',
          duration: 2000
        });
        this.chooseMoreMsg = false
      },
      clickMenu(index, e) {
        // console.log('clickMenu-',index);
        if (index < 2) {
          this.chooseFileSendMsg(index === 0 ? 'image' : 'video')
        }
        if (index === 2) {
          // #ifdef APP-NVUE
          return uni.showToast({
            title: '暂不支持,发送文件',
            icon: 'none'
          });
          // #endif
          this.chooseFileSendMsg('all')
        }
        e.stopPropagation()
      },
      clickEmojiItem(emojiUniCode, e) {
        this.chatInputContent += emojiUniCode
        e.stopPropagation()
      },
      tapUnreadCount() {
        //点击未读消息文字按钮事件
        if (this.isWidescreen) {
          // this.$emit('tapUnreadCount') //点击后会话列表自动滚动 置顶 待读项
          // console.log('tapUnreadCount');
        } else {
          uni.navigateBack();
        }
      },
      updateNavTitle(){
        this.navTitle = this.conversation.title
        if (this.conversation.group_id) {
          this.navTitle += '(' + Object.keys(this.conversation.group_member).length + ")";
        }
      }
    },
    onNavigationBarButtonTap(e) {
      if (e.index === 0) {
        if (this.conversation.group_id) {
          uni.navigateTo({
            url: "/uni_modules/uni-im/pages/group/info?conversation_id=" + this.conversation.id
          })
        } else {
          // console.log(this.conversation,6565);
          uni.navigateTo({
            url: `/uni_modules/uni-im/pages/chat/info?user_id=${this.conversation.friend_uid}&conversation_id=${this.conversation.id}`
          })
          // uni.showToast({
          // 	title: '仅群里可见,详细信息',
          // 	icon: 'none'
          // });
        }
      }
      // uni.navigateBack();
    }
  };
</script>

<style lang="scss" scoped>
  /* #ifndef APP-NVUE */
  view {
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
  }

  page {
    background-color: #efefef;
  }

  /* #endif */

  .page {
    /* #ifdef APP-NVUE */
    flex: 1;
    /* #endif */

    /* #ifndef APP-NVUE */
    height: calc(100vh - 45px);
    /* #endif */

    /* #ifndef APP-NVUE */
    background-color: #efefef;
    /* #endif */
    // border: solid 5px #2faf4c;
  }

  .chat-foot,.disable-input{
    flex-direction: column;
    border-top: 1rpx solid #BBBBBB;
    background-color: #F7F7F7;
    width: 750rpx;

    position: fixed;
    bottom: 0;

    /* #ifndef APP-NVUE */
    z-index: 9;
    // overflow: hidden;
    /* #endif */
  }
  
  .disable-input{
    padding: 20px;
    text-align: center;
    justify-content: center;
    color: #777777;
  }

  /* #ifdef H5 */
  .pc {
    // .pc内的元素只有pc端打开才显示,样式在index页面
    display: none;
  }
  
  .vue-codemirror {
    position: fixed;
    top: 100px;
    left: 50%;
    width: 500px;
  }

  /* #endif */

  /* #ifdef H5 */
  .chat-foot {
    border: none;
  }

  /* #endif */

  /* #ifndef APP-NVUE */
  .chat-foot * {
    //	border: solid 1px red;
  }

  /* #endif */
  .textarea-box {
    background-color: #ffffff;
    padding: 10px;
    width: 450rpx;
    border-radius: 10px;
  }

  .textarea {
    width: 400rpx;
    padding: 0;
    background-color: #ffffff;
    color: #666666;
    //padding: 20rpx;
    font-size: 32rpx;
  }

  .tip-view {
    position: fixed;
    top: 100px;
    width: 750rpx;
    align-items: center;
    color: #999999;
  }

  .tip-null-msg {
    color: #999999;
    font-size: 14px;
  }

  .beforeSendMsg {
    color: #ffffff;
    font-size: 24rpx;
    border-radius: 6px;
    background-color: #2faf4c;
    // width: 80rpx;
    height: 28px;
    line-height: 28px;
    text-align: center;
  }

  .icon {
    width: 70rpx;
    justify-content: center;
    align-items: center;
  }

  .loadMore {
    line-height: 80rpx;
    height: 80rpx;
    text-align: center;
    width: 750rpx;
    color: #adb3b7;
    font-size: 12px;
  }

  /* #ifndef APP-NVUE */
  .unread_count {
    position: absolute;
    top: -35px;
    left: 70rpx;
    z-index: 999;
    background-color: #dfe2e9;
    padding: 0 14rpx;
    height: 14px;
    line-height: 14px;
    border-radius: 9px;
    color: #0c1013;
    font-size: 12px;
    margin-top: 3px;
  }

  /* #endif */

  .input-box {
    flex-direction: row;
    padding: 10rpx 18rpx;
    justify-content: space-around;
    align-items: center;
  }

  .menu {
    padding: 36rpx;
    width: 750rpx;
    border-top: solid 1px #ededed;
    flex-direction: row;
    flex-wrap: wrap;
  }

  .menu-item,
  .menu-item-icon {
    width: 160rpx;
    height: 160rpx;
    justify-content: space-around;
    align-items: center;
  }

  .menu-item-icon {
    width: 80rpx;
    height: 80rpx;
    background-color: #ffffff;
    color: #6F6F6F;
    border-radius: 10px;
  }

  .menu-item-text {
    font-size: 12px;
  }

  .emojiListBox {
    width: 750rpx;
    padding: 27rpx;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: space-between;
  }

  .emoji-item {
    text-align: center;
    font-size: 65rpx;
    width: 87rpx;
    height: 87rpx;
    justify-content: center;
    align-items: center;
    /* #ifndef APP-NVUE */
    display: inline-block;
    /* #endif */
  }

  .uni-im-sound {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 999;
  }

  .answer-msg {
    width: 450rpx;
    padding: 2px 5px;
    margin: 5px 0 3px 0;
    background-color: #efefef;
    color: #6a6a6a;
    border-radius: 5px;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
  }
  
  /* #ifdef H5 */
  .answer-msg ::v-deep .uni-icons {
    cursor: pointer;
  }
  /* #endif */

  .answer-msg-text {
    /* #ifndef APP-NVUE */
    white-space: nowrap;
    overflow: hidden;
    /* #endif */
    lines: 2;
    text-overflow: ellipsis;
    font-size: 12px;
  }

  /* #ifdef H5 */
  .send-btn-box {
    flex-direction: row;
    justify-content: end;
    padding: 0 10px 10px 0;
    margin-top: 5px;
  }

  .send-btn-box .send {
    font-size: 12px;
    padding: 0 20px;
  }

  .send-btn-box .send-btn-tip {
    color: #919396;
    margin-right: 8px;
    font-size: 12px;
    line-height: 28px;
  }

  /* #endif */

  .member-list {
    position: fixed;
    width: 500rpx;
    height: 200px;
    bottom: 100px;
    left: 125rpx;
    z-index: 9999;
    background-color: #ffffff;
    
    overflow: hidden;
    border-radius: 15px;
    box-shadow: 0 0 100px rgba(0, 0, 0, 0.2);
  }
  .member-list-item {
    overflow: hidden;
    height: 40px;
    font-size: 14px;
    line-height: 40px;
    padding-left: 15px;
    border-radius: 10px;
    width: 500rpx;
    margin: 5px;
    /* 解决css特殊情况下 margin 重叠的问题 */
    margin-bottom: 10px;
    text-align: left;
  }

  .member-list-item-active {
    background-color: #efefef;
  }

  .member-list-mark {
    position: fixed;
    top: 0;
    left: 0;
    width: 750rpx;
    flex: 1;
    height: 9000px;
    /* #ifndef APP-NVUE */
    width: 100vw !important;
    height: 100vh !important;
    z-index: 9998;
    /* #endif */
    background-color: rgba(0, 0, 0, 0.1);
  }
  
  /* #ifdef H5 */
  @media screen and (min-device-width:960px){
    .member-list {
      width: 260px;
      left: auto;
      right: calc(50vw - 300px);
      bottom: 300px;
    }
    .member-list-item {
      width: 250px;
      cursor: pointer;
    }
  }
  /* #endif */
  
  .toolbar{
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 260px;
    background-color: #ededed;
    border-top: solid 1px #ededed;
    flex-direction: row;
    justify-content: space-around;
    align-items: center;
    z-index: 999;
  }
  .toolbar .item {
    align-items: center;
  }
  /* #ifdef H5 */
  .toolbar ::v-deep .uni-icons {
    cursor: pointer;
  }
  /* #endif */
  .toolbar .icons-box {
    background-color: #fff;
    justify-content: center;
    width: 60px;
    height: 60px;
    border-radius: 100px;
    margin-bottom: 10px;
  }
1854 1855 1856 1857 1858 1859 1860 1861
  
  .camera-filled-box {
    background-color: #3b81fd;
    justify-content: center;
    width: 26px;
    height: 26px;
    border-radius: 100px;
  }
DCloud_JSON's avatar
DCloud_JSON 已提交
1862
</style>