<script setup lang="ts">
import Brand from '@/components/Brand.vue'
import { useUserStore } from '@/stores/user'
import {
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  DashboardOutlined,
  UserOutlined,
  ShoppingOutlined,
  FileTextOutlined,
  UnorderedListOutlined,
  DollarOutlined,
  MonitorOutlined,
  WarningOutlined,
  LogoutOutlined,
  SettingOutlined,
  KeyOutlined,
  TeamOutlined,
  ApartmentOutlined,
} from '@ant-design/icons-vue'
import type { Component } from 'vue'

interface MenuItem {
  key: string
  icon: Component
  label: string
  adminOnly?: boolean
  children?: MenuItem[]
}

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

// 侧边栏折叠状态，持久化到 localStorage
const collapsed = ref(localStorage.getItem('sidebarCollapsed') === 'true')

watch(collapsed, (val) => {
  localStorage.setItem('sidebarCollapsed', String(val))
})

// 菜单选中项与路由同步
const selectedKeys = computed(() => [route.path])

// 子菜单展开状态
const openKeys = ref<string[]>([])

const initOpenKeys = () => {
  if (collapsed.value) return
  const path = route.path
  if (path.startsWith('/order')) openKeys.value = ['orders-group']
  else if (path.startsWith('/refund')) openKeys.value = ['refunds-group']
}

onMounted(initOpenKeys)
watch(() => route.path, initOpenKeys)

// 导航菜单配置
const menuItems: MenuItem[] = [
  { key: '/', icon: DashboardOutlined, label: '首页' },
  { key: '/users', icon: UserOutlined, label: '用户管理', adminOnly: true },
  { key: '/products', icon: ShoppingOutlined, label: '产品管理' },
  {
    key: 'orders-group',
    icon: FileTextOutlined,
    label: '订单管理',
    children: [
      { key: '/orders', icon: FileTextOutlined, label: '订单列表' },
      { key: '/order-items', icon: UnorderedListOutlined, label: '订单子项' },
    ],
  },
  {
    key: 'refunds-group',
    icon: DollarOutlined,
    label: '退款管理',
    children: [
      { key: '/refunds', icon: DollarOutlined, label: '退款列表' },
      { key: '/refund-items', icon: UnorderedListOutlined, label: '退款子项' },
    ],
  },
  { key: '/roles', icon: TeamOutlined, label: '角色管理', adminOnly: true },
  { key: '/route-groups', icon: ApartmentOutlined, label: '路由组管理', adminOnly: true },
  { key: '/mq-status', icon: MonitorOutlined, label: '队列监控', adminOnly: true },
  { key: '/failed-messages', icon: WarningOutlined, label: '失败消息', adminOnly: true },
]

const filteredMenuItems = computed(() =>
  menuItems.filter((item) => !item.adminOnly || userStore.isAdmin),
)

const username = computed(() => userStore.username || 'admin')

const handleMenuClick = ({ key }: { key: string | number }) => {
  const path = String(key)
  if (path.startsWith('/')) {
    router.push(path)
  }
}

const handleLogout = () => {
  userStore.logout()
  router.push('/login')
}

// 面包屑
const breadcrumbItems = computed(() => {
  const pathMap: Record<string, string> = {
    '/': '首页',
    '/users': '用户管理',
    '/products': '产品管理',
    '/orders': '订单列表',
    '/order-items': '订单子项',
    '/refunds': '退款列表',
    '/refund-items': '退款子项',
    '/roles': '角色管理',
    '/route-groups': '路由组管理',
    '/mq-status': '队列监控',
    '/failed-messages': '失败消息',
    '/profile': '个人信息',
    '/profile/password': '修改密码',
  }

  const items: Array<{ title: string; path: string }> = [{ title: '首页', path: '/' }]
  if (route.path !== '/') {
    items.push({ title: pathMap[route.path] || route.path, path: route.path })
  }
  return items
})
</script>

<template>
  <a-layout class="min-h-screen">
    <!-- Header -->
    <a-layout-header
      class="fixed top-0 w-full z-10 flex items-center justify-between px-4"
      style="height: 64px; line-height: 64px"
    >
      <div class="flex items-center gap-4">
        <Brand size="small" :show-app-name="!collapsed" />
        <component
          :is="collapsed ? MenuUnfoldOutlined : MenuFoldOutlined"
          class="text-white text-lg cursor-pointer hover:text-[#4da30d]"
          @click="collapsed = !collapsed"
        />
      </div>
      <a-dropdown>
        <span class="cursor-pointer text-white/85 hover:text-white flex items-center gap-1">
          <UserOutlined />
          {{ username }}
        </span>
        <template #overlay>
          <a-menu>
            <a-menu-item key="profile" @click="router.push('/profile')">
              <SettingOutlined class="mr-2" />
              个人信息
            </a-menu-item>
            <a-menu-item key="password" @click="router.push('/profile/password')">
              <KeyOutlined class="mr-2" />
              修改密码
            </a-menu-item>
            <a-menu-divider />
            <a-menu-item key="logout" @click="handleLogout">
              <LogoutOutlined class="mr-2" />
              退出登录
            </a-menu-item>
          </a-menu>
        </template>
      </a-dropdown>
    </a-layout-header>

    <a-layout class="mt-16">
      <!-- Sidebar -->
      <a-layout-sider
        v-model:collapsed="collapsed"
        :trigger="null"
        collapsible
        class="fixed left-0 top-16 bottom-0 overflow-y-auto"
      >
        <a-menu
          :selected-keys="selectedKeys"
          v-model:open-keys="openKeys"
          mode="inline"
          theme="dark"
          @click="handleMenuClick"
        >
          <template v-for="item in filteredMenuItems" :key="item.key">
            <a-sub-menu v-if="item.children" :key="item.key">
              <template #icon><component :is="item.icon" /></template>
              <template #title>{{ item.label }}</template>
              <a-menu-item v-for="child in item.children" :key="child.key">
                <template #icon><component :is="child.icon" /></template>
                {{ child.label }}
              </a-menu-item>
            </a-sub-menu>
            <a-menu-item v-else :key="item.key">
              <template #icon><component :is="item.icon" /></template>
              {{ item.label }}
            </a-menu-item>
          </template>
        </a-menu>
      </a-layout-sider>

      <!-- Content + Footer -->
      <a-layout
        :style="{
          marginLeft: collapsed ? '80px' : '200px',
          transition: 'margin-left 0.2s',
        }"
      >
        <a-layout-content class="p-6">
          <a-breadcrumb class="mb-4">
            <a-breadcrumb-item v-for="item in breadcrumbItems" :key="item.path">
              <router-link v-if="item.path !== route.path" :to="item.path">
                {{ item.title }}
              </router-link>
              <span v-else>{{ item.title }}</span>
            </a-breadcrumb-item>
          </a-breadcrumb>
          <slot />
        </a-layout-content>

        <a-layout-footer class="text-center text-gray-500">
          &copy; 2026 DataHub - 数据管理平台
        </a-layout-footer>
      </a-layout>
    </a-layout>
  </a-layout>
</template>

<style scoped>
:deep(.ant-layout-sider) {
  z-index: 9;
}
</style>
