<template>
  <div id="app">
    <router-view v-if="isRouterAlive"></router-view>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { WS_URL } from "./utils/websocketApi";
export default {
  name: "App",
  computed: {
    ...mapGetters(["oidcIsAuthenticated"]),
  },
  data() {
    return {
      isRouterAlive: true,
      // socket参数
      socket: null,
      timeout: 10 * 1000, // 45秒一次心跳
      timeoutObj: null, // 心跳心跳倒计时
      serverTimeoutObj: null, // 心跳倒计时
      timeoutnum: null, // 断开 重连倒计时
      lockReconnect: false, // 防止
    };
  },
  mounted() {
    this.initWebSocket();
  },
  methods: {
    initWebSocket() {
      // WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https
      let wsUrl = WS_URL;
      window.websocket = new WebSocket(wsUrl);
      window.websocket.onopen = this.websocketonopen;
      window.websocket.onerror = this.websocketonerror;
      window.websocket.onmessage = this.setOnmessageMessage;
      window.websocket.onclose = this.websocketclose;
      // 监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
      // window.onbeforeunload = that.onbeforeunload
    },
    start() {
      // console.log("start");
      //清除延时器
      this.timeoutObj && clearTimeout(this.timeoutObj);
      this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
      this.timeoutObj = setTimeout(() => {
        if (window.websocket && window.websocket.readyState == 1) {
          //发送消息，服务端返回信息，即表示连接良好，可以在socket的onmessage事件重置心跳机制函数
          window.websocket.send("heartBath");
        } else {
          this.reconnect();
        }
        //定义一个延时器等待服务器响应，若超时，则关闭连接，重新请求server建立socket连接
        this.serverTimeoutObj = setTimeout(() => {
          window.websocket.close();
        }, this.timeout);
      }, this.timeout);
    },
    reset() {
      // 重置心跳
      // 清除时间
      clearTimeout(this.timeoutObj);
      clearTimeout(this.serverTimeoutObj);
      // 重启心跳
      this.start();
    },
    // 重新连接
    reconnect() {
      if (this.lockReconnect) return;
      this.lockReconnect = true;
      //没连接上会一直重连，设置延迟避免请求过多
      this.timeoutnum && clearTimeout(this.timeoutnum);
      this.timeoutnum = setTimeout(() => {
        this.initWebSocket();
        this.lockReconnect = false;
      }, 5000);
    },
    async setOnmessageMessage(event) {
      console.log(event.data, "获得消息");
      this.reset();
      // 自定义全局监听事件
      window.dispatchEvent(
        new CustomEvent("onmessageWS", {
          detail: {
            data: event.data,
          },
        })
      );
    },
    websocketonopen() {
      //开启心跳
      this.start();
      console.log(
        "WebSocket连接成功!!!" + new Date() + "----" + window.websocket.readyState
      );
    },
    websocketonerror(e) {
      console.log("WebSocket连接发生错误" + e + ",重启socket");
      this.initWebSocket();
    },
    websocketclose(e) {
      window.websocket.close();
      clearTimeout(this.timeoutObj);
      clearTimeout(this.serverTimeoutObj);
      console.log("WebSocket连接关闭,重启socket");
      this.initWebSocket();
    },
    websocketsend(messsage) {
      window.websocket.send(messsage);
    },
    closeWebSocket() {
      // 关闭websocket
      window.websocket.close();
    },
  },
};
</script>
<style>
.flex {
  display: flex;
}
.flex-1 {
  flex: 1;
}
.jc-c {
  justify-content: center;
}
.jc-sb {
  justify-content: space-between;
}
.jc-e {
  justify-content: end;
}
.ai-c {
  align-items: center;
}
.column {
  flex-direction: column;
}
.fc-w {
  color: #fff;
}
.max-h {
  height: 100%;
}
.max-w {
  width: 100%;
}

.fz-16 {
  font-size: 16px;
}
.fz-14 {
  font-size: 14px;
}
.fz-10 {
  font-size: 10px;
}
.mt-1 {
  margin-top: 10px;
}
.mt-2 {
  margin-top: 20px;
}
.mr-1 {
  margin-right: 10px;
}
.mr-2 {
  margin-right: 20px;
}
.cursor {
  cursor: pointer;
}
.fw-b {
  font-weight: bold;
}
</style>
