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
<template>
  <div>
    <div class="drawContent">
      <!-- 凭证类型选择 -->
      <el-tabs v-model="activeTab" class="voucher-tabs">
        <!-- 密码凭证 -->
        <el-tab-pane name="password" :label="$t('voucher.password')">
          <div class="tab-content">
            <el-form ref="passwordForm" :model="form" :rules="rules">
              <el-form-item prop="password">
                <el-input v-model="form.password" type="text" :placeholder="$t('voucher.validPassword')" maxlength="6"
                  show-word-limit clearable>
                </el-input>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>
 
        <!-- 卡片凭证 -->
        <el-tab-pane name="card" :label="$t('voucher.card')">
          <div class="tab-content">
            <el-form ref="cardForm" :model="form" :rules="rules">
              <el-form-item prop="card">
                <el-input v-model="form.card" :placeholder="$t('voucher.validCard')" clearable></el-input>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>
 
        <!-- 人脸凭证 -->
        <el-tab-pane name="face" :label="$t('voucher.face')">
          <div class="tab-content face-tab">
            <!-- 注册方式选择 -->
            <div class="register-type-selector">
              <el-radio-group v-model="faceType" @change="handleRegisterTypeChange">
                <el-radio-button :label="0">{{ $t('voucher.photoRegistration') }}</el-radio-button>
                <el-radio-button :label="1">{{ $t('voucher.featureValueRegistration') }}</el-radio-button>
              </el-radio-group>
            </div>
 
            <!-- 照片上传注册 -->
            <div v-if="faceType == 0" class="photo-register">
              <div class="upload-area">
                <el-upload class="avatar-uploader" action="#" :show-file-list="false" accept=".jpg,.jpeg" :on-change="handleUploadChange"
                  :auto-upload="false">
                  <img v-if="faceImage" :src="faceImage" class="avatar" />
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                  <!-- 清除按钮 -->
                  <el-button v-if="faceImage" class="clear-btn" type="danger" icon="el-icon-delete" circle
                    @click.stop="clearImage"></el-button>
                </el-upload>
              </div>
            </div>
 
            <!-- 特征值注册 -->
            <div v-if="faceType == 1" class="feature-register">
              <div class="feature-input-area">
                <el-input type="textarea" clearable :rows="6" :placeholder="$t('common.placeholder')"
                  v-model="faceFeature" class="feature-textarea">
                </el-input>
              </div>
            </div>
          </div>
        </el-tab-pane>
 
        <!-- 指纹凭证 -->
        <el-tab-pane v-if="fingerprintEnabled" name="fingerprint" :label="$t('voucher.finger')">
          <div class="tab-content fingerprint-tab">
            <!-- 注册方式选择 -->
            <div class="register-type-selector">
              <el-radio-group v-model="fingerprintType" @change="handleFingerprintTypeChange">
                <el-radio-button :label="0">{{ $t('voucher.fingerRegistration') }}</el-radio-button>
                <el-radio-button :label="1">{{ $t('voucher.fingerFeatureRegistration') }}</el-radio-button>
              </el-radio-group>
            </div>
 
            <!-- 指纹录入 -->
            <div v-if="fingerprintType == 0" class="fingerprint-capture">
              <div class="capture-area">
                <div class="fingerprint-status">
                  <i :class="fingerprintStatusIcon" class="status-icon"></i>
                  <p class="status-text">{{ fingerprintStatusText }}</p>
                </div>
                <el-button 
                  type="primary" 
                  :loading="fingerprintLoading" 
                  :disabled="fingerprintLoading"
                  @click="enrollFinger">
                  {{ fingerprintLoading ? $t('voucher.fingerInputting') : (hasFingerprint ? $t('voucher.fingerReInput') : $t('voucher.startFingerInput')) }}
                </el-button>
                <div v-if="fingerprintLoading" class="capture-tips">
                  <p>{{ $t('voucher.fingerInput') }}</p>
                  <p class="timeout-text">{{ $t('voucher.fingerRemainingTime') }}: {{ fingerprintTimeout }}S</p>
                </div>
              </div>
            </div>
 
            <!-- 特征值注册 -->
            <div v-if="fingerprintType == 1" class="feature-register">
              <div class="feature-input-area">
                <el-input type="textarea" clearable :rows="6" :placeholder="$t('voucher.fingerInputTips')"
                  v-model="fingerprintFeature" class="feature-textarea">
                </el-input>
              </div>
            </div>
          </div>
        </el-tab-pane>
 
        <!-- PIN码凭证 -->
        <el-tab-pane name="code" :label="$t('voucher.code')" v-if="model == 'vf105' || model == 'vf114'">
          <Table :table-label="tableHeader" :table-data="tableData" :table-option="tableOption"></Table>
        </el-tab-pane>
      </el-tabs>
    </div>
 
    <!-- 操作按钮 -->
    <div class="dialog-footer">
      <el-button type="warning" @click="handleAddClose">
        {{ $t('common.cancel') }}
      </el-button>
      <el-button v-if="activeTab != 'code'" type="primary" :loading="isLoading" :disabled="isLoading" @click="addConfirm">
        {{ $t('common.confirm') }}
      </el-button>
    </div>
  </div>
</template>
 
<script>
import Table from "@/components/table/tableList";
import { generateRandomString, throttle } from '@/utils/index.js'
export default {
  props: {
    formData: {
      type: Object,
      default: () => ({})
    },
    addOrEditType: {
      type: String,
      default: 'add'
    },
  },
  components: {
    Table
  },
  data () {
    return {
      visible: false,
      userId: '',
      name: '',
      form: {
        password: '',
        card: '',
        face: '',
        fingerprint: '',
        // code100: '',
        // code101: '',
        // code103: '',
        oldPassword: '',
        oldCard: '',
        oldFace: '',
        oldFingerprint: '',
        // oldCode100: '',
        // oldCode101: '',
        // oldCode103: ''
      },
      keyId: {
        password: '',
        card: '',
        face: '',
        fingerprint: '',
        // code100: '',
        // code101: '',
        // code103: '',
      },
      rules: {
        password: [{ message: this.$t('voucher.validPassword'), trigger: ["blur"], pattern: /^\d{6}$/ }],
        card: [{ message: this.$t('voucher.validCard'), trigger: ["blur"], pattern: /^[0-9a-zA-Z]+$/ },],
      },
      model: '',
      isLoading: false,
      // 凭证数据
      activeTab: 'password',
      faceType: 0, // 注册方式:0-照片注册,1-特征值注册
      faceImage: '', // 人脸图片 base64 或 URL
      faceFeature: '', // 人脸特征值
      originalFaceData: null, // 存储原始人脸数据,用于判断是否修改
      
      // 指纹相关数据
      fingerprintType: 0, // 注册方式:0-指纹录入,1-特征值注册
      fingerprintFeature: '', // 指纹特征值
      fingerprintLoading: false, // 指纹录入加载状态
      fingerprintTimeout: 60, // 指纹录入超时时间
      fingerprintTimer: null, // 指纹录入定时器
      fingerprintPollTimer: null, // 指纹录入轮询定时器
      fingerprintStatusText: '等待录入', // 指纹状态文本
      fingerprintStatusIcon: 'el-icon-fingerprint', // 指纹状态图标
      originalFingerprintData: null, // 存储原始指纹数据,用于判断是否修改
      hasFingerprint: false, // 是否已有指纹凭证
      tableHeader: [
        {
          label: this.$t('voucher.credentialId'),
          list: 'keyId',
        },
        {
          label: this.$t('voucher.codeType'),
          list: 'type',
        },
        {
          label: this.$t('voucher.credentialValue'),
          list: 'code',
        },
      ],
      tableOption: {
        label: this.$t('common.operation'),
        width: "100px",
        value: 0,
        options: [
          {
            label: this.$t('common.delete'),
            key: 1,
            type: "text",
            State: true,
            method: (row) => {
              this.handleDeleteCode(row.keyId)
            },
          }
        ]
      },
      tableData: [],
    };
  },
  created () {
    this.initialForm = JSON.parse(JSON.stringify(this.form));
    this.initialKeyId = JSON.parse(JSON.stringify(this.keyId));
    this.userId = this.formData.userId
    let publicConfig = sessionStorage.getItem('publicConfig')
    let { finger, model } = publicConfig ? JSON.parse(publicConfig) : {}
    this.fingerprintEnabled = finger
    this.model = model
    this.getVoucher()
  },
  beforeDestroy() {
    // 清理定时器
    this.interruptFinger()
    this.clearFingerprintTimers()
  },
  methods: {
    // 查询凭证
    async getVoucher () {
      let data = {
        page: 0,
        size: 100,
        userId: this.userId
      }
      try {
        const res = await this.$http.post('/getKey', { data })
        if (res.code == 200) {
          console.log(res)
          let content = res.data.content
          let card = content.filter(v => v.type == 200)[0]
          if (card) {
            this.form.card = card.code
            this.form.oldCard = card.code
            this.keyId.card = card.keyId
          } else {
            this.keyId.card = ''
          }
          let face = content.filter(v => v.type == 300)[0]
          if (face) {
            // 保存原始人脸数据
            let faceType = face.extra ? JSON.parse(face.extra).faceType : 0
            this.originalFaceData = {
              keyId: face.keyId,
              code: face.code,
              faceType
            }
            if (face.extra) {
              if (faceType == 0) {
                this.faceImage = "data:image/jpeg;base64," + face.code
              } else if (faceType == 1) {
                this.faceFeature = face.code
              }
              this.faceType = faceType
            }
            this.form.face = face.code
            this.form.oldFace = face.code
            this.keyId.face = face.keyId
          } else {
            this.keyId.face = ''
            this.originalFaceData = null
          }
          let password = content.filter(v => v.type == 400)[0]
          if (password) {
            this.form.password = password.code
            this.form.oldPassword = password.code
            this.keyId.password = password.keyId
          } else {
            this.keyId.password = ''
          }
          
          // 处理指纹凭证
          let fingerprint = content.filter(v => v.type == 500)[0]
          if (fingerprint) {
            let fingerprintType = fingerprint.extra ? JSON.parse(fingerprint.extra).fingerprintType : 0
            this.originalFingerprintData = {
              keyId: fingerprint.keyId,
              code: fingerprint.code,
              fingerprintType
            }
            // 如果已有指纹凭证,默认显示指纹录入页面(fingerprintType = 0)
            // 但保留原始 fingerprintType 用于判断是否修改
            this.fingerprintType = 0
            this.hasFingerprint = true
            // 如果原始是特征值注册,保存特征值用于显示
            if (fingerprint.extra && fingerprintType == 1) {
              this.fingerprintFeature = fingerprint.code
            }
            this.form.fingerprint = fingerprint.code
            this.form.oldFingerprint = fingerprint.code
            this.keyId.fingerprint = fingerprint.keyId
            // 设置状态文本为"指纹已录入"
            this.fingerprintStatusText = this.$t('voucher.fingerInputed')
            this.fingerprintStatusIcon = 'el-icon-success'
          } else {
            this.keyId.fingerprint = ''
            this.originalFingerprintData = null
            this.hasFingerprint = false
            // 重置状态文本
            this.fingerprintStatusText = this.$t('voucher.fingerWaitInput')
            this.fingerprintStatusIcon = 'el-icon-fingerprint'
          }
 
          this.tableData = content.filter(v => v.type == 100 || v.type == 101 || v.type == 103)
          console.log(this.tableData)
        } else {
          this.$message.error(res.message)
        }
      } catch (even) {
        console.log(even);
      }
    },
 
    // 处理注册方式变化
    handleRegisterTypeChange (value) {
      console.log('切换注册方式:', value);
    },
 
    // 处理指纹注册方式变化
    handleFingerprintTypeChange (value) {
      console.log('切换指纹注册方式:', value);
      // 清理定时器
      this.clearFingerprintTimers()
      // 根据是否已有指纹凭证设置状态文本
      if (value === 0) {
        this.fingerprintStatusText = this.hasFingerprint ? this.$t('voucher.fingerInputed') : this.$t('voucher.fingerWaitInput')
        this.fingerprintStatusIcon = this.hasFingerprint ? 'el-icon-success' : 'el-icon-fingerprint'
      } else {
        this.fingerprintStatusText = this.$t('voucher.fingerWaitInput')
        this.fingerprintStatusIcon = 'el-icon-fingerprint'
      }
    },
 
    // 清除定时器
    clearFingerprintTimers() {
      if (this.fingerprintTimer) {
        clearInterval(this.fingerprintTimer)
        this.fingerprintTimer = null
      }
      if (this.fingerprintPollTimer) {
        clearInterval(this.fingerprintPollTimer)
        this.fingerprintPollTimer = null
      }
    },
 
    // 开始指纹录入
    async enrollFinger() {
      if (!this.fingerprintEnabled) {
        this.$message.warning('当前设备不支持指纹操作')
        return
      }
      if (!this.userId) {
        this.$message.error(this.$t('person.userNotExist'))
        return false
      }
      this.fingerprintLoading = true
      this.fingerprintTimeout = 60
      this.fingerprintStatusText = this.$t('voucher.fingerInputNow')
      this.fingerprintStatusIcon = 'el-icon-loading'
 
      try {
        // 发送指纹录入指令
        const startRes = await this.$http.post('/control', {
          data: {
            command: 12,
            extra: {
              userId: this.userId,
              fingerprintAction: 0,
              isRemote: false
            },  
          }
        })
 
        if (startRes.code !== 200) {
          this.$message.error(startRes.message || this.$t('voucher.fingerInputFailed'))
          this.resetFingerprintStatus()
          return
        }
 
        // 开始倒计时
        this.fingerprintTimer = setInterval(() => {
          this.fingerprintTimeout--
          if (this.fingerprintTimeout <= 0) {
            this.handleFingerprintTimeout()
          }
        }, 1000)
 
        // 开始轮询查询指纹录入结果
        this.fingerprintPollTimer = setInterval(async () => {
          await this.checkFingerprintResult()
        }, 500) // 每0.5秒查询一次
 
      } catch (error) {
        console.error('指纹录入失败:', error)
        this.$message.error(this.$t('voucher.fingerReTry'))
        this.resetFingerprintStatus()
      }
    },
 
    // 中断指纹录入
    async interruptFinger () {
      if (!this.fingerprintLoading) return
      try {
        await this.$http.post('/control', {
          data: {
            command: 12,
            extra: {
              fingerprintAction: 1
            }
          }
        })
      } catch (error) {
        console.error('中断指纹采集失败:', error)
      } finally {
        this.fingerprintLoading = false
        this.clearFingerprintTimers()
      }
    },
 
    // 查询指纹录入结果
    async checkFingerprintResult() {
      try {
        const res = await this.$http.post('/getFingerChar', {
          data: {
            userId: this.userId
          }
        })
 
        if (res.code === 200 && res.data && typeof res.data.ret == 'string') {
          // 录入成功,将特征值填充到form.fingerprint和fingerprintFeature
          const featureValue = res.data.ret
          this.form.fingerprint = featureValue
          this.fingerprintFeature = featureValue
          
          this.fingerprintStatusText = this.$t('voucher.fingerInputSuccess')
          this.fingerprintStatusIcon = 'el-icon-success'
          this.$message.success(this.$t('voucher.fingerFilled'))
          this.resetFingerprintStatus(false)
          
          // 标记已有指纹凭证
          this.hasFingerprint = true
          
          // 录入成功后,自动切换到特征值注册模式,展示采集到的特征值
          // 无论是首次录入还是重新录入,都要切换到特征值注册页面
          this.fingerprintType = 1
        }else if (res.code === 200 && res.data && res.data.ret == -1) {
          this.$message.error(this.$t('voucher.fingerFailed'))
          this.handleFingerprintError()
        }
      } catch (error) {
        console.error('查询指纹结果失败:', error)
      }
    },
 
    // 处理指纹录入超时
    handleFingerprintTimeout() {
      this.$message.error(this.$t('voucher.fingerInputTimeout'))
      this.fingerprintStatusText = this.$t('voucher.fingerTimeout')
      this.fingerprintStatusIcon = 'el-icon-error'
      this.resetFingerprintStatus()
    },
 
    // 处理指纹录入失败
    handleFingerprintError() {
      this.$message.error(this.$t('voucher.fingerInputError'))
      this.fingerprintStatusText = this.$t('voucher.fingerError')
      this.fingerprintStatusIcon = 'el-icon-error'
      this.resetFingerprintStatus()
    },
 
    // 重置指纹录入状态
    resetFingerprintStatus(resetText = true) {
      this.fingerprintLoading = false
      this.clearFingerprintTimers()
      if (resetText) {
        setTimeout(() => {
          // 根据是否已有指纹凭证设置状态文本
          this.fingerprintStatusText = this.hasFingerprint ? this.$t('voucher.fingerInputed') : this.$t('voucher.fingerWaitInput')
          this.fingerprintStatusIcon = this.hasFingerprint ? 'el-icon-success' : 'el-icon-fingerprint'
        }, 2000)
      }
    },
 
    clearImage () {
      this.faceImage = ""
      this.form.face = ""
    },
 
    handleUploadChange (file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        console.log(e);
        let result = e.target.result
        this.faceImage = result
        this.form.face = result.split(',').pop()
      };
      reader.readAsDataURL(file.raw);
    },
 
    addConfirm: throttle (async function() {
      if (this.isLoading) return
      // 提交凭证逻辑
      try {
        // 如果是人脸凭证,需要根据当前类型设置数据
        if (this.activeTab === 'face') {
          if (this.faceType === 1) {
            // 特征值注册,直接使用特征值
            this.form.face = this.faceFeature
          }
          // 照片注册已经在handleUploadChange中设置好了form.face
        }
        
        // 如果是指纹凭证,需要根据当前类型设置数据
        if (this.activeTab === 'fingerprint') {
          if (this.fingerprintType === 1) {
            // 特征值注册,直接使用特征值
            this.form.fingerprint = this.fingerprintFeature
          }
          // 指纹录入已经在checkFingerprintResult中设置好了form.fingerprint
        }
        
        await this.$refs.passwordForm.validate();
        await this.$refs.cardForm.validate();
        this.submitData();
      } catch (error) {
        console.log(error)
      }
    }, 2000),
 
    handleAddClose () {
      this.interruptFinger()
      this.clearFingerprintTimers()
      this.$emit('close-drawer', false);
    },
 
    async submitData () {
      this.isLoading = true
      try {
        if (!this.userId) {
        this.$message.error(this.$t('person.userNotExist'))
        return false
        }
        let keyAddList = []
        let keyEditList = []
        let keyDeleteList = []
        // 处理密码凭证
        this.processPasswordVoucher(keyAddList, keyEditList, keyDeleteList)
        // 处理卡片凭证
        this.processCardVoucher(keyAddList, keyEditList, keyDeleteList)
        // 处理人脸凭证
        this.processFaceVoucher(keyAddList, keyEditList, keyDeleteList)
        // 处理指纹凭证
        if (this.fingerprintEnabled) {
          this.processFingerprintVoucher(keyAddList, keyEditList, keyDeleteList)
        }
        
        if (keyAddList.length) {
          const res = await this.$http.post(
            "/insertKey",
            {
              data: keyAddList
            }
          );
          if (res.code == 200) {
            this.$message.success(this.$t('common.saveSuccess'))
            this.getVoucher()
          } else {
            if (res.data && res.data[0]) {
              this.$message.error(res.data[0].errmsg)
            }
          }
        }
        if (keyEditList.length) {
          const res = await this.$http.post(
            "/modifyKey",
            {
              data: keyEditList
            }
          );
          if (res.code == 200) {
            this.$message.success(this.$t('common.saveSuccess'))
            this.getVoucher()
          } else {
            if (res.data && res.data[0]) {
              this.$message.error(res.data[0].errmsg)
            }
          }
        }
        if (keyDeleteList.length) {
          const res = await this.$http.post(
            "/delKey",
            {
              data: { keyIds: keyDeleteList }
            }
          );
          if (res.code == 200) {
            this.$message.success(this.$t('common.saveSuccess'))
            this.getVoucher()
          } else {
            if (res.data && res.data[0]) {
              this.$message.error(res.data[0].errmsg)
            }
          }
        }
        // 如果没有数据变化
        if (!keyAddList.length && !keyEditList.length && !keyDeleteList.length) {
          this.$message.info(this.$t('common.noDataSaved'))
        }
      } catch (error) {
        console.error('submitData error:', error)
      } finally {
        this.isLoading = false
      }
    },
 
    // 处理密码凭证
    processPasswordVoucher (keyAddList, keyEditList, keyDeleteList) {
      // 如果存在密码凭证,且密码有变化,则修改
      if (this.keyId.password) {
        if (this.form.password) {
          if (this.form.password !== this.form.oldPassword) {
            keyEditList.push({
              keyId: this.keyId.password,
              userId: this.userId,
              type: '400',
              code: this.form.password
            })
          }
        } else {
          keyDeleteList.push(this.keyId.password)
        }
      } else {
        // 不存在密码凭证,新增
        // 如果密码为空,不处理
        if (!this.form.password) return
        keyAddList.push({
          keyId: generateRandomString(),
          userId: this.userId,
          type: '400',
          code: this.form.password
        })
      }
    },
 
    // 处理卡片凭证
    processCardVoucher (keyAddList, keyEditList, keyDeleteList) {
      // 如果存在卡片凭证,且卡片号有变化,则修改
      if (this.keyId.card) {
        if (this.form.card) {
          if (this.form.card !== this.form.oldCard) {
            keyEditList.push({
              keyId: this.keyId.card,
              userId: this.userId,
              type: '200',
              code: this.form.card
            })
          }
        } else {
          keyDeleteList.push(this.keyId.card)
        }
      } else {
        // 不存在卡片凭证,新增
        // 如果卡片号为空,不处理
        if (!this.form.card) return
        keyAddList.push({
          keyId: generateRandomString(),
          userId: this.userId,
          type: '200',
          code: this.form.card
        })
      }
    },
 
    // 处理人脸凭证
    processFaceVoucher (keyAddList, keyEditList, keyDeleteList) {
      // 如果人脸数据为空,不处理
      const hasFaceVoucher = this.originalFaceData !== null
      // 如果存在人脸凭证,且人脸数据有变化,则修改
      if (hasFaceVoucher) {
        // 判断数据是否有变化
        const isDataChanged =
          this.form.face !== this.form.oldFace ||
          this.faceType !== this.originalFaceData.faceType
 
        if (isDataChanged) {
          if (this.form.face) {
            keyEditList.push({
              keyId: this.keyId.face,
              userId: this.userId,
              type: '300',
              code: this.form.face,
              extra: {
                faceType: this.faceType
              }
            })
          } else {
            keyDeleteList.push(this.keyId.face)
          }
        }
      } else {
        // 不存在人脸凭证,新增
        if (!this.form.face) return
        // 判断是否已存在人脸凭证
        keyAddList.push({
          keyId: generateRandomString(),
          userId: this.userId,
          type: '300',
          code: this.form.face,
          extra: {
            faceType: this.faceType
          }
        })
      }
    },
 
    // 处理指纹凭证
    processFingerprintVoucher (keyAddList, keyEditList, keyDeleteList) {
      // 如果指纹数据为空,不处理
      const hasFingerprintVoucher = this.originalFingerprintData !== null
      // 如果存在指纹凭证,且指纹数据有变化,则修改
      if (hasFingerprintVoucher) {
        // 确定要使用的 fingerprintType
        let finalFingerprintType = this.fingerprintType
        // 如果当前在指纹录入页面(fingerprintType === 0)且指纹数据没有变化,说明没有重新录入,保持原始的 fingerprintType
        if (this.fingerprintType === 0 && this.form.fingerprint === this.form.oldFingerprint) {
          finalFingerprintType = this.originalFingerprintData.fingerprintType
        }
        // 如果当前在特征值注册页面(fingerprintType === 1),使用特征值注册类型
        // 判断数据是否有变化
        const isDataChanged =
          this.form.fingerprint !== this.form.oldFingerprint ||
          finalFingerprintType !== this.originalFingerprintData.fingerprintType
 
        if (isDataChanged) {
          if (this.form.fingerprint) {
            keyEditList.push({
              keyId: this.keyId.fingerprint,
              userId: this.userId,
              type: '500',
              code: this.form.fingerprint,
              extra: {
                fingerprintType: finalFingerprintType
              }
            })
          } else {
            keyDeleteList.push(this.keyId.fingerprint)
          }
        }
      } else {
        // 不存在指纹凭证,新增
        if (!this.form.fingerprint) return
        keyAddList.push({
          keyId: generateRandomString(),
          userId: this.userId,
          type: '500',
          code: this.form.fingerprint,
          extra: {
            fingerprintType: this.fingerprintType
          }
        })
      }
    },
 
    handleDeleteCode (keyId) {
      let that = this
      this.$confirm(
        this.$t('common.deleteTips'),
        this.$t('common.tips'),
        {
          confirmButtonText: this.$t('common.confirm'),
          cancelButtonText: this.$t('common.cancel'),
          type: 'warning'
        }
      ).then(async () => {
        try {
          const res = await that.$http.post("/delKey", {
            data: {
              keyIds: [keyId]
            }
          })
          if (res.code == 200) {
            that.$message.success(this.$t('common.deleteSuccess'))
            that.getVoucher()
          } else {
            that.$message.error(res.message)
          }
        } catch (even) {
          console.log(even)
        }
      }).catch(() => { })
    },
 
  },
};
</script>
 
<style lang='less' scoped>
.voucher-tabs {
  margin-top: 10px;
}
 
.tab-content {
  padding: 10px 0;
}
 
/* 上传区域 */
.avatar-uploader {
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  cursor: pointer;
  width: 150px;
  height: 150px;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  background-color: #fafafa;
}
 
.avatar-uploader:hover {
  border-color: #409eff;
}
 
.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
 
.avatar-uploader-icon {
  font-size: 28px;
  color: #999;
}
 
.upload-tip {
  margin-top: 8px;
  font-size: 12px;
  color: #999;
}
 
/* 卡片提示 */
.card-scan-tip {
  font-size: 13px;
  color: #666;
  margin-top: 10px;
  padding: 10px;
  background: #e6f7ff;
  border-radius: 4px;
  border-left: 4px solid #1890ff;
}
 
.face-register-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}
 
.register-type-selector {
  margin-bottom: 20px;
  text-align: center;
}
 
.upload-area {
  text-align: center;
  margin-bottom: 20px;
}
 
.avatar-uploader {
  position: relative;
  display: inline-block;
}
 
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 150px;
  height: 150px;
}
 
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
 
/deep/.clear-btn {
  position: absolute;
  top: -10px;
  left: 5px;
  width: 24px !important;
  height: 24px !important;
  font-size: 12px;
  z-index: 10;
}
 
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 150px;
  text-align: center;
}
 
.avatar {
  width: 150px;
  height: 150px;
  display: block;
}
 
.feature-input-area {
  margin-top: 20px;
}
 
.feature-textarea {
  width: 100%;
}
 
.feature-tips {
  margin-top: 10px;
  font-size: 12px;
  color: #909399;
}
 
.action-buttons {
  margin-top: 20px;
  text-align: center;
}
 
.el-button {
  margin: 0 10px;
}
 
/* 指纹相关样式 */
.fingerprint-tab {
  min-height: 200px;
}
 
.capture-area {
  text-align: center;
  padding: 20px;
}
 
.fingerprint-status {
  margin-bottom: 20px;
}
 
.status-icon {
  font-size: 64px;
  color: #409EFF;
  display: block;
  margin-bottom: 10px;
}
 
.status-icon.el-icon-loading {
  animation: rotating 2s linear infinite;
}
 
.status-icon.el-icon-success {
  color: #67C23A;
}
 
.status-icon.el-icon-error {
  color: #F56C6C;
}
 
@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
 
.status-text {
  font-size: 16px;
  color: #606266;
  margin: 10px 0;
}
 
.capture-tips {
  margin-top: 20px;
  font-size: 14px;
  color: #909399;
}
 
.capture-tips p {
  margin: 5px 0;
}
 
.timeout-text {
  color: #F56C6C;
  font-weight: bold;
}
</style>