<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,
  FileSearchOutlined,
  ApiOutlined,
  HistoryOutlined,
  BarcodeOutlined,
  LinkOutlined,
} 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']
  else if (path.startsWith('/sku-')) openKeys.value = ['sku-group']
  else if (path.startsWith('/logs')) openKeys.value = ['logs-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: 'sku-group',
    icon: BarcodeOutlined,
    label: 'SKU 管理',
    children: [
      { key: '/sku-origins', icon: BarcodeOutlined, label: '内部 SKU' },
      { key: '/sku-mappings', icon: LinkOutlined, label: 'SKU 映射' },
    ],
  },
  {
    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: '/api-keys', icon: KeyOutlined, label: 'API Key 管理', adminOnly: true },
  { 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 },
  {
    key: 'logs-group',
    icon: FileSearchOutlined,
    label: '系统日志',
    adminOnly: true,
    children: [
      { key: '/logs/requests', icon: ApiOutlined, label: '请求日志' },
      { key: '/logs/operations', icon: HistoryOutlined, label: '操作日志' },
    ],
  },
]

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': '退款子项',
    '/sku-origins': '内部 SKU',
    '/sku-mappings': 'SKU 映射',
    '/roles': '角色管理',
    '/route-groups': '路由组管理',
    '/mq-status': '队列监控',
    '/failed-messages': '失败消息',
    '/logs/requests': '请求日志',
    '/logs/operations': '操作日志',
    '/api-keys': 'API Key 管理',
    '/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>
  <div class="min-h-screen flex flex-col">
    <!-- Header -->
    <header
      class="fixed top-0 w-full z-20 flex items-center justify-between px-4 bg-[#001529] h-16"
    >
      <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>
    </header>

    <div class="flex pt-16 min-h-screen">
      <!-- Sidebar -->
      <aside
        class="fixed left-0 top-16 bottom-0 z-10 overflow-y-auto bg-[#001529] transition-[width] duration-200"
        :style="{ width: collapsed ? '80px' : '200px' }"
      >
        <a-menu
          :inline-collapsed="collapsed"
          :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>
      </aside>

      <!-- Content + Footer -->
      <div
        class="flex flex-col flex-1 min-h-[calc(100vh-4rem)]"
        :style="{ marginLeft: collapsed ? '80px' : '200px', transition: 'margin-left 0.2s' }"
      >
        <main class="flex-1 overflow-y-auto 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 />
        </main>

        <footer class="text-center text-gray-500 py-6 bg-[#f5f5f5]">
          &copy; 2026 DataHub - 数据管理平台
        </footer>
      </div>
    </div>
  </div>
</template>
