<template>
    <div id="app" style="background-color: #0e2e87" v-if="$route.meta.bigScreen">
        <router-view />
    </div>
    <div id="app" v-else>
        <router-view :key="language" />
        <!-- 告警提示框 -->
        <Notification v-if="showNotification" :message="notificationMessage" :showTip="showNotification" />
        <theme-picker />
    </div>
</template>

<script>
import ThemePicker from '@/components/ThemePicker';
import Notification from '@/components/Notification/Notification';
import { getUserId } from '@/utils/auth';

export default {
    name: 'App',
    components: { ThemePicker, Notification },
    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;
            },
        };
    },

    data() {
        return {
            showNotification: false,
            notificationMessage: null,
        };
    },
    computed: {
        language() {
            return this.$store.state.settings.language;
        },
        token() {
            return this.$store.state.user.token;
        },
    },

    mounted() {
        if (this.token) {
            this.$nextTick(() => {
                this.connectMqtt();
            });
        }
    },
    beforeDestroy() {
        this.$mqttTool.unsubscribe('/notify/alert/web/push/' + getUserId());
    },
    watch: {
        token(newToken) {
            if (newToken) {
                setTimeout(() => {
                    this.connectMqtt();
                }, 2000);
            }
        },
    },
    methods: {
        connectMqtt() {
            if (this.$mqttTool.client == null) {
                console.log('Connecting to MQTT...');
                this.$mqttTool.connect();
            }
            this.mqttCallback();
            this.$mqttTool.subscribe('/notify/alert/web/push/' + getUserId());
        },

        mqttCallback() {
            this.$mqttTool.client.on('message', (topic, message) => {
                message = JSON.parse(message.toString());
                this.notificationMessage = message;
                if (message.showDialog === 1) {
                    this.showNotification = true;
                }
                console.log('Received status', this.notificationMessage);
                if (!message) {
                    return;
                }
            });
        },
    },
};
</script>
<style scoped>
#app .theme-picker {
    display: none;
}
</style>
