<script lang="ts" setup>
import { computed, ref, watch } from 'vue';

import { useAntdDesignTokens } from '@vben/hooks';
import { preferences, usePreferences } from '@vben/preferences';
import { useUserStore as useVbenUserStore } from '@vben/stores';

import { App, ConfigProvider, theme } from 'ant-design-vue';

import { antdLocale } from '#/locales';
import { GlobalContextMenu } from '#/components/context-menu';
import { useWebSocket } from '#/views/business/chat/composables/useWebSocket';
import { useChatStore } from '#/views/business/chat/stores/chat';
import { useUserStore } from '#/views/business/chat/stores/user';

defineOptions({ name: 'App' });

const { connectWebSocket } = useWebSocket();
const userStore = useUserStore();
const chatStore = useChatStore();
const vbenUserStore = useVbenUserStore();

// 用户信息加载状态跟踪
const userInfoLoaded = ref(false);

// 监听userInfo加载完成
watch(
  () => vbenUserStore.userInfo,
  (newUserInfo) => {
    if (newUserInfo) {
      console.log('用户信息已加载：', newUserInfo)
      userStore.currentUser = newUserInfo;
      userStore.login(newUserInfo);
      userInfoLoaded.value = true;
    }
  },
  { immediate: true },
);

const { isDark } = usePreferences();
const { tokens } = useAntdDesignTokens();

const tokenTheme = computed(() => {
  const algorithm = isDark.value
    ? [theme.darkAlgorithm]
    : [theme.defaultAlgorithm];

  if (preferences.app.compact) {
    algorithm.push(theme.compactAlgorithm);
  }

  return {
    algorithm,
    token: tokens,
  };
});

const initWebsocket = () => {
  // 确保用户信息已加载
  if (!userStore.currentUser) return;

  // 初始化数据库
  chatStore.initDB();

  // 加载好友列表（使用用户ID）
  chatStore.loadFriends(userStore.presetUsers, userStore.currentUser?.doctor_id);

  // 创建WebSocket连接
  connectWebSocket();
};

// 当userInfo加载完成后再执行初始化
watch(userInfoLoaded, (loaded) => {
  if (loaded) {
    initWebsocket();
  }
});
</script>

<template>
  <ConfigProvider :locale="antdLocale" :theme="tokenTheme">
    <App>
      <RouterView />
      <GlobalContextMenu />
    </App>
  </ConfigProvider>
</template>
