import { ElMessage as message } from 'element-plus'
// import storage from 'store'
// import config from '@renderer/util/config.js'
const config = window.electron.readConfig();
let receiveMessage = null
import { reactive } from 'vue'
const socket = reactive({
  websocket: null,
  connectURL: config.swichWsUrl + '/ws/log',
  // 开启标识
  socket_open: false,
  // 心跳timer
  hearbeat_timer: null,
  // 心跳发送频率
  hearbeat_interval: 2 * 1000,
  // 是否自动重连
  is_reonnect: true,
  // 重连次数
  reconnect_count: 3,
  // 已发起重连次数
  reconnect_current: 1,
  // 重连timer
  reconnect_timer: null,
  // 重连频率
  reconnect_interval: 5 * 1000,
  init: (overrideReceiveMessage) => {
    if (overrideReceiveMessage) {
      receiveMessage = overrideReceiveMessage
    }
    if (!('WebSocket' in window)) {
      message.warning('浏览器不支持WebSocket')
      return null
    }
    socket.websocket = new WebSocket(socket.connectURL)
    socket.websocket.onmessage = (e) => {
      if (receiveMessage) {
        receiveMessage(e)
      }
    }
    socket.websocket.onclose = () => {
      console.log('socket连接关闭----------------------')
      socket.socket_open = false
      // 需要重新连接
      if (socket.is_reonnect) {
        socket.reconnect_timer = setTimeout(() => {
          // 超过重连次数
          if (socket.reconnect_current > socket.reconnect_count) {
            clearTimeout(socket.reconnect_timer)
            socket.is_reonnect = false
            return
          }
          console.log('socket重连次数：' + socket.reconnect_current)
          // 记录重连次数
          socket.reconnect_current++
          socket.reconnect()
        }, socket.reconnect_interval)
      }
    }
    // 连接成功
    socket.websocket.onopen = function () {
      socket.socket_open = true
      socket.is_reonnect = true
      // 开启心跳
      // socket.heartbeat()
    }
    // 连接发生错误
    socket.websocket.onerror = function () {}
  },
  heartbeat: () => {
    socket.hearbeat_timer && clearInterval(socket.hearbeat_timer)

    socket.hearbeat_timer = setInterval(() => {
      let data = {
        // token: storage.get('token')
      }
      socket.send(data)
    }, socket.hearbeat_interval)
  },
  send: (data, callback = null) => {
    // 开启状态直接发送
    if (socket.websocket.readyState === socket.websocket.OPEN) {
      socket.websocket.send(JSON.stringify(data))
      callback && callback()
    } else {
      clearInterval(socket.hearbeat_timer)
      message({
        type: 'warning',
        message: 'socket链接已断开',
        duration: 1000
      })
    }
  },
  close: () => {
    socket.is_reonnect = false
    socket.websocket.close()
  },
  /**
   * 重新连接
   */
  reconnect: () => {
    if (socket.websocket && !socket.is_reonnect) {
      socket.close()
    }
    socket.init(receiveMessage)
  }
})
export default socket
