<template>
  <a-card
    class="main-card"
		v-bind="cardAttrs"
		v-on="cardListeners">
		<keep-alive>
			<router-view />
		</keep-alive>
  </a-card>
</template>

<script>
import authority from '@iwotech/admin-common/mixins/authority'
export default {
	mixins: [authority],
	computed: {
		// tab 列表
		tabsList () {
			const menu = this.getTabRoute() || []
			return menu.map(v => ({ key: v.name, tab: v.meta.tab, authority: v.meta.authority }))
		},
		cardAttrs() {
			if (this.tabsList.length <= 1) {
				return { title: this.$route.meta.tab || '' }
			}
			return {
				tabList: this.tabsList,
				activeTabKey: this.$route.name || ''
			}
		},
		cardListeners() {
			if (this.tabsList.length <= 1) return {}
			return {
				tabChange: this.toggleTab
			}
		}
	},
	methods: {
		getTabRoute () {
			const matched = this.$route.matched
			let routes = this.$router.options.routes
			function getParent(rs, name) {
				const parent = rs.filter((v) => v.name === name)
				if (parent.length) return parent[0]
				return null
			}
			for (let i = 0; i < matched.length; i++) {
				const route = matched[i]
				const parent = getParent(routes, route.name)
				if (!parent) return []
				routes = parent.children || []
				const result = routes.filter((v) => v.meta && v.meta.tab)
				if (result.length) {
					const r = (result || []).filter(v => !v.meta.authority || (v.meta.authority && this.allow.includes(v.meta.authority)))
					if (r.length && result.length !== r.length) {
						!r.map(v => v.name).includes(this.$route.name) && this.toggleTab(r[0].name)
					}
					return r
				}
			}
		},
		toggleTab (key) {
			this.$router.replace({
				name: key
			})
		}
	}
}
</script>
