yxh
2026-10-05 936c01060eea0924b88ca5c35d221a972a6aba7d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
import router from './router'
import type { RouteRecordRaw } from 'vue-router'
import { isRelogin } from '@/config/axios/service'
import { getAccessToken, removeToken } from '@/utils/auth'
import { deleteUserCache } from '@/hooks/web/useCache'
import { useTitle } from '@/hooks/web/useTitle'
import { useNProgress } from '@/hooks/web/useNProgress'
import { usePageLoading } from '@/hooks/web/usePageLoading'
import { useDictStoreWithOut } from '@/store/modules/dict'
import { useCheckTypeStoreWithOut } from '@/store/modules/checkType'
import { useUserStoreWithOut } from '@/store/modules/user'
import { usePermissionStoreWithOut } from '@/store/modules/permission'
import { useRoomStoreWithOut } from "@/store/modules/room";
// 需求:30 分钟无操作才要求重新登录(前端空闲检测)
import { setupIdleLogout } from '@/hooks/web/useIdleLogout'
import { setupBedReleaseOnUnload } from '@/utils/releaseBed'
 
const { start, done } = useNProgress()
 
const { loadStart, loadDone } = usePageLoading()
 
const parseURL = (
  url: string | null | undefined
): { basePath: string; paramsObject: { [key: string]: string } } => {
  // 如果输入为 null 或 undefined,返回空字符串和空对象
  if (url == null) {
    return { basePath: '', paramsObject: {} }
  }
 
  // 找到问号 (?) 的位置,它之前是基础路径,之后是查询参数
  const questionMarkIndex = url.indexOf('?')
  let basePath = url
  const paramsObject: { [key: string]: string } = {}
 
  // 如果找到了问号,说明有查询参数
  if (questionMarkIndex !== -1) {
    // 获取 basePath
    basePath = url.substring(0, questionMarkIndex)
 
    // 从 URL 中获取查询字符串部分
    const queryString = url.substring(questionMarkIndex + 1)
 
    // 使用 URLSearchParams 遍历参数
    const searchParams = new URLSearchParams(queryString)
    searchParams.forEach((value, key) => {
      // 封装进 paramsObject 对象
      paramsObject[key] = value
    })
  }
 
  // 返回 basePath 和 paramsObject
  return { basePath, paramsObject }
}
 
// 路由不重定向白名单
const whiteList = [
  '/login',
  '/social-login',
  '/auth-redirect',
  '/bind',
  '/register',
  '/oauthLogin/gitee',
  '/calling-screen-big',
  '/calling-screen-room'
]
 
// 路由加载前
router.beforeEach(async (to, from, next) => {
  console.info("router.beforeEach to: " + to.fullPath + " from: " + from.fullPath)
  start()
  loadStart()
 
  if (whiteList.indexOf(to.path) !== -1) {
    next()
    return
  }
 
  if (!getAccessToken()) {
    next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
    return
  }
 
  // ==========================================================================
  // 【修复】以下所有 await 都必须包在 try/catch 内。
  //
  // 背景:localStorage 里可能残留**已失效的 token**(服务端重启、令牌过期等)。
  // 此时 getAccessToken() 仍有值 → 守卫不会跳登录页 → 继续用旧 token 请求后端
  // → 401 → handleAuthorized() 返回 Promise.reject('登录超时,请重新登录!')。
  // 原先该 reject 无人捕获,会一路冒泡到 setupRouter(),导致:
  //     [Vue Router warn] uncaught error during route navigation
  //     [Vue Router warn] Unexpected error when starting the router
  //     main.ts:76 Uncaught (in promise) 登录超时,请重新登录!
  // **路由安装失败,整个页面起不来**(用户必须手动重新登录才恢复)。
  //
  // 现在统一兜底:无论鉴权失败还是其他异常,都清掉本地失效凭证并转登录页,
  // 保证路由器一定能完成初始化。
  //
  // 注:原先此处还有 `if (to.path === '/login') next({path:'/'})`,
  // 因 '/login' 已在 whiteList 中提前 return,该分支永不可达,已移除。
  // ==========================================================================
  try {
    // 获取所有字典
    const dictStore = useDictStoreWithOut()
    const userStore = useUserStoreWithOut()
    const roomStore = useRoomStoreWithOut()
    const checkTypeStore = useCheckTypeStoreWithOut()
    const permissionStore = usePermissionStoreWithOut()
    if (!dictStore.getIsSetDict) {
      await dictStore.setDictMap()
    }
    if (!checkTypeStore.getIsSetCheckType) {
      await checkTypeStore.setCheckTypeMap()
    }
 
    if (userStore.getIsSetUser) {
 
      // <<<【诊室选择】<<<
      if (to.path !== '/roomselect' &&
          userStore.getRoles.includes("doctor") && !userStore.getRoles.includes("super_admin")
          && !roomStore.getIsSetRoom) {
        next({ path: `/roomselect?redirect=${to.fullPath}` })
        return
      }
 
      next()
      return
    }
 
    isRelogin.show = true
    await userStore.setUserInfoAction()
    isRelogin.show = false
 
    // 后端过滤菜单
    await permissionStore.generateRoutes()
    permissionStore.getAddRouters.forEach((route) => {
      router.addRoute(route as unknown as RouteRecordRaw) // 动态添加可访问路由表
    })
 
    // <<<【诊室选择】<<<
    if (to.path !== '/roomselect' &&
        userStore.getRoles.includes("doctor") && !userStore.getRoles.includes("super_admin")
        && !roomStore.getIsSetRoom) {
      next({ path: `/roomselect?redirect=${to.fullPath}` })
      return
    }
 
    const redirectPath = from.query.redirect || to.path
    // 修复跳转时不带参数的问题
    const redirect = decodeURIComponent(redirectPath as string)
    const { paramsObject: query } = parseURL(redirect)
    const nextData = to.path === redirect ? { ...to, replace: true } : { path: redirect, query }
    next(nextData)
  } catch (e) {
    // 兜底:清理本地失效凭证,放行到登录页,绝不让异常中断路由初始化
    console.warn('[permission] 路由守卫执行失败,已清理本地凭证并转登录页:', e)
    isRelogin.show = false
    removeToken()
    deleteUserCache()
    next(`/login?redirect=${to.fullPath}`)
  }
})
 
router.afterEach((to) => {
  useTitle(to?.meta?.title as string)
  done() // 结束Progress
  loadDone()
 
  // ==========================================================================
  // 需求:**30 分钟不操作**才要求重新输入密码。
  //
  // 背景:后端 token 是固定有效期(system_oauth2_client.access_token_validity_seconds,
  // 当前 default 客户端 = 3600 秒),与用户是否有操作无关 —— 挂着不动也会到点被踢。
  // 这里在前端补上**真正的空闲检测**:
  //   · 有鼠标/键盘/触摸/滚动等操作 → 计时重置;
  //   · 连续 30 分钟无任何操作   → 主动清凭证并跳登录页。
  // 仪表盘/叫号屏等白名单页面不会走到这里,不受影响。
  //
  // 只在**已登录**且非登录页时启动;setupIdleLogout 内部幂等,重复调用无副作用。
  // ==========================================================================
  if (getAccessToken() && to.path !== '/login') {
    setupIdleLogout()
    // 需求:退出系统时自动退出占用的诊疗床位。
    // 注册 `pagehide` 兜底(关闭标签页/刷新/跳走)—— 内部自带幂等保护,
    // 只是"尽力而为"的最后一层;主要保障在 useIdleLogout / userStore.loginOut /
    // axios 的 handleAuthorized 三处明确的退出路径上。
    setupBedReleaseOnUnload()
  }
})