// global.js
import { sendMsg, getAdminId } from '@/api/login'
// 1.引入vue
import Vue from 'vue'
import store from './store'
import router from './router'
// 2.新创建一个vue实例
const v = new Vue()
export default {
  ws: {},
  websocket: '',
  setWs: function(newWs) {
    this.ws = newWs
  },
  whetherWebSocket: function() {
    var that =this
    if (store.getters.adminId!='') {
      if ('WebSocket' in window) {
        if (process.env.NODE_ENV === 'production') {
          that.websocket = new WebSocket('wss://www.zthymaoyi.com/wss/websocket/' + store.getters.adminId)
        }
        else {
          that.websocket = new WebSocket('ws://localhost:8080/websocket/' + store.getters.adminId)
        }
        that.initWebSocket()
      } else {
        alert('当前浏览器不支持websocket')
      }
    }
  },
  initWebSocket: function() {
    // 连接错误
    this.websocket.onerror =evt => {
      console.log('WebSocket连接发生错误   状态码：' + this.websocket.readyState)
    }
    // 连接成功
    this.websocket.onopen = evt => {
      console.log('WebSocket连接成功    状态码：' + this.websocket.readyState)
    }
    // 收到消息的回调
    this.websocket.onmessage = event => {
      // 根据服务器推送的消息做自己的业务处理
      console.log('服务端返回：' + event.data)
      var msg = event.data.split('$')
      var that = this
      // document.getElementsByClassName('app-container').reload()
      v.$notify.warning({
        title: '新消息提醒',
        message: msg[0],
        duration: 0,
        onClick() {
          router.push({
            path: msg[1] }) // 你要跳转的路由 还可以传参 当然也可以通过其他方式跳转
        }
      })
      // console.log(router)
      var currentPage = router.history.current.path
      console.log(currentPage, 'currentPage')
      router.push({ path: '/' })
      console.log('执行成功1')
      router.push({ path: currentPage,
        query: {
          params: Date()
        }})
      console.log('执行成功')
    }
    // 连接关闭的回调
    this.websocket.onclose = evt => {
      console.log('WebSocket连接关闭    状态码：' + this.websocket.readyState)
    }

    // 监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
    window.onbeforeunload = this.onbeforeunload
  }
}
