<template>
  <el-breadcrumb class="app-breadcrumb" separator="/">
    <transition-group name="breadcrumb">
      <el-breadcrumb-item v-for="(item,index) in levelList" :key="item.path">
        <template v-if="item.menuName">
          <span v-if="item.redirect==='noRedirect'||index==levelList.length-1" class="no-redirect">{{ t(item.menuName) }}</span>
          <a v-else >{{ t(item.menuName) }}</a>
        </template>
      </el-breadcrumb-item>
    </transition-group>
  </el-breadcrumb>
</template>

<script lang="ts">
import { RouteLocationMatched } from 'vue-router'
import { usePermissionStore } from '@/portal/store/permission'
import { SyncDataMenuItem } from '@/types/module'
import { computed, defineComponent, ref, watch } from 'vue-demi'
import router from 'common/utils/router'
import { useI18n } from 'vue-i18n'

type MenuItemInfo = Omit<SyncDataMenuItem, 'children'>

export default defineComponent({
  name: 'BreadcrumbIndex',
  setup () {
    const permissionStore = usePermissionStore()
    const levelList = ref<Array<RouteLocationMatched & Partial<MenuItemInfo>>>([])
    const menus = computed(() => permissionStore.menus ?? [])

    function getRouteMap (arr: Array<SyncDataMenuItem> = [], map = new Map<string, MenuItemInfo>()) {
      return arr.reduce((collect, cur) => {
        collect.set(cur.menuPath, cur)
        if (cur.children) getRouteMap(cur.children, map)
        return collect
      }, map)
    }

    function getBreadcrumb () {
      const config = getRouteMap(menus.value)
      const matched = router.currentRoute.value.matched.map(item => ({
        ...item,
        ...(config.get(item.path) ?? {})
      }))

      levelList.value = matched.filter(item => item?.menuName && item?.breadcrumb !== false)
    }

    watch(router.currentRoute, (route) => {
      if (route.path.startsWith('/redirect/')) {
        return
      }
      getBreadcrumb()
    })

    const { t } = useI18n()

    return {
      t,
      levelList
    }
  }
})
</script>

<style lang="scss" scoped>
.app-breadcrumb.el-breadcrumb {
  display: inline-block;
  font-size: 14px;
  line-height: 50px;
  margin-left: 8px;

  .no-redirect {
    color: #97a8be;
    cursor: text;
  }
}
</style>
