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

<script>
import ThemePicker from "@/components/ThemePicker";
import MessageBox from "@/components/MessageBox/index.vue";

export default {
  name: "App",
  components: { ThemePicker, MessageBox },
  data() {
    return {
      socket: null, // WebSocket实例
      baseWsUrl: process.env.VUE_APP_WS_URL, // WebSocket服务器地址
    };
  },
  metaInfo() {
    return {
      title:
        this.$store.state.settings.dynamicTitle &&
        this.$store.state.settings.title,
      titleTemplate: (title) => {
        return title
          ? `${title} - ${process.env.VUE_APP_TITLE}`
          : process.env.VUE_APP_TITLE;
      },
    };
  },
  methods: {
    showAlarm(data) {
      this.$notify({
        title: data.alarmMessage,
        dangerouslyUseHTMLString: true,
        message: this.$createElement("MessageBox", {
          props: { message: data },
        }),
        // duration: 0,
      });
    },
  },
  mounted() {
    if (this.socket) {
      return;
    }
    // 初始化WebSocket连接
    this.socket = new WebSocket(this.baseWsUrl + "/websocket");
    this.socket.onmessage = (event) => {
      const data = JSON.parse(event.data);
      console.log("Received message:", data);
      if (data.alarmImageUrl) {
        this.showAlarm(data);
      }
    };
  },
  beforeDestroy() {
    // 确保在组件销毁时关闭WebSocket连接
    if (this.socket) {
      this.socket.close();
    }
  },
};
</script>
<style scoped>
#app .theme-picker {
  display: none;
}
</style>
