import type {
  RouteLocationNormalized,
  LocationQuery,
  RouteParams
} from 'vue-router'
import { defineStore } from 'pinia'
import { DEFAULT_ROUTE, DEFAULT_ROUTE_NAME } from '@/router/routes/index'
import { TabBarState, TagProps } from './types'

const formatTag = (route: RouteLocationNormalized): any => {
  const { name, meta, fullPath, query, params } = route
  return {
    title: meta.title || '',
    name: String(name),
    fullPath,
    query: query || {},
    params: params || {},
    ignoreCache: meta.ignoreCache || false,
    reset: meta.reset,
    parent: {}
  }
}

const useAppStore = defineStore('tabBar', {
  state: (): TabBarState => ({
    cacheTabList: new Set([]),
    tagList: [DEFAULT_ROUTE]
  }),

  getters: {
    getTabList(): TagProps[] {
      return this.tagList
    },
    getCacheList(): string[] {
      return Array.from(this.cacheTabList)
    }
  },

  actions: {
    removeTab(name: string, reset: boolean): number {
      const index = this.tagList.findIndex(item => {
        return (
          item.name === name &&
          item.reset === reset &&
          item.query.keyword !== undefined
        )
      })
      return index
    },
    updateTabList(route: RouteLocationNormalized) {
      const index = this.removeTab(
        route.name as string,
        route.meta.reset as boolean
      )
      if (index >= 0) {
        this.tagList.splice(index, 1)
      }
      if (route.name !== 'login') {
        this.tagList.push(formatTag(route))
      }
      if (!route.meta.ignoreCache) {
        this.cacheTabList.add(route.name as string)
      }
    },
    deleteTag(idx: number, tag: TagProps) {
      this.tagList.splice(idx, 1)
      this.cacheTabList.delete(tag.name)
    },
    freshTabList(tags: TagProps[]) {
      this.tagList = tags
      this.cacheTabList.clear()
      // 要先判断ignoreCache
      this.tagList
        .filter(el => !el.ignoreCache)
        .map(el => el.name)
        .forEach(x => this.cacheTabList.add(x))
    },
    resetTabList() {
      this.tagList = [DEFAULT_ROUTE]
      this.cacheTabList.clear()
      this.cacheTabList.add(DEFAULT_ROUTE_NAME)
    },
    async setTabTitle(title: string, route: RouteLocationNormalized) {
      const findTab = this.getTabList.find(
        item =>
          item.params?.id === route.params?.id &&
          item.query?.type === route.query?.type
      )
      if (findTab) {
        findTab.title = title
      }
    },
    /**
     * 根据详情页的params.id 从列表删除此项时，如果tagList里有则关闭
     * @param id
     */
    async closeDetailTagById(id: string, type?: number) {
      this.tagList = this.tagList.filter(item => {
        if (type) {
          return (
            item.params?.id !== id || parseInt(item.query?.type, 10) !== type
          )
        }

        return item.params?.id !== id
      })
    },
    async closeDetailTag(query: LocationQuery, params: RouteParams) {
      this.tagList = this.tagList.filter(item => {
        return (
          JSON.stringify(item.query) !== JSON.stringify(query) &&
          item.params?.id !== params.id
        )
      })
    }
  }
})

export default useAppStore
