websocket.js 4.56 KB

let websock = null
let websockInterval = null
const timer = 0
let notifyInterval = null
let messageList = [] // 消息队列
let lockReconnect = false
let heartTimeout = null

// 创建通知
function createNotify(options) {
  var PERMISSON_GRANTED = 'granted'
  //   var PERMISSON_DENIED = 'denied'
  //   var PERMISSON_DEFAULT = 'default'
  console.log(Notification.permission)
  if (Notification.permission == PERMISSON_GRANTED) {
    sendNotify(options)
  } else {
    Notification.requestPermission().then((res) => {
      if (res == PERMISSON_GRANTED) {
        sendNotify(options)
      }
    })
  }
}

// 消息弹框
function sendNotify(options) {
  // 如果有弹框未关闭,则把消息放进队列,暂时不弹
  options.id = Math.random()
  options.requireInteraction = true
  if (notifyInterval) {
    messageList.push(options)
    return false
  }
  generateNotification(options)
}

// 生成浏览器弹框
function generateNotification(options) {
  const notification = new Notification(options.title, {
    body: options.body,
    requireInteraction: options.requireInteraction
  })
  notifyInterval = Math.random()
  // notifyInterval = setInterval(function () {
  //   if (timer >= Number(options.time || 60)) {
  //     // clearInterval(notifyInterval)
  //     // timer = 0
  //     notification.close()
  //     return false
  //   }
  //   timer += 1
  // }, 1000)

  // 监听消息框展示
  notification.onshow = function() {
    console.log('开始时间', new Date().getTime())
    setTimeout(function() {
      console.log('时间到', new Date().getTime())
      notification.close()
    }, 60000)
  }

  // 监听消息框点击事件
  notification.onclick = function(event) {
    // event.preventDefault()
    if (options.openUrl) {
      // window.open(options.openUrl)
      window.location.href = options.openUrl
    }
  }

  // 监听消息框关闭
  notification.onclose = function(event) {
    // event.preventDefault()
    console.log('非正常结束时间', new Date().getTime())
    if (notifyInterval) {
      // clearInterval(notifyInterval)
      // timer = 0
      notifyInterval = null
    }

    // 关闭消息,从队列中删除对应的消息
    if (messageList && messageList.length) {
      messageList = messageList.filter(k => k.id != options.id)
    }
    console.log(messageList)
    // 如果队列中还有消息,则继续弹出下一条
    if (messageList[0]) {
      generateNotification(messageList[0])
    }
  }
}

// 初始化websocket
function initWebSocket(id) { // 初始化weosocket
  // ws地址 实例化socket,这里我把用户名传给了后台,使后台能判断要把消息发给哪个用户,其实也可以后台直接获取用户IP来判断并推送
  // const wsuri = 'ws://bhg.dev.glsx.com.cn/carservice/usercenter/websocket/'+this.$store.getters.navbarId;
  let _host = window.location.host
  const _hostName = window.location.hostname
  if (_hostName == 'localhost') {
    _host = 'bhg.dev.glsx.com.cn'
  }
  const wsuri = `wss://${_host}/carservice/usercenter/websocket/${id}`
  websock = new WebSocket(wsuri)
  websock.onmessage = function(e) {
    const obj = e.data ? JSON.parse(e.data) : {}
    const data = obj.data ? JSON.parse(obj.data) : {}
    console.log(data)

    if (data.contentType) {
      return false
    }

    createNotify({
      title: '审核提示',
      body: '您有新的待审核工单,请及时处理!',
      openUrl: `${window.location.origin}/#/order/verify?orderId=${data.orderId}&workOrderNo=${data.workOrderNo}`
    })

    // websocketonmessage(e);
  }
  websock.onclose = function(e) {
    // websocketclose(e);
    if (websockInterval) {
      clearInterval(websockInterval)
    }
  }
  websock.onopen = function() {
    keepHeart()
  }
  // 连接发生错误的回调方法
  websock.onerror = function() {
    console.log('WebSocket连接发生错误')
    reconnect()
  }
}

// 保持心跳
function keepHeart() {
  clearTimeout(heartTimeout)
  clearInterval(websockInterval)
  websockInterval = setInterval(function() {
    const msg = { content: 'keep live', contentType: 'heart' }
    websock.send(JSON.stringify(msg))
  }, 40000)
  heartTimeout = setTimeout(function() {
    if (websock.readyState != 1) {
      reconnect()
    }
  }, 3000)
}

// 重连
function reconnect() {
  // 如果状态等于1,表示websocket连接正常
  if (websock.readyState === 1) {
    return
  }
  // 阻止进入下一个循环
  if (lockReconnect) {
    return
  }
  lockReconnect = true
  setTimeout(function() {
    const userId = sessionStorage.getItem('userId')
    initWebSocket(userId)
  }, 5000)
}

export { initWebSocket }