import {defineStore} from "pinia";
import router from '@/router'

const viewTagsStore = defineStore("viewTags", {
	state: () => ({
		viewTags: []
	}),
	actions: {
		pushViewTags(route){
			let backPathIndex = this.viewTags.findIndex(item => item.fullPath == router.options.history.state.back)
			let target = this.viewTags.find((item) => item.fullPath === route.fullPath)
			let isName = route.name
			if(!target && isName){
				const _route = {
					name: route.name,
					fullPath: route.fullPath,
					component: route.component,
					path: route.path,
					scrollTop: route.scrollTop,
					meta: {
						hidden: route?.meta?.hidden,
						icon: route?.meta?.icon,
						affix: route?.meta?.affix,
						type: route?.meta?.type,
						title: route?.meta?.title,
					},
					query: route.query,
					params: route.params,
					hash: route.hash,
					props: route.props
				}
				if(backPathIndex == -1){
					this.viewTags.push(_route)
				}else{
					// 后台首页移动到首个标签中
					if (_route.fullPath === "/dashboard") {
						this.viewTags.unshift(_route)
					}else {
						this.viewTags.splice(backPathIndex+1, 0, _route)
					}
				}
			}
		},
		removeViewTags(route){
			this.viewTags.forEach((item, index) => {
				if (item.fullPath === route.fullPath){
					this.viewTags.splice(index, 1)
				}
			})
		},
		updateViewTags(route){
			this.viewTags.forEach((item) => {
				if (item.fullPath == route.fullPath){
					// 追加数据
					item = Object.assign(item, route)
				}
			})
		},
		updateViewTagsTitle(title=''){
			const nowFullPath = location.hash.substring(1)
			this.viewTags.forEach((item) => {
				if (item.fullPath == nowFullPath){
					item.meta.title = title
				}
			})
		},
		clearViewTags(){
			this.viewTags = []
		},
		moveViewTags(oldIndex, newIndex) {
			const item = this.viewTags.splice(oldIndex, 1)[0]  // 取出 tags
			this.viewTags.splice(newIndex, 0, item)            // 插入新位置
		}
	},
	persist: true
})

export default viewTagsStore
