import { wsServerUrl } from '@/settings'

const wsUrl = process.env.NODE_ENV === 'development' ? wsServerUrl.dev : wsServerUrl.pro

// 封装websocket对象
const WS = {
  $ws: null, // websocket实例
  wsParams: null,
  timeout: 30000, // 心跳重连时间
  timeoutObj: null, // 定时器
  lockReconnect: false, // 避免重复重连
  reconnectTimes: 0, // 重连次数

  // 初始化webSocket
  createWS: function(params) {
    if ('WebSocket' in window) {
      if (WS.wsParams === null) { WS.wsParams = params }
      this.$ws = new WebSocket(wsUrl)
      this.$ws.onopen = this.wsOpen
      this.$ws.onmessage = this.wsMessage
      this.$ws.onerror = this.wsError
      this.$ws.onclose = this.wsClose
    } else {
      alert('Current browser Not support websocket')
    }
  },

  // webSocket 打开
  wsOpen: function() {
    WS.$ws.send('Hello WebSockets!')
    // store.commit('SET_WS_CONNECT', true)
    console.log('== websocket open ==')
    // 开始心跳
    WS.wsStartHeart()
  },

  // 接收到服务器消息
  wsMessage: function(msg) {
    console.log('== websocket message ==', msg)
    if (WS.wsParams !== null) {
      WS.wsParams.getMessage(msg)
    }
    // 每次接收到服务端消息后 重置websocket心跳
    WS.wsReSet()
    // store.commit('SET_WS_MSG', msg.data)
  },

  // 发生错误
  wsError: function(err) {
    console.log('== websocket error ==', err)
    // 发生错误重连socket
    if (WS.reconnectTimes < 10) {
      WS.wsReconnect()
    }
  },

  // 关闭连接
  wsClose: function(event) {
    console.log('== websocket close ==', event)
    if (WS.$ws && WS.$ws.readyState === 1) {
      WS.$ws.close()
      // store.commit('SET_WS_CONNECT', false)
    }
    if (WS.reconnectTimes < 10) { // 设置重连次数为10次
      WS.wsReconnect()
    }
  },

  // 开始心跳
  wsStartHeart: function() {
    WS.timeoutObj && clearTimeout(WS.timeoutObj)
    WS.timeoutObj = setTimeout(function() {
      // 判断websocket当前状态
      if (WS.$ws.readyState === 1) {
        WS.$ws.send('HeartBeat')
      }
    }, WS.timeout)
  },

  // 重置心跳
  wsReSet: function() {
    clearTimeout(WS.timeoutObj)
    WS.wsStartHeart()
  },

  // 重连
  wsReconnect: function() {
    console.log('Reconnection Socket')
    if (WS.lockReconnect) return
    WS.reconnectTimes++
    WS.lockReconnect = true
    setTimeout(function() { // 没连接上会一直重连，设置延迟避免请求过多
      WS.createWS()
      WS.lockReconnect = false
    }, 6000)
  },

  // 销毁-close为服务自动关闭所以做了重连机制，此处为了区分
  wsDestroy() {
    WS.timeoutObj && clearTimeout(WS.timeoutObj)
    WS.reconnectTimes = 11
    WS.$ws.close()
  }
}

export default WS
