import type { RouteKey } from '@elegant-router/types'
import type { RouteLocationRaw } from 'vue-router'
import { useRouter } from 'vue-router'
import { router as globalRouter } from '@/router'
import { useRouteStore } from '@/store/modules/route'

/**
 * 路由跳转
 *
 * 跳转到指定路由，可替换函数 router.push
 *
 * @param inSetup 是否在 vue script setup 中
 */
export function useRouterPush(inSetup = true) {
  const router = inSetup ? useRouter() : globalRouter
  const route = globalRouter.currentRoute

  const routerPush = router.push

  const routerBack = router.back

  async function routerPushByKey(key: RouteKey, options?: App.Global.RouterPushOptions) {
    const { query, params } = options || {}

    const routeLocation: RouteLocationRaw = {
      name: key,
    }

    if (Object.keys(query || {}).length) {
      routeLocation.query = query
    }

    if (Object.keys(params || {}).length) {
      routeLocation.params = params
    }

    return routerPush(routeLocation)
  }

  /**
   * 路由跳转并携带 meta 中的 query 参数
   *
   * @param key 路由名称
   */
  function routerPushByKeyWithMetaQuery(key: RouteKey) {
    const routeStore = useRouteStore()
    const allRoutes = router.getRoutes()
    const meta = allRoutes.find(item => item.name === key)?.meta || null

    const menu = routeStore.menus.find(item => item.key === key)
    if (menu?.children && menu.children.length > 0) {
      const visibleChildren = menu.children.filter((child) => {
        const childRoute = allRoutes.find(r => r.name === child.key)
        return childRoute && !childRoute.meta?.hideInMenu
      })
      if (visibleChildren.length === 1) {
        return routerPushByKey(visibleChildren[0].key as RouteKey)
      }
    }

    const query: Record<string, string> = {}

    meta?.query?.forEach((item) => {
      query[item.key] = item.value
    })

    return routerPushByKey(key, { query })
  }

  async function toHome() {
    return routerPushByKey('root')
  }

  /**
   * 跳转到登录页
   *
   * @param loginModule 登录模块
   * @param redirectUrl 重定向地址，若未指定，则为当前路由 fullPath
   */
  async function toLogin(loginModule?: UnionKey.LoginModule, redirectUrl?: string) {
    const module = loginModule || 'pwd-login'

    const options: App.Global.RouterPushOptions = {
      params: {
        module,
      },
    }

    const redirect = redirectUrl || route.value.fullPath

    options.query = {
      redirect,
    }

    return routerPushByKey('login', options)
  }

  /**
   * 切换登录模块
   *
   * @param module
   */
  async function toggleLoginModule(module: UnionKey.LoginModule) {
    const query = route.value.query as Record<string, string>

    return routerPushByKey('login', { query, params: { module } })
  }

  /**
   * 从登录页重定向
   *
   * @param [needRedirect] 登录后是否需要重定向。默认为 `true`
   */
  async function redirectFromLogin(needRedirect = true) {
    const redirect = route.value.query?.redirect as string

    if (needRedirect && redirect) {
      await routerPush(redirect)
    }
    else {
      await toHome()
    }
  }

  return {
    routerPush,
    routerBack,
    routerPushByKey,
    routerPushByKeyWithMetaQuery,
    toLogin,
    toggleLoginModule,
    redirectFromLogin,
  }
}
