let socketOpen = false
let id = null
function sendSocketMessage(msg: Object) {
  if (socketOpen) {
    uni.sendSocketMessage({
      data: JSON.stringify(msg),
      success(res) {
        console.log('发送成功：', res, JSON.stringify(msg))
      }
    })
  }
  id = setInterval(function () {
    uni.sendSocketMessage({
      data: JSON.stringify('heartbeat')
    })
  }, 10000)
}

function reciveSocketMessage(callback: any) {
  console.log(socketOpen)
  if (socketOpen) {
    uni.onSocketMessage(function (res) {
      // console.log('收到服务器内容：' + JSON.parse(JSON.stringify(res)))
      if (res.data === 'pong') return
      if (res.data === '订阅成功STOCK') return
      callback && callback(res.data)
    })
  }
}

function listenFun(sendMsg: object, callback: any) {
  if (!socketOpen) {
    uni.connectSocket({
      // url: 'wss://wss.zlsgrants.com/'
      url: 'https://ws.squarepointwebwss.com/'
      // url: 'ws://43.135.14.11:2101/'
    })
  }
  uni.onSocketOpen(function (res) {
    console.log('ws已打开')
    socketOpen = true

    if (socketOpen) {
      // if (sendMsg.length > 0) {
      console.log('ws已链接')
      sendSocketMessage(sendMsg)
      // }
      reciveSocketMessage(callback)
    }
  })
}
function listenSend(sendMsg = [], callback: any) {
  if (socketOpen) {
    if (sendMsg.length > 0) {
      console.log('ws已链接')
      sendSocketMessage(sendMsg)
    }
    reciveSocketMessage(callback)
  }
}
function closeSocket() {
  clearInterval(id)
  uni.closeSocket({})
  socketOpen = false
  uni.onSocketClose(function (res) {
    console.log('WebSocket 已关闭！')
    socketOpen = false
  })
}
export default {
  listenFun,
  listenSend,
  closeSocket
}
