import {
  createRouter,
  createWebHistory,
  RouteLocationNormalized,
  NavigationGuardNext,
  type RouteRecordRaw,
} from 'vue-router'
import { cleanupImagePreview } from '@/utils/hooks/useImagePreview.'

import Login from '@/views/Login.vue'
import Reset from '@/views/Reset.vue'
import Home from '@/views/Home.vue'
import Error from '@/views/error/404.vue'
import { Dashboard } from '@/router/dynamicRoutes'
import { getToken } from '@/api/axios'
import { getSysPermissionApi } from '@/api/role'
import useMenuTreeStore from '@/store/menuTree'

export const HOME_ROUTE_NAME = 'HomeShell'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      name: HOME_ROUTE_NAME,
      redirect: '/user/login',
      component: Home,
      children: [
        {
          path: '/dashboard',
          meta: {
            title: '概览',
          },
          component: Dashboard,
        },
      ],
    },
    // 登录
    {
      path: '/user/login',
      component: Login,
    },
    {
      path: '/user/reset',
      component: Reset,
    },

    // 其他路由
    {
      path: '/:pathMatch(.*)*',
      component: Error,
    },
  ],
})

/**
 * 把 sysMenus 对应的业务路由全部挂到 / (Home) 下。
 * - 静态路由（login/reset/404/dashboard）永远存在
 * - 业务路由由后端菜单决定
 * - 重复注册前先 removeRoute(path) 防止堆叠
 */
export function registerDynamicRoutes(records: RouteRecordRaw[]) {
  for (const r of records) {
    if (router.hasRoute(r.path)) {
      router.removeRoute(r.path)
    }
    router.addRoute(HOME_ROUTE_NAME, r)
  }
}

let pendingReqMenu = ''

router.beforeEach(
  async (
    to: RouteLocationNormalized,
    _from: RouteLocationNormalized,
    next: NavigationGuardNext,
  ) => {
    // 路由切换时清理图片预览，防止预览元素残留
    cleanupImagePreview()
    const token = getToken()
    if (to.query.factoryCode) {
      localStorage.setItem('factory_code', String(to.query.factoryCode))
    }
    if (!token && to.path !== '/user/login') {
      next({ path: '/user/login' })
      return
    }

    // 把 getSysPermissionApi 从 afterEach 整体挪到 beforeEach 并 await：
    // 保证组件 onMounted 触发 getTreeNum 时，reqMenu.buttons 已就绪，
    // 避免 children 一上来就被 roleShow 一次性过滤成空数组。
    // 进入新页面前先把 buttons 清空，避免上一页按钮残留（option 4 思路）。
    if (token && to.path !== '/user/login') {
      const reqMenu = (to.meta?.permissionRoute as string) || to.path
      if (reqMenu && reqMenu !== pendingReqMenu) {
        pendingReqMenu = reqMenu
        const menuTreeStore = useMenuTreeStore()
        menuTreeStore.setReqMenu({ buttons: [] })
        try {
          const res = await getSysPermissionApi(reqMenu)
          if (pendingReqMenu === reqMenu && res?.data) {
            menuTreeStore.setReqMenu(res.data)
          }
        } catch {
          if (pendingReqMenu === reqMenu) {
            pendingReqMenu = ''
          }
          // 静默失败：roleShow 在 buttons 为空时直接返回 false
        }
      }
    }

    next()
  },
)

export default router
