import Vue from "vue";
class ControlWs {
  constructor() {
    this.wsUrl = window._config.wsUrl;
    // 心跳计时器
    this.timer = null;
    // ws实例对象
    this.ws = null;
    // 避免ws重复连接
    this.lockReconnect = false;
    // 可以继续连接 false 不能再连接 true 可以请求连接
    this.needreconnect = true;
    this.myevent = new Vue();
  }
  setWs() {
    if (this.wsUrl) {
      this.needreconnect = true;
      this.createWebSocket(); //连接ws
    }
  }
  closeWs() {
    if (this.ws) {
      this.needreconnect = false;
      this.ws.close();
      this.myevent.$off("ws_error");
      this.myevent.$off("ws_open");
      this.myevent.$off("ws_getmsg");
      if (this.timer) {
        clearInterval(this.timer);
      }
    }
  }
  createWebSocket() {
    try {
      if ("WebSocket" in window) {
        this.ws = new WebSocket(this.wsUrl);
      } else {
        alert(
          "您的浏览器不支持websocket协议,建议使用新版谷歌、火狐等浏览器，请勿使用IE10以下浏览器，360浏览器请使用极速模式，不要使用兼容模式！"
        );
      }
      this.initEventHandle();
    } catch (e) {
      this.reconnect();
    }
  }
  initEventHandle() {
    this.ws.onclose = () => {
      console.log("ws连接关闭!");
      if (this.needreconnect) {
        this.reconnect();
      }
    };
    this.ws.onerror = () => {
      console.error("ws连接错误!");
      if (this.timer) {
        clearInterval(this.timer);
      }
      if (this.needreconnect === true) {
        this.myevent.$emit("ws_error");
        this.reconnect();
      }
    };
    this.ws.onopen = () => {
      if (this.timer) {
        clearInterval(this.timer);
      }
      this.timer = setInterval(() => {
        let blob = new Blob(["ping"], { type: "text/plain" });
        if (this.ws && this.ws.readyState === 1) {
          this.ws.send(blob);
        } else {
          clearInterval(this.timer);
        }
      }, 1000 * 10);
      console.log("ws连接成功!");
      this.myevent.$emit("ws_open");
    };
    this.ws.onmessage = (event) => {
      //如果获取到消息，心跳检测重置
      if (event.data && JSON.parse(event.data)) {
        // console.info("接收到消息", event.data);
        this.myevent.$emit("ws_getmsg", JSON.parse(event.data));
      } else {
        console.error(event.data);
      }
    };
  }
  reconnect() {
    if (this.lockReconnect) return;
    this.lockReconnect = true;
    setTimeout(() => {
      //没连接上会一直重连，设置延迟避免请求过多
      this.createWebSocket();
      this.lockReconnect = false;
    }, 2000);
  }
}
export default ControlWs;
