import store from '../store'
const defaultFunc = () => {}
const Im = {
  socket: null,
  init(msgfunc = defaultFunc, openfunc = defaultFunc, options) {
    // let vm = this;
    if (window.WebSocket) {
      let url = options?.url || 'ws://192.168.1.114:8001'
      this.socket = new WebSocket(url)
      let socket = this.socket
      socket.onopen = () => {
        console.log('服务器连接成功')
        openfunc && openfunc()
      }
      socket.onclose = () => {
        console.log('服务器关闭')
        this.socket = null
      }
      socket.onerror = () => {
        console.log('连接出错')
        this.socket = null
      }
      // 接收服务器的消息
      socket.onmessage = (res) => {
        if (typeof res.data === 'string') {
          msgfunc && msgfunc(res.data)
        } else {
          let message = JSON.parse(res.data)
          if (message.users) {
            store.dispatch('setUsersStatus', message.users)
            return
          }
          if (message.groups) {
            // this.groups = message.groups;
            store.dispatch('setGroups', message.groups)
          }

          // 判断当前聊天对话框是否是消息所对应的用户 添加消息提示
          if (message.bridge) {
            let { uid, sessionList, activeIndex } = store.state.im
            let otheruid = message.bridge.find((v) => v !== uid)
            if (otheruid && sessionList[activeIndex].uid !== otheruid) {
              store.dispatch('setUnread', { otheruid, unread: true })
            }
          }
          msgfunc && msgfunc(message)
        }
      }
    }
  },
  send(options) {
    if (this.socket) {
      this.socket.send(JSON.stringify(options))
    }
  },
}
export default Im
