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: '/MyDownloads',
          name: 'MyDownloads',
          meta: {
            title: '我的下载',
          },
          component: () => import('@/views/MyDownloads.vue'),
        },
      ],
    },
    // 登录
    {
      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 放到 beforeEach 并 await：
    // 进入新页面前先把 buttons 清空，避免上一页按钮残留。
    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
