import store from '@/store'
import { notification } from 'ant-design-vue'

export default class SocketService {
  static webSocket = null
  static reConnectTimeout = 1000
  static init() {
    const token = sessionStorage.getItem('Access-Token') || localStorage.getItem('Access-Token')
    const ws = new WebSocket(`${process.env.VUE_APP_WEBSOCKET}?token=${token}`)

    this.reConnectTimeout = 1000
    ws.onmessage = this.onmessage
    ws.onerror = this.onerror
    ws.onclose = this.onclose
    ws.onopen = this.onopen

    this.webSocket = ws

    store.commit('SET_WEBSOCKET', ws)

    return ws
  }

  static onclose() {
    console.info('连接关闭')
  }

  static onopen() {
    console.info('连接建立')
  }

  static onerror() {
    console.info('连接发生错误')
    store.commit('SET_WEBSOCKET', null)
  }

  static reconnect() {
    this.webSocket = null
    setTimeout(() => {
      console.info('reconnect at ', new Date())
      this.init(store.getters.userInfo.id)
      this.reConnectTimeout = this.reConnectTimeout + 5000
    }, this.reConnectTimeout)
  }



  static onmessage(e) {
    const { data } = e
    if (data == '1' || data == '2') {
      const message = data == '1' ? '用户已支付，请派单' : '用户已支付'
      notification.open({
        message: '消息提醒',
        description: message,
        key: 'orderNotification',
        btn: h => {
          return h(
            'a-button',
            {
              props: {
                type: 'primary',
                size: 'small',
              },
              on: {
                click: () => this.$notification.close('orderNotification'),
              },
            },
            '确定',
          );
        },
      });
    }
  }
}


// 心跳检测
// eslint-disable-next-line no-unused-vars
const heartCheck = {
  interval: 60000,
  intervalObj: null,
  start: function () {
    console.log('start heart check');
    this.intervalObj && clearInterval(this.intervalObj);
    this.intervalObj = setInterval(function () {
      //发送测试信息，后端收到后，返回一个消息，
      console.info('heart beat check')
      SocketService.webSocket.send('hello');
    }, this.interval)
  }
}