<template>
	<a-breadcrumb v-if="routeMatched.length > 1" style="padding: 1em 0">
		<a-breadcrumb-item v-for="item in routeMatched" :key="item.path">
			<router-link :to="item.path">{{ item.title }}</router-link>
		</a-breadcrumb-item>
	</a-breadcrumb>
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue'
import { useRoute } from 'vue-router'
import { onBeforeRouteUpdate } from 'vue-router'
import { BreadcrumbRoute } from './type'

export default defineComponent({
	setup() {
		const route = useRoute()
		// 正则匹配 url带有参数的路径
		const reg = /\/[a-zA-Z]+(\/:[a-zA-Z](\?)?)+/
		// 带有参数的url使用当前页面的url
		const routeDisabled = ref<boolean>(false)

		const getMatched = (route): BreadcrumbRoute[] => {
			return route.matched
				.filter(f => f.name != 'View' && !f.meta.hideMenu)
				.map(m => {
					routeDisabled.value = reg.test(m.path)
					return {
						title: m.meta.title,
						path: m.redirect
							? m.redirect
							: routeDisabled.value
							? ''
							: m.path,
					}
				})
		}
		const routeMatched = ref<BreadcrumbRoute[]>(getMatched(route))
		// 监听路由更新前，重置菜单选中
		onBeforeRouteUpdate(to => {
			routeMatched.value = getMatched(to)
		})
		return {
			routeMatched,
		}
	},
})
</script>
