<template>
  <ui-editor-menu :menu="items" class="menu global-menu" :class="{ show: !hide }">
    <template v-slot="{ raw }">
      <MenuItem 
        :menu="raw" 
        :activePaths="activePaths" 
        @select="item => $emit('select', item.name, item)"
      />
    </template>
    <template #attach v-if="logo">
      <div class="logo">
        <ui-icon :type="logo"></ui-icon>
      </div>
    </template>
  </ui-editor-menu>
</template>

<script lang="ts">
import { defineComponent, computed } from 'vue'
import { router } from '@/router'
import MenuItem from './menu-item.vue'

import type { PropType } from 'vue'

export type Item = {
  name: string
  title: string
  icon: string
  children?: Items
}
export type Items = Item[]


// 查找某个菜单的链条
export const findMenuPaths = (
  menus: Items, 
  activeName: Item['name'], 
  paths: Item['name'][] = []
): Item['name'][] => {
  for (const menu of menus) {
    if (menu.name === activeName) {
      return [...paths, menu.name]
    } else if (menu.children) {
      const queryPaths = findMenuPaths(
        menu.children, 
        activeName, 
        [...paths, menu.name]
      )
      if (queryPaths.length) {
        return queryPaths
      }
    }
  }
  return []
}

export default defineComponent({
  name: 'slide-menu',
  props: {
    items: {
      type: Array as PropType<Items>,
      required: true,
    },
    active: { 
      type: String as PropType<Item['name']> 
    },
    hide: { type: Boolean },
    logo: { type: String }
  },
  emits: {
    select: (name: Item['name'], item: Item) => true
  },
  setup(props) {
    const activePaths = computed(() => 
      props.active ? findMenuPaths(props.items, props.active) : []
    )

    return {
      activePaths,
    }
  },
  components: {
    MenuItem
  }
})
</script>

<style lang="sass" scoped src="./style.scss"/>
<style lang="scss">
.global-menu {
  display: flex;
  flex-direction: column;

  .ui-editor-menu-item {
    position: relative;
  }

  >div:not(.logo, .menu-close) {
    flex: 1;
  }

  .logo {
    flex: none;
    width: auto;
    height: auto;
  }
}

.readonly .menu-item {
  cursor: inherit;
  pointer-events: none;
  color: var(--editor-men-color) !important;
}
</style>
