<script setup>
import { ref, watch } from 'vue';
import { RouterView, useRoute, useRouter } from 'vue-router';
import { AccountBookOutlined, BookOutlined, LogoutOutlined, TeamOutlined, TrophyOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import { authState, logout } from '@/stores/auth';

// 获取当前路由和路由实例
const route = useRoute();
const router = useRouter();
const current = ref([route.name]);

// 监听路由变化，更新选中菜单
watch(() => route.name, (newName) => {
  current.value = [newName];
});

// 处理菜单点击事件
const handleMenuClick = (e) => {
  const key = e.key;
  router.push({ name: key });
};

const handleLogout = async () => {
  try {
    await logout();
    router.replace({ name: 'login' });
  }
  catch (err) {
    message.error(err.response?.data?.message ?? err.message);
  }
};

</script>

<template>
  <header v-if="route.name !== 'login'" class="app-header">
    <a-menu class="app-menu" v-model:selectedKeys="current" mode="horizontal" @click="handleMenuClick">
      <a-menu-item key="home">
        <template #icon>
          <account-book-outlined />
        </template>
        策略
      </a-menu-item>
      <a-menu-item key="leagues">
        <template #icon>
          <team-outlined />
        </template>
        联赛
      </a-menu-item>
      <a-menu-item key="games">
        <template #icon>
          <trophy-outlined />
        </template>
        比赛
      </a-menu-item>
      <a-menu-item key="locales">
        <template #icon>
          <book-outlined />
        </template>
        翻译
      </a-menu-item>
    </a-menu>

    <div class="header-actions">
      <span class="username">{{ authState.user?.username }}</span>
      <a-button type="text" @click="handleLogout">
        <template #icon>
          <logout-outlined />
        </template>
        退出
      </a-button>
    </div>
  </header>

  <router-view v-slot="{ Component }">
    <keep-alive :include="['games', 'leagues', 'locales']">
      <component :is="Component" />
    </keep-alive>
  </router-view>

</template>

<style scoped>
.app-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid rgba(5, 5, 5, 0.06);
}
.app-menu {
  flex: 1;
  min-width: 0;
  border-bottom: 0;
}
.header-actions {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 0 16px;
  white-space: nowrap;
}
.username {
  color: rgba(0, 0, 0, 0.65);
}
</style>
