import {nextTick} from 'vue'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import router from '@/router'
import viewTagsStore from "@/store/viewTags";
import keepAliveStore from "@/store/keepAlive";
import iframeStore from "@/store/iframe";

export default {
	//刷新标签
	refresh() {
		NProgress.start()
		const keepAlive = keepAliveStore()
		const route = router.currentRoute.value
		keepAlive.removeKeepLive(route.name)
		keepAlive.setRouteShow(false)
		nextTick(() => {
			keepAlive.pushKeepLive(route.name)
			keepAlive.setRouteShow(true)
			NProgress.done()
		}).then(() => {
		})
	},
	//关闭标签
	close(tag) {
		const viewTags = viewTagsStore()
		const keepAlive = keepAliveStore()
		const iframe = iframeStore()
		const route = tag || router.currentRoute.value
		const tagList = viewTags.viewTags
		// 查询标签位置
		const index = tagList.findIndex(item => item.fullPath === route.fullPath)
		// 移除标签
		viewTags.removeViewTags(route)
		iframe.removeIframeList(route)
		keepAlive.removeKeepLive(route.name)
		if (index <= 0 && tagList.length >= index) {
			const latestView = tagList.slice(-1)[0]
			if (latestView) {
				router.push(latestView)
			} else {
				router.push('/')
			}
		} else {
			// 关闭标签向前一位
			const latestView = tagList[index-1]
			router.push(latestView)
		}
	},
	//关闭标签后处理
	closeNext(next) {
		const viewTags = viewTagsStore()
		const keepAlive = keepAliveStore()
		const iframe = iframeStore()
		const route = router.currentRoute.value
		viewTags.removeViewTags(route)
		iframe.removeIframeList(route)
		keepAlive.removeKeepLive(route.name)
		if (next) {
			const tagList = viewTags.viewTags
			next(tagList)
		}
	},
	//关闭其他
	closeOther() {
		const viewTags = viewTagsStore()
		const route = router.currentRoute.value
		const tagList = [...viewTags.viewTags]
		tagList.forEach(tag => {
			if (tag.meta && tag.meta.affix || route.fullPath == tag.fullPath) {
				return true
			} else {
				this.close(tag)
			}
		})
	},
	//设置标题
	setTitle(title) {
		const viewTags = viewTagsStore()
		viewTags.updateViewTagsTitle(title)
	}
}
