import { defineStore } from 'pinia'
import { RouteLocationNormalized } from 'vue-router'
import { Searchs } from '@/utils/searchs'
// 不需要出现在标签页中的路由
const whiteList = ['Redirect', 'login']
const searchs = new Searchs('')
export type RouteItem = Partial<RouteLocationNormalized> & {
  fullPath: string
  path: string
  name: string
  hash: string
  meta: object
  params: object
  query: object
}

export type ITabsViewState = {
  tabsList: RouteItem[] // 标签页
}

//保留固定路由
function retainAffixRoute(list: any[]) {
  return list.filter((item) => item?.meta?.affix ?? false)
}

export const useTabsViewStore = defineStore({
  id: 'app-tabs-view',
  state: (): ITabsViewState => ({
    tabsList: []
  }),
  getters: {},
  actions: {
    initTabs(routes: any) {
      // 初始化标签页
      this.tabsList = routes
    },
    addTabs(route: any): boolean {
      // 添加标签页
      if (whiteList.includes(route.name)) return false
      // console.log(route, 'addTabs fullPath')
      const isExists = this.tabsList.some((item) => item.path == route.path)
      if (!isExists) {
        this.tabsList.push(route)
      }
      return true
    },
    closeLeftTabs(route: any) {
      // 关闭左侧
      const index = this.tabsList.findIndex((item) => item.path == route.path)
      this.tabsList = this.tabsList.filter((item, i) => i >= index || (item?.meta?.affix ?? false))
    },
    closeRightTabs(route: any) {
      // 关闭右侧
      const index = this.tabsList.findIndex((item) => item.path == route.path)
      this.tabsList = this.tabsList.filter((item, i) => i <= index || (item?.meta?.affix ?? false))
    },
    closeOtherTabs(route: any) {
      // 关闭其他
      this.tabsList = this.tabsList.filter(
        (item) => item.path == route.path || (item?.meta?.affix ?? false)
      )
      searchs.removeByOtherRouter(route.path)
    },
    closeCurrentTab(route: any) {
      // 关闭当前页
      if (route) {
        searchs.removeByRouter(route.path)
        const index = this.tabsList.findIndex((item) => item.path == route.path)
        if (index != -1) {
          this.tabsList.splice(index, 1)
        }
      }
    },
    closeAllTabs() {
      // 关闭全部
      searchs.removeAll()
      this.tabsList = retainAffixRoute(this.tabsList)
    }
  }
})
