<template>
	<lay-tab v-if="appStore.tab" :modelValue="route.path" :allowClose="allowClose" @change="change" @close="close">
		<template :key="tab" v-for="tab in tabs">
			<lay-tab-item :id="tab['id']" :title="tab['title']" :closable="tab['closable']"></lay-tab-item>
		</template>
	</lay-tab>
</template>

<script lang="ts">
	export default {
		name: "GlobalTab"
	}
</script>

<script lang="ts" setup>
	import {
		ref,
		watch
	} from "vue";
	import {
		useRoute,
		useRouter
	} from "vue-router";
	import {
		useAppStore
	} from "../../store/app";

	const router = useRouter();
	const route = useRoute();
	const appStore = useAppStore();
	const allowClose = ref(true);
	let defaults = [];
	defaults.push({
		"title": "首页",
		"id": "/",
		"closable": false
	});
	if (route.path != "/" && route.path != "/index") {
		let find = {
			"title": "",
			"id": route.path,
			"closable": true
		};
		let title = "";
		router.options.routes.forEach((r1) => {
			if (find.id == r1.path) {
				find["title"] = (r1.children.length > 0 ? r1.children[0].meta["title"] : r1.meta[
					"title"]) as string;
			} else {
				r1.children.forEach((r2) => {
					if (find.id == r2.path) find["title"] = (r2.meta["title"]) as string;
				});
			}
		})
		if (find["title"] != "") defaults.push(find);
	}
	const tabs = ref(defaults);
	const change = function(id: string) {
		router.push(id);
	};

	const close = function(path: string) {
		tabs.value = tabs.value.filter((ele) => ele['id'] != path);
		//当关闭的是最后一个的时候默认跳转倒数
		let chose = tabs.value.find(s => s['id'] == route['path']);
		if (chose == null && tabs.value.length > 0) {
			change(tabs.value[tabs.value.length - 1]['id'])
		}
	};

	watch(route, function() {
		if (route.path != "/" && route.path != "/index") {
			let bool = false;
			tabs.value.forEach((tab) => {
				if (tab['id'] === route['path']) {
					bool = true;
				}
			});

			if (!bool) {
				tabs.value.push({
					id: route.fullPath,
					title: route.meta.title
				});
			}
		}
	});
</script>
