<template>
	<div class="tab-container">
		<div class="tabs">
			<div class="label" @click="selected = index" :class="{selected: index === selected}" v-for="(item, index) in list">
				{{ item.name }}
				<a-icon class="close" @click.stop="deleteItems(item.name)" type="close" />
			</div>
		</div>
		<keep-alive>
			<component :is="list[selected]&&list[selected].component" ></component>
		</keep-alive>
	</div>
</template>

<script>
export default {
	name: "TabContainer",
	data: function () {
		return {
			list: [],
			selected: 0
		}
	},
	props: {
		id: String
	},
	mounted() {
		this.checkIsAvailable();
	},
	methods: {
	    checkIsAvailable() {
	    	if (this.id) {
	    		this.bus.$on(`${this.id}-push-tab`, this.pushTab);
			    this.bus.$on(`${this.id}-shift-tab`, this.deleteItems);
		    }
	    },
		pushTab(data) {
	    	if (!this.list.some(item => item.name === data.name)) {
			    this.list.push(data);
			    this.selected = this.list.length - 1;
		    }
		},
		deleteItems(name) {
	    	const index = this.list.findIndex(item => item.name === name);
	    	const target = this.list[index];
	    	target.onDelete();
	    	this.list.splice(index, 1);
		}
	},
	beforeDestroy() {
		this.bus.$off(`${this.id}-push-tab`, this.pushTab);
	}
}
</script>

<style scoped lang="scss">
.tab-container {
	height: 100%;
	width: 100%;
	display: grid;
	grid-template-rows: 40px 1fr;
	.tabs {
		width: 100%;
		height: 40px;
		display: flex;
		background-color: #21242B;
		.label {
			height: 100%;
			display: flex;
			align-items: center;
			padding: 0 10px;
			border-bottom: 2px solid transparent;
			&.selected {
				background: #383E49;
				border-bottom: 2px solid #2764CA;
			}
			.close {
				cursor: pointer;
				margin-left: 5px;
			}
		}
	}
}
</style>
