<template>
  <!-- LayoutSider -->
  <a-layout-sider
    breakpoint="lg"
    collapsed-width="80"
  >
    <div
      class="logo"
      @click="toHomeHandle"
    >
      LOGO
    </div>
    <a-menu
      v-model:selectedKeys="selectedKeys"
      theme="dark"
      mode="inline"
    >
      <component
        :is="menu.children?.length ? SubMenu: MenuItem"
        v-for="menu in menus"
        :key="menu.name"
        :title="menu.meta?.title || menu.name"
        @click="menu.children?.length ? null :toPageHandle(menu.name)"
      >
        <template #icon>
          <component :is="getIcon(menu.meta?.icon)" />
        </template>
        <template v-if="menu.children?.length">
          <MenuItem
            v-for="child in menu.children"
            :key="child.name"
            @click="toPageHandle(child.name)"
          >
            <span class="nav-text">{{ child.meta?.title || child.name }}</span>
          </MenuItem>
        </template>
        <template v-else>
          <span class="nav-text">{{ menu.meta?.title || menu.name }}</span>
        </template>
      </component>
    </a-menu>
  </a-layout-sider>
</template>
<script lang="ts" setup>
  import { AppStore } from '@/store/modules/app';
  import type { RouteRecordName, RouteLocationNormalized, RouteMeta } from 'vue-router'
  import { MenuItem, SubMenu } from 'ant-design-vue';
  import * as Icon from '@ant-design/icons-vue';

  const router = useRouter()
  const route = useRoute()
  const store = AppStore()
  const selectedKeys = ref<string[]>([])
  const menus = computed(() => store.authRoutes)
  const matchRouteHandle = (to: RouteLocationNormalized) => {
    menus.value.forEach(el => {
      if (el.name === to.name) {
        selectedKeys.value = [to.name as string]
      }
    })
  }
  matchRouteHandle(route)
  const toHomeHandle = () => {
    router.push('/')
  }
  const toPageHandle = (name: RouteRecordName | undefined) => {
    router.push({ name })
  }
  const getIcon = (name: unknown) => {
    // 这里将字符串假定为UserOutlined来通过Icon的类型校验
    return Icon[name as 'UserOutlined'] || 'AppstoreOutlined'
  }
</script>

<style lang="less" scoped>
.logo {
  margin: 16px;
  height: 32px;
  line-height: 32px;
  text-align: center;
  background-color: #fff;
  font-weight: 600;
  cursor: pointer;
}
</style>
