<template>
	<a-tabs
		v-model:activeKey="activeKey"
		hide-add
		type="editable-card"
		@edit="onEdit"
		@change="onChange"
	>
		<a-tab-pane
			v-for="pane in tabPanesList"
			:key="pane.name"
			:tab="pane.title"
			:closable="pane.closable"
		>
			<router-link :to="pane.path" />
		</a-tab-pane>
	</a-tabs>
</template>
<script lang="ts">
import { defineComponent, ref, computed, watch } from 'vue'
import { useRoute } from 'vue-router'
import { onBeforeRouteUpdate } from 'vue-router'

import { TabPanesRoute } from './type'
import { tabPanesStore } from '@/store/modules/tabPanes'

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

		const getMatched = (route): TabPanesRoute[] => {
			let _routeArr = ref<TabPanesRoute[]>([])

			_routeArr.value = route.matched
				.filter(
					f =>
						f.name != 'Root' &&
						!f.meta.hideMenu &&
						f.name != 'Auth' &&
						f.name != 'Errors'
				) //  && f.name != 'DesignUserAuth'
				.map(m => {
					routeDisabled.value = reg.test(m.path)
					return {
						title: m.meta.title,
						path: m.redirect
							? m.redirect
							: routeDisabled.value
							? ''
							: m.path,
						name: m.name,
						closable: true,
						params: route.params,
					}
				})
				.pop()
			return _routeArr.value
		}

		const activeKey = ref<string>(useTabPanesStore.activeKey)

		const tabPanesList = computed(() => {
			let _list = useTabPanesStore.tabPanesList || []
			// activeKey.value = useTabPanesStore.activeKey
			return _list
		})

		watch(
			() => useTabPanesStore.activeKey,
			newValue => {
				activeKey.value = newValue
			},
			{ deep: true, immediate: true }
		)

		useTabPanesStore.setTabPanesList(getMatched(route))
		// 监听路由更新前，重置菜单选中
		onBeforeRouteUpdate(to => {
			useTabPanesStore.setTabPanesList(getMatched(to))
		})

		// 关闭tab按钮
		const onEdit = (targetKey: string) => {
			useTabPanesStore.deleteTabPanesList(targetKey)
		}

		// 切换tab
		const onChange = (targetKey: string) => {
			activeKey.value = targetKey
			useTabPanesStore.setActiveTabPanes(targetKey)
		}

		return {
			tabPanesList,
			activeKey,
			onEdit,
			onChange,
		}
	},
})
</script>
