<script lang="tsx">
// @ts-nocheck
import { useAppStore } from '@/store'
import { openWindow, regexUrl } from '@/utils'
import { listenerRouteChange } from '@/utils/route-listener'
import { compile, computed, defineComponent, h, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import type { RouteMeta } from 'vue-router'
import {
  isNavigationFailure,
  NavigationFailureType,
  RouteRecordRaw,
  useRoute,
  useRouter,
} from 'vue-router'
import useMenuTree from './use-menu-tree'
import { COMMON_ICONS } from '@/views/ops/pages/system-settings/menu-management/menuIcons'

export default defineComponent({
  emit: ['collapse'],
  setup() {
    const { t } = useI18n()
    const appStore = useAppStore()
    const router = useRouter()
    const route = useRoute()
    const { menuTree } = useMenuTree()
    const collapsed = computed({
      get() {
        if (appStore.device === 'desktop') return appStore.menuCollapse
        return false
      },
      set(value: boolean) {
        appStore.updateSettings({ menuCollapse: value })
      },
    })

    const topMenu = computed(() => appStore.topMenu)
    const openKeys = ref<string[]>([])
    const selectedKey = ref<string[]>([])

    const goto = (item: RouteRecordRaw) => {
      // Open external link
      if (regexUrl.test(item.path) || item.meta?.isNewTab) {
        openWindow(`${window.location.origin}/#${item.path}`)
        selectedKey.value = [item.name as string]
        return
      }
      // Eliminate external link side effects
      const { hideInMenu, activeMenu } = item.meta as RouteMeta
      if (route.name === item.name && !hideInMenu && !activeMenu) {
        selectedKey.value = [item.name as string]
        return
      }
      const name = item.name
      if (name == null || name === '') {
        console.warn('[Menu] 无法跳转：路由缺少 name', item.path, item.meta?.locale)
        return
      }
      if (!router.hasRoute(name as string)) {
        console.warn('[Menu] 无法跳转：未注册的路由 name', name, item.meta?.locale)
        return
      }
      router.push({ name }).catch((err) => {
        if (isNavigationFailure(err, NavigationFailureType.duplicated)) {
          return
        }
        console.error('[Menu] 路由跳转失败', name, err)
      })
    }
    const findMenuOpenKeys = (target: string) => {
      const result: string[] = []
      let isFind = false
      const backtrack = (item: RouteRecordRaw, keys: string[]) => {
        if (item.name === target) {
          isFind = true
          result.push(...keys)
          return
        }
        if (item.children?.length) {
          item.children.forEach((el) => {
            backtrack(el, [...keys, el.name as string])
          })
        }
      }
      menuTree.value.forEach((el: RouteRecordRaw) => {
        if (isFind) return // Performance optimization
        backtrack(el, [el.name as string])
      })
      return result
    }
    listenerRouteChange((newRoute) => {
      const { requiresAuth, activeMenu, hideInMenu } = newRoute.meta
      if (requiresAuth && (!hideInMenu || activeMenu)) {
        const menuOpenKeys = findMenuOpenKeys((activeMenu || newRoute.name) as string)

        const keySet = new Set([...menuOpenKeys, ...openKeys.value])
        openKeys.value = [...keySet]

        const leafKey = (activeMenu || menuOpenKeys[menuOpenKeys.length - 1]) as string | undefined
        selectedKey.value = leafKey ? [leafKey] : []
      }
    }, true)
    const setCollapse = (val: boolean) => {
      if (appStore.device === 'desktop') appStore.updateSettings({ menuCollapse: val })
    }

    // 获取图标组件 - 支持 Arco Design 图标和 @tabler/icons-vue
    const getIconComponent = (iconName: string) => {
      if (!iconName) return null
      
      // 检查是否是 Tabler 图标（不以 'icon-' 开头）
      if (!iconName.startsWith('icon-')) {
        const IconComponent = COMMON_ICONS[iconName]
        if (IconComponent) {
          return () => h(IconComponent, { size: 18 })
        }
      }
      
      // 回退到 Arco Design 图标
      return () => h(compile(`<${iconName}/>`))
    }

    const renderSubMenu = () => {
      function travel(_route: RouteRecordRaw[], nodes = []) {
        if (_route) {
          _route.forEach((element) => {
            // This is demo, modify nodes as needed
            const icon = element?.meta?.icon ? getIconComponent(element?.meta?.icon as string) : null
            const node =
              element?.children && element?.children.length !== 0 ? (
                <a-sub-menu
                  key={element?.name}
                  v-slots={{
                    icon,
                    title: () => element?.meta?.locale,
                  }}
                >
                  {travel(element?.children)}
                </a-sub-menu>
              ) : (
                <a-menu-item key={element?.name} v-slots={{ icon }} onClick={() => goto(element)}>
                  {element?.meta?.locale}
                </a-menu-item>
              )
            nodes.push(node as never)
          })
        }
        return nodes
      }
      return travel(menuTree.value)
    }

    return () => (
      <a-menu
        theme='dark'
        mode={topMenu.value ? 'horizontal' : 'vertical'}
        v-model:collapsed={collapsed.value}
        v-model:open-keys={openKeys.value}
        show-collapse-button={appStore.device !== 'mobile'}
        auto-open={false}
        selected-keys={selectedKey.value}
        auto-open-selected={true}
        level-indent={34}
        style='height: 100%;width:100%;'
        onCollapse={setCollapse}
      >
        {renderSubMenu()}
      </a-menu>
    )
  },
})
</script>

<style lang="less" scoped>
:deep(.arco-menu-inner) {
  .arco-menu-inline-header {
    display: flex;
    align-items: center;
  }
  .arco-icon {
    &:not(.arco-icon-down) {
      font-size: 18px;
    }
  }
}
</style>
