import router from '@/routers'
import { defineStore } from 'pinia'
import { TabsState, TabsMenuProps } from '@/stores/interface'
import piniaPersistConfig from '@/config/piniaPersist'

export const useTabsStore = defineStore({
  id: 'tabs',
  state: (): TabsState => ({
    tabsMenuList: []
  }),
  actions: {
    // 添加Tab标签
    async addTabs(tabItem: TabsMenuProps) {
      if (this.tabsMenuList.every(item => item.path !== tabItem.path)) {
        this.tabsMenuList.push(tabItem)
      }
    },
    // 删除Tab标签
    async removeTabs(tabPath: string, isCurrent: boolean = true) {
      const tabsMenuList = this.tabsMenuList
      if (isCurrent) {
        tabsMenuList.forEach((item, index) => {
          if (item.path !== tabPath) return
          const nextTab = tabsMenuList[index - 1] || tabsMenuList[index + 1]
          if (!nextTab) return
          router.push(nextTab.path)
        })
      }
      this.tabsMenuList = tabsMenuList.filter(item => item.path !== tabPath)
    },
    // 关闭其他Tab标签
    async closeMultipleTab(tabsMenuValue?: string) {
      this.tabsMenuList = this.tabsMenuList.filter(item => {
        return item.path === tabsMenuValue || !item.close
      })
    },
    // 关闭左侧/右侧Tab标签
    async closeSomeTabs(menus: TabsMenuProps[]) {
      this.tabsMenuList = this.tabsMenuList.filter(v => !menus.includes(v))
    }
  },

  persist: piniaPersistConfig('tabs')
})
