import { defineStore } from 'pinia'
import { ref } from 'vue'
import { RouteRecordRaw } from 'vue-router'
import router, { routes } from '@/router'
import { useAppRouter } from '@/store/router'

export const useRouterTravelStore = defineStore('routerTravelStore', () => {
  const appRouter = useAppRouter()

  const history = ref<RouteRecordRaw[]>([])

  const currentRoute = ref<RouteRecordRaw>()

  const currenRouteIndex = ref<number>(0)

  const keyCount = ref<number>(0)

  const init = () => {
    push(JSON.parse(JSON.stringify(routes[1].children[0])))
    currentRoute.value = history.value[0]
  }

  const del = (path: string) => {
    const index = history.value.findIndex(item => item.path === path)

    if (index === currenRouteIndex.value) {
      currenRouteIndex.value = index - 1
      currentRoute.value = history.value[currenRouteIndex.value]
      history.value.splice(currenRouteIndex.value + 1, 1)
    } else {
      history.value.splice(index, 1)
    }

    router.push(currentRoute.value!.path)
  }

  const push = (route: RouteRecordRaw) => {
    const index = history.value.findIndex(item => item.path === route.path)
    if (index !== -1) {
      currenRouteIndex.value = index
    } else {
      history.value.push(route)
      currenRouteIndex.value = history.value.length - 1
    }
    currentRoute.value = route

    // console.log('寻找顶级节点:')
  }

  const setCurrentRoute = (route: RouteRecordRaw) => {
    currentRoute.value = route

    router.push(currentRoute.value!.path)
  }

  const closeOtherPage = () => {
    history.value = [JSON.parse(JSON.stringify(routes[1].children[0])), currentRoute.value]
    currenRouteIndex.value = history.value.length - 1
  }

  init()

  return {
    history,
    currentRoute,
    currenRouteIndex,
    keyCount,
    setCurrentRoute,
    push,
    del,
    closeOtherPage
  }
}, {
  persist: true
})
