廖井涛
2025-05-15 78e7b539b446c3dae568fe3ae3441efd8166caea
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
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
<script setup>
import {computed, nextTick, onMounted, onUnmounted, reactive, ref, toRefs} from "vue";
import {useRouter,useRoute} from 'vue-router'
import request from "@/utils/request";
import {ElMessage} from "element-plus";
import {changeFilterEvent, filterChanged} from "@/hook"
import domZIndex from 'dom-zindex'
import {indexOf} from "xe-utils";
import {addListener, toolbarButtonClickEvent} from "@/hook/mouseMove";
import userInfo from "@/stores/userInfo"
import { useI18n } from 'vue-i18n'
import footSum from "@/hook/footSum"
import companyInfo from "@/stores/sd/companyInfo"
domZIndex.setCurrent(3000)
const company = companyInfo()
//语言获取
const { t } = useI18n()
let brokenVisible = ref(false)
const xGrid = ref()
const brokenGrid =ref()
const router = useRouter()
const route = useRoute()
const user=userInfo()
//定义表头数据
const titleUploadData = ref({
  //是否合片工序
  laminating:'',
  reportingWorkId: null,
  //流程卡号
  processId: null,
  //销售单号
  orderId: '',
  reviewedState:0,
  //生产单号
  productionId: '',
  //设备类型
  deviceName: '',
  //班组名称
  teamsGroupsName: '',
  //生产日期
  reportingWorkTime: '',
  //报工工序
  thisProcess: '',
  //上工序
  previousProcess: '',
  //下工序
  nextProcess: '',
  //备注
  notes: '',
  //本工序完工数
  thisCompletedQuantity: '',
  //本工序报废数
  thisWornQuantity: '',
  //班次
  classes: '',
  //责任工序
  responsibleProcess: '',
  order: {
    //客户编号
    customerId: '',
    //客户名称
    customerName: '',
    //项目名称
    project: '',
  },
  flowCard: {
    //可报工数量
    quantity: ''
  },
 
 
})
let detail = ref([])
let layer=''
let technologicalProcess=''
 
//定义接收加载表头下拉数据
const titleSelectJson = ref({
  deviceType: [],
  teamsType: [],
  processType: [],
  thisProcessType: [],
  mateProcessType: [],
  historyDevice:[],
  historyTeams:[],
  historyProcess:[],
  breakageType:[],
  breakageReason:[]
 
})
 
 
 
let inputDisabled = ref(false)
onMounted(async () =>{
  await initTiltle()
  if(route.query.processId !== undefined && route.query.processId!=='' && route.query.processId!=null ){
    titleUploadData.value.processId = route.query.processId
    //当质检审核后加载明细信息
    if(route.query.reviewStatus === '1'){
      if(titleUploadData.value.thisProcess !== undefined
          && titleUploadData.value.thisProcess!==''
          && titleUploadData.value.thisProcess!=null){
        getWork()
        getQuantity()
      }
    }
  }
   //route.query.reportingWorkId = 'BG2403150004'
  //判断是否传入报工编号
  if(route.query.reportingWorkId !== '' && route.query.reportingWorkId!=null){
    request.post(`reportingWork/selectUpdateReportingWork/${route.query.reportingWorkId}`).then(res=>{
      if(res.code === '200'){
        titleUploadData.value = res.data.reportingWork
        titleSelectJson.value = res.data.basic
        layer= res.data.layer
 
        //添加补片状态列
        let column = {field: 'patchStatusOther', width: 90,title: t('reportingWorks.patchCondition')}
        gridOptions.columns.push(column)
 
        const s01Values = [];
        for (let i = 0; i < res.data.reportingWorkDetails.length; i++) {
          const s01Values = [];
          // 遍历 detailList 数组,提取 S01 值到 s01Values 数组
          if (res.data.reportingWorkDetails[i].other_columns!=null|| res.data.reportingWorkDetails[i].other_columns!=undefined){
            res.data.reportingWorkDetails.forEach(element => {
              const otherColumnsObject = JSON.parse(element.other_columns);
              const s01Value = otherColumnsObject.S01;
              s01Values.push(s01Value || ''); // 如果 S01 值为空,添加空字符串或者其他默认值
            });
 
            // 将 s01Values 中的值赋给每个订单详情对象的 s01Value 属性
            res.data.reportingWorkDetails.forEach((detail, index) => {
              detail.s01Value = index < s01Values.length ? s01Values[index] : ''; // 赋值给 s01Value 属性
            });
          }
 
        }
 
 
        //titleUploadData.value.processId=titleUploadData.value.processId+'/'+layer
        xGrid.value.reloadData(res.data.reportingWorkDetails)
        let button =  {
          code: 'update',
          name: t('basicData.update'),
          status: 'primary',
        }
        if(route.query.reviewStatus === "1"){
          button.name=t('basicData.review')
          titleUploadData.value.qualityInspector=user.user.userName
        }
        gridOptions.toolbarConfig.buttons.push(button)
      }
     // getQuantity()
      inputDisabled.value = true
    })
  }
})
 
const data = [{id:1,num:2},{id:1,num:3},{id:2,num:2},{id:1,num:2}];
 
//表尾求和
const sumNum = (list, field) => {
  let count = 0
  list.forEach(item => {
    count += Number(item[field])
  })
  return count.toFixed(2)
}
 
 
 
const optionVal = ref('')
 
//班次
const classesVal = ref(t('reportingWorks.early'))
const classesOption = [
  {
    value: t('reportingWorks.early'),
    label: t('reportingWorks.early'),
  },
  {
    value: t('reportingWorks.nightShift'),
    label: t('reportingWorks.nightShift'),
  },
]
 
 
const gridOptions = reactive({
  border: "full",//表格加边框
  keepSource: true,//保持源数据
  align: 'center',//文字居中
  stripe: true,//斑马纹
  rowConfig: {isCurrent: true, isHover: true, height: 30},//鼠标移动或选择高亮
  id: 'AddReportingWork_1',
  showFooter: true,//显示脚
  printConfig: {},
  importConfig: {},
  exportConfig: {},
  scrollY: {enabled: true},//开启虚拟滚动
  showOverflow: true,
  columnConfig: {
    resizable: true,
    useKey: true
  },
  filterConfig: {   //筛选配置项
                    // remote: true
  },
  customConfig: {
    storage: true
  },
  mouseConfig:{selected: true},//鼠标选中
  keyboardConfig:{
    isArrow: true,
    isDel: true,
    isEnter: true,
    isTab: true,
    isEdit: true,
    isChecked: true
  },
  editConfig: {
    trigger: 'dblclick',
    mode: 'row',
    showStatus: true
  },
  menuConfig: {
    body: {
    //右键菜单
      options: [
        [
          {
            code: 'copyChecked',
            name: t('basicData.selectSame'),
            prefixIcon: 'vxe-icon-copy',
            visible: true,
            disabled: false
          },
          {
            code: 'copyAll',
            name: t('basicData.sameAfterwards'),
            prefixIcon: 'vxe-icon-feedback',
            visible: true,
            disabled: false
          },
          {
            code: 'clearChecked',
            name: t('basicData.clearSelection'),
            prefixIcon: 'vxe-icon-indicator',
            visible: true,
            disabled: false
          },
          {
            code: 'SecondaryBreakage',
            name: "序号次破相同",
            prefixIcon: 'vxe-icon-indicator',
            visible: true,
            disabled: false
          },
          {
            code: 'checkedBreakage',
            name: "选中次破相同",
            prefixIcon: 'vxe-icon-indicator',
            visible: true,
            disabled: false
          },
        ]
      ]
    }
  },
  //表头参数
  columns: [
    //  {type:'expand',fixed:"left",slots: { content:'content' },width: 50},
    {
      field: 'order_number',
      title: t('order.OrderNum'),
      filters: [{data: ''}],
      slots: {filter: 'num1_filter'},
      filterMethod: filterChanged
    },
    {
      field: 's01Value',
      title: t('reportingWorks.glassNumber'),
      filters: [{data: ''}],
      slots: {filter: 'num1_filter'},
      filterMethod: filterChanged
    },
    {
      field: 'glass_child',
      title: t('reportingWorks.glassChild'),
      showOverflow: "ellipsis",
      filters: [{data: ''}],
      slots: {filter: 'num1_filter'},
      filterMethod: filterChanged
    },
    {
      field: 'technology_number',
      title: t('processCard.technologyNumber'),
      filters: [{data: ''}],
      slots: {filter: 'num1_filter'},
      filterMethod: filterChanged
    },
    {
      field: 'glass_address',
      title: t('reportingWorks.glassAddress'),
      filters: [{data: ''}],
      slots: {filter: 'num1_filter'},
      filterMethod: filterChanged
    },
    {
      field: 'quantity_card',
      title: t('reportingWorks.numberProcessCards'),
      filters: [{data: ''}],
      slots: {filter: 'num1_filter'},
      showOverflow: "ellipsis",
      filterMethod: filterChanged
    },
    {
      field: 'child_width',
      title: t('order.width'),
      filters: [{data: ''}],
      slots: {filter: 'num1_filter'},
      filterMethod: filterChanged
    },
    {
      field: 'child_height',
      title: t('order.height'),
      filters: [{data: ''}],
      slots: {filter: 'num1_filter'},
      filterMethod: filterChanged
    },
    {
      field: 'shape',
      title: t('order.shape'),
      filters: [{data: ''}],
      slots: {filter: 'num1_filter'},
      showOverflow: "ellipsis",
      filterMethod: filterChanged
    },
    {field: 'quantity', title: t('reportingWorks.reportableQuantityOk'),},
    {
      field: 'completedQuantity', title: t('reportingWorks.completedQuantity'),width: 120,
      editRender: {
        name: 'input',
        attrs: {placeholder: ''}
      },
 
    },
    {
      field: 'breakageQuantity',  title: t('reportingWorks.quantityBroken'),
    },
    {field: 'completed', width: 90, title:t('reportingWorks.completed'),},
    {field: 'onceBroken', width: 90, title: t('reportingWorks.onceBroken'),},
    {
      field: 'reviewed_state',
      title: t('processCard.reviewedState'),
      filters: [{data: ''}],
      slots: {filter: 'num1_filter'},
      filterMethod: filterChanged
    },
 
  ],
//表单验证
  editRules: {
    completedQuantity: [
      {
        validator ({ row }) {
          const regex = /^[0-9]\d*$/
          const brokenNum =
              (row.breakageQuantity === undefined || row.breakageQuantity===null) ? 0 : row.breakageQuantity
          if (row.completedQuantity && !regex.test(row.completedQuantity)) {
            return new Error(t('reportingWorks.enterIntegerGreaterThanEqualTo'))
          }else if((row.completedQuantity*1+brokenNum*1)>row.quantity*1){
            return new Error((`${row.completedQuantity}+${brokenNum}>${row.quantity}`))
          }else  if(row.quantity_card<row.completedQuantity){
            return new Error(t('reportingWorks.pleaseNumber10'))
          }
          const completedNum =
              (row.completedQuantity === undefined || row.completedQuantity===null || row.completedQuantity==='') ? 0 : row.completedQuantity
          if(titleUploadData.value.reportingWorkId!=null  && completedNum>row.minQuantity){
            return new Error(`${t('reportingWorks.pleaseGreaterThanOrEqual1')}
            ${row.minQuantity}
            ${t('reportingWorks.pleaseGreaterThanOrEqual2')}`)
          }
 
        }
      }
    ]
  },
  toolbarConfig: {//表头按钮
    buttons: [
      // {code: 'empty', name: '清空报工数量'},
      // {code: 'sameCompletion', name: '完工相同'},
      // {code: 'sameDamage', name: '次破相同'},
      // {code: 'sameOneCompletion', name: '完工一列相同'},
      // {code: 'sameOneDamage', name: '次破一列相同'},
      {code: 'saveReportingWork', name: t('basicData.save'), status: 'primary', icon: 'vxe-icon-save',disabled:true},
      {code: 'saveReportingWorkReview', name: t('reportingWorks.saveAndReview'), status: 'primary', icon: 'vxe-icon-save',disabled:true},
    ],
    // import: false,
    // export: true,
    // print: true,
    zoom: true,
    custom: true
  },
  //脚部求和
  footerMethod ({ columns, data }) {//页脚函数
    return[
      columns.map((column, columnIndex) => {
        if (columnIndex === 0) {
          return t('basicData.total')
        }
        const List = ["quantity_card",'quantity','completedQuantity','completed','onceBroken']
        if (List.includes(column.field)) {
          return footSum(data, column.field)
        }
        return ''
      })
    ]
  }
 
})
 
let brokenRow = ref({
  glass_child:'',
  order_number:'',
  technology_number:''
 
})
const gridEvents = {
  async toolbarButtonClick({code}) {
    const $grid = xGrid.value
    if ($grid) {
      switch (code) {
        case 'saveReportingWork':  {//保存
          const errMap = await $grid.validate(true)
          if (errMap) {
            ElMessage.error(t('basicData.msg.checkoutLose'))
            return
          }
          saveReportingWork(0,'save')
          break
        }
        case 'saveReportingWorkReview':  {
          const errMap = await $grid.validate(true)
          if (errMap) {
            ElMessage.error(t('basicData.msg.checkoutLose'))
            return
          }
          saveReportingWork(1,'save')
          break
        }
        case 'update':  {//修改
          //根据补片状态判断是否能修改
          // request.post(`/reportingWork/getPatchCondition/${route.query.reportingWorkId}`).then(async (res) => {
          //   if (res.code == 200) {
          //     if (res.data > 0) {
          //       ElMessage.error("该报工包含已补片数据,不可修改!")
          //       return
          //     } else {
                getQuantity()
                const errMap = await $grid.validate(true)
                if (errMap) {
                  ElMessage.error(t('basicData.msg.checkoutLose'))
                  return
                }
                saveReportingWork(0, 'update')
           //   }
          //   } else {
          //     ElMessage.warning(res.msg)
          //   }
          // })
 
          break
        }
      }
    }
  },
  cellDblclick (params) {//表格内容双击打开产品界面
    const { row } = params
    brokenRow.value = row
    if(brokenRow.value.damageDetails=== undefined){
      brokenRow.value.damageDetails=[]
    }
    //brokenGrid.value.reloadData(brokenRow.damageDetail)
    //改变brokenVisible的值触发openedBrokenTable()方法
    const { rows, column, cell } = params; // 解构获取行、列和单元格信息
    //点击次破数量时打开明细界面
    if(column.field=="breakageQuantity"){
      if (row.patchStatusOther!="已补片"){
        brokenVisible.value = true
      }
    }
  },
  menuClick({menu, row, column}) {//右键菜单
    const $grid = xGrid.value
    if ($grid) {
      switch (menu.code) {
        case 'copyChecked' : {
          let result = toolbarButtonClickEvent()
          if (result.cell === "completedQuantity"){
            if (result) {
              const dataList = xGrid.value.getTableData().visibleData
              const val = dataList[result.start][result.cell]
              dataList.forEach((item, index) => {
                if (index >= result.start && index <= result.end) {
                  item[result.cell] = val
                }
              })
            }
          }
 
          break
        }
        case 'copyAll' : {
          let result = toolbarButtonClickEvent()
          if (result.cell === "completedQuantity" ) {
            if (result) {
              const dataList = xGrid.value.getTableData().visibleData
              const val = dataList[result.start][result.cell]
              dataList.forEach((item, index) => {
                if (index >= result.start) {
                  item[result.cell] = val
                }
              })
            }
          }
          break
        }
        case 'clearChecked' : {
          let result = toolbarButtonClickEvent()
          if (result.cell === "completedQuantity" ) {
            if (result) {
              const dataList = xGrid.value.getTableData().visibleData
              dataList.forEach((item, index) => {
                if (index >= result.start && index <= result.end) {
                  item[result.cell] = ''
                }
              })
            }
          }
          break
        }
        case 'SecondaryBreakage' : {
          let result = toolbarButtonClickEvent()
          if (result.cell === "breakageQuantity" || result.cell === "completedQuantity"){
            if (result) {
              const dataList = xGrid.value.getTableData().visibleData
              const seenOrders = {}
              dataList.forEach((item, index) => {
                const list = item.damageDetails
                if (list!== null || list.length > 0){
                  const { order_number, damageDetails, breakageQuantity } = item;
                  // 如果 order_number 还没有处理过
                  if (!seenOrders[order_number]) {
                    // 记录第一个出现的 damageDetails 和 breakageQuantity
                    seenOrders[order_number] = {
                      damageDetails,
                      breakageQuantity
                    };
                  } else {
                    // 将后续的 damageDetails 和 breakageQuantity 更新为第一个的
                    item.damageDetails = seenOrders[order_number].damageDetails;
                    item.breakageQuantity = seenOrders[order_number].breakageQuantity;
                  }
                }
 
              })
            }
          }
          break
        }
        case 'checkedBreakage' : {
          let result = toolbarButtonClickEvent()
          if (result.cell === "breakageQuantity" || result.cell === "completedQuantity"){
            if (result) {
              const dataList = xGrid.value.getTableData().visibleData
              const val = dataList[result.start].damageDetails
              const quantity = dataList[result.start].breakageQuantity
              dataList.forEach((item, index) => {
                if (index >= result.start && index <= result.end) {
                  item.damageDetails = val
                  item.breakageQuantity =  quantity
                  if (index!=result.start){
                    item.completedQuantity = item.completedQuantity - quantity
                  }
 
                }
              })
            }
          }
          break
        }
      }
    }
  },
}
 
 
 
const brokenGridOptions = reactive({
  border: "full",//表格加边框
  keepSource: true,//保持源数据
  align: 'center',//文字居中
  stripe: true,//斑马纹
  rowConfig: {isCurrent: true, isHover: true, height: 30},//鼠标移动或选择高亮
  id: 'AddReportingWork_2',
  //showFooter: true,//显示脚
  printConfig: {},
  importConfig: {},
  exportConfig: {},
  //scrollY: {enabled: true},//开启虚拟滚动
  showOverflow: true,
  columnConfig: {
    resizable: true,
    useKey: true
  },
  filterConfig: {   //筛选配置项
    // remote: true
  },
  customConfig: {
    storage: true
  },
  editConfig: {
    trigger: 'click',
    mode: 'row',
    showStatus: true
  },//表头参数
  columns: [
    {type: 'checkbox', fixed: "left", title: t('basicData.check'),width: 78},
    {type: 'seq',fixed:"left", title: t('basicData.Number'), width: 80 },
    // {
    //   field: 'order_number',
    //   title: '序号'
    // },
 
    {
      field: 'breakageQuantity',
      title: t('reportingWorks.quantityBroken'),
      editRender: {name: 'input', attrs: {placeholder: ''}}
    },
    {field: 'available',
      title: t('reportingWorks.available'),
      slots: {default: 'available'}
    },
    {field: 'returnProcess', title: t('reportingWorks.returnProcess'),
      editRender: {},
      slots: {default: 'returnProcess_default', edit: 'returnProcess'}
    },
    {
      field: 'breakageType', title: t('reportingWorks.breakageType'),
      editRender: {},
      slots: {default: 'breakageType_default', edit: 'breakageType'}
    },
    {
      field: 'breakageReason', title: t('reportingWorks.breakageReason'),
      editRender: {},
      slots: {default: 'breakageReason_default', edit: 'breakageReason'}
    },
    {
      field: 'responsibleProcess', title: t('reportingWorks.responsibleProcess'),
      editRender: {},
      slots: {default: 'responsibleProcess_default', edit: 'responsibleProcess'}
    },
    {
      field: 'responsibleEquipment',
      title: t('reportingWorks.responsibleEquipment'),
      editRender: {},
      slots: {default: 'reportingDeviceSort_default', edit: 'reportingDeviceSort'}
      // editRender: {name: 'input', attrs: {placeholder: ''}}
    },
 
    {
      field: 'responsibleTeam',  title: t('reportingWorks.responsibleTeam'),
      editRender: {},
      slots: {default: 'responsibleTeam_default', edit: 'responsibleTeam'}
    },
    {
      field: 'responsiblePersonnel',
      title: '责任信息',
      editRender: {name: 'input', attrs: {placeholder: ''}}
 
    },
 
  ],
//表单验证
  editRules: {
    breakageQuantity: [
      {
        validator ({ cellValue }) {
          const regex = /^[1-9]\d*$/
          if (!regex.test(cellValue)) {
            return new Error(t('reportingWorks.enterIntegerGreaterThan'))
          }
        }
      }
    ],
    returnProcess:[
      {
        validator ({ row }) {
          const regex = /^\s*$/i
          if(row.available===true && (regex.test(row.returnProcess)==='' || row.returnProcess===null)){
            return new Error(t('reportingWorks.availableOkReturnProcess'))
          }
        }
      }
    ],
    breakageType: [
      { required: true, message: t('reportingWorks.selectBreakageType') }
    ],
    breakageReason: [
      { required: true, message: t('reportingWorks.selectBreakageReason') }
    ],
    responsibleProcess: [
      { required: true, message: t('reportingWorks.selectResponsibleProcess')}
    ],
    responsibleEquipment: [
      { required: true, message: t('reportingWorks.selectResponsibleEquipment') }
    ],
    responsibleTeam: [
      { required: true, message: t('reportingWorks.selectResponsibleTeam') }
    ],
  },
  toolbarConfig: {//表头按钮
    buttons: [
      {code: 'addRow', name: t('reportingWorks.increase'), status: 'primary', icon: 'vxe-icon-square-plus'},
      {code: 'removeRow', name: t('basicData.delete'), status: 'primary', icon: 'vxe-icon-delete'},
    ],
    // import: false,
    // export: true,
    // print: true,
    zoom: true,
    custom: true
  },
})
const brokenGridEvents = {
  toolbarButtonClick({code}) {
    const $grid = brokenGrid.value
    if ($grid) {
      switch (code) {
        case 'addRow':  {
          $grid.insertAt({})
          break
        }
        case 'removeRow':  {
          const $grid = brokenGrid.value
          const checkedList = $grid.getCheckboxRecords()
          if(checkedList){
            $grid.remove(checkedList)
          }
          break
        }
      }
    }
  }
}
const openedBrokenTable = () => {
  //addListener(brokenGrid.value,brokenGridOptions)
  let damage =ref(brokenRow.value.damageDetails)
  brokenGrid.value.reloadData(damage.value)
}
 
 
const checkClose = async (done) => {
  if(brokenGrid.value.getTableData().fullData.length===0){
    brokenRow.value.breakageQuantity=null
    brokenRow.value.completedQuantity = brokenRow.value.quantity
    brokenRow.value.damageDetails=[]
    done()
    return true
  }
  const errMap = await brokenGrid.value.validate(true)
  if (errMap) {
    ElMessage.error(t('basicData.msg.checkoutLose'))
    return false
  }
  let breakageQuantityCount = 0
  brokenRow.value.breakageQuantity=0
  brokenGrid.value.getTableData().fullData.forEach((row) =>{
    breakageQuantityCount+=row.breakageQuantity*1
  })
 
  let reportingWorkNum = isNaN(brokenRow.value.completedQuantity*1)?0:brokenRow.value.completedQuantity*1
  if((breakageQuantityCount>brokenRow.value.quantity*1) ){
    ElMessage.warning(`${t('reportingWorks.lossCount1')}':'${breakageQuantityCount}
                               ${t('reportingWorks.lossCount2')}${brokenRow.value.quantity*1}`)
    return false
  }
  brokenRow.value.completedQuantity = brokenRow.value.quantity-breakageQuantityCount
  breakageQuantityCount = breakageQuantityCount === 0 ? null : breakageQuantityCount
  brokenRow.value.breakageQuantity = breakageQuantityCount
  brokenRow.value.damageDetails=brokenGrid.value.getTableData().fullData
  // xGrid.value.getTableData().fullData.forEach(
  //
  // )
  const equalByOrderNum = xGrid.value.getTableData().fullData.filter((row) =>{
    return row.order_number === brokenRow.value.order_number
  })
  const maxQuantity =  Math.max(...equalByOrderNum.map(item =>item.breakageQuantity || 0))
  let process = titleUploadData.value.thisProcess
  let laminating = titleUploadData.value.laminating
  equalByOrderNum.forEach((row) =>{
    if (laminating != ''){
      row.completedQuantity= brokenRow.value.quantity*1-maxQuantity
    }
  })
 
 
  getQuantity()
 
  done()
}
 
 
//第一次加载数据
let groupChangeProcess = ref(false)//用于本班组显示问题
const initTiltle = async () => {
  await request.post(`/reportingWork/selectProcess/${user.user.userId}`).then((res) => {
    if (res.code == 200) {
      titleSelectJson.value.processType = res.data.process
      if(user.user.address!==null && user.user.address!==''){
        titleUploadData.value.thisProcess = user.user.address
        titleUploadData.value.teamsGroupsName = user.user.userName
        groupChangeProcess.value = true
        if (user.user.address==='技术部多曲' || user.user.address==='夹胶'){
          groupChangeProcess.value = false
        }
        gridOptions.toolbarConfig.buttons[1].visible=false
      }
 
    } else {
      ElMessage.warning(res.msg)
    }
  })
}
 
 
function checkSameNumForId(data, targetId) {
  // 初始化一个对象来存储遇到的id及其对应的num值
  const idNums = {};
  let firstNum = null;
 
  for (const item of data) {
    if (item.order_number === targetId) {
      // 如果找到了目标id,检查num是否与第一个遇到的num相同
      if (firstNum === null) {
        // 如果是第一个遇到的,记录num值
        firstNum = item.completedQuantity;
      } else if (item.completedQuantity !== firstNum) {
        // 如果num值与第一个遇到的num不同,返回false
        return false;
      }
    }
  }
 
  // 如果遍历完数组后没有返回false,那么所有具有目标id的对象都具有相同的num值
  return true;
}
 
 
 
 
 
 
const saveReportingWork = (state,saveType) => {
 
  if(xGrid.value.getTableData().fullData.length===0){
    ElMessage.warning(t('reportingWorks.selectProcessCardData'))
    return
  }
  const device = titleUploadData.value.deviceName
  if(device === null || device === undefined || device === ''){
    ElMessage.error(t('reportingWorks.selectWorkReportingEquipment'))
    return
  }
  const teamsGroupsName = titleUploadData.value.teamsGroupsName
  if(teamsGroupsName === null || teamsGroupsName === undefined || teamsGroupsName === ''){
    ElMessage.error(t('reportingWorks.selectWorkReportingTeam'))
    return
  }
 
  const seenIds = {}
  const uniqueByOrderNum = xGrid.value.getTableData().fullData.filter(item => {
    // 检查item的id是否已经在seenIds中
    if (!seenIds[item.order_number]) {
      // 如果不在,添加它并返回true以保留这个对象
      seenIds[item.order_number] = true;
      return true;
    }
    // 如果已经在seenIds中,返回false以过滤掉这个对象
    return false;
  });
  const notFinishList = xGrid.value.getTableData().fullData.filter(item =>{
    return item.saveFlag === 0
  })
  let process = titleUploadData.value.thisProcess
  //暂时取消
  for(let item of uniqueByOrderNum){
    if(!checkSameNumForId(notFinishList,item.order_number ) && (process=='夹胶' || process=='中空' || process=='包装' ||process=='打胶和粘框')){
      ElMessage.error(`${t('reportingWorks.pleaseCheckTheOrderNumber1')}:
      ${item.order_number}
       ${t('reportingWorks.pleaseCheckTheOrderNumber1')}`)
      return false
    }
  }
 
  titleUploadData.value.creator = user.user.userName
  titleUploadData.value.creatorId = user.user.userId
  const requestDetailData = xGrid.value.getTableData().fullData.filter((row) => {
    const a = (row.completedQuantity !== undefined && row.completedQuantity !== null && row.completedQuantity !== '' && row.completedQuantity*1!==0)
    const b = (row.breakageQuantity !== undefined && row.breakageQuantity !== null && row.breakageQuantity !== '' && row.breakageQuantity*1!==0)
    return (a || b)
  })
  if(requestDetailData.length === 0 &&  (route.query.reportingWorkId===undefined)){
    ElMessage.warning(t('reportingWorks.atLeastOneFinishedAndWornEligible'))
    return false
  }
  let status=company.qualityInsStatus
  const requestData = {
    title:titleUploadData.value,
    detail:xGrid.value.getTableData().fullData,
    type:state,//审核状态
    userId:user.user.userId,
    userName:user.user.userName,
    qualityInsStatus:status
  }
  gridOptions.toolbarConfig.buttons[0].disabled=true
  gridOptions.toolbarConfig.buttons[1].disabled=true
  //判断保存还是修改
  if(saveType==='save'){
    saveReportingWorkRequest(requestData)
  }else{
    updateReportingWorkRequest(requestData)
  }
 
}
 
const saveReportingWorkRequest = (requestData) =>{
  request.post(`/reportingWork/saveReportingWork`,requestData).then(res =>{
    if (res.code == 200){
      ElMessage.success(t('reportingWorks.successfulJobApplication'))
      router.push({path:'/main/reportingWorks/AddReportingWork',query:{processId:titleUploadData.value.processId,random:Math.random()}})
    }else{
      const errorObj = JSON.parse(res.msg)
      const msg = t('reportingWorks.pleaseNumber1')+":"+errorObj.orderNumber+'\n'
          +t('reportingWorks.pleaseNumber2')+':'+errorObj.technologyNumber+'\n'
          +t('reportingWorks.pleaseNumber3')+':'+errorObj.processNum+'<'+
          +t('reportingWorks.pleaseNumber4')+':'+errorObj.sumNum+'\n'
          +t('reportingWorks.pleaseNumber5')
 
      ElMessage.error(msg)
    }
  }).catch(err =>{
    ElMessage.error('提交失败,请刷新后重试')
  }).finally(()=>{
 
    gridOptions.toolbarConfig.buttons[0].disabled=false
    gridOptions.toolbarConfig.buttons[1].disabled=false
  })
}
 
//更新报工数据
const updateReportingWorkRequest = (requestData) =>{
  let reviewState = 'update'
  if(route.query.reviewStatus==="1"){
    reviewState = 'review'
  }
  request.post(`/reportingWork/updateReportingWork/${reviewState}`,requestData).then(res =>{
    if (res.code == 200 && res.data===true){
      ElMessage.success(t('reportingWorks.successfulModificationOfWorkApplication'))
      router.push({path:'/main/reportingWorks/AddReportingWork',
        query:{
          processId:titleUploadData.value.processId,
          random:Math.random()}
      })
    } else {
      ElMessage.warning(t('reportingWorks.changeFailed'))
    }
  })
}
 
 
//查询责任设备
const computedDevice = computed((responsibleProcess) => {
  return function (responsibleProcess){
    return titleSelectJson.value.historyDevice.filter((item) => {
      return item.basic_category === responsibleProcess
    })
  }
})
// 查询责任班组
const computedResponsibleTeam = computed((responsibleProcess) => {
  titleSelectJson.value.historyTeams.push({basic_name: user.user.userName, process: titleUploadData.value.thisProcess, basic_type: 'teamsgroups', basic_category: 179, id: 555})
  return function (responsibleProcess){
    return titleSelectJson.value.historyTeams.filter((item) => {
      return item.process === responsibleProcess
    })
  }
})
 
//判断是否点击可利用 显示返回工序
const computedReturnProcess =  computed((available) => {
  return function (available){
    if(available){
      return titleSelectJson.value.historyProcess
    }
  }
})
 
let loadingFlag = ref(false)
let disabledFlag = ref(true)
const reviewReportingWork = () => {
  const processId = titleUploadData.value.processId
  if (processId.indexOf("/") < 0) {
    ElMessage.warning(t('reportingWorks.correctFormatProcessCard'))
    return
  }
  let indexOfChar = processId.indexOf("/")
  let leftString = processId.slice(0, indexOfChar)
  if (leftString.length < 14) {
    ElMessage.warning(t('reportingWorks.processCardCorrectNumberDigits'))
    return
  }
//工序
  let process = titleUploadData.value.thisProcess
  if (process === "" || process == null) {
    ElMessage.warning(t('reportingWorks.selectProcess'))
    return
  }
  if(titleUploadData.value.previousProcess===''){
    ElMessage.warning(t('reportingWorks.firstProcessNotReview'))
    return
  }
  //匹配“/”前后字符串
  const regex =  /([^\/]+)\/([^\/]+)/;
  //查找匹配的字符串
  const result = processId.match(regex);
  //流程卡号
  let processIdStr = result[1];
  //层号
  let technologyStr = result[2];
  const reportWork = {
    process: titleUploadData.value.previousProcess,
    processId:processId,
    thisProcess:titleUploadData.value.thisProcess,
    technologyStr:technologyStr,
    userName:user.user.userName
  }
  loadingFlag.value= true
  request.post("/reportingWork/reviewReportingWork",reportWork).then((res) =>{
    if(res.code === '200'){
      ElMessage.success(t('basicData.msg.ReviewSuccess'))
      router.push({path:'/main/reportingWorks/AddReportingWork',
        query:{
          processId:titleUploadData.value.processId,
          reviewStatus:1,
          random:Math.random()
        }
      })
    }
  }).finally(
      loadingFlag.value= false
  )
 
}
 
 
//下拉款选择工序时查询
const getWork = () => {
 
  let processId = titleUploadData.value.processId
  if (processId == "" || processId == null) {
    ElMessage.warning(t('reportingWorks.theProcessCardNumberCannotBeEmpty'))
    return
  }
  let parts = processId.split('/');
 
  if (processId.indexOf("/") < 0 ||parts[1].trim() == '') {
    ElMessage.warning(t('reportingWorks.correctFormatProcessCard'))
    return
  }
  let indexOfChar = processId.indexOf("/")
  let leftString = processId.slice(0, indexOfChar)
  if (leftString.length < 14) {
    ElMessage.warning(t('reportingWorks.processCardCorrectNumberDigits'))
    return
  }
//工序
  let process = titleUploadData.value.thisProcess
  if (process == "" || process == null) {
    ElMessage.warning(t('reportingWorks.selectProcess'))
    return
  }
  if (titleSelectJson.value.thisProcessType.length!=0){
    if (titleSelectJson.value.thisProcessType.indexOf(process) === -1 && process !== t('machine.cutting')) {
      ElMessage.warning(t('reportingWorks.thisProcessNotProcessCard'))
      return
    }
  }
 
  //匹配“/”前后字符串
  const regex =  /([^\/]+)\/([^\/]+)/;
  //查找匹配的字符串
  const result = processId.match(regex);
  //流程卡号
  let processIdStr = result[1];
  //层号
  let technologyStr = result[2];
 
  let reportType= company.reportType
  request.post(`/reportingWork/addSelectLastWork/${processIdStr}/${technologyStr}/${process}/${reportType}`).then((res) => {
    if (res.code == 200) {
      if(res.data.data==null){
        ElMessage.error(t('reportingWorks.noDataThisProcessCard'))
        return
      }
      technologicalProcess=res.data.technologicalProcess
      //表头赋值
      titleUploadData.value = res.data.data
      titleUploadData.value.processId = processId
      titleUploadData.value.teamsGroupsName = user.user.userName
      titleUploadData.value.laminating = res.data.laminating
      //设备下拉框
      titleSelectJson.value.deviceType = res.data.device
      //班组下拉框
      //titleSelectJson.value.teamsType = res.data.teams
      //当前流程卡工序
      titleSelectJson.value.thisProcessType = res.data.thisProcess
      //历史班组
      titleSelectJson.value.historyTeams= res.data.historyTeams
      //历史设备
      titleSelectJson.value.historyDevice = res.data.historyDevice
      //历史工序
      titleSelectJson.value.historyProcess =  res.data.historyProcess
      //次破类型
      titleSelectJson.value.breakageType =  res.data.breakageType
      //次破原因
      titleSelectJson.value.breakageReason =  res.data.breakageReason
      if(titleUploadData.value.reviewedState==1){
        gridOptions.toolbarConfig.buttons[0].disabled=false
        gridOptions.toolbarConfig.buttons[1].disabled=false
        disabledFlag.value=true
      }else {
        gridOptions.toolbarConfig.buttons[0].disabled=true
        gridOptions.toolbarConfig.buttons[1].disabled=true
        disabledFlag.value=false
      }
 
      //判断早晚班
      titleUploadData.value.classes=t('reportingWorks.early')
      titleUploadData.value.reportingWorkTime = formatCurrentTime()
 
      //处理编号列
      //定义存放编号数组
      const s01Values = [];
      for (let i = 0; i < res.data.Detail.length; i++) {
        const s01Values = [];
        // 遍历 detailList 数组,提取 S01 值到 s01Values 数组
        if (res.data.Detail[i].other_columns!=null|| res.data.Detail[i].other_columns!=undefined){
          res.data.Detail.forEach(element => {
            const otherColumnsObject = JSON.parse(element.other_columns);
            const s01Value = otherColumnsObject.S01;
            s01Values.push(s01Value || ''); // 如果 S01 值为空,添加空字符串或者其他默认值
          });
 
          // 将 s01Values 中的值赋给每个订单详情对象的 s01Value 属性
          res.data.Detail.forEach((detail, index) => {
            detail.s01Value = index < s01Values.length ? s01Values[index] : ''; // 赋值给 s01Value 属性
          });
        }
 
      }
 
 
      //绑定下方表格
      detail.value = res.data.Detail
      // 使用map方法来处理每个对象
      let modifiedCollection = detail.value.map(item => {
        if (item.reviewed_state === 1) {
          return { ...item, reviewed_state: "已审核" };
        }
        else if (item.reviewed_state === 0) {
          return { ...item, reviewed_state: "未审核" };
        }
        else {
          // 其他情况保持不变
          return item;
        }
      });
      xGrid.value.reloadData(modifiedCollection)
    } else {
      ElMessage.warning(res.msg)
    }
  })
}
 
//判断完工次破数量是否满足条件
const verifyNum = () => {
  const $grid = xGrid.value
  const table = $grid.getTableData().fullData
  let sum = 0;
  let sumBreak = 0;
  table.forEach((item) => {
    if (item.completedQuantity == null || item.completedQuantity == "") {
      item.completedQuantity = 0;
    }
    if (item.breakageQuantity == null || item.breakageQuantity == "") {
      item.breakageQuantity = 0;
    }
 
    if (item.quantity < item.completedQuantity) {
      ElMessage.success(t('reportingWorks.pleaseNumber6') + item.order_number + t('reportingWorks.pleaseNumber7'))
 
 
    } else if (item.breakageQuantity * 1 + item.completedQuantity * 1 > item.quantity * 1) {
      ElMessage.success(t('reportingWorks.pleaseNumber8') + item.order_number + t('reportingWorks.pleaseNumber9'))
    }
 
    sum = item.completedQuantity * 1 + sum * 1
 
    sumBreak = item.breakageQuantity * 1 + sumBreak * 1
 
  })
  titleUploadData.value.thisCompletedQuantity = sum
  titleUploadData.value.thisWornQuantity = sumBreak
}
 
//获取当前时间
function formatCurrentTime() {
  let dateObj = new Date(); // 创建一个表示当前时间的Date对象
  let year = dateObj.getFullYear(); // 年份
  let month = (dateObj.getMonth() + 1).toString().padStart(2, '0'); // 月份(注意需要加上1)
  let day = dateObj.getDate().toString().padStart(2, '0'); // 天数
  let hours = dateObj.getHours().toString().padStart(2, '0'); // 小时
  let minutes = dateObj.getMinutes().toString().padStart(2, '0'); // 分钟
  let seconds = dateObj.getSeconds().toString().padStart(2, '0'); // 秒数
  if(parseInt(hours)>=17 && parseInt(hours)<8)titleUploadData.value.classes=t('reportingWorks.nightShift')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`; // 返回格式化后的时间字符串
}
 
const editClosedEvent = ({ row, column }) => {
  let process = titleUploadData.value.thisProcess
  let laminating = titleUploadData.value.laminating
  if (column.property==='completedQuantity') {
    xGrid.value.getTableData().fullData.forEach((item, index) =>{
      if(item.order_number===row.order_number && laminating != ''){
        item.completedQuantity=row.completedQuantity
      }
    })
    getQuantity()
  }
}
const  getQuantity = () => {
  titleUploadData.value.thisCompletedQuantity = 0
  titleUploadData.value.thisWornQuantity = 0
  let laminating = titleUploadData.value.laminating
  const arr = xGrid.value.getTableData().fullData
  //根据是否合片工序过滤
  const returnArr =
      laminating != ""
          ? arr.filter((obj, index, self) =>
              self.findIndex((t) => t.order_number === obj.order_number) === index
          )
          : arr;
  let sumBreak = 0
  let sumQuantity = 0
  returnArr.forEach((item)=>{
    sumQuantity+=Number(item.completedQuantity*1)
  })
  arr.forEach((item)=>{
    sumBreak+=Number(item.breakageQuantity) || 0
  })
  titleUploadData.value.thisCompletedQuantity = sumQuantity
  titleUploadData.value.thisWornQuantity = sumBreak
}
 
const changeTable=()=>{
  const $grid = xGrid.value
  this.$grid.commitProxy('data', yourData)
}
onMounted(() => {
  window.addEventListener('keypress', qrcodeScanner);
  addListener(xGrid.value, gridOptions)
})
 
// 在组件卸载时移除键盘事件监听
onUnmounted(() => {
  window.removeEventListener('keypress', qrcodeScanner);
})
 
let code = '';
let codeArr = [];
let lastTime,nextTime = ''
let lastCode,nextCode = ''
const qrcodeScanner = (e) =>{
 
  nextCode = e.key;
 
 
  // 当前触发时间
  nextTime = new Date().getTime();
  // 第一次获取
  if(!lastTime &&  !lastCode && e.key !== 'Enter'){
    codeArr = []
    codeArr.push(e.key)
  }
 
  if(lastCode && lastTime && (nextTime - lastTime > 50)){
    // 相隔时间大于30 说明不是扫码枪扫描的 清空重新
    codeArr = []
    // 当扫码前有keypress事件时,防止首字缺失
  } else if(lastCode  && lastTime && e.key !== 'Enter'){
    codeArr.push(e.key)
  }
  lastCode = nextCode
  lastTime = nextTime
  // 扫描结束
  if(e.keyCode === 13){
    // 可进行下一步操作
    /* 下一步操作 */
    if(codeArr.length!==0){
      titleUploadData.value.processId = codeArr.join('')
    }
    if(user.user.address!==null || user.user.address!==''){
      getWork()
    }
 
    codeArr=[]
    lastTime = ''
    nextTime = ''
    lastCode = ''
    nextCode = ''
  }
 
}
 
 
const cellClassName = ({ row, column }) => {
  if (column.field === 'breakageQuantity') {
      return 'col-red'
  }
 
}
const changeRowClass =  ({ row, rowIndex, $rowIndex }) => {
    return row?.rowClass
 
}
const editConfigDisable = reactive({
  trigger: 'click',
  mode: 'cell',
  beforeEditMethod ({ row }) {
    if (row.patchStatusOther === '已补片') {
      return false
    }
    return true
  }
})
 
</script>
 
<template>
  <div  style="width: 100%;height: 100%">
    <div class="head">
      <el-input :disabled="inputDisabled" v-if="titleUploadData.reportingWorkId" v-model="titleUploadData.reportingWorkId" :placeholder="$t('reportingWorks.reportingWorkId')" style="width: 200px" />
      <el-input :disabled="inputDisabled" v-model="titleUploadData.processId" :placeholder="$t('processCard.processId')" style="width: 200px" @keyup.enter.native="getWork();getQuantity()"/>
      &nbsp;
      <el-select :disabled="inputDisabled || groupChangeProcess"
                 v-model="titleUploadData.thisProcess"
                 clearable
                 :placeholder="$t('reportingWorks.selectProcess')"
                 style="width: 120px"
                 @change="getWork();getQuantity()">
        <el-option
            v-for="item in titleSelectJson['processType']"
            :key="item.id"
            :label="item.basic_name"
            :value="item.basic_name"
        />
      </el-select>
      &nbsp;
      <el-button :disabled="disabledFlag" :loading="loadingFlag" @click="reviewReportingWork" type="primary">{{$t('reportingWorks.passAudit')}}
      </el-button>
<!--      <el-button type="primary">审核不通过</el-button>-->
      &nbsp;
      <label>{{technologicalProcess}}</label>
    </div>
    <div class="head1">
      <el-row>
        <el-col :span="2">
          <el-text>{{$t('order.orderId')}}:</el-text>
        </el-col>
        <el-col :span="3">
          <el-text>{{ titleUploadData.orderId }}</el-text>
        </el-col>
        <el-col :span="2">
          <el-text>{{$t('workOrder.productionId')}}:</el-text>
        </el-col>
        <el-col :span="3">
          <el-text>{{ titleUploadData.productionId }}</el-text>
        </el-col>
        <el-col :span="2">
          <el-text>{{$t('processCard.customerId')}}:</el-text>
        </el-col>
        <el-col :span="2">
          <el-text>{{ titleUploadData.order.customerId }}</el-text>
        </el-col>
        <el-col :span="2">
          <el-text>{{$t('processCard.customerName')}}:</el-text>
        </el-col>
        <el-col :span="3">
          <el-text class="customClass"></el-text>
        </el-col>
        <el-col :span="2">
          <el-text >{{$t('order.project')}}:</el-text>
        </el-col>
        <el-col :span="3">
          <el-input :readonly="true" v-model="titleUploadData.order.project"/>
<!--          <el-text style="white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">{{ titleUploadData.order.project }}</el-text>-->
        </el-col>
 
      </el-row>
      <el-row>
        <el-col :span="2">
          <el-text>{{$t('reportingWorks.deviceType')}}:</el-text>
        </el-col>
        <el-col :span="3">
          <el-select @change="getQuantity" v-model="titleUploadData.deviceName" clearable :placeholder="$t('reportingWorks.pleaseDevice')">
            <el-option
                v-for="item in titleSelectJson['deviceType']"
                :key="item.id"
                :label="item.basicName"
                :value="item.basicName"
            />
          </el-select>
        </el-col>
        <el-col :span="2">
          <el-text>{{$t('reportingWorks.previousProcess')}}:</el-text>
        </el-col>
        <el-col :span="3">
 
          <el-text>{{ titleUploadData.previousProcess }}</el-text>
        </el-col>
        <el-col :span="2">
          <el-text>{{$t('reportingWorks.numberReported')}}:</el-text>
        </el-col>
        <el-col :span="2">
          <el-text>{{ titleUploadData.previousProcessQuantity }}</el-text>
 
        </el-col>
        <el-col :span="2">
          <el-text>{{$t('reportingWorks.thisCompletedQuantity')}}:</el-text>
        </el-col>
        <el-col :span="3">
          <el-text>{{ titleUploadData.thisCompletedQuantity }}</el-text>
        </el-col>
        <el-col :span="2">
          <el-text>{{$t('reportingWorks.thisWornQuantity')}}:</el-text>
        </el-col>
        <el-col :span="3">
          <el-text>{{ titleUploadData.thisWornQuantity }}</el-text>
        </el-col>
 
      </el-row>
      <el-row>
        <el-col :span="2">
          <el-text>{{$t('reportingWorks.teamsType')}}:</el-text>
        </el-col>
        <el-col :span="3">
          <el-select :disabled="groupChangeProcess"
                     v-model="titleUploadData.teamsGroupsName"
                     clearable
                     :placeholder="$t('reportingWorks.selectTeam')">
            <el-option
                v-for="item in titleSelectJson['teamsType']"
                :key="item.id"
                :label="item.basicName"
                :value="item.basicName"
            />
          </el-select>
        </el-col>
        <el-col :span="2">
          <el-text>{{$t('reportingWorks.classes')}}:</el-text>
        </el-col>
        <el-col :span="3">
          <el-select v-model="titleUploadData.classes" class="processesSt" :placeholder="$t('reportingWorks.selectClasses')">
            <el-option
                v-for="item in classesOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-col>
        <el-col :span="2">
          <el-text>{{$t('reportingWorks.nextProcess')}}:</el-text>
        </el-col>
        <el-col :span="2">
          <el-text>{{ titleUploadData.nextProcess }}</el-text>
 
        </el-col>
        <el-col :span="2">
          <el-text>{{$t('reportingWorks.reportingWorkTime')}}:</el-text>
        </el-col>
        <el-col :span="3">
          <el-date-picker
              v-model="titleUploadData.reportingWorkTime"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder=""
              style="width: 100%"
              type="datetime"
          />
        </el-col>
        <el-col :span="2">
          <el-text>{{$t('basicData.remarks')}}:</el-text>
        </el-col>
        <el-col :span="3">
          <el-input v-model="titleUploadData.notes" placeholder="" />
        </el-col>
 
      </el-row>
    </div>
    <div class="main-table">
      <vxe-grid
          ref="xGrid"
          class="mytable-scrollbar"
          :row-class-name="changeRowClass"
          height="100%"
          size="small"
          v-bind="gridOptions"
          v-on="gridEvents"
          @edit-closed="editClosedEvent"
          :cell-class-name="cellClassName"
          :edit-config="editConfigDisable"
 
      >
 
 
        <template #num1_filter="{ column, $panel }">
          <div>
            <div v-for="(option, index) in column.filters" :key="index">
              <input v-model="option.data" type="type"
                     @keyup.enter.native="$panel.confirmFilter()"
                     @input="changeFilterEvent($event, option, $panel)"/>
            </div>
          </div>
        </template>
 
 
      </vxe-grid>
    </div>
      <el-dialog
          @opened="openedBrokenTable"
          :before-close="checkClose"
          v-model="brokenVisible"
          :close-on-click-modal="false"
          :close-on-press-escape="false"
          :title="$t('reportingWorks.damageList')+':'
          +brokenRow.glass_child+'.'+brokenRow.order_number+'.'+brokenRow.technology_number"
          style="width: 80%;height:75% ">
        <vxe-grid
 
            height="400px"
            ref="brokenGrid"
            class="mytable-scrollbar"
            v-bind="brokenGridOptions"
            v-on="brokenGridEvents">
          <!--        返回工序-->
          <template #returnProcess="{ row }">
            <vxe-select v-model="row.returnProcess"
                        filterable
                        clearable
                        placeholder="" >
              <vxe-option v-for="item in computedReturnProcess(row.available)"
                          :key="item.basic_category"
                          :label="item.basic_category"
                          :value="item.basic_category"/>
            </vxe-select>
          </template>
          <template #returnProcess_default="{ row }">
            <span>{{ row.returnProcess }}</span>
          </template>
 
          <!--        责任工序-->
          <template #responsibleProcess="{ row }">
            <vxe-select v-model="row.responsibleProcess"
                        filterable
                        clearable
                        placeholder="" >
              <vxe-option v-for="item in titleSelectJson.historyProcess"
                          :key="item.basic_category"
                          :label="item.basic_category"
                          :value="item.basic_category"/>
            </vxe-select>
          </template>
          <template #responsibleProcess_default="{ row }">
            <span>{{ row.responsibleProcess }}</span>
          </template>
          <!--     刺破类型breakageType   -->
          <template #breakageType="{ row }">
            <vxe-select v-model="row.breakageType "
                        clearable placeholder=" " allow-create  filterable>
              <vxe-option v-for="item in titleSelectJson.breakageType" :key="item.id" :label="item.basic_name" :value="item.basic_name"/>
            </vxe-select>
          </template>
          <template #breakageType_default="{ row }">
            <span>{{ row.breakageType }}</span>
          </template>
 
          <!--次破原因-->
          <template #breakageReason="{ row }">
            <vxe-select v-model="row.breakageReason "
                        clearable placeholder=" " allow-create  filterable>
              <vxe-option v-for="item in titleSelectJson.breakageReason" :key="item.id" :label="item.basic_name" :value="item.basic_name"/>
            </vxe-select>
          </template>
          <template #breakageReason_default="{ row }">
            <span>{{ row.breakageReason }}</span>
          </template>
 
 
 
          <!--     责任设备    -->
          <template #reportingDeviceSort="{ row }">
            <vxe-select v-model="row.responsibleEquipment"
                        filterable
                        clearable
                        placeholder="">
              <vxe-option v-for="item in computedDevice(row.responsibleProcess)" :key="item.id" :label="item.basic_name" :value="item.basic_name"/>
            </vxe-select>
          </template>
          <template #reportingDeviceSort_default="{ row }">
            <span>{{ row.responsibleEquipment }}</span>
          </template>
 
          <!--     责任设备    -->
          <template #responsibleTeam="{ row }">
            <vxe-select v-model="row.responsibleTeam"
                        filterable
                        clearable
                        placeholder="">
              <vxe-option v-for="item in computedResponsibleTeam(row.responsibleProcess)" :key="item.id" :label="item.basic_name" :value="item.basic_name"/>
            </vxe-select>
          </template>
          <template #responsibleTeam_default="{ row }">
            <span>{{ row.responsibleTeam }}</span>
          </template>
          <!--   可利用       -->
          <template #available="{ row }">
            <el-checkbox v-model="row.available" />
          </template>
 
        </vxe-grid>
      </el-dialog>
  </div>
</template>
 
<style scoped>
.head{
  width: 100%;
  height: 35px;
}
.head1{
  width: 100%;
  height: 105px;
  background-color: white;
}
 
.main-table{
  width: 100%;
  height: calc(100% - 135px);
}
 
.processCard {
  width: 140px;
}
 
.processesSt {
  height: 33px;
  width: 120px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 5px;
}
 
#titleTable tr, #titleTable td {
  border: 1px solid #000;
}
 
#titleTable {
  border-collapse: collapse;
  text-align: center;
  width: 100%;
  height: 100%;
}
 
#titleTable td {
  width: 100px;
  height: 30px;
}
 
#titleTable td:nth-child(1) {
  width: 100px;
  height: 30px;
}
 
#titleTable td:nth-child(2) {
  width: 100px;
}
 
.chaxun {
  background-color: #D5EAFF;
  border: none;
}
 
.customClass {
  white-space: nowrap; /* 不换行 */
}
 
.el-text {
 
}
 
.el-col .el-select {
  width: 100%;
  height: 100%;
}
 
.el-col {
  text-align: center;
  border: #181818 1px solid;
}
.vxe-grid {
  /* 禁用浏览器默认选中 */
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}
 
::v-deep(.mytable-scrollbar .col-red) {
  background-color: rgb(66,159,254);
  color: #fff;
}
 
 
::v-deep(.latter) {
  //display: none;
}
</style>