import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useTagsViewStore = defineStore('tagsView', () => {
    const visitedViews = ref([])
    const affixTags = ref([])

    // 添加访问过的标签
    const addVisitedView = (view) => {
        if (visitedViews.value.some(v => v.path === view.path)) return

        // 过滤404和登录页
        if (view.name === 'NotFound' || view.name === 'Login') return

        visitedViews.value.push(
            Object.assign({}, view, {
                title: view.meta.title || 'unknown'
            })
        )
    }

    // 删除访问过的标签
    const delVisitedView = (view) => {
        return new Promise((resolve) => {
            const index = visitedViews.value.findIndex(v => v.path === view.path)
            if (index > -1) {
                visitedViews.value.splice(index, 1)
            }
            resolve([...visitedViews.value])
        })
    }

    // 删除其他标签
    const delOthersViews = (view) => {
        return new Promise((resolve) => {
            visitedViews.value = visitedViews.value.filter(v => {
                return v.meta.affix || v.path === view.path
            })
            resolve([...visitedViews.value])
        })
    }

    // 删除所有标签
    const delAllViews = () => {
        return new Promise((resolve) => {
            visitedViews.value = visitedViews.value.filter(tag => tag.meta.affix)
            resolve([...visitedViews.value])
        })
    }

    // 删除左侧标签
    const delLeftViews = (view) => {
        return new Promise((resolve) => {
            const index = visitedViews.value.findIndex(v => v.path === view.path)
            if (index === -1) {
                resolve([...visitedViews.value])
                return
            }
            visitedViews.value = visitedViews.value.filter((v, i) => {
                return v.meta.affix || i >= index
            })
            resolve([...visitedViews.value])
        })
    }

    // 删除右侧标签
    const delRightViews = (view) => {
        return new Promise((resolve) => {
            const index = visitedViews.value.findIndex(v => v.path === view.path)
            if (index === -1) {
                resolve([...visitedViews.value])
                return
            }
            visitedViews.value = visitedViews.value.filter((v, i) => {
                return v.meta.affix || i <= index
            })
            resolve([...visitedViews.value])
        })
    }

    return {
        visitedViews,
        affixTags,
        addVisitedView,
        delVisitedView,
        delOthersViews,
        delAllViews,
        delLeftViews,
        delRightViews
    }
})
