import {
  ElButton,
  ElIcon,
  ElMenu,
  ElMenuItem,
  ElMenuItemGroup,
  ElSubMenu,
  type MenuItemRegistered,
} from 'element-plus'
import { elIcons } from '@/common/element/element.ts'
import AIcon from '@/components/a-icon/AIcon.vue'
import type { IconName } from '@/components/a-icon/iconfont.ts'
import styles from '@/pages/a-frame/aaside.module.styl'
import { useAppSettingStore } from '@/common/app/app-setting-store.ts'
import Colls from '@/common/utils/colls.ts'
import { MenuCategory } from '@/common/app/constants.ts'
import { useRouter } from 'vue-router'
import { computed } from 'vue'
import Nav from '@/common/router/nav.ts'

export interface Menu extends G.TreeNode {
  // Id
  id: string;
  // 编码
  sn: string;
  // 上级 Id; 层级为 1 的节点值为 0
  pid: string;
  // 菜单名称
  title: string;
  // 图标
  icon: string;
  // 层级; >= 1
  tier: number;
  // 排序
  sort: number;
  // 路由名称
  routeName: string;
  // 面包路径
  breadcrumb: string[];
  // 类型
  menuCategory: 'Catalog' | 'Group' | 'Page' | 'SubPage' | 'Btn';
  // 子菜单
  children?: Menu[];
}

export default defineComponent(
  () => {
    const router = useRouter()
    const appSettingStore = useAppSettingStore()
    const defaultActive = ref('')
    const isCollapse = ref(false)

    onMounted(() => {
      const currentRouteName = router.currentRoute.value.name
      defaultActive.value = appSettingStore.menus.find(it => it.routeName === currentRouteName)?.id
    })

    const menuTree = computed(() => {
      return Colls.toTree(appSettingStore.menus.filter((it) => it.menuCategory === MenuCategory.Page || it.menuCategory === MenuCategory.Group || it.menuCategory === MenuCategory.Catalog).sort((a, b) => (a.sort ?? 0) - (b.sort ?? 0)))
    })

    const onMenuClick = (menuItem: MenuItemRegistered) => {
      const menu = appSettingStore.menus.find(it => it.id === menuItem.index)
      Nav.open({
        insId: menu?.routeName ?? '',
        routeName: menu?.routeName ?? '',
      })
    }
    const renderMenu = (it: Menu) => {
      let renderChildNode: (() => VNode[] | undefined) | undefined = undefined
      if (it.children != null && it.children.length > 0) {
        renderChildNode = () => it.children?.map(renderMenu)
      }
      let currentNode: VNode
      switch (it.menuCategory) {
        case 'Catalog': {
          currentNode = (
            <ElSubMenu index={it.id}>
              {{
                title: () => (
                  <>
                    <AIcon class={styles.aIcon} name={it.icon as IconName}/>
                    <span>{it.title}</span>
                  </>
                ),
                default: renderChildNode,
              }}
            </ElSubMenu>
          )
          break
        }
        case 'Group': {
          currentNode = (
            <ElMenuItemGroup title={it.title}>
              {{
                default: renderChildNode,
              }}
            </ElMenuItemGroup>
          )
          break
        }
        case 'Page': {
          currentNode = (
            <ElMenuItem index={it.id} onClick={onMenuClick}>
              {{
                title: () => <span>{it.title}</span>,
                default: () => <AIcon class={styles.aIcon} name={it.icon as IconName}/>,
              }}
            </ElMenuItem>
          )
          break
        }
        default:
          currentNode = <></>
      }
      return currentNode
    }

    return () => (
      <>
        <ElMenu default-active={defaultActive.value} collapse={isCollapse.value} style={{height: '100%', overflow: 'auto', '--el-menu-base-level-padding': '10px'}} class={[ styles.aMenus, 'menus' ]}>
          {{
            default: () => menuTree.value.map(renderMenu),
          }}
        </ElMenu>
        <ElButton
          style={{position: 'absolute', right: '6px', bottom: '6px', width: '32px', height: '32px'}}
          onClick={() => {
            isCollapse.value = !isCollapse.value
          }}
        >
          <ElIcon style={{cursor: 'pointer'}}>{isCollapse.value ? <elIcons.Fold/> : <elIcons.Expand/>}</ElIcon>
        </ElButton>
      </>
    )
  },
  {
    name: 'AAside',
  },
)
