sinake
9 天以前 12ed29b3cd8471e6145cd847c6e33d6aa2f535ba
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
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
<template>
  <div class="app-container">
    <el-form
      class="opo-query-form"
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="90px"
    >
 
      <el-form-item label="发票名称" prop="invoiceName">
        <el-input
          v-model="queryParams.invoiceName"
          placeholder="请输入发票名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="案列号码" prop="caseId">
        <el-input
          v-model="queryParams.caseId"
          placeholder="案列号码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="报销状态" prop="reimburseState">
        <el-select
          v-model="queryParams.reimburseState"
          placeholder="请选择报销状态"
          clearable
          size="small"
          style="width: 140px"
        >
          <el-option label="未报销" value="0" />
          <el-option label="已报销" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
 
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleUpload"
          v-hasPermi="['project:invoice:add']"
          >上传发票</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>
 
    <!-- 手机端:卡片列表 -->
    <div v-if="isMobile" class="invoice-cards" v-loading="loading">
      <div
        v-for="row in invoiceList"
        :key="row.id"
        class="invoice-card"
      >
        <div class="invoice-card__head">
          <span
            class="invoice-card__title"
            @click="handleUpdate(row)"
            >{{ row.invoiceName || "未命名发票" }}</span
          >
          <el-tag
            size="mini"
            :type="
              String(row.reimburseState) === '1' ? 'success' : 'info'
            "
          >
            {{ String(row.reimburseState) === "1" ? "已报销" : "未报销" }}
          </el-tag>
        </div>
        <div class="invoice-card__row">
          <span class="label">案例</span>
          <span class="value">{{ row.caseId || "-" }}</span>
        </div>
        <div class="invoice-card__row">
          <span class="label">金额</span>
          <span class="value">{{ amountText(row.invoiceAmount) }}</span>
        </div>
        <div class="invoice-card__row">
          <span class="label">日期</span>
          <span class="value">{{
            normalizeDate(row.occurDate) || row.occurDate || "-"
          }}</span>
        </div>
        <div class="invoice-card__row">
          <span class="label">号码</span>
          <span class="value">{{ row.invoiceNo || "-" }}</span>
        </div>
        <div class="invoice-card__row">
          <span class="label">报销ID</span>
          <span class="value">{{ row.reimburseId || "-" }}</span>
        </div>
        <div class="invoice-card__actions">
          <el-button
            type="text"
            icon="el-icon-view"
            @click="openPreview(row.invoiceUrl, row.invoiceName)"
            >预览</el-button
          >
          <el-button
            v-if="String(row.reimburseState) !== '1'"
            type="text"
            icon="el-icon-check"
            @click="handleReimburse(row)"
            v-hasPermi="['project:invoice:edit']"
            >已报销</el-button
          >
          <el-button
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(row)"
            v-hasPermi="['project:invoice:edit']"
            >修改</el-button
          >
          <el-button
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(row)"
            v-hasPermi="['project:invoice:remove']"
            >删除</el-button
          >
        </div>
      </div>
      <div v-if="!invoiceList.length && !loading" class="invoice-empty">
        暂无数据
      </div>
    </div>
 
    <el-table v-else v-loading="loading" border :data="invoiceList">
      <el-table-column type="index" label="序号" width="55" align="center" />
      <el-table-column label="案例" align="center" prop="caseId"  width="100">
        
      </el-table-column>
     
      <el-table-column
        prop="invoiceType"
        label="发票类型"
        width="130"
        align="center"
        show-overflow-tooltip
      />
      <el-table-column
        prop="invoiceName"
        label="发票名称"
        align="center"
        show-overflow-tooltip
      />
      <el-table-column
        prop="invoiceNo"
        label="发票号码"
        width="150"
        align="center"
        show-overflow-tooltip
      />
      <el-table-column
        prop="invoiceAmount"
        label="发票金额"
        width="120"
        align="center"
      />
      <el-table-column label="发生日期" width="120" align="center">
        <template slot-scope="scope">
          {{ normalizeDate(scope.row.occurDate) || scope.row.occurDate }}
        </template>
      </el-table-column>
      <el-table-column label="报销状态" width="110" align="center">
        <template slot-scope="scope">
          <el-tag
            size="mini"
            :type="
              String(scope.row.reimburseState) === '1' ? 'success' : 'info'
            "
          >
            {{ String(scope.row.reimburseState) === "1" ? "已报销" : "未报销" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="reimburseId"
        label="报销ID"
        width="150"
        align="center"
        show-overflow-tooltip
      />
      <el-table-column
        label="操作"
        width="200"
        align="center"
        :fixed="isMobile ? false : 'right'"
      >
        <template slot-scope="scope">
          <el-button
            type="text"
            icon="el-icon-view"
            @click="openPreview(scope.row.invoiceUrl, scope.row.invoiceName)"
            >文件预览</el-button
          >
          <el-button
            v-if="String(scope.row.reimburseState) !== '1'"
            type="text"
            icon="el-icon-check"
            @click="handleReimburse(scope.row)"
            v-hasPermi="['project:invoice:edit']"
            >已报销</el-button
          >
          <el-button
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['project:invoice:edit']"
            >修改</el-button
          >
          <el-button
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['project:invoice:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
 
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
 
    <!-- 上传发票 / 发票信息确认 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="760px"
      append-to-body
      :fullscreen="isMobile"
      :close-on-click-modal="false"
      @closed="revokeThumbObjectUrl"
    >
      <!-- 第一步:选案例、用户,上传发票 -->
      <div v-if="mode === 'upload'">
        <el-form
          ref="uploadForm"
          :model="uploadForm"
          :rules="uploadRules"
          label-width="100px"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item label="案例ID" prop="caseId">
                <el-input
                  v-model.number="uploadForm.caseId"
                  placeholder="请输入案例ID"
                />
              </el-form-item>
            </el-col>
           
          </el-row>
          <el-form-item label="发票文件">
            <el-upload
              class="invoice-upload"
              drag
              multiple
              :action="uploadFileUrl"
              :headers="headers"
              :data="uploadData"
              :show-file-list="false"
              :before-upload="beforeUpload"
              :on-success="handleUploadSuccess"
              :on-error="handleUploadError"
              accept="image/*,.pdf"
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">
                将发票拖到此处,或<em>点击上传</em>
              </div>
              <div class="el-upload__tip" slot="tip">
                支持图片、PDF,可多选文件批量上传,单个文件不超过 10MB;上传后自动识别发票信息,识别结果可在下方编辑
              </div>
            </el-upload>
          </el-form-item>
          <el-form-item
            v-if="uploadedList.length"
            label="上传结果"
          >
            <el-table
              :data="uploadedList"
              border
              size="mini"
              max-height="260"
              style="width: 100%"
            >
              <el-table-column
                prop="invoiceNo"
                label="发票号码"
                show-overflow-tooltip
              />
              <el-table-column
                prop="invoiceType"
                label="发票类型"
                show-overflow-tooltip
              />
              <el-table-column
                prop="invoiceAmount"
                label="发票金额"
                width="110"
                align="center"
              />
              <el-table-column label="发生日期" width="120" align="center">
                <template slot-scope="scope">
                  {{
                    normalizeDate(scope.row.occurDate) || scope.row.occurDate
                  }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80" align="center">
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    @click="openEditForm(scope.row)"
                    >编辑</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-form>
      </div>
 
      <!-- 第二步:识别结果确认,字段均可修改 -->
      <el-form
        v-else
        ref="form"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="案例ID" prop="caseId">
              <el-input
                v-model.number="form.caseId"
                placeholder="请输入案例ID"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发票类型" prop="invoiceType">
              <el-input
                v-model="form.invoiceType"
                placeholder="请输入发票类型"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发票名称" prop="invoiceName">
              <el-input
                v-model="form.invoiceName"
                placeholder="请输入发票名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发票号码" prop="invoiceNo">
              <el-input
                v-model="form.invoiceNo"
                placeholder="请输入发票号码"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发票金额" prop="invoiceAmount">
              <el-input
                v-model="form.invoiceAmount"
                placeholder="请输入发票金额"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发生日期" prop="occurDate">
              <el-date-picker
                v-model="form.occurDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择发生日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="发票开始日期" prop="invoiceStartDate">
              <el-date-picker
                v-model="form.invoiceStartDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择发票开始日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发票结束日期" prop="invoiceEndDate">
              <el-date-picker
                v-model="form.invoiceEndDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择发票结束日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="销售方名称" prop="sellerName">
              <el-input
                v-model="form.sellerName"
                placeholder="请输入销售方名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报销状态" prop="reimburseState">
              <el-select
                v-model="form.reimburseState"
                placeholder="请选择报销状态"
                style="width: 100%"
              >
                <el-option label="未报销" value="0" />
                <el-option label="已报销" value="1" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报销ID" prop="reimburseId">
              <el-input
                v-model="form.reimburseId"
                maxlength="20"
                placeholder="请输入报销ID"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="form.remark"
                type="textarea"
                :rows="2"
                maxlength="500"
                show-word-limit
                placeholder="请输入备注"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="发票预览">
              <el-button
                type="text"
                icon="el-icon-view"
                :disabled="!form.invoiceUrl"
                @click="openPreview(form.invoiceUrl, form.invoiceName)"
                >文件预览</el-button
              >
              <img
                v-if="
                  form.invoiceUrl && getFileType(form.invoiceUrl) === 'image'
                "
                :src="thumbObjectUrl || form.invoiceUrl"
                class="invoice-thumb"
                title="点击预览"
                @click="openPreview(form.invoiceUrl, form.invoiceName)"
                style="width: 400px;height: 240px;"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
 
      <span slot="footer" class="dialog-footer">
        <el-button
          v-if="mode === 'edit' && uploadedList.length > 1"
          @click="mode = 'upload'"
          >返回列表</el-button
        >
        <el-button @click="open = false">取 消</el-button>
        <el-button
          v-if="mode === 'edit'"
          type="primary"
          :loading="saving"
          @click="submitForm"
          >保 存</el-button
        >
      </span>
    </el-dialog>
 
    <!-- 发票文件预览 -->
    <el-dialog
      title="发票文件预览"
      :visible.sync="previewOpen"
      width="1000px"
      append-to-body
      :fullscreen="isMobile"
      :destroy-on-close="true"
      @closed="handlePreviewClosed"
    >
      <div class="invoice-preview-wrap" v-loading="previewLoading">
        <attachment-preview-pane
          v-if="invoiceEmbeddedFile"
          :file="invoiceEmbeddedFile"
          style="flex: 1; min-width: 0;"
        />
      </div>
    </el-dialog>
  </div>
</template>
 
<script>
import {
  listInvoice,
  getInvoice,
  updateInvoice,
  delInvoice
} from "@/api/project/invoice";
import { getUserProfile } from "@/api/system/user";
import { getToken } from "@/utils/auth";
 
 
 
export default {
  name: "ServiceInvoice",
  data() {
    return {
      // 遮罩层
      loading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 发票列表
      invoiceList: [],
      // 弹窗
      open: false,
      // upload:上传发票;edit:识别结果确认
      mode: "upload",
      title: "",
      saving: false,
      // 当前登录用户ID,用作默认用户ID
      currentUserId: null,
      // 文件上传地址与请求头
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/project/invoice/uploadOCR",
      headers: {
        Authorization: "Bearer " + getToken()
      },
      // 上传阶段表单(用户ID取当前登录用户,不在此处编辑)
      uploadForm: {
        caseId: ""
      },
      uploadRules: {
       
      },
      // 本次上传识别出的发票(支持一次多张)
      uploadedList: [],
      // 正在上传的文件数,用于判断一批上传是否结束
      uploadingCount: 0,
      // 识别结果 / 修改表单
      form: {},
      rules: {
       
      },
      // 文件预览(AttachmentPreviewPane 所需的 file 对象)
      previewOpen: false,
      previewLoading: false,
      invoiceEmbeddedFile: null,
      // 预览用的 blob 地址,关闭时释放
      previewObjectUrl: "",
      // 编辑弹窗缩略图的 blob 地址
      thumbObjectUrl: "",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        caseId: "",
        userId: this.currentUserId,
        invoiceName: "",
        reimburseState: ""
        
      }
    };
  },
  computed: {
    // 是否手机端(弹窗全屏、操作列不固定等适配)
    isMobile() {
      return this.$store.state.app.device === "mobile";
    },
    // 上传时携带的用户ID(当前登录用户)、案例ID(后端 uploadOCR 必传)
    uploadData() {
      return {
        userId: this.currentUserId,
        caseId: this.uploadForm.caseId
      };
    }
  },
  async created() {
    await this.getCurrentUser();
    this.getList();
  },
  methods: {
    /** 查询发票列表 */
    getList() {
      this.loading = true;
      this.queryParams.userId=this.currentUserId
      listInvoice(this.queryParams)
        .then(response => {
          this.invoiceList = response.rows;
          this.total = response.total;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    /** 当前登录用户ID,单据的用户ID直接取该值 */
    async getCurrentUser() {
      try {
        const response = await getUserProfile();
        this.currentUserId = response.data ? response.data.userId : 0;
      } catch (e) {
        this.currentUserId = 0;
      }
      return this.currentUserId;
    },
    /** 案例下拉显示文本 */
    formatCase(item) {
      if (!item) {
        return "";
      }
      return [item.donorno, item.name].filter(Boolean).join(" ");
    },
 
    /** 日期统一成 yyyy-MM-dd,兼容 OCR 的“2024年01月02日”等格式 */
    normalizeDate(value) {
      if (!value) {
        return null;
      }
      const text = String(value)
        .replace(/[年月]/g, "-")
        .replace(/日/g, "")
        .replace(/\//g, "-")
        .trim();
      const match = text.match(/^(\d{4})-(\d{1,2})-(\d{1,2})/);
      if (!match) {
        return null;
      }
      return (
        match[1] +
        "-" +
        String(match[2]).padStart(2, "0") +
        "-" +
        String(match[3]).padStart(2, "0")
      );
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.caseId = "";
      this.queryParams.invoiceName = "";
      this.queryParams.reimburseState = "";
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 上传发票按钮操作 */
    async handleUpload() {
      if (!this.currentUserId) {
        await this.getCurrentUser();
      }
      this.uploadForm = {
        caseId: ""
      };
      this.uploadedList = [];
      this.uploadingCount = 0;
      this.form = {};
      this.mode = "upload";
      this.title = "上传发票";
      this.open = true;
    },
    /** 上传前校验 */
    beforeUpload(file) {
      if (!this.currentUserId) {
        this.$modal.msgWarning("未获取到当前用户ID,请重新登录后再试");
        return false;
      }
      const isAllowed = /\.(jpg|jpeg|png|gif|bmp|pdf)$/i.test(file.name);
      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isAllowed) {
        this.$modal.msgError("仅支持图片、PDF格式的发票文件");
        return false;
      }
      if (!isLt10M) {
        this.$modal.msgError("发票文件大小不能超过10MB");
        return false;
      }
      this.uploadingCount++;
      return true;
    },
    /** 上传成功:后端已 OCR 并保存,结果汇总到本次上传列表 */
    handleUploadSuccess(response) {
      this.uploadingCount = Math.max(0, this.uploadingCount - 1);
      if (!response || response.code !== 200) {
        this.$modal.msgError((response && response.msg) || "发票上传失败");
        this.afterUploadBatch();
        return;
      }
      const invoiceList = response.invoiceList || [];
      this.uploadedList = this.uploadedList.concat(invoiceList);
      this.getList();
      if (!invoiceList.length) {
        this.$modal.msgWarning("该文件未识别到发票信息,请确认文件清晰");
      } else {
        this.$modal.msgSuccess(
          "发票上传成功,识别到 " + invoiceList.length + " 张发票"
        );
      }
      this.afterUploadBatch();
    },
    /** 一批上传结束后:只识别到一张发票时直接进入信息确认 */
    afterUploadBatch() {
      if (this.uploadingCount > 0) {
        return;
      }
      if (this.uploadedList.length === 1) {
        this.openEditForm(this.uploadedList[0]);
      }
    },
    /** 上传失败 */
    handleUploadError() {
      this.uploadingCount = Math.max(0, this.uploadingCount - 1);
      this.$modal.msgError("发票上传失败,请稍后重试");
      this.afterUploadBatch();
    },
    /** 打开发票信息确认弹窗 */
    async openEditForm(record) {
      this.form = {
        id: record.id,
        caseId: record.caseId,
        userId: record.userId,
        invoiceType: record.invoiceType,
        invoiceName: record.invoiceName,
        invoiceNo: record.invoiceNo,
        invoiceUrl: record.invoiceUrl,
        invoiceAmount: record.invoiceAmount,
        occurDate: this.normalizeDate(record.occurDate),
        invoiceStartDate: this.normalizeDate(record.invoiceStartDate),
        invoiceEndDate: this.normalizeDate(record.invoiceEndDate),
        sellerName: record.sellerName,
        reimburseState: record.reimburseState || "0",
        reimburseId: record.reimburseId,
        remark: record.remark
      };
      this.mode = "edit";
      this.title = "发票信息确认";
      this.open = true;
      this.refreshThumb();
    },
    /** 缩略图同样带 token 拉取,避免直接引用鉴权地址显示不出来 */
    async refreshThumb() {
      this.revokeThumbObjectUrl();
      const url = this.form.invoiceUrl;
      if (!url || this.getFileType(url) !== "image") {
        return;
      }
      const objectUrl = await this.loadPreviewBlob(url);
      if (objectUrl && this.form.invoiceUrl === url) {
        this.thumbObjectUrl = objectUrl;
      } else if (objectUrl) {
        URL.revokeObjectURL(objectUrl);
      }
    },
    revokeThumbObjectUrl() {
      if (this.thumbObjectUrl) {
        URL.revokeObjectURL(this.thumbObjectUrl);
        this.thumbObjectUrl = "";
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      getInvoice(row.id).then(response => {
        this.openEditForm(response.data);
      });
    },
    /** 文件预览:带 token 拉取成 blob 再预览,兼容需要鉴权的 /profile 资源 */
    async openPreview(url, name) {
      if (!url) {
        this.$modal.msgWarning("该记录暂无发票文件");
        return;
      }
      const type = this.getFileType(url);
      const fileName = name || this.getFileName(url);
      this.revokePreviewObjectUrl();
      this.invoiceEmbeddedFile = null;
      this.previewLoading = true;
      this.previewOpen = true;
      const objectUrl = await this.loadPreviewBlob(url);
      this.previewLoading = false;
      if (objectUrl) {
        this.previewObjectUrl = objectUrl;
        this.invoiceEmbeddedFile = { name: fileName, url: objectUrl, type };
      } else {
        // 拉取失败时退回原始地址,交给浏览器直接加载
        this.invoiceEmbeddedFile = { name: fileName, url: url, type };
      }
    },
    /** 依次尝试原始地址、接口前缀地址,带 token 拉取成 blob */
    async loadPreviewBlob(url) {
      const headers = { Authorization: "Bearer " + getToken() };
      const candidates = this.buildPreviewCandidates(url);
      for (let i = 0; i < candidates.length; i++) {
        try {
          const response = await fetch(candidates[i], { headers });
          if (!response.ok) {
            continue;
          }
          const blob = await response.blob();
          if (blob && blob.size > 0) {
            return URL.createObjectURL(blob);
          }
        } catch (e) {
          // 跨域/网络异常,继续尝试下一个地址
        }
      }
      return "";
    },
    /** 预览地址候选:原始地址 + 走接口前缀(/dev-api、/prod-api)的地址 */
    buildPreviewCandidates(url) {
      const list = [url];
      if (/^https?:\/\//i.test(url)) {
        const base = (process.env.VUE_APP_BASE_API || "").replace(/\/$/, "");
        let path = url.replace(/^https?:\/\/[^/]+/i, "");
        if (base && (path === base || path.indexOf(base + "/") === 0)) {
          path = path.slice(base.length);
        }
        if (base) {
          list.push(base + path);
        }
      }
      return list.filter((item, index) => list.indexOf(item) === index);
    },
    /** 关闭预览时释放 blob 地址 */
    handlePreviewClosed() {
      this.revokePreviewObjectUrl();
      this.invoiceEmbeddedFile = null;
    },
    revokePreviewObjectUrl() {
      if (this.previewObjectUrl) {
        URL.revokeObjectURL(this.previewObjectUrl);
        this.previewObjectUrl = "";
      }
    },
    /** 金额显示:保留两位小数 */
    amountText(value) {
      if (value === null || value === undefined || value === "") {
        return "0.00";
      }
      const num = Number(value);
      return Number.isFinite(num) ? num.toFixed(2) : value;
    },
    /** 从地址中取文件名(无发票名称时兜底) */
    getFileName(url) {
      const path = String(url || "").split("?")[0];
      return path.substring(path.lastIndexOf("/") + 1) || "发票文件";
    },
    /** 根据文件地址判断预览类型 */
    getFileType(url) {
      const path = String(url || "")
        .split("?")[0]
        .toLowerCase();
      if (/\.(jpg|jpeg|png|gif|bmp|webp)$/.test(path)) {
        return "image";
      }
      if (/\.pdf$/.test(path)) {
        return "pdf";
      }
      return "other";
    },
    /** 保存修改 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return;
        }
        this.saving = true;
        updateInvoice(this.form)
          .then(() => {
            this.$modal.msgSuccess("保存成功");
            this.open = false;
            this.getList();
          })
          .finally(() => {
            this.saving = false;
          });
      });
    },
    /** 操作列“已报销”:把报销状态置为 1 */
    handleReimburse(row) {
      this.$modal
        .confirm('确认发票"' + (row.invoiceName || row.invoiceNo) + '"已报销?')
        .then(() => updateInvoice({ id: row.id, reimburseState: "1" }))
        .then(() => {
          this.$modal.msgSuccess("操作成功");
          this.getList();
        })
        .catch(() => {});
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal
        .confirm('是否确认删除发票"' + (row.invoiceNo || row.id) + '"?')
        .then(() => delInvoice(row.id))
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    }
  }
};
</script>
 
<style scoped lang="scss">
.invoice-upload {
  width: 100%;
 
  ::v-deep .el-upload {
    width: 100%;
  }
 
  ::v-deep .el-upload-dragger {
    width: 100%;
  }
}
 
.invoice-thumb {
  width: 100px;
  height: 70px;
  margin-left: 12px;
  border: 1px solid #ebeef5;
  vertical-align: middle;
  object-fit: contain;
  background: #f5f7fa;
  cursor: pointer;
}
 
.invoice-preview-wrap {
  display: flex;
  width: 100%;
  height: 70vh;
}
 
/* 手机端卡片列表 */
.invoice-cards {
  min-height: 60px;
}
 
.invoice-card {
  padding: 12px;
  margin-bottom: 10px;
  background: #fff;
  border: 1px solid #ebeef5;
  border-radius: 6px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04);
 
  &__head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 10px;
  }
 
  &__title {
    flex: 1;
    min-width: 0;
    margin-right: 8px;
    font-size: 15px;
    font-weight: 600;
    color: #303133;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
 
  &__row {
    display: flex;
    align-items: center;
    margin-bottom: 6px;
    font-size: 13px;
    color: #606266;
 
    .label {
      flex: 0 0 40px;
      color: #909399;
    }
 
    .value {
      flex: 1;
      min-width: 0;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
 
  &__actions {
    display: flex;
    justify-content: flex-end;
    margin-top: 8px;
    padding-top: 6px;
    border-top: 1px dashed #ebeef5;
 
    ::v-deep .el-button + .el-button {
      margin-left: 16px;
    }
  }
}
 
.invoice-empty {
  padding: 40px 0;
  text-align: center;
  font-size: 14px;
  color: #909399;
}
 
/* 手机端适配 */
@media (max-width: 992px) {
  .app-container {
    padding: 8px;
  }
 
  .opo-query-form {
    ::v-deep .el-form-item {
      display: flex;
      width: 100%;
      margin-right: 0;
      margin-bottom: 10px;
    }
 
    ::v-deep .el-form-item__content {
      flex: 1;
      min-width: 0;
    }
 
    ::v-deep .el-select,
    ::v-deep .el-input,
    ::v-deep .el-date-editor {
      width: 100% !important;
    }
  }
 
  /* 弹窗内两列表单在手机端变单列 */
  .el-col-12 {
    width: 100%;
  }
 
  /* 全屏弹窗里的预览区占满剩余高度 */
  .invoice-preview-wrap {
    height: calc(100vh - 120px);
  }
 
  .invoice-thumb {
    display: block;
    margin: 8px 0 0;
  }
}
</style>