import { defineStore } from 'pinia'

const useTagsViewStore = defineStore('tags-view', {
  state: () => ({
    visitedViews: [], // 存放打开的标签页列表 [{ path, title, name, affix }]
    cachedViews: []   // 存放需要缓存的组件名称 (用于 keep-alive)
  }),
  actions: {
    // 添加标签页
    addView(view) {
      this.addVisitedView(view)
      this.addCachedView(view)
    },
    addVisitedView(view) {
      this.visitedViews = localStorage.getItem('visitedViews') && JSON.parse(localStorage.getItem('visitedViews')) || []
      this.visitedViews.forEach(item => {
        item.active = false
      })
      // 防止重复添加
      const isExists = this.visitedViews.some(v => v.path === view.path)
      if (!isExists) {
        // 可以给不同路由设置不同的标题，比如从 route.meta.title 获取
        this.visitedViews.push({
          ...view,
          title: view.meta?.title || '未命名'
        })
        localStorage.setItem('visitedViews', JSON.stringify(this.visitedViews))
      } else {
        this.visitedViews.forEach(v => {
          if (v.path === view.path) {
            v.active = true
          }
        })
      }
    },
    addCachedView(view) {
      // 只有配置了 keepAlive: true 的路由才加入缓存数组
      if (view.meta?.keepAlive && !this.cachedViews.includes(view.name)) {
        this.cachedViews.push(view.name)
      }
    },
    // 关闭当前标签页
    delView(view) {
      return new Promise((resolve) => {
        // 1. 先从缓存数组中移除（如果有）
        this.delCachedView(view)

        // 2. 再从访问数组中移除
        const index = this.visitedViews.findIndex(v => v.path === view.path)
        if (index !== -1) {
          this.visitedViews.splice(index, 1)
        }
        localStorage.setItem('visitedViews', JSON.stringify(this.visitedViews))
        resolve([...this.visitedViews])
      })
    },

    // 从缓存中移除
    delCachedView(view) {
      if (view.meta?.keepAlive) {
        const index = this.cachedViews.indexOf(view.name)
        if (index !== -1) {
          this.cachedViews.splice(index, 1)
        }
      }
    },

    loadVisitedViewFromLocalStorage() {
      const saved = localStorage.getItem('visitedViews')
      if (saved) {
        this.items = JSON.parse(saved)
      }
    },


    // 关闭其他/右侧/全部
    delOthersViews(view) {
      // ...
    }
  }
})

export default useTagsViewStore