<script lang="tsx">
import { defineComponent, ref, h, compile, computed } from 'vue'
import { useRoute, useRouter, RouteRecordRaw } from 'vue-router'
import type { RouteMeta } from 'vue-router'
import { useAppStore } from '@/store'
import { openWindow, regexUrl } from '@/utils'
import { listenerRouteChange } from '@/logics/mitt/routeChange'
import { useUndoneCount } from '@/hooks/useUndoneCount'
import { useToggle } from '@vueuse/core'
import useMenuTree from './use-menu-tree'

export default defineComponent({
  emit: ['collapse'],
  setup() {
    const appStore = useAppStore()
    const [subShowBadge, toggle] = useToggle()
    const { undoneCount } = useUndoneCount()
    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 openKeys = ref<string[]>([])
    const selectedKey = ref<string[]>([])

    const goto = (item: RouteRecordRaw, e: PointerEvent) => {
      e.stopPropagation()
      // Open external link
      if (regexUrl.test(item.path)) {
        openWindow(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
      }
      // Trigger router change
      router.push({
        name: item.name
      })
    }

    const expandSubMenu = (item: RouteRecordRaw) => {
      console.log(selectedKey.value)
      const { showBadge } = item.meta as RouteMeta
      if (showBadge) {
        toggle()
      }
    }
    const findMenuOpenKeys = (name: string) => {
      const result: string[] = []
      let isFind = false
      const backtrack = (
        item: RouteRecordRaw,
        keys: string[],
        target: string
      ) => {
        if (item.name === target) {
          isFind = true
          result.push(...keys, item.name as string)
          return
        }
        if (item.children?.length) {
          item.children.forEach(el => {
            backtrack(el, [...keys], target)
          })
        }
      }
      menuTree.value.forEach((el: RouteRecordRaw) => {
        if (isFind) return // Performance optimization
        backtrack(el, [el.name as string], name)
      })
      return result
    }
    const setCollapse = (val?: boolean) => {
      if (appStore.device === 'desktop')
        appStore.updateSettings({ menuCollapse: !!val })
    }
    listenerRouteChange(newRoute => {
      const { requiresAuth, activeMenu, hideInMenu, menuCollapse } =
        newRoute.meta
      setCollapse(menuCollapse)
      if (requiresAuth && (!hideInMenu || activeMenu)) {
        const menuOpenKeys = findMenuOpenKeys(
          (activeMenu || newRoute.name) as string
        )
        const keySet = new Set([...menuOpenKeys, ...openKeys.value])
        openKeys.value = [...keySet]
        const activeKey =
          (activeMenu as string) || menuOpenKeys[menuOpenKeys.length - 1]
        selectedKey.value = [activeKey]
        if (selectedKey.value && newRoute.name === 'Dashboard') {
          selectedKey.value = ['Home']
        }

        if (
          ['AllWork', 'CompletedWork', 'IncompleteWork'].includes(
            selectedKey.value[0]
          )
        ) {
          subShowBadge.value = true
        }
        // newRoute.meta.showBadge = false
      }
    }, true)
    // <icon-font type="icon-map" :size="16" />
    const renderSubMenu = () => {
      function travel(_route: RouteRecordRaw[], nodes = []) {
        if (_route) {
          _route.forEach(element => {
            const icon = element?.meta?.icon
              ? () => h(compile(`<${element?.meta?.icon}/>`))
              : null
            const node =
              element?.children && element?.children.length !== 0 ? (
                <a-sub-menu
                  key={element?.name}
                  selectable={true}
                  class={element?.meta?.showBadge ? 'badge-sub-menu' : '2'}
                  onClick={() => expandSubMenu(element)}
                  v-slots={{
                    icon,
                    title: () =>
                      element?.meta?.showBadge && !subShowBadge.value
                        ? h(
                            compile(`<a-badge
                            :count="${Number(undoneCount.value) || 0}"
                            :offset="[12, -2]"
                            >
                              ${element?.meta?.title}
                            </a-badge>`)
                          )
                        : h(compile(element?.meta?.title as string))
                  }}
                >
                  {travel(element?.children)}
                </a-sub-menu>
              ) : (
                <a-menu-item
                  key={element?.name}
                  v-slots={{
                    icon
                  }}
                  onClick={(e: any) => goto(element, e)}
                >
                  {element?.meta?.showBadge ? (
                    <a-badge
                      count={Number(undoneCount.value) || 0}
                      offset={[12, -2]}
                    >
                      {element?.meta?.title}
                    </a-badge>
                  ) : (
                    `${element?.meta?.title}`
                  )}
                </a-menu-item>
              )
            nodes.push(node as never)
          })
        }
        return nodes
      }
      return travel(menuTree.value)
    }

    return () => (
      <a-menu
        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%"
        onCollapse={setCollapse}
      >
        {renderSubMenu()}
      </a-menu>
    )
  }
})
</script>

<style lang="less" scoped>
:deep(.arco-menu-inner) {
  .arco-menu-inline-header {
    display: flex;
    align-items: center;
  }

  .arco-menu-icon {
    margin-right: 5px;
  }

  .arco-icon {
    &:not(.arco-icon-down) {
      font-size: 18px;
    }
  }
}
:deep(.badge-sub-menu) {
  .arco-menu-inline-header {
    .arco-menu-title {
      overflow: initial !important;
    }
  }
}
</style>
