<script lang="tsx">
import type { RouteMeta, RouteRecordRaw } from 'vue-router';

import { useAppStore } from '@/stores';
import { useSidebarStore } from '@/stores/modules/side-bar';
import { listenerRouteChange } from '@/utils/route-listener';
import { openWindow, regexUrl } from '@/utils';
import useMenuTree from './use-menu-tree';

export default defineComponent({
  emit: ['collapse'],
  setup() {
    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 sidebarStore = useSidebarStore();
    const onMenuItemClick = (item: RouteRecordRaw) => {
      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 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)) {
      if (!hideInMenu || activeMenu) {
        const menuOpenKeys = findMenuOpenKeys((activeMenu || newRoute.name) as string);
        const keySet = new Set([...menuOpenKeys, ...openKeys.value]);
        openKeys.value = [...keySet];
        selectedKey.value = [activeMenu || menuOpenKeys[menuOpenKeys.length - 1]];

        // 自动设置 activeMenuId
        sidebarStore.setActiveMenuIdByRoute(newRoute);
      }
    }, true);
    const setCollapse = (val: boolean) => {
      if (appStore.device === 'desktop') appStore.updateSettings({ menuCollapse: val });
    };
    const renderSubMenu = () => {
      function travel(_route: RouteRecordRaw[] = [], nodes: any[] = []) {
        if (!Array.isArray(_route)) return nodes;
        _route.forEach((element) => {
          // 跳过没有 name 的菜单项，防止 key 报错
          if (!element?.name) return;

          // const icon element?.meta?.icon
          const icon = element?.meta?.icon
            ? (() => {
                if (typeof element.meta.icon === 'string') {
                  return h(
                    'svg',
                    {
                      style: {
                        width: '16px',
                        height: '16px',
                      },
                    },
                    [
                      h('use', {
                        'xlink:href': element.meta.icon,
                      }),
                    ],
                  );
                } else {
                  // 如果是对象，按原来的方式渲染
                  return h(element.meta.icon as object);
                }
              })()
            : null;
          if (element.children && element.children.length > 0) {
            nodes.push(
              <a-sub-menu
                key={String(element.name)}
                v-slots={{
                  icon,
                  title: () => element?.meta?.locale || '',
                }}
              >
                {travel(element.children)}
              </a-sub-menu>,
            );
          } else {
            nodes.push(
              <a-menu-item key={String(element.name)} v-slots={{ icon }} onClick={() => onMenuItemClick(element)}>
                {element?.meta?.locale || ''}
              </a-menu-item>,
            );
          }
        });
        return nodes;
      }
      return travel(menuTree.value ?? []);
    };
    return () => (
      <a-menu
        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={24}
        style="height: 100%;width:100%;"
        onCollapse={setCollapse}
      >
        {renderSubMenu()}
      </a-menu>
    );
  },
});
</script>

<style lang="scss" scoped>
:deep(.arco-menu-inner) {
  padding: 20px 24px 0 12px !important;
  .arco-menu-inline-header {
    display: flex;
    align-items: center;
    height: 40px;
    margin-bottom: 12px;
    border-radius: 8px;
    .arco-menu-icon {
      margin-right: 8px;
    }
    .arco-menu-title {
      color: var(--Text-2, #3c4043);
      font-family: $font-family-medium;
      font-size: 16px;
      font-style: normal;
      font-weight: 400;
      line-height: 22px; /* 137.5% */
    }
    &:hover {
      background: var(--BG-200, #f2f3f5) !important;
    }
    &.arco-menu-selected {
      .arco-menu-title {
        color: var(--Brand-Brand-6, #6d4cfe) !important;
      }
    }
  }
  .arco-icon {
    &:not(.arco-icon-down) {
      font-size: 18px;
    }
  }
  .arco-menu-item {
    border-radius: 8px;
    .arco-menu-item-inner {
      color: var(--Text-3, #737478);
      font-family: $font-family-regular;
      font-size: 16px;
      font-style: normal;
      font-weight: 400;
      line-height: 22px; /* 137.5% */
    }
    &:hover {
      background: var(--BG-200, #f2f3f5) !important;
    }
    &.arco-menu-selected {
      background: var(--Brand-Brand-1, #f0edff) !important;
      .arco-menu-item-inner {
        color: var(--Brand-Brand-6, #6d4cfe) !important;
      }
    }
  }
}
</style>
