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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
<template>
  <div class="room-select">
    <!--
      本页是**顶层路由**(不在 Layout 里),全屏独占、没有侧边菜单,
      所以必须自己提供出口(本次需求:原来进来后出不去)。
    -->
    <div class="room-select__topbar">
      <span class="room-select__title">选择诊室工位</span>
      <div class="room-select__topbar-right">
        <el-button size="default" @click="goBack">
          <Icon icon="ep:back" class="mr-4px" />返回
        </el-button>
        <el-button size="default" @click="showIpDebug">
          <Icon icon="ep:monitor" class="mr-4px" />IP 诊断
        </el-button>
        <el-button size="default" type="danger" plain @click="doLogout">
          <Icon icon="ep:switch-button" class="mr-4px" />退出登录
        </el-button>
      </div>
    </div>
 
    <!-- 选择工位模式提示区:当前电脑IP + 未自动匹配到的原因(模式 1/3) -->
    <div class="room-select__hint" v-if="hintText">
      <el-alert :title="hintText" :type="hintType" :closable="false" show-icon />
      <div class="room-select__ip">
        <span>当前电脑IP:<b>{{ clientIp || '未识别' }}</b></span>
        <el-button link type="primary" @click="loadClientIp">重新获取</el-button>
        <el-tag v-if="(mode === 2 || mode === 3) && canBindIp" size="small" type="success" effect="plain">入座后会把该IP绑定到所选工位</el-tag>
        <el-tag v-else-if="(mode === 2 || mode === 3) && isIpv6" size="small" type="warning" effect="plain">IPv6 访问,本次不写入IP绑定(仅采用 IPv4)</el-tag>
        <el-tag v-else-if="(mode === 2 || mode === 3) && isLoopback" size="small" type="warning" effect="plain">本机访问(回环地址),本次不会写入IP绑定</el-tag>
      </div>
    </div>
    <div class="room-select__scroll">
      <div class="room-select__list">
        <div class="room-select__item" v-for="(bed, index) in bedList" :key="`${bed.roomId}-${bed.bedNo}-${index}`">
          <RoomBedSelect :bed="bed" :curBed="curSel" :curUser='curUser' @event-haveseat="haveSeat" @event-leaveseat="leaveSeat" @event-setcurseat="setCurSeat" @event-takeover="takeOverConfirm"/>
        </div>
        <el-empty v-if="isEmptyOpeningBed" class="room-select__empty" description="工位没有开放"/>
      </div>
    </div>
    <div class="room-select__actions">
      <el-button type="primary" size="large" @click="confirmCurSel">确认</el-button>
      <el-button size="large" @click="resetPage">重置</el-button>
    </div>
 
    <!-- IP 诊断结果(排查"工位绑定的IP不对") -->
    <el-dialog v-model="ipDebugVisible" title="IP 诊断(后端实际识别到的客户端地址)" width="640px">
      <pre class="room-select__ip-debug">{{ ipDebugText }}</pre>
      <template #footer>
        <el-button @click="showIpDebug">重新诊断</el-button>
        <el-button type="primary" @click="ipDebugVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>
 
<script setup lang="ts">
import {RoomBedSelect} from "@/components/RoomBedSelect"
import { RoomApi, RoomVO, isUsableSeatIp } from '@/api/ecg/room'
import {useUserStore} from "@/store/modules/user";
import {ElMessage, ElMessageBox} from "element-plus";
import {cloneDeep} from "lodash-es";
import {DoctorApi} from "@/api/ecg/doctor";
import {useRoomStore} from "@/store/modules/room";
const { push, back } = useRouter()
 
defineOptions({ name: 'RoomLoginSelect' })
 
const route = useRoute();
 
const userStore = useUserStore()
const roomStore = useRoomStore()
const curUser = userStore.getUser
 
/* ==================== 选择工位模式(0/1/2/3)相关 ==================== */
/** 选择工位模式:0 强制选择 / 1 IP匹配 / 2 手动选择并写IP / 3 系统默认 */
const mode = ref<number>(-1)
/** 后端识别到的本机IP */
const clientIp = ref<string>('')
/** 该IP是否是本机回环(127.x / ::1)——说明浏览器和服务在同一台机器,不能作为工位绑定标识 */
const isLoopback = ref<boolean>(false)
/** 该IP是否是 IPv6(本系统工位绑定仅采用 IPv4) */
const isIpv6 = ref<boolean>(false)
/** 被强制跳来时的原因:force/nomatch/occupied/error */
const reason = ref<string>(new URLSearchParams(location.search).get('reason') || '')
/** 工位被占用时的占用人 */
const occupiedBy = ref<string>(new URLSearchParams(location.search).get('who') || '')
 
const hintText = computed(() => {
  if (reason.value === 'multi') {
    return `本机IP(${clientIp.value || '未识别'})对应多个工位,无法自动确定,请点选你所在的工作位置`
  }
  if (reason.value === 'occupied') {
    return `未自动匹配到可用工位:该IP对应的工位已被${occupiedBy.value || '其他医生'}占用,请手动选择工位`
  }
  if (reason.value === 'ip_is_server') {
    return `识别到的是【服务器自身地址】(${clientIp.value || '未识别'}):说明当前是在服务器上/远程桌面里访问,或代理把客户端地址写成了服务器地址 —— 不能作为工位标识,请在医生电脑上、用服务器的 IPv4 地址访问;可点右上「IP 诊断」查看详情`
  }
  if (reason.value === 'ip_invalid') {
    return `本机IP不可用(${clientIp.value || '未识别'}):回环地址或 IPv6 不能作为工位标识,请改用服务器的 IPv4 地址访问;也可直接手动选择工位`
  }
  if (reason.value === 'nomatch') {
    return `未自动匹配到工位(本机IP:${clientIp.value || '未识别'}),请手动选择工位`
  }
  if (reason.value === 'error') {
    return '自动匹配工位失败,请手动选择工位'
  }
  if (mode.value === 2 || mode.value === 3) {
    return '请选择你的工位:确认后会把本机IP绑定到该工位,以后登录将按IP自动匹配'
  }
  return ''
})
 
const hintType = computed(() => (reason.value === 'occupied' ? 'warning' : 'info'))
 
/** 取本机IP(后端识别),用于提示与模式2/3的绑定 */
const loadClientIp = async () => {
  try {
    const resp: any = await RoomApi.getIpBed()
    clientIp.value = resp?.clientIp || ''
    isLoopback.value = !!resp?.ipLoopback
    isIpv6.value = !!resp?.ipv6
  } catch (e) {
    clientIp.value = ''
    isLoopback.value = false
    isIpv6.value = false
  }
}
 
/* ==================== 本页出口(本次需求:原来进来后出不去) ==================== */
 
/**
 * 返回上一页;没有历史时回首页。
 *
 * 说明:本页是**顶层路由**、全屏独占(不在 Layout 里),因此没有侧边菜单可用。
 * 非医生角色(如 admin)点这里即可正常离开;**未入座的医生**若"返回"到工作台页,
 * 会被路由守卫再次送回本页(这是"强制选工位"的既定行为)—— 那种情况请用「退出登录」。
 */
const goBack = () => {
  if (window.history.length > 1) {
    back()
  } else {
    push({ path: '/' })
  }
}
 
/** 退出登录:任何情况都能离开本页(兜底出口) */
const doLogout = async () => {
  try {
    await ElMessageBox.confirm('确定退出登录吗?', '提示', {
      confirmButtonText: '确定退出',
      cancelButtonText: '取消',
      type: 'warning'
    })
  } catch {
    return // 用户取消
  }
  await userStore.loginOut()
}
 
/* ==================== IP 诊断(排查"工位绑定的IP不对") ==================== */
 
const ipDebugVisible = ref(false)
const ipDebugText = ref('')
 
/** 调后端诊断接口,把"后端到底把谁当成了客户端"逐项摊开 */
const showIpDebug = async () => {
  try {
    const data: any = await RoomApi.ipDebug()
    ipDebugText.value = Object.entries(data || {})
      .map(([k, v]) => {
        let text: string
        if (Array.isArray(v)) {
          text = v.length ? v.join('、') : '(无)'
        } else if (v === null || v === undefined || v === '') {
          text = '(空)'
        } else {
          text = String(v)
        }
        return `${k}:${text}`
      })
      .join('\n')
    ipDebugVisible.value = true
  } catch (e: any) {
    ElMessage({
      message: 'IP 诊断失败:' + (e?.message || e),
      type: 'warning',
      duration: 4000
    })
  }
}
 
/** 本机IP是否可用于绑定(回环/未指定/未识别 → 不能绑定) */
const canBindIp = computed(() => isUsableSeatIp(clientIp.value) && !isLoopback.value)
 
/**
 * 模式 2/3:把本机IP写到所选工位。
 * 若该IP已绑在别的工位,先弹确认,用户同意后带 force=true 覆盖。
 * @returns 是否可以继续入座
 */
const bindIpIfNeeded = async (bed: RoomVO): Promise<boolean> => {
  if (mode.value !== 2 && mode.value !== 3) {
    return true // 模式 0/1 不写IP
  }
  if (bed.id == null) {
    return true
  }
  // 回环(127.x / ::1)说明浏览器和服务在同一台机器,无法作为工位绑定标识
  if (isLoopback.value || !canBindIp.value) {
    let msg: string
    if (isLoopback.value) {
      msg =
        '当前访问来自本机(回环地址 ' +
        clientIp.value +
        '),本次不写入IP绑定;请在实际医生的电脑上访问后再绑定'
    } else if (isIpv6.value) {
      msg =
        '当前访问使用的是 IPv6 地址(' +
        clientIp.value +
        '),本系统工位绑定仅采用 IPv4,本次不写入IP绑定;请改用服务器的 IPv4 地址访问'
    } else {
      msg = '未能识别可用的本机IPv4地址(' + (clientIp.value || '空') + '),本次不写入IP绑定'
    }
    ElMessage({ message: msg, type: 'warning', duration: 5000 })
    return true
  }
  try {
    let resp: any = await roomStore.bindCurrentIp(bed.id as number, false)
    if (resp?.code === 409 || resp?.conflict) {
      const target = `「${bed.roomName || ''} / ${bed.bedNo || ''}」`
      await ElMessageBox.confirm(
        `${resp.msg},是否改绑到${target}?(改绑后原工位将不再自动匹配本机)`,
        '提示',
        { confirmButtonText: '确定改绑', cancelButtonText: '取消', type: 'warning' }
      )
      resp = await roomStore.bindCurrentIp(bed.id as number, true)
    }
    if (resp?.code !== 200) {
      ElMessage({ message: resp?.msg || '绑定本机IP失败', type: 'warning', duration: 3000 })
      return false
    }
    clientIp.value = resp.clientIp || clientIp.value
    return true
  } catch (err: any) {
    if (err === 'cancel') {
      return false
    }
    console.error('[bindIpIfNeeded] 绑定本机IP异常', err)
    ElMessage({ message: '绑定本机IP失败:' + (err?.message || err), type: 'warning', duration: 3000 })
    return false
  }
}
 
const isEmptyOpeningBed = ref<boolean>(true);
const bedMap = ref() // 列表的数据
const curSel = ref<RoomVO>({
  id: null,
  roomId: null,
  roomName: null,
  bedNo: null,
  status: null,
  docId: null,
  docName: null,
  ip: "",
  checkTypes: [],
  opType: 0
})
 
// 一个床位一个卡片:把 {诊室名: 床位[]} 拍平成床位列表
const bedList = computed<RoomVO[]>(() => {
  const list: RoomVO[] = []
  const map = bedMap.value
  if (!map) {
    return list
  }
  for (const key in map) {
    const beds = map[key] as RoomVO[]
    if (beds && beds.length > 0) {
      list.push(...beds)
    }
  }
  return list
})
 
/** 初始化 **/
onMounted(async () => {
  console.info( curUser.id + " onMounted")
    // 读取「选择工位模式」并取本机IP(模式 2/3 需要在入座时把IP写到工位)
    mode.value = await roomStore.loadRoomSelectMode()
    loadClientIp()
    getList()
})
 
onActivated(() => {
  console.info( curUser.id + " onActivated")
    getList()
})
 
const resetPage = () => {
    getList()
}
 
/** 查询列表 */
const getList = async () => {
  resetCurSel()
 
  console.info("getList before")
  const data = await RoomApi.getOpeningBedMap()
  bedMap.value = data;
  console.info("getList after " + data)
 
  isEmptyOpeningBed.value = true
  for (const key in data) {
    isEmptyOpeningBed.value = false
 
    if (roomStore.getIsSetRoom) {
      const roomVOArray = data[key] as RoomVO[];
      roomVOArray.forEach((roomVO) => {
        // 用字符串比较,避免 docId(number) 与 userId(string) 类型不同导致匹配不上
        if (String(roomVO.docId) === String(curUser.id)
            && roomVO.roomId === roomStore.room!.roomId
            && roomVO.bedNo === roomStore.room!.bedNo) {
          // ⚠️ 必须**拷贝**:curSel 若与列表项共用同一个对象,
          // 后续 resetCurSel() 就地清零会把列表里那张卡片的诊室名/工位号一起清掉
          // (现场反馈的"切换工位后原工位编号/名称有时不显示"就是这个原因)。
          curSel.value = { ...roomVO }
          roomStore.setRoomInfoAction(curSel.value)
        }
      })
    }
  }
}
 
/** 工位作业类型 → 工作台路由(0检查 1领用 2装机) */
const workbenchPath = (opType?: number | null) => {
  if (opType === 0) return '/ecg/doc/routine'
  if (opType === 1) return '/ecg/doc/dev-ready'
  if (opType === 2) return '/ecg/doc/dev-install'
  return ''
}
 
/**
 * 入座/切换工位**之后**的去向。
 *
 * 【本次需求】不再"选完工位就自动打开叫号检查页" —— 系统不知道用户接下来是要做
 * 叫号检查、设备领用、装机还是拆机,替他决定反而要多点一次返回。规则:
 *  ① 若是**被路由守卫踢过来**的(带 redirect / redirectedFrom)→ 回到他原本想去的那一页;
 *  ② `forceEnter=true`(用户主动点了顶部「确认」按钮)→ 按工位作业类型进入对应工作台
 *     (这是用户明确表达的"我要进去",不算替他决定);
 *  ③ 其余(自己点顶栏进来换工位)→ **停留在本页**,由用户自己从菜单选目标页。
 */
const gotoAfterSeat = (opType?: number | null, forceEnter = false) => {
  const redirect = (route.query.redirect as string) || route.redirectedFrom?.fullPath || ''
  if (redirect && redirect !== '/roomselect') {
    push({ path: redirect })
    return
  }
  if (forceEnter) {
    const path = workbenchPath(opType)
    if (path) {
      push({ path })
      return
    }
  }
  const seat = roomStore.getCurrentSeat
  ElMessage({
    message: `已入座:${seat?.roomName || ''} ${seat?.bedNo || ''}(请从左侧菜单进入需要的工作台)`,
    type: 'success',
    duration: 4000
  })
}
 
const confirmCurSel = () => {
  if (curSel.value.docId === null ) {
    ElMessage({
      message: '请先选择工作的位置!',
      type: 'info',
      duration: 3000 // 自动关闭时间,默认为3000ms
    });
    return
  }
  // 用户主动点「确认」= 明确要进入工作台 → 按工位作业类型进入(若本次是被踢过来的,优先回原目标页)
  gotoAfterSeat(curSel.value.opType, true)
}
 
const haveSeatConfirm = async (newRoomVO: RoomVO) => {
  if (newRoomVO !== curSel.value) {
    // 模式 2/3:先把本机IP绑定到所选工位(冲突时由 bindIpIfNeeded 弹确认)
    const canProceed = await bindIpIfNeeded(newRoomVO)
    if (!canProceed) {
      return
    }
 
    resetCurSel()
 
    const tempRoomVO = cloneDeep(newRoomVO)
    tempRoomVO.docId = curUser.id
    tempRoomVO.docName = curUser.nickname
 
    // 【本需求·一人多工位】走 store 的入座动作:服务端**不再释放**我账号下的其它工位,
    // 因此这里是"新增一个我的工位"(值班多岗位),并把工位信息写进会话缓存。
    const seated = await roomStore.seatRoom(tempRoomVO)
    if (!seated) {
      // 失败时自动调诊断接口,把库里真实行与结论一起给出(便于现场一键定位)
      await reportSeatFailure(tempRoomVO)
      getList()
      return
    }
 
    // 顶栏"当前工位"标签刷新(后端为准)
    await roomStore.fetchMySeat()
 
    // ⚠️ 用**拷贝**更新"当前工位":newRoomVO 是列表里的对象,
    // 直接改它虽然能让卡片显示"我的工位",但后续 resetCurSel() 会连带清掉卡片的
    // 诊室名/工位号(现场反馈的现象)。改为拷贝后,列表数据只由 getList() 统一刷新。
    curSel.value = { ...newRoomVO, docId: curUser.id, docName: curUser.nickname }
 
    // 【本次修复】入座成功后**重新拉一次列表**:否则卡片还是旧的 docId=null,
    // 会一直显示"空闲"(现场反馈"入座后的工位还是显示空闲")。
    await getList()
  }
 
  // 【本次需求】入座/切换成功后不再自动打开叫号检查页:
  // 被守卫踢过来的回原目标页,自己点进来换工位的则停在本页(见 gotoAfterSeat 说明)
  gotoAfterSeat(newRoomVO.opType, false)
}
 
/**
 * 【本需求·接班自助接管】对"别人占用"的工位执行接管。
 *
 * 场景:上一班医生下班没点「离座」,下一班医生在同一工位接班 —— 原来只能找管理员清空。
 * 现在:二次确认 → 后端强制原占用人离座并把工位给我 → 刷新列表/我的工位。
 */
const takeOverConfirm = async (roomVO: RoomVO) => {
  const bedText = `${roomVO.roomName || '诊室' + roomVO.roomId} · ${roomVO.bedNo}`
  const owner = roomVO.docName || '其他医生'
  try {
    await ElMessageBox.confirm(
      `工位「${bedText}」当前由「${owner}」占用。\n` +
        `确认接管?接管后「${owner}」将被强制离座(其页面会提示重新就坐),工位立即归你使用。`,
      '接管工位',
      { confirmButtonText: '确认接管', cancelButtonText: '取消', type: 'warning' }
    )
  } catch {
    return
  }
  const ok = await roomStore.takeOverBed(roomVO.roomId, roomVO.bedNo)
  if (!ok) {
    ElMessage({ message: '接管失败,请稍后重试或联系管理员', type: 'error', duration: 4000 })
    return
  }
  ElMessage.success(`已接管工位:${bedText}`)
  resetCurSel()
  curSel.value = { ...roomVO, docId: curUser.id, docName: curUser.nickname }
  await roomStore.fetchMySeat()
  await getList()
  // 接管后进入该岗位对应的工作台(接管会带上该工位"就诊中"患者)
  gotoAfterSeat(roomVO.opType, true)
}
 
const leaveSeatConfirm = async (roomVO: RoomVO) => {
  // 【本次需求】离座只能清**自己的** doc_id(服务端 setBedDoctorOff 已加 doc_id 条件),
  // 这里先拦一道,避免"旁观/其他医生"点离座把正在操作的人踢掉。
  // 用字符串比较,避免 number/string 类型差异导致误判。
  if (roomVO.docId != null && String(roomVO.docId) !== String(curUser.id)) {
    ElMessage({
      message: `该工位由「${roomVO.docName || '其他医生'}」操作中,您不能让他离座`,
      type: 'warning',
      duration: 4000
    })
    return
  }
 
  if (roomVO.docId !== null) {
      let data = await DoctorApi.bedDoctorOff(roomVO)
      if (data !== 0) {
          ElMessage({
              message: '内部错误!' + data,
              type: 'info',
              duration: 3000 // 自动关闭时间,默认为3000ms
          });
          return
      }
  }
 
  resetCurSel()
  await roomStore.clearRoomInfoAction()
  getList()
}
 
/**
 * 按 roomId + bedNo 取该工位**最新**的数据。
 *
 * 为什么入座前要再拉一次:页面上的列表是进入本页时拉的,医生可能停留很久,
 * 期间别人正好把某个工位坐上了 —— 这时按旧数据判断"空闲"就会发出入座请求,
 * 被后端拒绝(现场反馈的"选了别人已入座的工位报错"正是这种情况)。
 */
const findLatestBed = async (bed: RoomVO): Promise<RoomVO | null> => {
  try {
    const map: any = await RoomApi.getOpeningBedMap()
    const all: RoomVO[] = []
    for (const key in map || {}) {
      const arr = map[key]
      if (Array.isArray(arr)) {
        all.push(...arr)
      }
    }
    return (
      all.find(
        (b) => String(b.roomId) === String(bed.roomId) && String(b.bedNo) === String(bed.bedNo)
      ) || null
    )
  } catch (e) {
    console.warn('[findLatestBed] 刷新工位最新状态失败,按页面现有数据继续', e)
    return null
  }
}
 
/**
 * 入座失败时的自助诊断(本次新增)。
 *
 * 现场出现过"工位在库里明明空闲,入座却报状态异常",光靠弹一句错误提示无法定位。
 * 这里在失败时自动调 `GET /clinic/room/bed-state`,把库里**原始行**与结论一起弹给用户,
 * 用户把弹窗内容发回即可定位(结尾空格 / 状态不对 / 已被删除 / 已被别人占用)。
 */
const reportSeatFailure = async (bed: RoomVO) => {
  let detail = ''
  try {
    const data: any = await RoomApi.bedState({ id: bed.id, roomId: bed.roomId, bedNo: bed.bedNo })
    const row = Array.isArray(data?.行明细) && data.行明细.length ? data.行明细[0] : null
    detail =
      (data?.诊断结论 ? `\n\n诊断:${data.诊断结论}` : '') +
      (row
        ? `\n\n库内该行:id=${row.id} room_id=${row.room_id} bed_no=[${row.bed_no}](len=${row.bed_no_len}, HEX=${row.bed_no_hex}) status=${row.status} doc_id=${row.doc_id} doc_name=${row.doc_name} deleted=${row.deleted}`
        : '')
    console.warn('[reportSeatFailure] 工位状态诊断', data)
  } catch (e) {
    console.warn('[reportSeatFailure] 诊断接口调用失败', e)
  }
  await ElMessageBox.alert(
    `入座未成功:该工位可能已被他人占用,或状态不允许(已关闭)。${detail}`,
    '入座失败',
    { confirmButtonText: '知道了', type: 'warning' }
  )
}
 
/**
 * 点「入座」按钮的入口。
 *
 * 【本次需求】两条规则:
 *  ① **不挤掉别人**:工位已被他人操作时不能入座(原来会先把对方"离座"再抢占,
 *     服务端已改为只允许清自己的 doc_id,这里给出明确提示而不是让接口报错);
 *  ② **一人一工位**:我已经在别的工位时,弹确认后切换,原工位由服务端自动释放。
 *
 * 另:入座前会**重新拉一次最新状态**,避免拿几分钟前的数据去入座(别人可能刚坐上)。
 */
const haveSeat = async (bedFromPage: RoomVO) => {
  // ⓪ 先用最新数据核对(这一步是本次现场"选了别人已入座的工位→报错"的对症修复)
  const latest = await findLatestBed(bedFromPage)
  if (!latest) {
    ElMessage({
      message: '该工位已不可用(可能已被关闭),列表已刷新,请重新选择',
      type: 'warning',
      duration: 4000
    })
    getList()
    return
  }
  const newRoomVO = latest
 
  // ① 已被**别人**占用 → 不抢,并刷新列表让卡片显示"已入座:X"
  if (newRoomVO.docId != null && String(newRoomVO.docId) !== String(curUser.id)) {
    ElMessage({
      message: `该工位已由「${newRoomVO.docName || '其他医生'}」操作中,不能入座(不挤掉正在操作的人)`,
      type: 'warning',
      duration: 5000
    })
    getList()
    return
  }
 
  // ② 就是我当前这个工位 → 不必重复入座(避免多弹一次确认)
  const mySeat = roomStore.getCurrentSeat
  const alreadyMine = newRoomVO.docId != null && String(newRoomVO.docId) === String(curUser.id)
  const sameAsMySeat =
    !!mySeat?.seated &&
    String(mySeat.roomId) === String(newRoomVO.roomId) &&
    mySeat.bedNo === newRoomVO.bedNo
  if (alreadyMine && sameAsMySeat) {
    ElMessage({
      message: `您已入座「${newRoomVO.roomName || ''} / ${newRoomVO.bedNo || ''}」,无需重复入座`,
      type: 'info',
      duration: 3000
    })
    await roomStore.fetchMySeat()
    return
  }
 
  // ③ 我已入座其它工位 → 确认后切换(服务端入座时会自动退出原工位)
  const switching =
    !!mySeat?.seated &&
    (String(mySeat.roomId) !== String(newRoomVO.roomId) || mySeat.bedNo !== newRoomVO.bedNo)
  const message = switching
    ? `您已在「${mySeat?.roomName || ''} / ${mySeat?.bedNo || ''}」入座,确定切换到「${newRoomVO.roomName || ''} / ${newRoomVO.bedNo || ''}」吗?(原工位会自动退出)`
    : '入座, 是否继续?'
 
  try {
    await ElMessageBox.confirm(message, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await haveSeatConfirm(newRoomVO)
  } catch (err) {
    // 只有用户主动点击取消时才忽略,其他报错可以打印出来方便排查
    if (err !== 'cancel') {
      console.error('入座流程异常:', err)
    }
  }
}
 
const leaveSeat = (roomVO: RoomVO) => {
  ElMessageBox.confirm(
      '离座, 是否继续?',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {
    leaveSeatConfirm(roomVO)
  }).catch(() => {
  });
}
 
// 同时坐了多个工位时,设定当前会话的工位
const setCurSeat = (roomVO: RoomVO) => {
  // 拷贝一份再放进 curSel,避免与列表项共用对象(见 getList 里的说明)
  const seat = { ...roomVO }
  roomStore.setRoomInfoAction( seat )
  curSel.value = seat
  // 顶栏标签同步(以服务端为准)
  roomStore.fetchMySeat()
 
  // 【本次需求】不自动打开工作台页(见 gotoAfterSeat 说明):
  // 若本次是被守卫踢过来的会回原目标页,否则停留在选工位页
  gotoAfterSeat(roomVO.opType, false)
}
 
/**
 * 重置"当前工位"。
 *
 * ⚠️【本次修复】必须**赋一个新对象**,不能就地清空 curSel.value 的字段:
 * 原实现(curSel.value.bedNo = null 之类)在 curSel 与列表项共用对象时,
 * 会把页面卡片上的「工位编号 / 诊室名称」一起清掉 —— 也就是现场反馈的
 * "切换到其他工位后,原工位有时工位编号没显示,有时诊室名称不显示"。
 */
const resetCurSel = () => {
  curSel.value = {
    id: null,
    roomId: null,
    roomName: null,
    bedNo: null,
    ip: null,
    status: null,
    docId: null,
    docName: null,
    checkTypes: [],
    opType: 0
  } as RoomVO
}
 
</script>
 
<style scoped lang="scss">
// 床位多时全部压缩在一屏内显示,不出现页面滚动条
.room-select {
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  height: 100vh;
  padding: 15px;
  overflow: hidden;
 
  /* 选择工位模式提示区:说明为什么被要求手动选工位 */
  &__hint {
    flex: none;
    margin-bottom: 10px;
  }
 
  &__ip {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 10px;
    margin-top: 8px;
    font-size: 13px;
    color: #606266;
  }
 
  // 高度随卡片数量自适应;卡片多到装不下时才内部滚动(页面本身始终不滚动)
  &__scroll {
    flex: 0 1 auto;
    min-height: 0;
    overflow-y: auto;
  }
 
  &__list {
    display: grid;
    // 固定列宽:卡片不会被拉伸变形,从左到右、从上往下排列
    grid-template-columns: repeat(auto-fit, 188px);
    justify-content: center;
    gap: 12px;
  }
 
  &__item {
    min-width: 0;
  }
 
  // 空状态跨满整行,避免被挤到单独一列里
  &__empty {
    grid-column: 1 / -1;
  }
 
  &__actions {
    flex: none;
    padding-top: 12px;
    text-align: center;
  }
 
  /*
    顶部条(本次需求):本页是顶层路由、没有侧边菜单,出口只能自己给。
    左标题 + 右「返回 / IP 诊断 / 退出登录」。
  */
  &__topbar {
    flex: none;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 4px 0 10px;
    border-bottom: 1px solid var(--el-border-color-lighter);
    margin-bottom: 8px;
  }
 
  &__title {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
  }
 
  &__topbar-right {
    display: flex;
    align-items: center;
    gap: 8px;
  }
 
  /* IP 诊断结果:保留原样空格与换行,便于逐项核对 */
  &__ip-debug {
    margin: 0;
    max-height: 60vh;
    overflow: auto;
    padding: 10px 12px;
    background: var(--el-fill-color-light);
    border-radius: 4px;
    font-size: 13px;
    line-height: 1.8;
    white-space: pre-wrap;
    word-break: break-all;
  }
}
</style>