<template>
  <template v-if="!route.meta?.hidden">
    <app-link v-if="!hasShowChild" :to="{ path: routePath, query: routeQuery }">
      <el-menu-item :index="routePath">
        <icon
          :name="routeMeta.icon"
          size="var(--el-font-size-medium)"
          :type="routeMeta.iconType"
          v-if="routeMeta?.icon"
        />
        <template #title>
          <span>{{ routeMeta?.title }}</span>
        </template>
      </el-menu-item>
    </app-link>
    <el-sub-menu :popper-class="sideTheme + '-menu-popper'" v-else :index="routePath">
      <template #title>
        <icon
          :name="routeMeta.icon"
          size="var(--el-font-size-medium)"
          :type="routeMeta.iconType"
          v-if="routeMeta?.icon"
        />
        <span>{{ routeMeta?.title }}</span>
      </template>
      <menu-item
        v-for="item in route?.children"
        :key="getResolvePath(item.path)"
        :route="item"
        :route-path="getResolvePath(item.path)"
      />
    </el-sub-menu>
  </template>
</template>

<script setup lang="ts">
import type { RouteRecordRaw } from 'vue-router'
import { useSettingStore } from '@/stores/modules/setting'
import { isExternal, parseStringToObject, resolvePath } from '@/utils/util'
import appLink from './Link.vue'

interface Props {
  route: RouteRecordRaw
  routePath: string
}
const props = defineProps<Props>()

const settingStore = useSettingStore()
const sideTheme = computed(() => settingStore.sideTheme)
const hasShowChild = computed(() => {
  const children: RouteRecordRaw[] = props.route.children ?? []
  return !!children.filter((item) => !item.meta?.hidden).length
})
const routeMeta = computed(() => {
  return props.route.meta
})
const routeQuery = computed(() => {
  const query = props.route.meta?.query as string
  return parseStringToObject(query)
})

const getResolvePath = (path: string) => {
  if (isExternal(path)) {
    return path
  }
  const newPath = resolvePath(props.routePath, path)
  return newPath
}
</script>
