import store from '../store'
const WS = {
    $ws: null,
    type:"",
    // webscoket实例  
    wsUrl: 'ws://8.142.143.40:8885/websocket/1',
    // websocket链接地址       
    createWS: function (val) {
      this.type=val;
      console.log(this.type);
        if ('WebSocket' in window) {
            this.$ws = new WebSocket(this.wsUrl)
            this.$ws.onopen = this.wsOpen
            this.$ws.onmessage = this.wsMessage
            this.$ws.onerror = this.wsError
            this.$ws.onclose = this.wsClose
        } else {
            alert('当前浏览器不支持webSocket')
        }
    },
    wsOpen: function () {
        this.send(WS.type)
        console.log('== websocket open ==',"传值为" + WS.type)
        heartBeat.start()
    },
    wsMessage: function (msg) {
        // console.log( msg.data)
       
        heartBeat.reset()
        store.commit('websocket/SET_WS_MSG', msg.data)
    },
     wsError: function (err) { 
         console.log('== websocket error ==', err)
         }, 
         wsClose: function (event) {
              console.log('== websocket close ==', event)
             }
}
const heartBeat = {
    timeout: 30000, // 心跳重连时间  
    timeoutObj: null, // 定时器  
    reset: function () {
        clearInterval(this.timeoutObj)
        console.log('websocket 心跳')
        heartBeat.start()
    },
    start: function () {
        this.timeoutObj = setTimeout(function () {
            if (WS.$ws.readyState === 1) {
                WS.$ws.send('HeartBeat')
            }
        }, this.timeout)
    }
}
export default WS