let ResponseCarTrack;
// let protobuf = require("protobufjs");
// protobuf.load("../wj-manage-web/RealtimeCarInfo.proto", function (event, root) {
//   ResponseCarTrack = root.lookupType("com.wanji.holo.proto.RealtimeCarTrack");
// });

// readyState: 0-正在连接 1-已经连接 2-连接正在关闭 3-已关闭或没连接成功

function onError(e, data) {
//   console.log("ws error...", e, data);
}

function onClose(e, data) {
//   console.log("ws close...", e, data);
}
// { url: '', name: '', callback: '' }
export function initWs(data) {
  if (typeof WebSocket === undefined) {
    console.error("您的浏览器不支持socket");
  } else {
    // console.log("init...", data);
    let currentSocket = new ReconnectingWebSocket(data.url);
    // 监听socket连接open
    // currentSocket.onopen = (e) => onOpen(e, data)
    // 监听socket错误信息
    currentSocket.onerror = (e) => onError(e, data);
    // 断开连接
    currentSocket.onclose = (e) => onClose(e, data);
    // 接收消息
    currentSocket.onmessage = (res) => {
      // protobuf 解压数据
      // if (data.name === "callCar") {
      //   let reader = new FileReader();
      //   reader.onload = (e) => {
      //     let buf = new Uint8Array(e.target.result);
      //     let responseCarTrack = ResponseCarTrack.decode(buf);
      //     data.callback(responseCarTrack.carInfo);
      //   };
      //   reader.readAsArrayBuffer(res.data);
      // } else {
        if (res.data.startsWith("[") || res.data.startsWith("{")) {
          data.callback(JSON.parse(res.data));
        }
      // }
    };
    return {
      name: data.name,
      url: data.url,
      ws: currentSocket,
    };
  }
}
