Im.vue 7.67 KB
<template>
  <div id="chat">
    <div class="chatBox">
      <div class="chatBox-middle">
        <div class="chatInfo" id="chatInfo">
          <div class="chatUser-box">
            <div class="chatUser-info">
              <span class="chatUser-info-text notice">
                <img class="icon-notice" src="@/assets/images/icon-notice.png" />
                欢迎来到直播间!
                <p>{{ notifyTxt }}</p>
              </span>
            </div>
          </div>
          <div class="chatUser-box" v-for="(item, index) in messageList" :key="index">
            <div class="chatUser-info">
              <span class="chatUser-info-text">
                <span class="chatUser-info-name">{{ item.userName }}:</span>
                <span>{{ item.content }}</span>
              </span>
            </div>
          </div>
        </div>
      </div>
      <div class="chatBox-infoDesk" action="javascript:return true">
        <van-field :class="['chatBox-input', isFocus ? 'focus-input' : '']" v-model="messageContent" maxlength="200" center placeholder="聊一聊..." use-button-slot @click="fixInputBeCovered($event)" @focus="handleInputFocus" @blur="handleInputFocus">
          <img class="icon-send" slot="button" @click="sendTextMessage" src="@/assets/images/send.png" />
        </van-field>
        <action :videoFullscreen="true" class="action" v-show="isAction && !isFocus" :isImAction="true"></action>
      </div>
    </div>
  </div>
</template>
<script>
import { Notify } from 'vant'
import { util } from 'utils'
import { shopmallApi } from '@/api'
import IM from './im.js'
let timObj = null
const msgMaxNum = 100

export default {
  name: 'Im',
  data() {
    return {
      isFocus: false,
      notifyTxt: '直播间内严禁出现违法违规、低俗、涉黄、吸烟酗酒等内容,直播期间请勿相信私下交易,诱导购买等信息,以防人身或财产损失。请大家注意财产安全,谨防网络诈骗,文明观看直播。',
      messageContent: '',
      messageList: []
    }
  },
  props: {
    detail: {
      type: Object,
      default: () => { }
    },
    liveDetail: {
      type: Object,
      default: () => {
        return {
          imGroupId: '',
          imSdkAppId: ''
        }
      }
    },
    isAction: {
      type: Boolean,
      default: false
    }
  },
  computed: {},
  created() {
    this.getUserSig()
    this.scrollToBottom()
  },
  updated() {
    this.scrollToBottom()
  },
  mounted() { },
  beforeDestroy() {
    timObj.quit()
  },
  methods: {
    fixInputBeCovered({ target }) {
      setTimeout(function () {
        target.scrollIntoView(true)
      }, 100)
    },
    handleInputFocus() {
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.isFocus = !this.isFocus
      }, 300)
    },
    getUserSig() {
      const userInfo = util.getUserInfo()
      const userId = userInfo.openid || userInfo.uuid
      // const userId = userInfo.nickName || userInfo.userName
      const params = this.getLocalStorage('wx_scrm_link_params') || {}
      // sourceShopId-来源门店;visitSource-访问来源;bizType-业务类型(0-众筹);bizCode-业务标识(众筹-活动ID)
      const obj = {
        userId: userId,
        sourceShopId: params.merchantId || '',
        visitSource: 'H5-众筹',
        bizType: 0,
        bizCode: this.detail.id
      }
      shopmallApi.getLiveSig(obj).then(res => {
        this.userSig = res.userSig
        this.initTim()
      })
    },
    initTim() {
      const userInfo = util.getUserInfo()
      const imOptions = {
        userID: userInfo.openid || userInfo.uuid,
        userSig: this.userSig,
        groupID: this.liveDetail.imGroupId,
        SDKAppID: this.liveDetail.imSdkAppId,
        onMessageReceived: this.onMessageReceived,
        onNetStateChange: this.onNetStateChange
      }
      timObj = new IM(imOptions)
      timObj.join(imOptions).then(res => {
        // console.log('login-------')
        timObj.updateMyProfile({ nick: userInfo.nickName })
      })
    },
    // 收到消息触发
    onMessageReceived(data) {
      // console.log('收到消息:', data)
      let msgLen = this.messageList.length
      let dataLen = data.length
      if (msgLen + dataLen > msgMaxNum) {
        this.messageList = this.messageList.slice(msgLen - dataLen)
      }
      data.forEach(item => {
        // 根据消息类型判断,执行不同操作
        if (item.type == 'TIMTextElem') {
          // 群成员发送消息
          // let eleData = JSON.parse()
          let eleData = {
            userName: item.nick,
            content: item.payload.text
          }
          // 获取群聊消息,消息上屏
          this.updateMessageList(eleData)
        }
      })
    },
    // 网络异常处理
    onNetStateChange(notify) {
      Notify(notify)
    },
    // 更新数据push进消息列表
    updateMessageList(data) {
      this.messageList = [...this.messageList, data]
      this.scrollToBottom()
    },
    // changeChatHeight(height = '230px') {
    //   var chatBoxDom = this.$el.querySelector('.chatBox-middle')
    //   chatBoxDom.style.height = height
    //   this.scrollToBottom()
    // },
    // handleFocus() {
    //   this.changeChatHeight('116px')
    // },
    //发送聊天
    sendTextMessage() {
      // this.changeChatHeight()
      if (this.messageContent === '' || this.messageContent.trim().length === 0) {
        this.messageContent = ''
        return
      }
      // console.log(this.messageContent, '准备发咯--')
      timObj.send(this.messageContent)
      this.messageContent = ''
    },
    scrollToBottom() {
      this.$nextTick(() => {
        let container = this.$el.querySelector('#chatInfo')
        container.scrollTop = container.scrollHeight
      })
    }
  }
}
</script>
<style lang="scss" scoped>
html,
body {
  background-color: #e8e8e8;
  height: 100%;
}
#chat .chatBox {
  width: 100%;
  height: auto;
  margin: auto 0;
  border-radius: 0.625rem;
}
#chat .chatBox-middle {
  width: 100%;
  height: 230px;
  margin: 1.25rem auto;
  overflow: hidden;
}

#chat .chatBox-infoDesk {
  display: flex;
  margin: 0 10px 10px;
  .chatBox-input {
    width: 148px;
    // background-color: transparent;
    background-color: rgba(255, 255, 255, 0.4) !important;
    border-radius: 2rem !important;
    margin-right: 8px;
    padding: 0 0;
    color: #ffffff;
    .icon-send {
      width: 20px;
      height: 20px;
      margin-right: 10px;
    }
  }
  .chatBox-input.focus-input {
    width: 100%;
    transition: width 0.5s;
    .icon-send {
      border-radius: 50%;
    }
  }
  .action {
    width: calc(100% - 156px);
  }
}

#chat .chatInfo {
  width: 100%;
  height: 100%;
  overflow-y: scroll;
}
#chat .chatInfo::-webkit-scrollbar {
  width: 0 !important;
}

#chat .chatUser-box {
  width: 100%;
  margin-bottom: 3px;
  display: flex;
  flex-direction: row;
}
#chat .chatUser-info {
  margin: 0 10px;
  width: 65%;
  line-height: 22px;
  font-size: 12px;
}

#chat .chatUser-info-name {
  color: rgb(234, 201, 36);
  margin-right: 0.4rem;
  font-weight: 600;
}

#chat .chatUser-info-text {
  margin-top: 3px;
  padding: 2px 6px;
  font-size: 12px;
  background: rgba(0, 0, 0, 0.3);
  border-radius: 18px;
  color: #ffffff;
  float: left;
  table-layout: fixed;
  word-break: break-all;
  overflow: hidden;
  .icon-notice {
    width: 28px;
    height: 16px;
    vertical-align: middle;
  }
}

#chat .chatUser-info-text.notice {
  padding: 2px 3px 2px 6px;
}
</style>
<style>
#chat .chatBox-infoDesk .chatBox-input .van-field__control {
  /* background-color: rgba(255, 255, 255, 0.4) !important;
  border-radius: 2rem !important; */
  color: #ffffff;
  height: 40px;
  padding: 0 10px;
}
#chat .chatBox-infoDesk .van-cell::after {
  border: none;
}
</style>