import { pinia, useKeepAliveStore } from '../index'
import { TabsMenuProps } from '../interface'
import router from '@/router'

export const useTabsStore = defineStore('eco-tabs', {
  state: () => ({
    tabsMenuList: [] as TabsMenuProps[]
  }),
  getters: {
    getTabsMenuList: state => state.tabsMenuList
  },
  actions: {
    addTabs(tabItem: TabsMenuProps) {
      const keepAliveStore = useKeepAliveStore()
      const index = this.tabsMenuList.findIndex(item => item.path === tabItem.path)
      if (index === -1) {
        this.tabsMenuList.push(tabItem)
      } else {
        this.tabsMenuList.splice(index, 1, tabItem)
      }
      if (!keepAliveStore.keepAliveName.includes(tabItem.name) && tabItem.isKeepAlive) {
        keepAliveStore.addKeepAliveName(tabItem.name)
      }
    },
    removeTabs(tabPath: string, isCurrent = true) {
      const tabsMenus = this.tabsMenuList
      if (isCurrent) {
        tabsMenus.forEach((item, index) => {
          if (item.path !== tabPath) return
          const nextTab = tabsMenus[index + 1] || tabsMenus[index - 1]
          if (!nextTab) return
          router.push(nextTab.path)
        })
      }
      this.tabsMenuList = tabsMenus.filter(item => item.path !== tabPath)
    },
    closeTabsOnSide(path: string, type: string) {
      const keepAliveStore = useKeepAliveStore()
      const currentIndex = this.tabsMenuList.findIndex(item => item.path === path)
      if (currentIndex !== -1) {
        const range = type === 'left' ? [0, currentIndex] : [currentIndex + 1, this.tabsMenuList.length]
        this.tabsMenuList = this.tabsMenuList.filter((item, index) => {
          return index < range[0] || index >= range[1] || !item.close
        })
      }
      keepAliveStore.setKeepAliveName(this.tabsMenuList.map(item => item.name))
    },
    closeMultipleTab(tabsMenuValue?: string) {
      const keepAliveStore = useKeepAliveStore()
      this.tabsMenuList = this.tabsMenuList.filter(item => {
        return item.path === tabsMenuValue || !item.close
      })
      keepAliveStore.setKeepAliveName(this.tabsMenuList.map(item => item.name))
    },
    setTabs(menus: TabsMenuProps[]) {
      this.tabsMenuList = menus
    },
    setTabsTitle(title: string) {
      const nowFullPath = location.hash.substring(1)
      this.tabsMenuList.forEach(item => {
        if (item.path === nowFullPath) item.title = title
      })
    }
  },
  persist: true
})

export const useTabsStoreWithOut = () => {
  return useTabsStore(pinia)
}
