yxh
yxh
2026-11-08 09dc74e264b6262cbe41c9c8476e24705871d4a6
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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
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'
 
const { start, done } = useNProgress()
 
const { loadStart, loadDone } = usePageLoading()
 
/**
 * 「选择工位模式」的跳转判定(0/1/2/3)。
 *
 * - 0 按需要强制选择工位:未入座 → 强制去选工位页
 * - 1 登录IP匹配工位:先按本机IP自动匹配并自动入座;匹配不到 → 按 0(去选工位页,带原因)
 * - 2 登录时手动选择工位:强制去选工位页,并在确认时把本机IP写入所选工位(写IP在选工位页里做)
 * - 3 按系统默认处理:该IP未绑定过工位 → 按 2(选一次并记住IP);已绑定 → 按 1;匹配不到 → 按 0
 *
 * @returns true 表示已放行(无需跳转),false 表示已经发起跳转
 */
const checkRoomSelect = async (
  to: { path: string; fullPath: string },
  next: (v?: any) => void
): Promise<boolean> => {
  const userStore = useUserStoreWithOut()
  const roomStore = useRoomStoreWithOut()
 
  // 非医生角色、或已入座 → 不干预
  const isDoctor =
    userStore.getRoles.includes('doctor') && !userStore.getRoles.includes('super_admin')
  if (!isDoctor || roomStore.getIsSetRoom || to.path === '/roomselect') {
    // 现场排查用:说明"为什么这次没有自动入座"(admin 等非医生角色按设计不自动入座,
    // 需要点顶栏的「未入座」标签进选工位页手动选一次)
    if (!isDoctor) {
      console.info('[room] 当前角色非医生(roles=' + userStore.getRoles.join(',') + '),跳过按IP自动入座')
    }
    return true
  }
 
  const mode = await roomStore.loadRoomSelectMode()
 
  // 模式 1 / 3:先尝试按本机IP自动匹配并自动入座(成功就直接进)
  if (mode === 1 || mode === 3) {
    const res = await roomStore.tryAutoSeatByIp()
    if (res.seated) {
      return true
    }
 
    // 【本需求】本机 IP 对应的工位**有人坐着**(上一班医生没退出工位)→ 提示是否接管。
    // 接管后立即成为该工位主人,并按现有逻辑自动加载该工位「就诊中」患者。
    if (res.reason === 'occupied' && res.roomId != null && res.bedNo) {
      const bedText = `${res.roomName || '诊室' + res.roomId} · ${res.bedNo}`
      try {
        await ElMessageBox.confirm(
          `本机对应的工位「${bedText}」当前由「${res.occupiedBy || '其他医生'}」占用。\n` +
            `是否接管该工位继续工作?(接管后对方将被强制离座)`,
          '工位被占用',
          { confirmButtonText: '接管工位', cancelButtonText: '先不接管(只读围观)', type: 'warning' }
        )
        const ok = await roomStore.takeOverBed(res.roomId, res.bedNo)
        if (ok) {
          ElMessage.success(`已接管工位:${bedText}`)
          return true
        }
        ElMessage.warning('接管失败,已按只读围观进入(可稍后在顶栏「工位」里再试)')
      } catch {
        // 用户选择不接管 → 按只读围观进入
        console.info('[room] 用户放弃接管工位,按只读围观进入')
      }
    }
 
    // 【主/围观】没自动入座也**不再强制跳"选工位页"**:
    // 允许以"未入座 / 围观"身份进入工作台(只读),由工作台顶部的「工位」下拉
    // 选择要查看(围观)或要入座的工位。若一律弹回选工位页,就永远无法围观别人。
    console.info('[room] 未自动入座(' + (res.reason || 'nomatch') + '),按"可围观"放行')
    return true
  }
 
  // 模式 0 / 2:原来强制去选工位页;本次同样放行,理由同上(由顶部下拉选择工位)。
  // 选工位页仍可从顶栏工位标签 / 顶部下拉进入。
  console.info('[room] 选择工位模式=' + mode + ':不强制跳选工位页,允许进入后自行选择/围观')
  return true
}
 
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 checkTypeStore = useCheckTypeStoreWithOut()
    const permissionStore = usePermissionStoreWithOut()
    if (!dictStore.getIsSetDict) {
      await dictStore.setDictMap()
    }
    if (!checkTypeStore.getIsSetCheckType) {
      await checkTypeStore.setCheckTypeMap()
    }
 
    if (userStore.getIsSetUser) {
 
      // <<<【诊室选择】按「选择工位模式」参数(0/1/2/3)决定是否强制选择工位 >>>
      if (!(await checkRoomSelect(to, next))) {
        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) // 动态添加可访问路由表
    })
 
    // <<<【诊室选择】按「选择工位模式」参数(0/1/2/3)决定是否强制选择工位 >>>
    if (!(await checkRoomSelect(to, next))) {
      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()
    // 【本次变更】**已移除** `setupBedReleaseOnUnload()`(pagehide + sendBeacon)。
    //
    // 原行为:关闭标签页 / 刷新 / 跳走时都会释放占用的工位,导致
    //   · 按 F5 刷新一次就丢工位;
    //   · 浏览器崩溃恢复、切走一会儿回来,也可能因 pagehide 丢工位。
    // 现在工位只在**用户主动操作**时释放:手动「离座」、手动「退出登录」。
    // 医生下班忘离座的兜底:① 闭诊时统一清空当班工位;② 管理员「清空工位」。
  }
})