yxh
yxh
10 天以前 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
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
<!-- 常规检查 医生界面-->
<template>
  <el-form class="patient-compact-form" ref="formRef" :model="formData" :rules="formRules" label-width="100px" v-loading="formLoading">
    <!--
      【本需求】紧急加做操作提示(编辑区上方,常驻)
      紧急病人不排队:在下面三个输入框任一个里输入后按回车,查到预约记录即可直接做检查。
    -->
    <el-alert type="warning" :closable="false" class="emergency-tip">
      <template #title>
        <span class="emergency-tip__text">
          有紧急病人时,请输入<span class="emergency-tip__key">申请单号</span>、或<span class="emergency-tip__key">就诊号</span>、或<span class="emergency-tip__key">患者编号</span>后按<span class="emergency-tip__enter">回车键</span>,查到病人预约记录即可做检查!!!
        </span>
      </template>
    </el-alert>
    <!-- ===== 编辑区(需要录入的字段)===== -->
      <el-row :gutter="4">
        <el-col :xs="24" :sm="12" :md="12" :lg="6">
          <el-form-item label="申请单号" prop="applyNo">
            <!-- 【本需求:紧急加做】回车即按申请单号查近一个月的预约 -->
            <el-input
              v-model="formData.applyNo"
              placeholder="请输入申请单号"
              @keyup.enter="searchEmergencyCandidates('applyNo')"
            />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="12" :lg="6">
          <el-form-item label="检查项目" prop="">
            {{ formData?.checkType && getCheckTypeName(formData?.checkType) }}
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="12" :lg="6">
          <el-form-item label="就诊号" prop="episodeId">
            <!-- 【本需求:紧急加做】回车即按就诊号查近一个月的预约 -->
            <el-input
              v-model="formData.episodeId"
              placeholder="请输入就诊流水号"
              @keyup.enter="searchEmergencyCandidates('episodeId')"
            />
            <!--
              【本需求】条码从「患者编号」挪到这里(就诊号下方):
                · 内容 = 就诊号;默认是否显示由「检查类型 → 是否显示条码」配置决定;
                · 医生可用切换按钮手动显隐(显示中→「隐藏」;隐藏中→「条码」);
                · 「复制」只在条码显示时出现。
            -->
            <div v-if="showBarcodeToggle || showBarCode" class="barcode-row">
              <Barcode v-if="showBarCode" :value="barcodeContent" :width="100" />
              <el-button v-if="showBarcodeToggle" size="small" @click="toggleBarcode()">
                {{ barcodeToggleLabel }}
              </el-button>
              <el-button v-if="showCopyButton" size="small" :disabled="!barcodeContent" @click="copyBarcode()">
                复制
              </el-button>
            </div>
          </el-form-item>
        </el-col>
        <!-- 【本需求】患者姓名这一列已去掉:下方 PatientInfoBlock 已有姓名展示 -->
        <el-col :xs="24" :sm="12" :md="12" :lg="6">
          <el-form-item label="患者编号" prop="patId">
            <!-- 【本需求:紧急加做】回车即按患者编号查近一个月的预约 -->
            <el-input
              v-model="formData.patId"
              placeholder="请输入患者编号"
              @input="getRentInfoByPatId"
              @keyup.enter="searchEmergencyCandidates('patId')"
            />
          </el-form-item>
        </el-col>
      </el-row>
 
    <!-- ===== 患者信息(需求1:18 项统一展示,**一行四列**)=====
         原先本面板把 18 项手写在多行 el-col(span=6/18 混排),
         现统一改用 PatientInfoBlock 组件,与预约签到/设备领用/装机/拆机各页**口径一致**。 -->
    <PatientInfoBlock :data="formData" check-type-field="checkType" :span="6" />
    <el-row>     
      <el-col :xs="24" :sm="12" :md="12" :lg="6">
        <el-form-item label="检查时间" prop="rentTime">
          <el-date-picker v-model="formData.rentTime" type="date" value-format="x" placeholder="选择时间" />
        </el-form-item>
      </el-col> 
      <el-col :xs="24" :sm="24" :md="12" :lg="18">
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
  <div class="patient-actions">
  <el-button size="small" @click="submitForm" type="primary" :disabled="formLoading">检查完成</el-button>
  <el-button size="small" @click="cancelInstall" :disabled="formLoading">放弃检查</el-button>
  <el-button size="small" @click="resetForm()">重 置</el-button>
  <el-button size="small" @click="yddownload()" :loading="yddownloadLoading" :disabled="yddownloadLoading">平板运动心电图知情同意书</el-button>
  <el-button size="small" @click="sgdownload()" :loading="sgdownloadLoading" :disabled="sgdownloadLoading">食管心脏电生理诊疗知情同意书</el-button>
  <el-button size="small" v-if="needAutoFeeConfirm(formData.checkType)" @click="feeConfirm" :disabled="formLoading || formData.id == null">确费</el-button>
  <el-button size="small" v-if="needAutoFeeConfirm(formData.checkType)" @click="feeCancel" :disabled="formLoading || formData.id == null">取消确费</el-button>
  </div>
 
  <!-- 医生装机列表 -->
  <!--
    已完成记录列表。
    滚动方式:**中间内容区自身滚动**(.doctor-page__content 为 overflow-y:auto),
    患者信息用 sticky 固定在顶部;底部 footer 由 DoctorPageLayout 固定,无需滚动即可见。
    (曾尝试让 el-table 内部滚动以固定表头,但本项目 Element Plus 2.7.0 下
       height/maxHeight 均未生效,已回退,详见《部署清单》5.3.15。)
  -->
  <!-- 【本次需求】操作功能区与已完成记录之间的标题栏 -->
  <div class="records-title">
    <span class="records-title__bar"></span>
    <span class="records-title__text">已完成列表</span>
  </div>
  <div class="records-host">
    <ContentWrap class="records-wrap">
      <el-table
        v-loading="loading"
        :data="list"
        :stripe="true"
        :show-overflow-tooltip="true"
        @row-click="onRowClick"
      >
      <!--
        需求11(修正):把「撤销」放在**已完成检查记录列表的第一列**里。
        原先放在表格上方的独立按钮行,位置不对 —— 现改为该列的**表头插槽**,
        使其成为表格的第一列(且只出现一次,作用于最近一位已完成患者,
        语义与后端 lastFinishedPatient 一致)。
      -->
      <el-table-column label="撤销" align="center" width="90px" fixed="left">
        <template #header>
          <el-button
            link
            type="warning"
            :disabled="undoDisabled"
            :loading="undoLoading"
            @click="$emit('event_undo_finish')"
          >
            撤销
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="检查状态" align="center" prop="lost">
        <template #default="scope">
          <!-- 【本需求】完成被撤销过:该条记录显示「已撤销」;再次完成时后端 undone 自动变回 false -->
          <el-tag v-if="scope.row.undone" type="danger" size="small">已撤销</el-tag>
          <span v-else-if="scope.row.jobType === 60">已检查</span>
          <span v-if="scope.row.jobType === 50">已放弃</span>
        </template>
      </el-table-column>
      <!--      <el-table-column label="作业类型" align="center" prop="jobType" />-->
      <!--      <el-table-column label="医生编号" align="center" prop="docId" />-->
      <el-table-column label="医生名称" align="center" prop="docName" />
      <!--      <el-table-column label="设备编号" align="center" prop="devId" />-->
      <el-table-column label="患者编号" align="center" prop="patId" />
      <el-table-column label="患者名称" align="center" prop="patName" />
      <el-table-column label="作业时间" align="center" prop="jobTime" :formatter="dateFormatter" width="180px" />
      <!--      <el-table-column label="作业概要" align="center" prop="summary" />-->
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="创建时间" align="center" prop="createTime" :formatter="dateFormatter" width="180px" />
      <!--
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
              link
              type="primary"
              @click="openForm('update', scope.row.id)"
              v-hasPermi="['ecg:job-record:update']"
          >
            编辑
          </el-button>
          <el-button
              link
              type="danger"
              @click="handleDelete(scope.row.id)"
              v-hasPermi="['ecg:job-record:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
-->
      </el-table>
    </ContentWrap>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
 
  <!--
    【本需求:紧急患者不排队直接检查】预约选择框
    触发:在「申请单号 / 就诊号 / 患者编号」任一输入框内按回车。
    多条预约时弹此框,按预约时间倒序(最近的在前)。
  -->
  <Dialog v-model="emergencyVisible" title="选择预约记录(紧急加做)" width="880px" append-to-body>
    <el-alert type="warning" :closable="false" class="mb-10px">
      <template #title>
        <span class="text-13px">
          找到 {{ emergencyList.length }} 条预约记录:**点选一行**(整行高亮 + 左侧蓝条 + 「已选」标签)后点「选择并检查」,
          也可直接**双击**该行。选中后可直接检查,完成后同样进入「已完成列表」(不排队、不占号)。
        </span>
      </template>
    </el-alert>
    <el-table
      ref="emergencyTableRef"
      class="emergency-table"
      :data="emergencyList"
      v-loading="emergencyLoading"
      highlight-current-row
      border
      max-height="360px"
      :row-class-name="emergencyRowClass"
      @row-click="(row) => (emergencySelected = row)"
      @current-change="(row) => (emergencySelected = row)"
      @row-dblclick="(row) => confirmEmergency(row)"
    >
      <!-- 【本需求】选中标识列:选中行显示「✓ 已选」,避免只靠背景色分辨不清 -->
      <el-table-column label="选择" width="80" align="center" fixed="left">
        <template #default="scope">
          <el-tag v-if="isEmergencySelected(scope.row)" type="primary" effect="dark" size="small">
            ✓ 已选
          </el-tag>
          <span v-else class="text-gray-400">—</span>
        </template>
      </el-table-column>
      <el-table-column label="预约日期" align="center" prop="bookDate" width="120">
        <template #default="scope">{{ formatDate(scope.row.bookDate, 'YYYY-MM-DD') }}</template>
      </el-table-column>
      <el-table-column label="时段" align="center" width="120">
        <template #default="scope">{{ formatTimeslot(scope.row.bookTimeslot) }}</template>
      </el-table-column>
      <el-table-column label="检查项目" align="center" min-width="130">
        <template #default="scope">{{ getCheckTypeName(scope.row.bookCheckType) }}</template>
      </el-table-column>
      <el-table-column label="患者名称" align="center" prop="patName" min-width="100" />
      <el-table-column label="患者编号" align="center" prop="patId" min-width="110" />
      <el-table-column label="申请单号" align="center" prop="applyNo" min-width="130" />
      <el-table-column label="状态" align="center" width="90">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.ECG_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
    </el-table>
    <template #footer>
      <!-- 底部回显已选哪一条,避免选错 -->
      <span v-if="emergencySelected" class="emergency-selected-hint">
        已选:{{ formatDate(emergencySelected.bookDate, 'YYYY-MM-DD') }}
        {{ formatTimeslot(emergencySelected.bookTimeslot) }}
        {{ getCheckTypeName(emergencySelected.bookCheckType) }}
        <span class="text-gray-500">({{ emergencySelected.patName }})</span>
      </span>
      <el-button @click="emergencyVisible = false">取 消</el-button>
      <el-button type="primary" :disabled="!emergencySelected" @click="confirmEmergency()">
        选择并检查
      </el-button>
    </template>
  </Dialog>
</template>
 
<script setup lang="ts">
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
 
import { DevRentApi, DevRentVO } from '@/api/ecg/devrent'
import { dateFormatter, formatDate } from '@/utils/formatTime'
import { formatTimeslot } from '@/utils/formatter'
import { AppointmentApi, AppointmentVO } from '@/api/ecg/appointment'
import { JobRecordApi, JobRecordVO } from '@/api/ecg/jobrecord'
import { isStringEmpty } from '@/utils/stringUtil'
import { calculateAge, curDayEnd, curDayStart, formatTimestamp } from '@/utils/dateUtil'
import { calGender } from '@/utils'
import dayjs from 'dayjs'
import { QueueVO } from '@/api/ecg/queue'
import { RoomBedVO, DoctorApi } from '@/api/ecg/doctor'
import { Barcode } from '@/components/Barcode'
import { useCheckTypeStore } from '@/store/modules/checkType'
import { getCheckTypeName, needAutoFeeConfirm } from '../../../../utils/checkTypeFormatter'
import { useRoomStore } from '@/store/modules/room'
// ⚠️ 必须显式 import:`unplugin-vue-components` 的 globs 只覆盖
//    `src/components/**`(见 build/vite/index.ts 的 Components({ globs: [...] })),
//    因此 src/components/ 下的 Dialog、ContentWrap、Pagination 等可自动引入,
//    但 **src/views/** 下的本组件必须手写 import**。
//    若漏写,Vue 会把它当成「未知标签」**静默不渲染**(只有控制台 warning),
//    而 vite build 与 ESLint 都不会报错 —— 实测因改造时误删本行 import,
//    导致「叫号检查」页面患者信息**整块消失**。
import PatientInfoBlock from '@/views/ecg/doctor/components/PatientInfoBlock.vue'
 
/** 设备装机 表单 */
defineComponent({ name: 'RoutinePanel' })
 
const props = defineProps({
  room: {
    type: Object as PropType<RoomBedVO>,
    required: true
  },
  setappointmentId: {
    type: [String, Number],
    required: false,
    default: null
  },
  /**
   * 需求11:记录列表第一列的「撤销」按钮状态,由父页面控制
   * (撤销动作请求后端、需要 loading 与禁用态,逻辑保留在父页面)。
   */
  undoDisabled: {
    type: Boolean,
    required: false,
    default: false
  },
  undoLoading: {
    type: Boolean,
    required: false,
    default: false
  }
})
 
const emit = defineEmits(['event_routine', 'event_undo_finish'])
 
const checkTypeStore = useCheckTypeStore()
 
const setPatient = (queueVO: QueueVO | undefined) => {
  resetForm()
  formData.value.applyNo = queueVO?.applyNo
  formData.value.episodeId = queueVO?.episodeId
  formData.value.patId = queueVO?.patId
  formData.value.patName = queueVO?.patName
  formData.value.checkType = queueVO?.bookCheckType
  // 以下字段由后端从预约单补齐(queue 表不存),用于医生端展示
  formData.value.patGender = queueVO?.patGender
  formData.value.tolerance = queueVO?.tolerance
  formData.value.patBirthday = queueVO?.patBirthday
  formData.value.registerDate = queueVO?.registerDate
  formData.value.doctor = queueVO?.doctor
  formData.value.doctorTime = queueVO?.doctorTime
  // 需求1:补齐排队序号 / 状态 / 病区 / 床号 / 电话 / 来源 / 门诊号
  // 这些平铺字段由后端 QueueServiceImpl#fillAppointmentInfo 回填,
  // 原先这里没有赋值,导致模板里读不到(显示为空)。
  formData.value.seqNum = queueVO?.seqNum
  formData.value.status = queueVO?.status
  formData.value.patSrc = queueVO?.patSrc
  // 【本次修复】条码/打印小票依赖 patDetails(含 source/appointmentId),
  // 队列行本就带着它;原先只在 getFreeRentInfo() 查到"待检查单"时才赋值,
  // 导致绝大多数情况下 patDetails 为 undefined → 条码不显示。
  formData.value.patDetails = queueVO?.patDetails
  formData.value.patMobile = queueVO?.patMobile
  formData.value.patPhone = queueVO?.patPhone
  formData.value.patWardDesc = queueVO?.patWardDesc
  formData.value.patBedNo = queueVO?.patBedNo
  formData.value.medicalCard = queueVO?.medicalCard
  formData.value.outpatientNo = queueVO?.outpatientNo
    // 需求1:医嘱号(此前 3 个面板都遗漏了该字段的赋值,导致 PatientInfoBlock 恒显示 '-')
    formData.value.doctorAdviceNo = queueVO?.doctorAdviceNo
  formData.value.patIdentityId = queueVO?.patIdentityId
  getFreeRentInfo(formData.value)
}
defineExpose({ setPatient, getList: () => getList() }) // 提供 setPatient 方法,用于设置患者
 
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
 
const dialogVisible = ref(false) // 弹窗的是否展示
const yddownloadLoading = ref(false);
const sgdownloadLoading = ref(false);
const formLoading = ref(false) // 表单的加载中:1)修改时的数据加载;2)提交的按钮禁用
 
const formData = ref<Partial<DevRentVO>>({
  id: undefined,
  devId: undefined,
  patId: undefined,
  patName: undefined,
  patGender: undefined,
  patDetails: undefined,
  checkType: undefined,
  rentTime: new Date().getTime(),
  returnTime: undefined,
  tolerance: undefined,
  patBirthday: undefined,
  registerDate: undefined,
  doctor: undefined,
  doctorTime: undefined,
  remark: undefined,
  paid: undefined
})
 
/** 后端日期统一是毫秒时间戳,转成 YYYY-MM-DD 展示 */
const fmtDate = (value?: number | null) => (value ? formatTimestamp(value as unknown as Date) : '')
 
// 性别:1 男 2 女。为空时不走 calGender(它会把空值当成"女")
const genderText = computed(() => {
  const gender = formData.value.patGender
  return gender === 1 || gender === 2 ? calGender(gender) : ''
})
 
// 年龄:按出生日期计算
const ageText = computed(() => {
  const birthday = formData.value.patBirthday
  if (!birthday) {
    return ''
  }
  const age = calculateAge(birthday as unknown as Date)
  return Number.isFinite(age) ? `${age}岁` : ''
})
 
// 距今天数:按开单日期(doctorTime)计算
const daysFromOrder = computed(() => {
  const orderTime = formData.value.doctorTime
  if (!orderTime) {
    return ''
  }
  return `${dayjs().startOf('day').diff(dayjs(orderTime).startOf('day'), 'day')}天`
})
 
const formRules = reactive({
  // devId: [{ required: true, message: '设备编号不能为空', trigger: 'blur' }],
  rentTime: [{ required: true, message: '请选择装机日期', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
 
 
// =====================================================================================
// 【本需求:紧急患者不排队直接检查】
//   在「申请单号 / 就诊号 / 患者编号」任一输入框回车 → 查近一个月、本窗口检查项目的预约记录
//   → 1 条直接读入;多条弹选择框(按预约时间倒序)→ 读入后可直接「检查完成」
//   → 后端在"今天没有待检查单"时按预约单补建,从而像排队患者一样进入「已完成列表」
// =====================================================================================
const emergencyMode = ref(false) // 当前表单是否来自"紧急加做"
const emergencyVisible = ref(false) // 选择框
const emergencyLoading = ref(false)
const emergencyList = ref<AppointmentVO[]>([])
const emergencySelected = ref<AppointmentVO | undefined>()
/** 选择表格引用(保留:后续如需 scrollToRow 等能力可用) */
const emergencyTableRef = ref<any>()
 
/** 选中判断(模板里用,避免直接比较对象引用) */
const isEmergencySelected = (row: AppointmentVO) =>
  null != emergencySelected.value && emergencySelected.value.id === row?.id
 
/** 选中行加 is-selected 类,配合下方样式做「整行高亮 + 左侧蓝条 + 加粗」 */
const emergencyRowClass = ({ row }: { row: AppointmentVO }) =>
  isEmergencySelected(row) ? 'is-selected' : ''
 
/** 本窗口(诊室)开展的检查项目,用于过滤候选预约;为空表示不限制 */
const currentWindowCheckTypes = (): number[] | undefined => {
  const fromProp = props.room?.checkTypes
  const types =
    Array.isArray(fromProp) && fromProp.length > 0 ? fromProp : (roomStore.room?.checkTypes as number[] | undefined)
  return Array.isArray(types) && types.length > 0 ? [...types] : undefined
}
 
/** 回车:按输入框里的值查预约候选 */
const searchEmergencyCandidates = async (field: 'applyNo' | 'episodeId' | 'patId') => {
  const code = String((formData.value as Record<string, any>)[field] ?? '').trim()
  if (!code) return
  emergencyLoading.value = true
  try {
    const list = (await AppointmentApi.getEmergencyCandidates(code, currentWindowCheckTypes())) as AppointmentVO[]
    const rows = Array.isArray(list) ? list : []
    if (rows.length === 0) {
      message.warning('近一个月内没有找到本窗口检查项目的预约记录')
      return
    }
    if (rows.length === 1) {
      applyAppointment(rows[0])
      message.success('已读入预约记录,可直接点「检查完成」')
      return
    }
    emergencyList.value = rows
    emergencySelected.value = undefined
    emergencyVisible.value = true
  } finally {
    emergencyLoading.value = false
  }
}
 
/** 选择框确认(也支持双击行直接确认) */
const confirmEmergency = (row?: AppointmentVO) => {
  const target = row ?? emergencySelected.value
  if (!target) return
  applyAppointment(target)
  emergencyVisible.value = false
}
 
/**
 * 把预约单读入表单。
 * 注意:这里是"紧急加做",**不排队**——不建 queue 行、不取号;
 * 「检查完成」时由后端按需补建「待检查」检查单(见 DevRentServiceImpl#prepareEmergencyDevRent)。
 */
const applyAppointment = (appt: AppointmentVO) => {
  resetForm()
  emergencyMode.value = true
  formData.value.applyNo = appt.applyNo
  formData.value.episodeId = appt.episodeId
  formData.value.patId = appt.patId
  formData.value.patName = appt.patName
  formData.value.checkType = appt.bookCheckType
  formData.value.patGender = appt.patGender
  formData.value.patBirthday = appt.patBirthday
  formData.value.patSrc = appt.patSrc
  formData.value.tolerance = appt.tolerance
  formData.value.doctor = appt.doctor
  formData.value.doctorTime = appt.doctorTime
  formData.value.registerDate = appt.registerDate
  formData.value.paid = appt.paid
  formData.value.doctorAdviceNo = appt.doctorAdviceNo
  formData.value.patMobile = appt.patMobile
  formData.value.patPhone = appt.patPhone
  formData.value.patIdentityId = appt.patIdentityId
  formData.value.outpatientNo = appt.outpatientNo
  formData.value.patWardDesc = appt.patWardDesc
  formData.value.patBedNo = appt.patBedNo
  formData.value.medicalCard = appt.medicalCard
  // 条码/打印小票依赖 patDetails.source
  formData.value.patDetails = {
    source: appt.patSrc,
    appointmentId: appt.id
  } as unknown as typeof formData.value.patDetails
  message.success('已读入预约记录,可直接点「检查完成」')
}
 
/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    formData.value.roomId = props.room.roomId
    formData.value.bedNo = props.room.bedNo
    // 【本需求:紧急患者不排队直接检查】带上"紧急加做"标记:
    //   后端据此在「今天没有待检查单」时按预约单补建一行,从而能正常完成并写入「已完成列表」
    const data = formData.value as unknown as DevRentVO & { emergency?: boolean }
    data.emergency = emergencyMode.value
    // 后端 routine-finish 已返回本次完成的检查单 id(紧急加做时是服务端新建的那条)
    const rentId = (await DevRentApi.routineFinish(data)) as unknown as number | string | undefined
 
    // 自动确费:用返回的 rentId;无 id 时静默跳过(不再弹「请先检查」)
    if (needAutoFeeConfirm(formData.value.checkType)) {
      feeConfirm(rentId)
    }
 
    message.success(t('操作成功'))
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('event_routine')
    resetForm()
    getList() // 医生作业历史
  } finally {
    formLoading.value = false
  }
}
 
/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    devId: undefined,
    patId: undefined,
    patName: undefined,
    patGender: undefined,
    checkType: undefined,
    rentTime: new Date().getTime(),
    returnTime: undefined,
    tolerance: undefined,
    patBirthday: undefined,
    registerDate: undefined,
    doctor: undefined,
    doctorTime: undefined,
    interference: undefined,
    baseline: undefined,
    detachment: undefined,
    remark: undefined,
    patDetails: undefined,
    paid: undefined,
    doctorAdviceNo: undefined,
    roomId: props.room.roomId,
    bedNo: props.room.bedNo
  }
  // 【本需求】换患者/重置时:条码显隐回到"跟随配置默认",紧急加做标记清空
  barcodeVisible.value = null
  emergencyMode.value = false
  formRef.value?.resetFields()
}
const yddownload = async () => {
  // 检查 setappointmentId 是否存在
  if (!props.setappointmentId) {
    message.warning('当前无就诊中患者请先叫号')
    return
  }
 
  yddownloadLoading.value = true
  try {
    const response = await DoctorApi.yddownload(props.setappointmentId)
    console.log(response, 'xml1')
    console.log(response.fileContent, 'xml2')
    downloadWordFile(response.fileContent, response.fileName)
  } finally {
    yddownloadLoading.value = false
  }
}
 
const sgdownload = async () => {
  // 检查 setappointmentId 是否存在
  if (!props.setappointmentId) {
    message.warning('当前无就诊中患者请先叫号')
    return
  }
 
  sgdownloadLoading.value = true
  try {
    const response = await DoctorApi.sgdownload(props.setappointmentId)
    downloadWordFile(response.fileContent, response.fileName)
  } finally {
    sgdownloadLoading.value = false
  }
}
const downloadWordFile = (data, filename = 'document') => {
  try {
    // 1. 确保文件名以.doc结尾
    if (!filename.endsWith('.doc')) {
      filename += '.doc'
    }
 
    // 2. 创建Blob对象,指定MIME类型为Word文档[9,10](@ref)
    // 对于Word 2003 XML格式,使用'application/msword'
    const blob = new Blob([data], { type: 'application/msword' })
 
    // 3. 为Blob对象创建一个临时的下载URL[8,10](@ref)
    const url = URL.createObjectURL(blob)
 
    // 4. 创建一个隐藏的不可见的<a>链接元素[10](@ref)
    const link = document.createElement('a')
    link.style.display = 'none' // 隐藏链接
    link.href = url
    link.download = filename // 设置下载的文件名
 
    // 5. 将链接添加到DOM中,模拟点击,然后移除它[10](@ref)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
 
    // 6. 释放URL对象以释放内存[9,10](@ref)
    // 使用setTimeout确保下载触发后再释放
    setTimeout(() => {
      URL.revokeObjectURL(url)
    }, 100)
 
    console.log('文件下载已触发!')
  } catch (error) {
    console.error('下载文件时发生错误:', error)
    // 这里可以添加更友好的用户错误提示,例如使用alert或页面弹窗
  }
}
const getRentInfoByPatId = () => {
  const tempPatId = formData.value.patId
  resetForm()
  if (isStringEmpty(tempPatId)) return
 
  formData.value.patId = tempPatId
  getFreeRentInfo(formData.value)
}
 
const getFreeRentInfo = async (devRentVO) => {
  if (
    (devRentVO.devId == null || devRentVO.devId === '') &&
    (devRentVO.patId == null || devRentVO.patId === '')
  )
    return
 
  const data = await DevRentApi.getFreeRent(devRentVO)
  if (null === data) return
 
  // formDate 对应  DevRent
  // formData.value = data  //不能整个赋值, 默认领用时间被清空
  formData.value.id = data.id //rent id
  formData.value.applyNo = data.applyNo
  formData.value.episodeId = data.episodeId
  formData.value.patDetails = data.patDetails
}
 
const loading = ref(true) // 列表的加载中
const list = ref<JobRecordVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
// 当前诊室信息(用于取诊室开展的检查项目做兜底,见 syncRoomCheckTypes)
const roomStore = useRoomStore()
 
 
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  jobType: [50, 60],
  docId: undefined,
  docName: undefined,
  devId: undefined,
  patId: undefined,
  patName: undefined,
  jobTime: [curDayStart(), curDayEnd()],
  summary: undefined,
  remark: undefined,
  createTime: [],
  // ========================================================================
  // 按**当前诊室开展的检查项目**隔离已完成记录。
  //
  // 背景:`job_record` 表只有 doc_id + check_type,**没有 room_id**;
  // 而 /ecg/job-record/doctor-page 是强制按登录医生查"自己的记录"。
  // 于是同一医生在多个诊室坐诊时(如 1号门诊 ct=[100,1100]、6号门诊 ct=[400] 平板运动心电),
  // 叫号检查页会把**多个诊室的记录混在一起**显示 —— 正是用户反馈的现象。
  //
  // 由各页面(Routine.vue / index.vue / DevInstall.vue)在 onMounted 时
  // 用当前诊室的 checkTypes 赋值,并在每次查询前同步,确保切诊室后立即生效。
  // ========================================================================
  checkTypes: undefined as number[] | undefined
})
 
/**
 * 把「当前诊室开展的检查项目」同步到查询条件,实现已完成记录按诊室隔离。
 * 见 queryParams.checkTypes 的说明。
 */
const syncRoomCheckTypes = () => {
  // 优先用页面传入的诊室信息;为空时回退到 store(更可靠,见 TitlePanel 同处说明)
  const fromProp = props.room?.checkTypes
  const types = (Array.isArray(fromProp) && fromProp.length > 0)
    ? fromProp
    : roomStore.room?.checkTypes
  queryParams.checkTypes = (Array.isArray(types) && types.length > 0) ? [...types] : undefined
}
/** 查询列表 */
const getList = async () => {
  // 查询前同步当前诊室开展的检查项目,保证只显示本诊室的记录
  syncRoomCheckTypes()
  loading.value = true
  try {
    const data = await JobRecordApi.getJobRecordDoctorPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}
 
const onRowClick = (cur) => {
  if (cur !== null) getSelectedRent(cur.rentId)
}
 
/**
 * 点击「已完成检查记录」的某一行:只把**该条记录**的信息合入表单。
 *
 * ⚠️ 原实现是 `formData.value = await DevRentApi.getDevRent(rentId)` —— **整个替换**。
 * 而实测 `GET /ecg/dev-rent/get` 的响应里,除 `patName` 外的患者字段**全是 null**:
 *   {"patName":"…","patGender":null,"patBirthday":null,"registerDate":null,"doctor":null,
 *    "patMobile":null,"patPhone":null,"patWardDesc":null,"patBedNo":null,"outpatientNo":null,
 *    "patIdentityId":null,"doctorAdviceNo":null,"tolerance":null}
 * 原因:`dev_rent` 表**不存**这些字段,它们是由 `DevRentServiceImpl` 从 appointment
 * 回填的;而 `/dev-rent/get` 这条路径**没有做回填**。
 *
 * 后果:医生一点记录行,PatientInfoBlock 里除姓名外的信息**全部变成 '-'**,
 * 表现为"患者信息缺失"。
 *
 * 修复:**保留当前患者信息**,只用返回的记录字段覆盖(仅当返回值为非空时)。
 */
const getSelectedRent = async (rentId) => {
  const record = await DevRentApi.getDevRent(rentId)
  if (!record) return
  const merged = { ...formData.value } as Record<string, any>
  Object.keys(record as Record<string, any>).forEach((k) => {
    const v = (record as Record<string, any>)[k]
    // 只覆盖"确有值"的字段,避免用 null 冲掉已回填好的患者信息
    if (v !== null && v !== undefined && v !== '') {
      merged[k] = v
    }
  })
  // 记录里可能完全没有患者字段,此时保留原患者信息
  if (!merged.patName) merged.patName = formData.value.patName
  formData.value = merged as typeof formData.value
}
 
const cancelInstall = async () => {
  formData.value.roomId = props.room.roomId
  formData.value.bedNo = props.room.bedNo
  const data = formData.value as unknown as DevRentVO
  await DevRentApi.routineCheckCancel(data)
 
  // 发送操作成功的事件
  emit('event_routine')
  resetForm()
  getList()
 
  message.success(t('操作成功'))
}
 
/**
 * 确费。
 * @param rentId 本次检查完成返回的检查单 id;不传则用表单里的 id。
 * 【本次修复】原实现在 id 为空时弹「请先检查」—— 紧急加做患者没有 id,点「检查完成」会先弹这个错,
 * 再弹「操作成功」,让人误以为操作失败。现在改为静默跳过(按钮本身也会在无 id 时禁用)。
 */
const feeConfirm = async (rentId?: number | string | null) => {
  const id = rentId ?? formData.value.id
  if (id == null || id === '') {
    console.warn('[feeConfirm] 无检查单 id,跳过确费')
    return
  }
 
  try {
    const result = await DevRentApi.feeConfirm(id as number)
    if (0 == result) {
      //message.success(t('确费操作成功'))
    }
  } catch (err) {
    // 框架 会给出 后台的 错误信息
  }
}
 
const feeCancel = async () => {
  // 【本次修复】无检查单 id 时静默跳过(按钮已禁用),不再弹「请先检查」
  if (formData.value.id == null || formData.value.id === '') {
    console.warn('[feeCancel] 无检查单 id,跳过取消确费')
    return
  }
 
  try {
    const result = await DevRentApi.feeCancel(formData.value.id)
    if (0 == result) {
      // message.success(t('确费取消成功'))
    }
  } catch (err) {
    // 框架 会给出 后台的 错误信息
  }
}
/**
 * 【本需求】患者条码:位置在「就诊号」下方,内容 = 就诊号(episodeId),可显隐
 *
 *  · 默认可见性 = 「检查类型 → 是否显示条码」配置里**包含该患者来源**
 *      - 已勾选该来源 → 默认显示
 *      - 未配置 / 配置里没有该来源 → 默认不显示(例如住院(3)通常不会勾选)
 *  · 医生可用按钮手动覆盖默认:显示中 → 「隐藏」;隐藏中 → 「条码」
 *  · 「复制」按钮只在条码显示时出现
 */
const barcodeVisible = ref<boolean | null>(null) // null = 未手动操作,跟随配置默认
 
const patSourceValue = computed<number | null>(() => {
  const source = formData.value.patDetails?.source ?? formData.value.patSrc
  return source === null || source === undefined || source === '' ? null : Number(source)
})
 
/** 配置口径:该检查类型的「显示条码」是否包含当前患者来源 */
const barcodeEnabled = computed<boolean>(() => {
  if (formData.value.checkType == null) return false
  const displayBarcode: number[] | undefined = checkTypeStore.getCheckTypeDispBarCode(formData.value.checkType)
  if (displayBarcode == null || displayBarcode.length === 0) return false
  const patSource = patSourceValue.value
  if (patSource == null) return false
  return displayBarcode.map(Number).includes(patSource)
})
 
/** 条码 / 复制的内容:统一取「就诊号」 */
const barcodeContent = computed<string>(() => formData.value.episodeId ?? '')
 
/** 实际是否显示:手动覆盖优先,否则跟配置默认 */
const barcodeVisibleEffective = computed<boolean>(() => barcodeVisible.value ?? barcodeEnabled.value)
 
/** 条码:可见且内容非空才渲染 */
const showBarCode = computed<boolean>(() => barcodeVisibleEffective.value && barcodeContent.value !== '')
 
/** 「复制」按钮:只在条码显示时出现 */
const showCopyButton = computed<boolean>(() => showBarCode.value)
 
/** 切换按钮:只要有就诊号就给(不受配置限制,配置只管"默认是否显示") */
const showBarcodeToggle = computed<boolean>(() => barcodeContent.value !== '')
 
/** 切换按钮文案:显示中 → 隐藏;隐藏中 → 条码 */
const barcodeToggleLabel = computed<string>(() => (showBarCode.value ? '隐藏' : '条码'))
 
const toggleBarcode = () => {
  barcodeVisible.value = !barcodeVisibleEffective.value
}
 
const copyBarcode = async () => {
  if (!barcodeContent.value) return
  await navigator.clipboard.writeText(barcodeContent.value)
}
 
/** 初始化 **/
onMounted(() => {
  resetForm()
  getList()
})
</script>
 
<style scoped lang="scss">
 
/* 【本次需求】「已完成列表」标题栏:左侧主色竖线 + 加粗小标题,紧凑高度不挤压表格 */
/* 【本需求】编辑区上方的「紧急加做」操作提示:一行显示、醒目但不占高度 */
.emergency-tip {
  padding: 4px 10px;
  margin-bottom: 6px;
 
  :deep(.el-alert__title) {
    padding: 0;
    font-size: 13px;
    line-height: 20px;
  }
 
  &__text {
    color: var(--el-color-warning-dark-2);
  }
 
  /* 关键字段/按键做强调,方便一眼看懂要输什么、按什么 */
  &__key {
    font-weight: 600;
    color: var(--el-color-danger);
  }
 
  &__enter {
    padding: 0 4px;
    margin: 0 2px;
    border: 1px solid var(--el-color-danger);
    border-radius: 3px;
    font-weight: 600;
    color: var(--el-color-danger);
    background-color: var(--el-color-danger-light-9);
  }
}
/* 【本需求】紧急加做:预约选择框的「选中行」要足够明显
   (原来只有默认的浅色 current-row 背景,现场反馈"只是变深一点,看不清") */
.emergency-table {
  :deep(.el-table__row) {
    cursor: pointer;
  }
  :deep(.el-table__row:hover > td) {
    background-color: var(--el-color-primary-light-9) !important;
  }
  /* 选中行:主色背景 + 加粗 + 左侧 4px 主色条 */
  :deep(.el-table__row.is-selected > td) {
    background-color: var(--el-color-primary-light-6) !important;
    color: var(--el-color-primary-dark-2);
    font-weight: 600;
  }
  :deep(.el-table__row.is-selected > td:first-child) {
    box-shadow: inset 4px 0 0 var(--el-color-primary);
  }
}
 
/* 选择框底部「已选」回显 */
.emergency-selected-hint {
  float: left;
  line-height: 32px;
  font-size: 13px;
  color: var(--el-color-primary);
  font-weight: 600;
}
/* 【本需求】就诊号下方的条码行:条码 + [隐藏|条码] + [复制] 同一行,紧凑不撑高 */
.barcode-row {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-top: 4px;
  flex-wrap: wrap;
}
.records-title {
  display: flex;
  align-items: center;
  flex: none;
  gap: 6px;
  padding: 2px 0 6px;
 
  &__bar {
    width: 3px;
    height: 14px;
    background-color: var(--el-color-primary);
    border-radius: 2px;
  }
 
  &__text {
    font-size: 14px;
    font-weight: 600;
    color: var(--el-text-color-primary);
  }
}
/* ==========================================================================
   需求:表单内容挤占了下方记录表格的空间 —— 压缩行间距。
   Element Plus 默认 `.el-form-item { margin-bottom: 18px }`;
   本页表单含 18 项患者信息(4 列 = 5 行)+ 9 项设备信息,
   仅间距就要上百 px,把 el-table 挤到看不见。
   这里统一压到 4px。注意 :deep 是必需的(el-form-item 是本组件的子组件渲染)。
   ========================================================================== */
.patient-compact-form :deep(.el-form-item) {
  margin-bottom: 4px;
}
 
/* ==========================================================================
   患者信息固定在内容区顶部。
   内容区自身不滚动(滚动条在记录表格上),因此**不需要 position:sticky** ——
   直接作为 flex 的固定项(flex:none)即可始终留在顶部。
   背景不透明,保证与下方记录表格视觉分离。
   ========================================================================== */
:deep(.doctor-page__content) > .patient-compact-form {
  flex: none;
  padding-bottom: 4px;
  background-color: var(--el-bg-color);
  border-bottom: 1px solid var(--el-border-color-lighter);
}
 
 
 
/* ==========================================================================
   患者信息固定在内容区顶部。
   内容区(.doctor-page__content)自身滚动,所以这里必须用 position:sticky
   才能让 18 项患者信息在记录列表滚动时保持可见。
   背景不透明,避免滚动内容从表单项间隙透出。
   ========================================================================== */
:deep(.doctor-page__content) > .patient-compact-form {
  position: sticky;
  top: 0;
  z-index: 3;
  padding-bottom: 4px;
  background-color: var(--el-bg-color);
  border-bottom: 1px solid var(--el-border-color-lighter);
}
 
/* ==========================================================================
   患者操作功能块:位于「患者信息」与「已完成记录列表」之间,独立成块。
   需求:各功能按钮(检查完成 / 放弃检查 / 重置 / 知情同意书 …)**排在一行**。
   做法:flex + gap,并 **禁止换行**(flex-wrap:nowrap);
   按钮用 size="small" 以容纳全部按钮;即使宽度不足也不折行。
   上下边框 + 底色,使它与患者信息、记录列表在视觉上分区。
   ========================================================================== */
.patient-actions {
  display: flex;
  flex: none;
  /* 按钮多时允许换行,避免挤在一行(检查页最多 6 个按钮) */
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
  /*
    【本次需求】操作功能区做一点视觉区分,方便医生一眼定位:
    极浅的主色底 + 细边框 + 左侧 3px 主色竖条(与「▎已完成列表」标题条同款语言)。
    只做"稍有区分",不改按钮本身的尺寸/颜色/顺序。
  */
  padding: 8px 10px;
  margin: 2px 0 10px;
  background-color: var(--el-color-primary-light-9);
  border: 1px solid var(--el-color-primary-light-7);
  border-left: 3px solid var(--el-color-primary);
  border-radius: 4px;
 
  /* Element Plus 给相邻 el-button 默认加了 margin-left:12px,会与 gap 叠加,清掉 */
  :deep(.el-button + .el-button) {
    margin-left: 0;
  }
}
</style>