<template>
    <div class="mobile-desk-view">
        <div class="mobile-desk-content">
            <router-view />
        </div>
        <MobileBottomTabs v-if="!hideBottomTabs" />
    </div>
</template>

<script setup lang="ts">
import { computed, onMounted, onUnmounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import MobileBottomTabs from '../components/MobileBottomTabs/index.vue';
import toast from '../../../utils/toast.ts';
import AIDeskCoreInstance, { AI_DESK_EVENTS, StoreName } from '@tencentcloud/ai-desk-core';

const route = useRoute();
const router = useRouter();
const hideBottomTabs = computed(() => route.matched.some((record) => record.meta.hideBottomTabs));

type ConnectionState = 'disconnected' | 'connected' | 'connecting' | 'reconnecting';

const redirectToSessionList = () => {
    if (route.path !== '/mobileDesk/sessionList') {
        void router.replace('/mobileDesk/sessionList');
    }
};

const onConnectionStateUpdated = (state: ConnectionState) => {
    if (state === 'disconnected') {
        redirectToSessionList();
    }
};

const onIMNetStatusUpdated = (state: ConnectionState) => {
    if (state === 'disconnected' || state === 'reconnecting') {
        redirectToSessionList();
    }
};

const onKickedOutEvent = () => {
    toast.error('您已被踢下线，请重新登录');
};
const onForcedOfflineEvent = () => {
    toast.error('您已被强制下线，请重新登录');
};

onMounted(() => {
    AIDeskCoreInstance.coreStore.watch(StoreName.USERINFO, {
        connectionState: onConnectionStateUpdated,
        IMNetStatus: onIMNetStatusUpdated,
    });
    AIDeskCoreInstance.eventCenter.addEvent(AI_DESK_EVENTS.KICKED_OUT, onKickedOutEvent);
    AIDeskCoreInstance.eventCenter.addEvent(AI_DESK_EVENTS.FORCED_OFFLINE, onForcedOfflineEvent);
});

onUnmounted(() => {
    AIDeskCoreInstance.coreStore.unwatch(StoreName.USERINFO, {
        connectionState: onConnectionStateUpdated,
        IMNetStatus: onIMNetStatusUpdated,
    });
    AIDeskCoreInstance.eventCenter.removeEvent(AI_DESK_EVENTS.KICKED_OUT, onKickedOutEvent);
    AIDeskCoreInstance.eventCenter.removeEvent(AI_DESK_EVENTS.FORCED_OFFLINE, onForcedOfflineEvent);
});

</script>

<style scoped>
:deep(*) {
    box-sizing: border-box;
}

.mobile-desk-view {
    display: flex;
    flex-direction: column;
    height: 100%;
    background: #f5f7fa;
}

.mobile-desk-content {
    flex: 1;
    min-height: 0;
    overflow: hidden;
}
</style>