import router from '@/router'
import tool from '@/utils/tool'

export default {
	state: {
		viewTags: tool.data.get('viewTags') || []
	},
	mutations: {
		pushViewTags(state, route){
			let backPathIndex = state.viewTags.findIndex(item => item.fullPath == router.options.history.state.back)
			let target = state.viewTags.find((item) => item.fullPath === route.fullPath)
			let isName = route.name
			if(!target && isName){
				if(backPathIndex == -1){
					state.viewTags.push(tool.get_data_field(route, ['fullPath', 'hash', 'href', 'meta', 'name', 'params', 'query', 'scrollTop']))
				}else{
					state.viewTags.splice(backPathIndex+1, 0, tool.get_data_field(route, ['fullPath', 'hash', 'href', 'meta', 'name', 'params', 'query', 'scrollTop']))
				}
				tool.data.set('viewTags', state.viewTags)
			}
		},
		removeViewTags(state, route){
			state.viewTags.forEach((item, index) => {
				if (item.fullPath === route.fullPath){
					state.viewTags.splice(index, 1)
				}
			})
			tool.data.set('viewTags', state.viewTags)
		},
		updateViewTags(state, route){
			state.viewTags.forEach((item) => {
				if (item.fullPath == route.fullPath){
					item = Object.assign(item, route)
				}
			})
			tool.data.set('viewTags', state.viewTags)
		},
		updateViewTagsTitle(state, title=''){
			const nowFullPath = location.hash.substring(1)
			state.viewTags.forEach((item) => {
				if (item.fullPath == nowFullPath){
					item.meta.title = title
				}
			})
			tool.data.set('viewTags', state.viewTags)
		},
		clearViewTags(state){
			state.viewTags = []
			tool.data.set('viewTags', state.viewTags)
		}
	}
}
