
let ws = false
let weboscket_callback = null
import { generateUUID } from './util'
import { showToast } from './feedback'

// 手动关闭 websocket
let closewebsocket = () => {
  console.log("关闭")
  ws = false;
  dd.offSocketOpen();
  dd.offSocketMessage();
  dd.offSocketError();
  dd.closeSocket();
  dd.offSocketClose();
}

let initWebSocket = (callback) => {
  //初始化 websocket
  
  dd.onSocketClose((res) => {
      // console.log(res);
  });

  // 打开
  dd.onSocketOpen((res) => {
    if(dd.globalData.token){
      let wsData = {
        type: 'auth',
        token: dd.globalData.token,
        machine: generateUUID()
      };
      sendSocketMessage(wsData)
    }
    ws = true;
    callback()
  });
  // 监听信息
  dd.onSocketMessage((res) => {
    let data = JSON.parse(res.data)
    if (data.type == "ping") {
      if (ws) {
        sendSocketMessage('续命')
      }
    }
    return weboscket_callback(data);
  })
  // 报错
  dd.onSocketError((res) => {
    showToast('服务器繁忙，请稍后再试！');
    return weboscket_callback({ type: 'error' })
    // opneWebSocket();
  });
  // 创建
  dd.connectSocket({
    url: 'wss://' + dd.globalData.webScoketUrl + '/ws/'
  });
}
// 发送消息
let sendSocketMessage = (message) => {
  dd.sendSocketMessage({
    data: JSON.stringify(message), // 需要发送的内容
    success: (res) => { },
  });
};

// 发送数据
let sendData = (data, callback) => {
  weboscket_callback = callback
  if (ws) {//周统计不需要验证
    sendSocketMessage(data);
  } else {
    initWebSocket(() => {
      sendData(data, callback);
    });
  }
}

// 导出
export {
  initWebSocket,
  sendData,
  closewebsocket
}
