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

<script>
import { mapActions } from "vuex";

export default {
  name: "App",
  async mounted() {
    this.initWebSocket();
    window.addEventListener("onmessageWS", this.getSocketData);
  },

  methods: {
    ...mapActions("cache", ["addCache", "removeCache"]),
    // 收集缓存（通过监听）
    collectCaches() {
      // 收集当前路由相关的缓存
      this.$route.matched.forEach((routeMatch) => {
        const instance = routeMatch.components?.default;
        const componentName = instance?.name;
        console.log(componentName);
        if (process.env.NODE_ENV === "development") {
          this.checkRouteComponentName(componentName, instance?.__file);
        }
        // 配置了meta.keepAlive的路由组件添加到缓存
        if (routeMatch.meta.keepAlive) {
          if (!componentName) {
            console.warn(`${routeMatch.path} 路由的组件名称name为空`);
            return;
          }
          this.addCache(componentName);
        } else {
          this.removeCache(componentName);
        }
      });
    },
    // 检测路由组件名称是否重复（组件重名会缓存到不该缓存的组件，而且不容易排查问题，所以开发环境时检测重名）
    checkRouteComponentName(name, file) {
      if (!this.cmpNames) this.cmpNames = {};
      if (this.cmpNames[name]) {
        if (this.cmpNames[name] !== file) {
          console.warn(
            `${file} 与${this.cmpNames[name]} 组件名称重复： ${name}`
          );
        }
      } else {
        this.cmpNames[name] = file;
      }
    },
    async initWebSocket() {
      this.$websocket.initWebSocket();
    },
    getSocketData(res) {
      console.log(res);
      this.$notify({
        title: "告警",
        message: res.detail.data,
        position: "bottom-right",
        type: "warning",
        duration: 0,
      });
    },
  },
  watch: {
    "$route.path": {
      immediate: true,
      handler() {
        this.collectCaches();
      },
    },
  },
  destroyed() {
    this.$websocket.close();
  },
};
</script>

<style lang="less">
* {
  margin: 0;
  padding: 0;
}
html,
body {
  width: 100%;
  height: 100%;
  overflow: hidden;
  color: #fff;
}
a {
  text-decoration: none;
  color: #fff;
}
#app {
  width: 100%;
  height: 100%;
}
body {
  font-family: "PingFang SC", "Helvetica Neue", Helvetica, "microsoft yahei",
    arial, STHeiTi, sans-serif;
}
// /* 整个滚动条 */
// ::-webkit-scrollbar {
//   width: 8px;
//   height: 8px;
// }

// /* 滚动条上的滚动滑块 */
// ::-webkit-scrollbar-thumb {
//   background-color: #ccc;
//   /* 关键代码 */
//   border-radius: 32px;
// }

// /* 滚动条轨道 */
// ::-webkit-scrollbar-track {
//   background-color: #f0f0f0;
//   border-radius: 32px;
// }
.el-dialog__headerbtn {
  top: 18px;
  .el-dialog__close {
    font-size: 26px;
    &:hover {
      background: #e2e2e2;
    }
  }
}
</style>
