import Evt from '@/common/utils/evt.ts'
import Nav from '@/common/router/nav.ts'

export const useTabListStore = defineStore('TabList', () => {

  const tabList = ref<TabList.Tab[]>([ {
    id: '1',
    title: '首页',
    routeName: 'home',
    breadcrumb: [ '首页' ]
  } ])

  const openTab = (tab: TabList.Tab) => {
    tab.breadcrumb.splice(tab.breadcrumb.length - 1, 1, tab.title)
    const oldTab = tabList.value.findIndex(it => it.id === tab.id)
    if (oldTab === -1) {
      tabList.value.unshift(tab)
      return true
    }
    if (oldTab === 0) {
      const item = tabList.value[0]
      item.title = tab.title
      item.breadcrumb = tab.breadcrumb
      return false
    }
    const item = tabList.value.splice(oldTab, 1)[0]
    item.title = tab.title
    item.breadcrumb = tab.breadcrumb
    tabList.value.unshift(item)
    return true
  }

  const closeTab = (id: string) => {
    if (id === '1') return
    const oldTabIndex = tabList.value.findIndex(it => it.id === id)
    if (oldTabIndex === -1) return
    if (oldTabIndex === 0) {
      Nav.open(tabList.value[0].routeName)
    }
  }

  function $reset() {
    tabList.value = [ {
      id: '1',
      title: '首页',
      routeName: 'home',
      breadcrumb: [ '首页' ]
    } ]
  }

  Evt.on('logout', $reset)

  return {
    tabList,
    openTab,
    closeTab,
    $reset,
  }
})
