import Colls from '@/common/utils/colls'
import {
  createRouter,
  createWebHistory,
} from 'vue-router'
import Evt from '@/common/utils/evt.ts'
import { useAppSettingStore } from '@/common/app/app-setting-store.ts'
import { useAppUserStore } from '@/common/app/app-user-store.ts'
import { MenuCategory } from '@/common/app/constants.ts'
import { appBaseUrl } from '@/common'
import strings from '@/common/utils/strings.ts'
import Strings from '@/common/utils/strings.ts'
import {
  getRoute,
  getRoutes,
} from '@/common/router/route-config.ts'
import { SpecialPage } from '@/common/router/constants.ts'
import { reloadUserInfo } from '@/common/app'

function addRoutes(routNames: string[]) {
  if (Colls.isEmpty(routNames)) return

  routNames = routNames.filter((it) => !strings.isEmpty(it) && !router.hasRoute(it))

  const routes = getRoutes(routNames)
  for (const routeInfo of routes) {
    const {parent, route} = routeInfo
    if (route.name === parent) {
      router.addRoute(route)
    } else {
      router.addRoute(parent, route)
    }
  }
}

export function removeRoutes(routNames: string[]) {
  if (Colls.isEmpty(routNames)) return
  for (const routName of routNames) {
    if (router.hasRoute(routName)) {
      router.removeRoute(routName)
    }
  }
}

// 创建路由实例
const router = function () {
  const mainRoute = getRoute(SpecialPage.Main)!.route
  const homeRouteInfo = getRoute(SpecialPage.Home)
  if (homeRouteInfo != null) {
    mainRoute.redirect = '/' + SpecialPage.Home
    mainRoute.children = [ homeRouteInfo.route ]
  }
  const loginRoute = getRoute(SpecialPage.Login)!.route
  const notFoundRoute = getRoute(SpecialPage.NotFound)!.route
  return createRouter({
    history: createWebHistory(appBaseUrl),
    routes: [ mainRoute, loginRoute, notFoundRoute ],
  })
}()

router.beforeEach((to, from) => {
  const appUserStore = useAppUserStore()
  const name = <string>to.name

  // 已登录
  if (appUserStore.isAuthenticated) {
    if (from.path === '/' && router.getRoutes().length <= 4) {// 浏览器刷新
      return reloadRouter()
        .then(succ => {
          if (!succ
            && SpecialPage.Login !== name
            && SpecialPage.Home !== name
            && SpecialPage.Main !== name
            && SpecialPage.NotFound !== name) {
            return {
              replace: true,
              name: SpecialPage.Home,
            }
          } else {
            let routeName = router.getRoutes().find((it) => it.path === to.path)?.name as string
            if (Strings.isBlank(routeName)) {
              routeName = SpecialPage.Home
            }
            setTimeout(() => {
              Evt.emit('browserReflash', routeName)
            })
            return false
          }
        })
      /* const succ = reloadRouter()
       if (!succ
       && SpecialPage.Login !== name
       && SpecialPage.Home !== name
       && SpecialPage.Main !== name
       && SpecialPage.NotFound !== name) {
       return {
       replace: true,
       name: SpecialPage.Home,
       }
       } else {
       let routeName = router.getRoutes().find((it) => it.path === to.path)?.name as string
       if (Strings.isBlank(routeName)) {
       routeName = SpecialPage.Home
       }
       setTimeout(() => {
       Evt.emit('browserReflash', routeName)
       })
       return false
       } */
    }
    return true
  }
  // 未登录
  if (SpecialPage.Login === name || SpecialPage.NotFound === name) {
    return true
  }

  return {
    replace: true,
    name: SpecialPage.Login,
  }
})

router.afterEach(() => {
})

export function reloadRouter() {
  const routes = router
    .getRoutes()
    .filter((it) => it.name !== SpecialPage.Main && it.name !== SpecialPage.Login && it.name !== SpecialPage.NotFound && it.name !== SpecialPage.Home)
    .map((it) => it.name as string)
  removeRoutes(routes)
  return reloadUserInfo()
    .then(() => {
      const routNames = useAppSettingStore()
        .menus.filter((it) => it.menuCategory === MenuCategory.Page || it.menuCategory === MenuCategory.SubPage)
        .map((it) => it.routeName)
      if (Colls.isEmpty(routNames)) {
        return false
      }
      addRoutes(routNames)
      return true
    })
}

export default router
