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
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
<template>
  <div class="app-container">
    <div class="search_form">
      <div>
        <el-form :model="searchForm"
                 :inline="true">
          <el-form-item label="申请单号:">
            <el-input v-model="searchForm.applicationNo"
                      placeholder="请输入"
                      clearable
                      :prefix-icon="Search"
                      @change="handleQuery" />
          </el-form-item>
          <el-form-item label="项目名称:">
            <el-input v-model="searchForm.projectName"
                      placeholder="请输入"
                      clearable
                      :prefix-icon="Search"
                      @change="handleQuery" />
          </el-form-item>
          <el-form-item label="供应商:">
            <el-select v-model="searchForm.supplierId"
                       placeholder="请选择"
                       filterable
                       clearable
                       style="width: 240px"
                       @change="handleQuery">
              <el-option v-for="item in supplierOptions"
                         :key="item.id"
                         :label="item.supplierName"
                         :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态:">
            <el-select v-model="searchForm.status"
                       placeholder="请选择"
                       clearable
                       style="width: 160px"
                       @change="handleQuery">
              <el-option label="草稿"
                         :value="0" />
              <el-option label="已生成订单"
                         :value="1" />
            </el-select>
          </el-form-item>
          <el-form-item label="申请日期:">
            <el-date-picker v-model="searchForm.applyDate"
                            value-format="YYYY-MM-DD"
                            format="YYYY-MM-DD"
                            type="daterange"
                            placeholder="请选择"
                            clearable
                            @change="changeDaterange" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary"
                       @click="handleQuery"> 搜索 </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="table_list">
      <div style="display: flex;justify-content: flex-end;margin-bottom: 20px;">
        <el-button type="primary"
                   @click="openForm('add')">新增申请单</el-button>
        <el-button type="danger"
                   plain
                   @click="handleDelete()">删除</el-button>
      </div>
      <el-table :data="tableData"
                border
                v-loading="tableLoading"
                @selection-change="handleSelectionChange"
                :row-key="(row) => row.id"
                show-summary
                :summary-method="summarizeMainTable"
                height="calc(100vh - 21.5em)">
        <el-table-column align="center"
                         type="selection"
                         width="55"
                         :selectable="row => row.status === 0" />
        <el-table-column align="center"
                         label="序号"
                         type="index"
                         width="60" />
        <el-table-column label="申请单号"
                         prop="applicationNo"
                         width="170"
                         show-overflow-tooltip />
        <el-table-column label="供应商名称"
                         prop="supplierName"
                         width="200"
                         show-overflow-tooltip />
        <el-table-column label="项目名称"
                         prop="projectName"
                         width="280"
                         show-overflow-tooltip />
        <el-table-column label="申请人"
                         prop="applicantName"
                         width="100"
                         show-overflow-tooltip />
        <el-table-column label="申请日期"
                         prop="applyDate"
                         width="110"
                         show-overflow-tooltip />
        <el-table-column label="期望到货日期"
                         prop="expectedArrivalDate"
                         width="130"
                         show-overflow-tooltip />
        <el-table-column label="合同金额(元)"
                         prop="contractAmount"
                         width="140"
                         show-overflow-tooltip
                         :formatter="formattedNumber" />
        <el-table-column label="付款方式"
                         prop="paymentMethod"
                         width="100"
                         show-overflow-tooltip />
        <el-table-column label="状态"
                         prop="status"
                         width="110"
                         align="center">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'info'"
                    size="small">
              {{ statusText[scope.row.status] || '--' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="备注"
                         prop="remarks"
                         width="200"
                         show-overflow-tooltip />
        <el-table-column fixed="right"
                         label="操作"
                         width="200"
                         align="center">
          <template #default="scope">
            <template v-if="scope.row.status === 0">
              <el-button link
                         type="primary"
                         @click="openForm('edit', scope.row)">编辑</el-button>
              <el-button link
                         type="primary"
                         @click="handleConvert(scope.row)">转订单</el-button>
              <el-button link
                         type="danger"
                         @click="handleDelete(scope.row)">删除</el-button>
            </template>
            <el-button v-else
                       link
                       type="primary"
                       @click="openForm('detail', scope.row)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0"
                  :total="total"
                  layout="total, sizes, prev, pager, next, jumper"
                  :page="page.current"
                  :limit="page.size"
                  @pagination="paginationChange" />
    </div>
    <FormDialog v-model="dialogFormVisible"
                :title="dialogTitle"
                :width="'70%'"
                :operation-type="operationType"
                @close="closeDia"
                @confirm="submitForm"
                @cancel="closeDia">
      <el-form :model="form"
               :disabled="isDetail"
               label-width="140px"
               label-position="top"
               :rules="rules"
               ref="formRef">
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="申请单号:"
                          prop="applicationNo">
              <el-input v-model="form.applicationNo"
                        placeholder="保存后自动生成"
                        disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="申请日期:"
                          prop="applyDate">
              <el-date-picker style="width: 100%"
                              v-model="form.applyDate"
                              value-format="YYYY-MM-DD"
                              format="YYYY-MM-DD"
                              type="date"
                              placeholder="请选择"
                              clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="采购合同号:"
                          prop="purchaseContractNumber">
              <el-input v-model="form.purchaseContractNumber"
                        placeholder="请输入"
                        clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="供应商名称:"
                          prop="supplierId">
              <el-select v-model="form.supplierId"
                         placeholder="请选择"
                         filterable
                         clearable
                         style="width: 100%">
                <el-option v-for="item in supplierList"
                           :key="item.id"
                           :label="item.supplierName"
                           :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目名称"
                          prop="projectName">
              <el-input v-model="form.projectName"
                        placeholder="请输入"
                        clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="申请人:"
                          prop="applicantId">
              <el-select v-model="form.applicantId"
                         placeholder="不选则默认为当前登录用户"
                         filterable
                         clearable
                         style="width: 100%">
                <el-option v-for="item in userList"
                           :key="item.userId"
                           :label="item.nickName"
                           :value="item.userId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="期望到货日期:"
                          prop="expectedArrivalDate">
              <el-date-picker style="width: 100%"
                              v-model="form.expectedArrivalDate"
                              value-format="YYYY-MM-DD"
                              format="YYYY-MM-DD"
                              type="date"
                              placeholder="请选择"
                              clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="最佳到站日期:"
                          prop="bestArrivalDate">
              <el-date-picker style="width: 100%"
                              v-model="form.bestArrivalDate"
                              value-format="YYYY-MM-DD"
                              format="YYYY-MM-DD"
                              type="date"
                              placeholder="请选择"
                              clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="付款方式:"
                          prop="paymentMethod">
              <el-input v-model="form.paymentMethod"
                        placeholder="请输入"
                        clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="8">
            <el-form-item label="录入人:"
                          prop="recorderId">
              <el-select v-model="form.recorderId"
                         placeholder="请选择"
                         filterable
                         clearable
                         style="width: 100%">
                <el-option v-for="item in userList"
                           :key="item.userId"
                           :label="item.nickName"
                           :value="item.userId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="签订日期:"
                          prop="executionDate">
              <el-date-picker style="width: 100%"
                              v-model="form.executionDate"
                              value-format="YYYY-MM-DD"
                              format="YYYY-MM-DD"
                              type="date"
                              placeholder="请选择"
                              clearable />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="录入日期:"
                          prop="entryDate">
              <el-date-picker style="width: 100%"
                              v-model="form.entryDate"
                              value-format="YYYY-MM-DD"
                              format="YYYY-MM-DD"
                              type="date"
                              placeholder="请选择"
                              clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <div class="form-section-title">采购入库提交</div>
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="申请提交时间:"
                          prop="applicationSubmitTime">
              <el-date-picker style="width: 100%"
                              v-model="form.applicationSubmitTime"
                              value-format="YYYY-MM-DD HH:mm:ss"
                              format="YYYY-MM-DD HH:mm:ss"
                              type="datetime"
                              placeholder="请选择"
                              clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="采购类别:"
                          prop="purchaseCategory">
              <el-radio-group v-model="form.purchaseCategory"
                              @change="purchaseCategoryChange">
                <el-radio value="客存">客存</el-radio>
                <el-radio value="代储">代储</el-radio>
                <el-radio value="采购入库">采购入库</el-radio>
                <el-radio value="采购直销">采购直销</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="物流方式:"
                          prop="logisticsMethod">
              <el-select v-model="form.logisticsMethod"
                         placeholder="请选择"
                         clearable
                         style="width: 100%">
                <el-option label="厂家配送"
                           value="厂家配送" />
                <el-option label="委外物流"
                           value="委外物流" />
                <el-option label="客户自提"
                           value="客户自提" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="提货方式:"
                          prop="pickupMethod">
              <el-radio-group v-model="form.pickupMethod">
                <el-radio value="暂不提货">暂不提货</el-radio>
                <el-radio value="提货">提货</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="采购油库:"
                          prop="oilDepotId">
              <el-select v-model="form.oilDepotId"
                         placeholder="请选择"
                         clearable
                         popper-class="oil-depot-select-popper"
                         style="width: 100%">
                <el-option v-for="item in oilDepotList"
                           :key="item.id"
                           :label="item.depotName"
                           :value="item.id">
                  <div class="oil-depot-option">
                    <div class="oil-depot-option-title">{{ item.depotName }}</div>
                    <div class="oil-depot-option-line">负责人:{{ item.chargePerson }}</div>
                    <div class="oil-depot-option-line">联系电话:{{ item.phone }}</div>
                    <div class="oil-depot-option-line">所属公司:{{ item.company }}</div>
                    <div class="oil-depot-option-line">启用日期:{{ item.enableDate }}</div>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户名称:"
                          prop="customerName">
              <el-input v-model="form.customerName"
                        placeholder="仅采购类别为代储/采购直销时可填写"
                        clearable
                        :disabled="!['代储', '采购直销'].includes(form.purchaseCategory)" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="合同金额(元):"
                          prop="contractAmount">
              <el-input-number v-model="form.contractAmount"
                               :precision="2"
                               :step="0.1"
                               :min="0"
                               placeholder="请输入"
                               style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="采购数量(吨):"
                          prop="purchaseQuantity">
              <el-input-number v-model="form.purchaseQuantity"
                               :precision="0"
                               :step="1"
                               :min="0"
                               placeholder="请输入"
                               style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <div class="form-section-title">系统信息</div>
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="采购申请订单状态:"
                          prop="purchaseOrderStatus">
              <el-select v-model="form.purchaseOrderStatus"
                         placeholder="请选择"
                         clearable
                         style="width: 100%">
                <el-option label="已申请,未装车"
                           value="已申请,未装车" />
                <el-option label="以出厂,未入库"
                           value="以出厂,未入库" />
                <el-option label="已入库"
                           value="已入库" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item label="产品信息:">
            <el-button v-if="!isDetail"
                       type="primary"
                       @click="openProductForm('add')">添加</el-button>
            <el-button v-if="!isDetail"
                       plain
                       type="danger"
                       @click="deleteProduct">删除</el-button>
          </el-form-item>
        </el-row>
        <el-table :data="productData"
                  border
                  @selection-change="productSelected"
                  show-summary
                  :summary-method="summarizeProTable">
          <el-table-column align="center"
                           type="selection"
                           width="55"
                           :selectable="() => !isDetail" />
          <el-table-column align="center"
                           label="序号"
                           type="index"
                           width="60" />
          <el-table-column label="产品大类"
                           prop="productCategory"
                           show-overflow-tooltip />
          <el-table-column label="规格型号"
                           prop="specificationModel"
                           show-overflow-tooltip />
          <el-table-column label="单位"
                           prop="unit"
                           width="70" />
          <el-table-column label="数量"
                           prop="quantity"
                           width="80" />
          <el-table-column label="库存预警数量"
                           prop="warnNum"
                           width="120"
                           show-overflow-tooltip />
          <el-table-column label="税率(%)"
                           prop="taxRate"
                           width="80" />
          <el-table-column label="含税单价(元)"
                           prop="taxInclusiveUnitPrice"
                           width="120"
                           :formatter="formattedNumber" />
          <el-table-column label="含税总价(元)"
                           prop="taxInclusiveTotalPrice"
                           width="120"
                           :formatter="formattedNumber" />
          <el-table-column label="不含税总价(元)"
                           prop="taxExclusiveTotalPrice"
                           width="130"
                           :formatter="formattedNumber" />
          <el-table-column label="发票类型"
                           prop="invoiceType"
                           width="110"
                           show-overflow-tooltip />
          <el-table-column label="是否质检"
                           prop="isChecked"
                           width="90">
            <template #default="scope">
              <el-tag :type="scope.row.isChecked ? 'success' : 'info'"
                      size="small">
                {{ scope.row.isChecked ? '是' : '否' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="备注"
                           prop="remark"
                           show-overflow-tooltip />
          <el-table-column v-if="!isDetail"
                           fixed="right"
                           label="操作"
                           width="80"
                           align="center">
            <template #default="scope">
              <el-button link
                         type="primary"
                         @click="openProductForm('edit', scope.row, scope.$index)">编辑
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-row :gutter="30">
          <el-col :span="24">
            <el-form-item label="备注:"
                          prop="remarks">
              <el-input v-model="form.remarks"
                        placeholder="请输入"
                        clearable
                        type="textarea"
                        :rows="2" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="24">
            <el-form-item label="附件材料:"
                          prop="storageBlobDTOS">
              <FileUpload v-model:file-list="fileList" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </FormDialog>
    <FormDialog v-model="productFormVisible"
                :title="productOperationType === 'add' ? '新增产品' : '编辑产品'"
                :width="'40%'"
                :operation-type="productOperationType"
                @close="closeProductDia"
                @confirm="submitProduct"
                @cancel="closeProductDia">
      <el-form :model="productForm"
               label-width="140px"
               label-position="top"
               :rules="productRules"
               ref="productFormRef">
        <el-row :gutter="30">
          <el-col :span="24">
            <el-form-item label="产品大类:"
                          prop="productId">
              <el-tree-select v-model="productForm.productId"
                              placeholder="请选择"
                              clearable
                              filterable
                              check-strictly
                              @change="getModels"
                              :data="productOptions"
                              :render-after-expand="false"
                              style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="24">
            <el-form-item label="规格型号:"
                          prop="productModelId">
              <el-select v-model="productForm.productModelId"
                         placeholder="请选择"
                         filterable
                         clearable
                         style="width: 100%"
                         @change="getProductModel">
                <el-option v-for="item in modelOptions"
                           :key="item.id"
                           :label="item.model"
                           :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="单位:"
                          prop="unit">
              <el-input v-model="productForm.unit"
                        placeholder="请输入"
                        clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="税率(%):"
                          prop="taxRate">
              <el-select v-model="productForm.taxRate"
                         placeholder="请选择"
                         clearable
                         style="width: 100%"
                         @change="calcTotals">
                <el-option v-for="dict in tax_rate"
                           :key="dict.value"
                           :label="dict.label"
                           :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="含税单价(元):"
                          prop="taxInclusiveUnitPrice">
              <el-input-number v-model="productForm.taxInclusiveUnitPrice"
                               :precision="2"
                               :step="0.1"
                               :min="0"
                               style="width: 100%"
                               @change="calcTotals" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数量:"
                          prop="quantity">
              <el-input-number v-model="productForm.quantity"
                               :precision="2"
                               :step="0.1"
                               :min="0"
                               placeholder="请输入"
                               style="width: 100%"
                               @change="calcTotals" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="含税总价(元):"
                          prop="taxInclusiveTotalPrice">
              <el-input-number v-model="productForm.taxInclusiveTotalPrice"
                               :precision="2"
                               disabled
                               style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="不含税总价(元):"
                          prop="taxExclusiveTotalPrice">
              <el-input-number v-model="productForm.taxExclusiveTotalPrice"
                               :precision="2"
                               disabled
                               style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="发票类型:"
                          prop="invoiceType">
              <el-select v-model="productForm.invoiceType"
                         placeholder="请选择"
                         clearable
                         style="width: 100%">
                <el-option label="增普票"
                           value="增普票" />
                <el-option label="增专票"
                           value="增专票" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库存预警数量:"
                          prop="warnNum">
              <el-input-number v-model="productForm.warnNum"
                               :precision="2"
                               :step="0.1"
                               :min="0"
                               clearable
                               style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="是否质检:"
                          prop="isChecked">
              <el-radio-group v-model="productForm.isChecked">
                <el-radio label="是"
                          :value="true" />
                <el-radio label="否"
                          :value="false" />
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="24">
            <el-form-item label="备注:"
                          prop="remark">
              <el-input v-model="productForm.remark"
                        placeholder="请输入"
                        clearable />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </FormDialog>
  </div>
</template>
 
<script setup>
  import FormDialog from "@/components/Dialog/FormDialog.vue";
  import pagination from "@/components/PIMTable/Pagination.vue";
  import {
    ref,
    reactive,
    toRefs,
    computed,
    getCurrentInstance,
    nextTick,
    onMounted,
  } from "vue";
  import { ElMessage, ElMessageBox } from "element-plus";
  import { Search } from "@element-plus/icons-vue";
  import dayjs from "dayjs";
  import router from "@/router";
  import usePermissionStore from "@/store/modules/permission";
  import {
    applicationList,
    getApplicationById,
    addApplication,
    editApplication,
    delApplication,
    convertToOrder,
  } from "@/api/procurementManagement/purchaseApplication.js";
  import { getOptions } from "@/api/procurementManagement/procurementLedger.js";
  import { modelList, productTreeList } from "@/api/basicData/product.js";
  import { allOilDepot } from "@/api/basicData/oilDepot.js";
  import { userListNoPage } from "@/api/system/user.js";
  import FileUpload from "@/components/AttachmentUpload/file/index.vue";
 
  const { proxy } = getCurrentInstance();
  const { tax_rate } = proxy.useDict("tax_rate");
  const permissionStore = usePermissionStore();
 
  const statusText = {
    0: "草稿",
    1: "已生成订单",
  };
 
  const tableData = ref([]);
  const productData = ref([]);
  const selectedRows = ref([]);
  const productSelectedRows = ref([]);
  const supplierOptions = ref([]);
  const supplierList = ref([]);
  const userList = ref([]);
  const oilDepotList = ref([]);
  const fileList = ref([]);
  const productOptions = ref([]);
  const modelOptions = ref([]);
  const tableLoading = ref(false);
  const dialogFormVisible = ref(false);
  const productFormVisible = ref(false);
  const operationType = ref("");
  const productOperationType = ref("");
  const productOperationIndex = ref("");
  const currentId = ref("");
  const total = ref(0);
  const page = reactive({ current: 1, size: 10 });
 
  const isDetail = computed(() => operationType.value === "detail");
  const dialogTitle = computed(() => {
    if (operationType.value === "add") return "新增采购申请";
    if (operationType.value === "edit") return "编辑采购申请";
    return "采购申请详情";
  });
 
  const searchForm = reactive({
    applicationNo: "",
    projectName: "",
    supplierId: "",
    status: "",
    applyDate: null,
    startDate: undefined,
    endDate: undefined,
  });
 
  const data = reactive({
    form: {
      id: "",
      applicationNo: "",
      // 以下字段与「新增采购台账」保持一致
      purchaseContractNumber: "",
      supplierId: "",
      projectName: "",
      applicantId: "",
      applyDate: "",
      expectedArrivalDate: "",
      bestArrivalDate: "",
      paymentMethod: "",
      recorderId: "",
      executionDate: "",
      entryDate: "",
      applicationSubmitTime: "",
      purchaseCategory: "",
      logisticsMethod: "",
      pickupMethod: "",
      oilDepotId: "",
      customerName: "",
      purchaseQuantity: "",
      purchaseOrderStatus: "",
      contractAmount: "",
      remarks: "",
    },
    rules: {
      applyDate: [{ required: true, message: "请选择", trigger: "change" }],
      projectName: [
        { required: true, message: "请输入项目名称", trigger: "blur" },
      ],
      supplierId: [{ required: true, message: "请输入", trigger: "blur" }],
      entryDate: [{ required: true, message: "请选择", trigger: "change" }],
      executionDate: [{ required: true, message: "请选择", trigger: "change" }],
      purchaseCategory: [
        { required: true, message: "请选择采购类别", trigger: "change" },
      ],
      oilDepotId: [
        { required: true, message: "请选择采购油库", trigger: "change" },
      ],
      purchaseQuantity: [
        { required: true, message: "请输入采购数量", trigger: "change" },
      ],
    },
  });
  const { form, rules } = toRefs(data);
 
  const productFormData = reactive({
    productForm: {
      productId: "",
      productCategory: "",
      productModelId: "",
      specificationModel: "",
      unit: "",
      quantity: "",
      taxRate: "",
      taxInclusiveUnitPrice: "",
      taxInclusiveTotalPrice: "",
      taxExclusiveTotalPrice: "",
      invoiceType: "",
      warnNum: "",
      isChecked: false,
      remark: "",
    },
    productRules: {
      productId: [{ required: true, message: "请选择", trigger: "change" }],
      productModelId: [{ required: true, message: "请选择", trigger: "change" }],
      unit: [{ required: true, message: "请输入", trigger: "blur" }],
      quantity: [{ required: true, message: "请输入", trigger: "blur" }],
      taxRate: [{ required: true, message: "请选择", trigger: "change" }],
      taxInclusiveUnitPrice: [
        { required: true, message: "请输入", trigger: "blur" },
      ],
      warnNum: [{ required: true, message: "请选择", trigger: "change" }],
    },
  });
  const { productForm, productRules } = toRefs(productFormData);
 
  const formattedNumber = (row, column, cellValue) => {
    if (cellValue === null || cellValue === undefined || cellValue === "") {
      return "--";
    }
    return Number(cellValue).toFixed(2);
  };
 
  const changeDaterange = value => {
    if (value) {
      searchForm.startDate = dayjs(value[0]).format("YYYY-MM-DD");
      searchForm.endDate = dayjs(value[1]).format("YYYY-MM-DD");
    } else {
      searchForm.startDate = undefined;
      searchForm.endDate = undefined;
    }
    handleQuery();
  };
 
  const handleQuery = () => {
    page.current = 1;
    getList();
  };
 
  const paginationChange = obj => {
    page.current = obj.page;
    page.size = obj.limit;
    getList();
  };
 
  const getList = () => {
    tableLoading.value = true;
    const { applyDate, ...rest } = searchForm;
    applicationList({ ...rest, pageNum: page.current, pageSize: page.size })
      .then(res => {
        const rows = res.rows || res.data?.rows || res.data?.records || [];
        tableData.value = rows;
        total.value = res.total ?? res.data?.total ?? 0;
      })
      .catch(() => {
        tableData.value = [];
        total.value = 0;
      })
      .finally(() => {
        tableLoading.value = false;
      });
  };
 
  const handleSelectionChange = selection => {
    selectedRows.value = selection;
  };
 
  const productSelected = selection => {
    productSelectedRows.value = selection;
  };
 
  const summarizeMainTable = param => {
    return proxy.summarizeTable(param, ["contractAmount"]);
  };
 
  const summarizeProTable = param => {
    return proxy.summarizeTable(param, [
      "taxInclusiveUnitPrice",
      "taxInclusiveTotalPrice",
      "taxExclusiveTotalPrice",
    ]);
  };
 
  // 供应商下拉:筛选用全量,表单仅可选白名单供应商(与采购台账一致)
  const getSupplierOptions = async () => {
    const res = await getOptions();
    const list = res.data || [];
    supplierOptions.value = list;
    supplierList.value = list.filter(item => item.isWhite === 0);
  };
 
  const getUserList = async () => {
    const res = await userListNoPage();
    userList.value = res.data || [];
  };
 
  const getOilDepotList = async () => {
    const res = await allOilDepot();
    oilDepotList.value = res?.data || [];
  };
 
  const getProductOptions = async () => {
    const res = await productTreeList();
    productOptions.value = convertIdToValue(res || []);
  };
 
  function convertIdToValue(list) {
    return list.map(item => {
      const { id, children, ...rest } = item;
      const newItem = { ...rest, value: id };
      if (children && children.length > 0) {
        newItem.children = convertIdToValue(children);
      }
      return newItem;
    });
  }
 
  const findNodeLabelById = (nodes, value) => {
    for (const node of nodes) {
      if (node.value === value) {
        return node.label;
      }
      if (node.children && node.children.length > 0) {
        const found = findNodeLabelById(node.children, value);
        if (found) return found;
      }
    }
    return "";
  };
 
  const findNodeValueByLabel = (nodes, label) => {
    for (const node of nodes) {
      if (node.label === label) {
        return node.value;
      }
      if (node.children && node.children.length > 0) {
        const found = findNodeValueByLabel(node.children, label);
        if (found) return found;
      }
    }
    return "";
  };
 
  const getModels = value => {
    if (!value) {
      productForm.value.productCategory = "";
      modelOptions.value = [];
      return Promise.resolve([]);
    }
    productForm.value.productCategory = findNodeLabelById(
      productOptions.value,
      value
    );
    return modelList({ id: value }).then(res => {
      modelOptions.value = res || [];
      return res;
    });
  };
 
  const getProductModel = value => {
    const matched = modelOptions.value.find(item => item.id === value);
    if (matched) {
      productForm.value.specificationModel = matched.model;
      productForm.value.unit = matched.unit;
    } else {
      productForm.value.specificationModel = "";
      productForm.value.unit = "";
    }
  };
 
  // 含税总价 = 含税单价 × 数量;不含税总价由含税总价与税率反算
  const calcTotals = () => {
    const { taxInclusiveUnitPrice, quantity, taxRate } = productForm.value;
    if (!taxInclusiveUnitPrice && taxInclusiveUnitPrice !== 0) return;
    if (!quantity && quantity !== 0) return;
    productForm.value.taxInclusiveTotalPrice =
      proxy.calculateTaxIncludeTotalPrice(taxInclusiveUnitPrice, quantity);
    if (taxRate) {
      productForm.value.taxExclusiveTotalPrice =
        proxy.calculateTaxExclusiveTotalPrice(
          productForm.value.taxInclusiveTotalPrice,
          taxRate
        );
    }
  };
 
  const openProductForm = async (type, row, index) => {
    productOperationType.value = type;
    productOperationIndex.value = index;
    productForm.value = {};
    proxy.resetForm("productFormRef");
    productFormVisible.value = true;
 
    if (productOptions.value.length === 0) {
      await getProductOptions();
    }
    await nextTick();
 
    if (type === "add") {
      productForm.value.isChecked = false;
      return;
    }
 
    productForm.value = { ...row };
    if (!productForm.value.productId && productForm.value.productCategory) {
      productForm.value.productId = findNodeValueByLabel(
        productOptions.value,
        productForm.value.productCategory
      );
    }
    if (productForm.value.productId) {
      await getModels(productForm.value.productId);
      await nextTick();
      if (productForm.value.productModelId) {
        getProductModel(productForm.value.productModelId);
      }
    }
  };
 
  const submitProduct = () => {
    proxy.$refs["productFormRef"].validate(valid => {
      if (!valid) return;
      if (productOperationType.value === "add") {
        productData.value.push({ ...productForm.value });
      } else {
        productData.value[productOperationIndex.value] = {
          ...productForm.value,
        };
      }
      closeProductDia();
    });
  };
 
  const deleteProduct = () => {
    if (productSelectedRows.value.length === 0) {
      proxy.$modal.msgWarning("请选择数据");
      return;
    }
    productData.value = productData.value.filter(
      item => !productSelectedRows.value.includes(item)
    );
    productSelectedRows.value = [];
  };
 
  const closeProductDia = () => {
    proxy.resetForm("productFormRef");
    productFormVisible.value = false;
  };
 
  // 采购类别改变:仅代储/采购直销时客户名称可用,切换后清空
  const purchaseCategoryChange = val => {
    if (!["代储", "采购直销"].includes(val)) {
      form.value.customerName = "";
    }
  };
 
  const openForm = async (type, row) => {
    operationType.value = type;
    currentId.value = row?.id || "";
    proxy.resetForm("formRef");
    form.value = {
      id: "",
      applicationNo: "",
      purchaseContractNumber: "",
      supplierId: "",
      projectName: "",
      applicantId: "",
      applyDate: dayjs().format("YYYY-MM-DD"),
      expectedArrivalDate: "",
      bestArrivalDate: "",
      paymentMethod: "",
      recorderId: "",
      executionDate: "",
      entryDate: dayjs().format("YYYY-MM-DD"),
      applicationSubmitTime: "",
      purchaseCategory: "",
      logisticsMethod: "",
      pickupMethod: "",
      oilDepotId: "",
      customerName: "",
      purchaseQuantity: "",
      purchaseOrderStatus: "",
      contractAmount: "",
      remarks: "",
    };
    productData.value = [];
    productSelectedRows.value = [];
    fileList.value = [];
 
    try {
      await Promise.all([
        getSupplierOptions(),
        getUserList(),
        getProductOptions(),
        getOilDepotList(),
      ]);
    } catch (error) {
      proxy.$modal.msgError("加载基础数据失败");
      return;
    }
 
    if (type === "add") {
      dialogFormVisible.value = true;
      return;
    }
 
    try {
      const res = await getApplicationById({ id: row.id });
      form.value = { ...(res.data || {}), id: row.id };
      productData.value = res.data?.productData || [];
      fileList.value = res.data?.storageBlobVOS || [];
    } catch (error) {
      proxy.$modal.msgError("加载采购申请详情失败");
      return;
    }
    dialogFormVisible.value = true;
  };
 
  const closeDia = () => {
    proxy.resetForm("formRef");
    dialogFormVisible.value = false;
  };
 
  // 只提交后端允许的字段,自动字段(单号、状态、租户等)一律不传
  const buildPayload = () => {
    const payload = {
      supplierId: form.value.supplierId || null,
      projectName: form.value.projectName,
      applyDate: form.value.applyDate,
      expectedArrivalDate: form.value.expectedArrivalDate || null,
      contractAmount:
        form.value.contractAmount === "" ? null : form.value.contractAmount,
      paymentMethod: form.value.paymentMethod,
      remarks: form.value.remarks,
      // 与「新增采购台账」对齐的字段
      purchaseContractNumber: form.value.purchaseContractNumber,
      bestArrivalDate: form.value.bestArrivalDate || null,
      recorderId: form.value.recorderId || null,
      executionDate: form.value.executionDate || null,
      entryDate: form.value.entryDate || null,
      applicationSubmitTime: form.value.applicationSubmitTime || null,
      purchaseCategory: form.value.purchaseCategory,
      logisticsMethod: form.value.logisticsMethod,
      pickupMethod: form.value.pickupMethod,
      oilDepotId: form.value.oilDepotId || null,
      customerName: form.value.customerName,
      purchaseQuantity:
        form.value.purchaseQuantity === "" ? null : form.value.purchaseQuantity,
      purchaseOrderStatus: form.value.purchaseOrderStatus,
      storageBlobDTOS: fileList.value,
      productData: productData.value.map(
        ({ id, purchaseApplicationId, ...rest }) => rest
      ),
    };
    // 申请人留空表示由后端取当前登录用户
    if (form.value.applicantId) {
      payload.applicantId = form.value.applicantId;
    }
    return payload;
  };
 
  const submitForm = () => {
    proxy.$refs["formRef"].validate(async valid => {
      if (!valid) return;
      const payload = buildPayload();
      try {
        if (operationType.value === "add") {
          await addApplication(payload);
        } else {
          await editApplication({ id: currentId.value, ...payload });
        }
        proxy.$modal.msgSuccess("保存成功");
        closeDia();
        getList();
      } catch (error) {
        // 错误信息由 request 拦截器统一提示
      }
    });
  };
 
  const handleDelete = row => {
    let ids = [];
    if (row) {
      ids = [row.id];
    } else if (selectedRows.value.length > 0) {
      ids = selectedRows.value.map(item => item.id);
    } else {
      proxy.$modal.msgWarning("请选择数据");
      return;
    }
    ElMessageBox.confirm("选中的内容将被删除,是否确认删除?", "删除", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(async () => {
        await delApplication(ids);
        proxy.$modal.msgSuccess("删除成功");
        getList();
      })
      .catch(() => {});
  };
 
  const handleConvert = async row => {
    try {
      await ElMessageBox.confirm(
        `确认将申请单「${row.applicationNo}」转为采购订单吗?转订单后将自动提交采购审批。`,
        "转订单",
        {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning",
        }
      );
    } catch {
      return;
    }
 
    try {
      const res = await convertToOrder(row.id);
      getList();
      await ElMessageBox.confirm(
        `转订单成功,已生成采购台账(id:${res?.data})。是否前往采购台账查看?`,
        "提示",
        {
          confirmButtonText: "前往查看",
          cancelButtonText: "留在本页",
          type: "success",
        }
      );
      await gotoLedger();
    } catch {
      // 转订单失败由请求拦截器提示;点「留在本页」也走这里,不额外处理
    }
  };
 
  // 跳转采购台账。路由匹配不上或 push 被拦截都给出可见提示,不静默
  const gotoLedger = async () => {
    const path = resolveLedgerPath();
    try {
      await router.push(path);
    } catch {
      ElMessage.warning(`跳转采购台账失败(${path}),请从侧边栏进入查看`);
    }
  };
 
  // 菜单标题可能与页面标题有空格差异,归一化后再比
  const normalizeMenuTitle = title => String(title ?? "").replace(/\s+/g, "").trim();
 
  const resolveLedgerPath = () => {
    const path =
      findLedgerPath(permissionStore.defaultRoutes) ||
      findLedgerPath(permissionStore.sidebarRouters);
    // 找不到菜单时兜底到仓库里多处使用的固定地址(采购管理首页卡片、首页快捷入口)
    return path || "/procurementManagement/procurementLedger";
  };
 
  // 从侧边栏菜单中定位采购台账路由
  const findLedgerPath = (routes, prefix = "") => {
    for (const route of routes || []) {
      if (!route) continue;
      const fullPath = String(route.path || "").startsWith("/")
        ? route.path
        : `${prefix}/${route.path || ""}`;
      if (normalizeMenuTitle(route.meta?.title ?? route.title) === "采购台账") {
        return fullPath.replace(/\/{2,}/g, "/").replace(/\/$/, "");
      }
      const found = findLedgerPath(route.children, fullPath);
      if (found) return found;
    }
    return "";
  };
 
  onMounted(() => {
    getList();
    getSupplierOptions();
  });
</script>
 
<style scoped lang="scss">
  // 表单分栏标题:蓝色竖条 + 浅蓝底色,突出分区
  .form-section-title {
    margin: 18px 0 14px;
    padding: 8px 14px;
    font-size: 15px;
    font-weight: 600;
    color: #1d6fd8;
    background: linear-gradient(90deg, rgba(64, 158, 255, 0.14), rgba(64, 158, 255, 0.02));
    border-left: 4px solid #409eff;
    border-radius: 3px;
  }
 
  // 采购油库下拉选项:小卡片样式
  .oil-depot-option {
    padding: 8px 10px;
 
    .oil-depot-option-title {
      font-size: 14px;
      font-weight: 600;
      color: #303133;
      margin-bottom: 4px;
    }
 
    .oil-depot-option-line {
      font-size: 12px;
      color: #909399;
      line-height: 1.8;
    }
  }
</style>
 
<style lang="scss">
  // 下拉面板渲染在 body 下,需全局样式
  .oil-depot-select-popper {
    .el-select-dropdown__item {
      height: auto;
      line-height: normal;
      padding: 4px 0;
    }
 
    .oil-depot-option {
      border: 1px solid #e4e7ed;
      border-radius: 6px;
      background-color: #fafbfc;
 
      &:hover {
        border-color: #409eff;
        background-color: #f0f7ff;
      }
    }
  }
</style>