var websock = null;
var global_callback = null;
//webSocket连接端口
var serverPort = '10086';

/**
 * 初始化weosocket
 */
function initWebSocket() {
  //ws地址
  //本地连214 线上连这个
  // var wsuri = "ws://47.96.23.199:" + serverPort;
  var wsuri = process.env.API_SK + serverPort;
  websock = new WebSocket(wsuri);
  websock.onmessage = function (e) {
    websocketonmessage(e);
  }
  websock.onclose = function (e) {
    websocketclose(e);
  }
  websock.onopen = function () {
    websocketOpen();
  }
  //连接发生错误的回调方法
  websock.onerror = function () {
    console.log("WebSocket连接发生错误");
  }
}

/**
 * 实际调用发送消息的方法
 * @param {*} postData 参数
 * @param {*} callback 回调函数
 */
function sendSock(postData, callback) {
  global_callback = callback;
  if (websock.readyState === websock.OPEN) {
    //若是ws开启状态
    websocketsend(postData)
  } else if (websock.readyState === websock.CONNECTING) {
    // 若是 正在开启状态，则等待1s后重新调用
    setTimeout(function () {
      sendSock(postData, callback);
    }, 1000);
  } else {
    // 若未开启 ，则等待1s后重新调用
    setTimeout(function () {
      sendSock(postData, callback);
    }, 1000);
  }
}

/**
 * 数据接收
 */
function websocketonmessage(e) {
  global_callback(e);
}

/**
 * 数据发送
 * @param {*} agentData 
 */
function websocketsend(agentData) {
  websock.send(JSON.stringify(agentData));
}

/**
 * 关闭
 */
function websocketclose(e) {
  console.log("connection closed (" + e.code + ")");
}

/**
 * 连接
 */
function websocketOpen(e) {
  console.log("连接成功");
}

initWebSocket();

export {
  sendSock
}
