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

<script>
import { mapGetters } from 'vuex'
import {setToken} from "./utils/auth";
let Socket_Url = process.env.VUE_APP_WEBSOCKET_URL
export default {
  name: 'App',
  computed: {
    ...mapGetters([
      'oidcIsAuthenticated'
    ])
  },
  provide(){
    return {
      reload: this.reload
    }
  },
  data(){
    return {
      isRouterAlive: true,
      // socket参数
      socket: null,
      timeout: 10 * 1000, // 45秒一次心跳
      timeoutObj: null, // 心跳心跳倒计时
      serverTimeoutObj: null, // 心跳倒计时
      timeoutnum: null, // 断开 重连倒计时
      lockReconnect: false, // 防止
    }
  },
  mounted() {
    this.initWebSocket();

    window.addEventListener('vuexoidc:userLoaded', this.userLoaded);
  },
  methods: {
    userLoaded: function(e) {
      console.log('I am listening to the user loaded event in vuex-oidc', e.detail)
    },
    reload(){
      this.isRouterAlive = false
      this.$nextTick(function(){
        this.isRouterAlive = true
      })
    },
    initWebSocket() {
      // WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https
      // let wsUrl = "";
      window.websocket = new WebSocket(Socket_Url);
      window.websocket.onopen = this.websocketonopen;
      window.websocket.onerror = this.websocketonerror;
      window.websocket.onmessage = this.setOnmessageMessage;
      window.websocket.onclose = this.websocketclose;
    },
    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");
    },
    websocketclose(e) {
      window.websocket.close();
      clearTimeout(this.timeoutObj);
      clearTimeout(this.serverTimeoutObj);
      console.log("WebSocket连接关闭,重启socket");
      this.reconnect();
    },
    websocketsend(messsage) {
      window.websocket.send(messsage);
    },
    closeWebSocket() {
      window.websocket.close();
    },
  },
  destroyed() {
    window.removeEventListener('vuexoidc:userLoaded', this.userLoaded)
  }
}
</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;
  }
  .mr-1{
    margin-right: 10px;
  }
  .mr-2{
    margin-right: 20px;
  }
  .cursor{
    cursor: pointer;
  }
</style>
