import { defineStore } from 'pinia'
import { ConstantStore } from '@/enum/store'
import { reactive, watch } from 'vue'
import RootRouter from '@/router'
import VueRouter, { RouteRecordRaw } from 'vue-router'

const initAppRouterState: ROUTER.RouterRecords = {
  navbar: {
    route: [],
    selectPath: []
  },
  sider: {
    route: [],
    selectPath: '',
    openKeys: []
  }
}

export const useAppRouter = defineStore(ConstantStore.ROUTER, () => {
  const appRouter = reactive<ROUTER.RouterRecords>(initAppRouterState)

  const initAppRouter = () => {
    appRouter.navbar.route = RootRouter.options.routes.map((route: any) => {
      return {
        path: route.link ? route.path.substr(1) : route.path,
        name: route.name,
        link: !!route.link,
        redirect: route.redirect || ''
      }
    }).filter(_ => _.path !== '/login')

    appRouter.sider.route = RootRouter.options.routes[1].children!
  }

  if (appRouter.navbar.route.length === 0) {
    initAppRouter()
  }

  const changeNavbarRoute = (route: ROUTER.RoutesProps) => {
    if (route.link) {
      window.open(route.path)
    } else {
      appRouter.navbar.selectPath = [route.path]
      RootRouter.push(route.path)
    }
  }

  // 根据当前子路由，逐级向上查找到根路由
  function findRootRoute (data, path: string) {
    const routes = RootRouter.options.routes as RouteRecordRaw[]

    const getParentRouteByPath = (routes: RouteRecordRaw, path: string) => {
      if (routes.children && routes.children.length > 0) {
        const index = routes.children.findIndex(route => route.path === path)
        return index >= 0
      } else {
        return false
      }
    }

    const count = 0

    const fn = (route: RouteRecordRaw) => {
      const chidlren = route.children
      if (!chidlren) {
        console.log(route.path === path)
        if (route.path === path) return true
      } else {
        for (let i = 0; i < chidlren.length; i++) {
          fn(chidlren[i])
        }
      }
    }

    routes.forEach(route => {
      console.log('fn(route):', fn(route))

      if (fn(route)) {
        console.log('寻找顶级及诶点:', route.path)
      }
    })
  }

  return {
    router: appRouter,
    changeNavbarRoute,
    findRootRoute: (path) => findRootRoute(RootRouter.options.routes, path)
  }
})
