import {
	defineStore
} from 'pinia'
import {
	ref,
	computed
} from 'vue'
import router from '@/router'

export const useTabsBarStore = defineStore('tabsbar', () => {

		const openedPageList = ref([])
		const activePage = ref({
			'name': '',
			'path': ''
		})

		function addTab(data) {
			//添加到当前活动页后面
			let index = 1
			for (let openedPage of openedPageList.value) {
				if (openedPage.path === activePage.value.path) {
					break
				}
				index++
			}
			openedPageList.value.splice(index, 0, {
				'name': data.name,
				'path': data.path
			})
			//删除刷新时产生的空白
			let indexRemove = 0
			for (let openedPage of openedPageList.value) {
				if (openedPage.name === null || openedPage.name === '') {
					break
				}
				indexRemove++
			}
			openedPageList.value.splice(indexRemove, 1)
		}

		function removeTab(path) {
			let index = 0
			for (let openedPage of openedPageList.value) {
				if (openedPage.path === path) {
					break
				}
				index++
			}
			openedPageList.value.splice(index, 1)

			if (openedPageList.value.length == 0) {
				openedPageList.value.push({
					'name': '主页',
					'path': '/main'
				})
				activePage.value = {
					'name': '主页',
					'path': '/main'
				}

				router.push({
					'path': '/main'
				})
			}

		}

		function setActive(data) {
			activePage.value = {
				name: data.name,
				path: data.path
			}
		}

		function setOpenedPageList(list) {
			openedPageList.value = list
		}

		return {
			openedPageList,
			activePage,

			addTab,
			removeTab,
			setActive,
			setOpenedPageList
		}
	}, {
		persist: true,
	}

)