于杰
2025-11-25 cfcec7e0d06c4ef942729a2b1b48f95f5cac61a6
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
<script setup>
import {nextTick, onMounted, reactive, ref, watch,onBeforeUnmount, provide } from "vue";
import {useI18n} from "vue-i18n";
import {Folder, Plus, Setting, Operation,} from "@element-plus/icons-vue";
import OptimizeCompute from "@/views/pp/glassOptimize/page/OptimizeCompute.vue";
import SetAmount from "@/views/pp/glassOptimize/page/SetAmount.vue";
import SetTrimming from "@/views/pp/glassOptimize/page/SetTrimming.vue";
import CheckInventory from "@/views/pp/glassOptimize/page/CheckInventory.vue";
import request from "@/utils/request";
import {ElMessage, ElMessageBox} from "element-plus";
import {useRoute, useRouter} from 'vue-router';
import useUserInfoStore from "@/stores/userInfo";
import useOrderInfoStore from "@/stores/sd/order/orderInfo";
import {addListener,toolbarButtonClickEvent} from "@/hook/mouseMove";
 
const { t } = useI18n();
const userStore = useUserInfoStore()
const orderInfo = useOrderInfoStore()
const username = userStore.user.userName
const router = useRouter()
 
let cellArea = ref()
const xGrid = ref()
const gridOptions = reactive({
  height: '100%',
  loading: false,
  border: "full",//表格加边框
  keepSource: true,//保持源数据
  align: 'center',//文字居中
  stripe: true,//斑马纹
  rowConfig: {isCurrent: true, isHover: true, height: 30, useKey: true},//鼠标移动或选择高亮
  id: 'ProjectDetail',
  scrollX: {enabled: true},
  scrollY: {enabled: true, gt: 0},//开启虚拟滚动
  showOverflow: true,
  columnConfig: {
    resizable: true,
    useKey: true
  },
  filterConfig: {   //筛选配置项
    remote: true
  },
  customConfig: {
    storage: true
  },
  editConfig: {
    trigger: 'dblclick',
    mode: 'row',
    showStatus: true
  },
 
  columns: [
    {type: 'seq', title: t('basicData.Number'), width: 80},
    {field: 'order_number', title: '订序', width: 70},
    {field: 'width',
      width: 100,
      title: t('order.width'),
      editRender: { name: 'input' },
      sortable: true
    },
    {
      field: 'height',
      width: 100,
      title: t('order.height'),
      editRender: { name: 'input' },
      sortable: true
    },
    {
      field: 'quantity',
      width: 150,
      title: t('order.quantity'),
      editRender: { name: 'input' },
      filters: [{data: ''}],
      slots: {filter: 'num1_filter'},
      sortable: true
    },
    {
      field: 'longGrind1',
      width: 150,
      title: '长磨1',
      editRender: { name: 'input' },filters:[{ data: '' }],slots: { filter: 'num1_filter' },
      sortable: true
    },
    {
      field: 'longGrind2',
      width: 150,
      title: '长磨2',
      editRender: { name: 'input' },filters:[{ data: '' }],slots: { filter: 'num1_filter' },
      sortable: true
    },
    {
      field: 'shortGrind1',
      width: 150,
      title: '短磨1',
      editRender: { name: 'input' },filters:[{ data: '' }],slots: { filter: 'num1_filter' },
      sortable: true
    },
    {
      field: 'shortGrind2',
      width: 150,
      title: '短磨2',
      editRender: { name: 'input' },filters:[{ data: '' }],slots: { filter: 'num1_filter' },
      sortable: true
    },
    {
      field: 'shape',
      width: 150,
      title: t('order.shape'),
      filters: [{data: ''}],
      slots: {filter: 'num1_filter'},
      sortable: true
    },
    {
      field: 'process_id',
      width: 150,
      title: '流程卡号',
      filters: [{data: ''}],
      slots: {filter: 'num1_filter'},
      sortable: true
    },
    {
      field: 'productName',
      width: 150,
      title: t('order.product'),
      filters: [{data: ''}],
      slots: {filter: 'num1_filter'},
      sortable: true
    },
    {
      field: 'price',
      width: 150,
      title: t('单价'),
      filters: [{data: ''}],
      slots: {filter: 'num1_filter'},
      sortable: true
    },
    {
      field: 'remark',
      width: 150,
      title: t('basicData.remarks'),
      filters: [{data: ''}],
      slots: {filter: 'num1_filter'},
      sortable: true
    },
    {
      field: 'buildingNumber',
      width: 150,
      title: '楼层号',
      filters: [{data: ''}],
      slots: {filter: 'num1_filter'},
      sortable: true
    },
    {
      field: 'perimeter',
      width: 150,
      title: t('order.perimeter'),
      filters: [{data: ''}],
      slots: {filter: 'num1_filter'},
      sortable: true
    },
    {
      field: 'area',
      width: 150,
      title: t('order.grossArea'),
      filters: [{data: ''}],
      slots: {filter: 'num1_filter'},
      sortable: true
    },
 
    {
      field: 'rackNo',
      width: 150,
      title: '架号',
      filters: [{data: ''}],
      slots: {filter: 'num1_filter'},
      sortable: true
    },
    {
      field: 'layer',
      width: 150,
      title: '层',
      filters: [{data: ''}],
      slots: {filter: 'num1_filter'},
      sortable: true
    },
    {
      field: 'glass_child',
      width: 150,
      title: '单片名称',
      filters: [{data: ''}],
      slots: {filter: 'num1_filter'},
      sortable: true
    },
    {
      field: 'markIcon',
      width: 150,
      title: '印标类型',
      filters: [{data: ''}],
      slots: {filter: 'num1_filter'},
      sortable: true
    },
  ],//表头参数
  data: null,//表格数据
  toolbarConfig: {
    buttons: [
    ],
    import: false,
    // export: true,
    // print: true,
    zoom: true,
    custom: true
  },
  //右键菜单
  menuConfig: {
    body: {
      options: [
        [
          {code: 'setAmount', name: '设置统一磨量',prefixIcon:'vxe-icon-edit'},
          {code: 'addRow', name: '添加临时小片', prefixIcon: 'vxe-icon-add', visible: true, disabled: false},
          {code: 'displayProcessCard', name: '显示流程卡',},
          {code: 'hideProcessCard', name: '隐藏流程卡',},
          {code: 'setShape', name: '设置图形',},
          {code: 'Export', name: '数据导出', prefixIcon: 'vxe-icon-download', visible: true, disabled: false},
          {code: 'safeDXF', name: '图形另存为DXF',},
          {code: 'exportOPTIMA', name: '导出数据到OPTIMA',},
          {
            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
          },
        ],
        []
      ]
    },
  },
})
const processCardColumns = reactive({
  columns:[
    {field: 'process_id', title: '流程卡', width: 200, align: 'center'},
    {field: 'project', title: '项目名', width: 150, align: 'center'},
    {field: 'order_number', title: '订序', width: 100, align: 'center'},
    {field: 'sizes', title: '尺寸', width: 200, align: 'center'},
    {field: 'layer', title: '层', width: 100, align: 'center'},
    {field: 'quantity', title: '数量', width: 100, align: 'center'}
  ],
  toolbarConfig: {
    buttons: [
    ],
    import: false,
    // export: true,
    // print: true,
 
  },
});
 
const checkAutoRedirectToOptimize = () => {
  // 检查路由中是否有自动跳转标识
  if (route.query.redirect === 'optimizeControl') {
    setTimeout(() => {
      const projectNo = route.params.projectNo || localStorage.getItem('currentProjectNo');
      if (projectNo) {
        router.push({
          name: 'OptimizeControl',
          params: {
            processId: projectNo
          }
        });
      }
    });
  }
};
 
 
// 右键菜单
const operationConfigs = [
  {
    code: 'setAmount', // 设置统一磨量
    successMsg: '已打开!',
    gridRef: xGrid,
    requiresRow: false,
    openAmount: async () => {
      dialogVisible.value[2] = true;
    }
  },
  {
    code: 'displayProcessCard',
    successMsg: '操作成功!',
    gridRef: xGrid,
    requiresRow: false,
    displayProcess: () => {
      getProcessCard();
      // 显示流程卡时,将 left-table 宽度改为 50%
      leftTableWidth.value = 60;
      showProcessCardTable.value = true;
    }
  },
  {
    code: 'hideProcessCard',
    successMsg: '操作成功!',
    gridRef: xGrid,
    requiresRow: false,
    hideProcess: () => {
      leftTableWidth.value = 100;
      showProcessCardTable.value = false;
    }
  },
  {
    code: 'setShape',
    successMsg: '操作成功!',
    gridRef: xGrid,
    requiresRow: false,
    showMessage: () => {
      ElMessage.info('此功能暂未完善,暂时无法执行设置图形操作。');
    }
  },
  {
    code: 'addRow',
    successMsg: '已添加',
    gridRef: xGrid,
    requiresRow: false,
    addNewRow: async () => {
      // 获取当前的磨量配置
      let currentGrindConfig = null;
      try {
        const res = await request.post(`/glassOptimize/getConfiguration/磨量/${username}`);
        if (res.code == "200" && res.data.data && res.data.data.length > 0) {
          const rawData = res.data.data[0];
          currentGrindConfig = {};
          for (const key in rawData) {
            if (typeof rawData[key] === 'string') {
              currentGrindConfig[key] = rawData[key].replace(/^\"|\"$/g, '');
            } else {
              currentGrindConfig[key] = rawData[key];
            }
          }
        }
      } catch (error) {
        console.warn('获取磨量配置失败:', error);
      }
 
      // 根据磨量配置设置默认值
      let defaultLongGrind1 = 0;
      let defaultLongGrind2 = 0;
      let defaultShortGrind1 = 0;
      let defaultShortGrind2 = 0;
 
      if (currentGrindConfig) {
        defaultLongGrind1 = parseFloat(currentGrindConfig.leftEdge) || 0;
        defaultLongGrind2 = parseFloat(currentGrindConfig.rightEdge) || 0;
        defaultShortGrind1 = parseFloat(currentGrindConfig.upEdge) || 0;
        defaultShortGrind2 = parseFloat(currentGrindConfig.downEdge) || 0;
      }
 
      // 创建新行数据,将 width、height、quantity 设置为数值类型
      const newRow = {
        order_number: 0,
        width: 0,
        height: 0,
        quantity: 0,
        longGrind1: defaultLongGrind1,
        longGrind2: defaultLongGrind2,
        shortGrind1: defaultShortGrind1,
        shortGrind2: defaultShortGrind2,
        shape: '',
        process_id: '',
        productName: '',
        price: 0,
        remark: '',
        buildingNumber: '',
        perimeter: 0,
        area: 0,
        rackNo: 1,
        layer: 1,
        glass_child: '',
        markIcon: '',
        processId: '',
        totalLayer: 0,
        patchState: 0,
        heatLayoutId: 0,
        process: '',
        orderNo: '',
        customerName: '',
        processingNote: '',
        projectName: ''
      };
 
      // 将新行添加到表格数据中
      const currentData = gridOptions.data || [];
      const updatedData = [...currentData, newRow];
      gridOptions.data = updatedData;
      xGrid.value.loadData(updatedData);
 
      // 获取新添加行的索引
      const newIndex = updatedData.length - 1;
 
      // 选中并编辑新行
      await nextTick();
      xGrid.value.setActiveRow(newRow);
    }
  },
  {
    code: 'safeDXF',
    successMsg: '操作成功!',
    gridRef: xGrid,
    requiresRow: false,
    showMessage: () => {
      ElMessage.info('此功能暂未完善,暂时无法执行图形另存为DXF操作。');
    }
  },
  {
    code: 'exportOPTIMA',
    successMsg: '操作成功!',
    gridRef: xGrid,
    requiresRow: false,
    showMessage: () => {
      ElMessage.info('此功能暂未完善,暂时无法执行导出数据到OPTIMA操作。');
    }
  },
  {
    code: 'copyChecked',
    successMsg: '操作成功!',
    gridRef: xGrid,
    requiresRow: false,
    hideProcess: () => {
    }
  },
  {
    code: 'copyAll',
    successMsg: '操作成功!',
    gridRef: xGrid,
    requiresRow: false,
    hideProcess: () => {
    }
  },
]
 
// 右键菜单点击逻辑
const gridEvents = {
  menuClick({menu}) {
    const $grid = xGrid.value;
    if ($grid) {
      const config = operationConfigs.find(c => c.code === menu.code);
      if (config) {
        if (config.code === 'Export') {
          config.gridRef.value.exportData();
          ElMessage.success(config.successMsg);
          return;
        }
        if (config.code === 'addRow') {
          // 添加确认提示弹窗,询问用户是否进行当前操作
          ElMessageBox.confirm('是否添加临时小片?', '确认操作', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            config.addNewRow();
            ElMessage.success(config.successMsg);
          }).catch(() => {
            ElMessage.info('已取消操作');
          });
          return;
        }
        if (config.code === 'copyChecked') {
          let result = toolbarButtonClickEvent()
          if(result){
            const dataList = xGrid.value.getTableData().visibleData
            let firstVal=null;
            if(result.cell.indexOf('.')>-1){
              firstVal = eval("dataList["+result.start +"]."+result.cell)
            }else {
              firstVal=dataList[result.start][result.cell];
            }
            dataList.forEach((item,index) =>{
              if(index>=result.start && index<=result.end){
                //取消选中
                if(parseInt(firstVal)<=0){
                  xGrid.value.setCheckboxRow(item, false);
                }
                if(result.cell.indexOf('.')>-1){
                  const  columnArr = result.cell.split('.')
                  item[columnArr[0]][columnArr[1]]  = firstVal
                }else{
                  item[result.cell]  = firstVal
                }
 
              }
            })
          }
          return;
        }
        if (config.code === 'copyAll') {
          let result = toolbarButtonClickEvent()
          if(result){
            const dataList = xGrid.value.getTableData().visibleData
            let firstVal=null;
            if(result.cell.indexOf('.')>-1){
              firstVal = eval("dataList["+result.start +"]."+result.cell)
            }else {
              firstVal=dataList[result.start][result.cell];
            }
            dataList.forEach((item,index) =>{
              if(index>=result.start){
                //取消选中
                if(parseInt(firstVal)<=0){
                  xGrid.value.setCheckboxRow(item, false);
                }
                if(result.cell.indexOf('.')>-1){
                  const  columnArr = result.cell.split('.')
                  item[columnArr[0]][columnArr[1]]  = firstVal
                }else{
                  item[result.cell]  = firstVal
                }
 
              }
            })
          }
          return;
        }
        // 添加确认提示弹窗,询问用户是否进行当前操作
        ElMessageBox.confirm('是否进行当前操作?', '确认操作', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if (config.code === 'setAmount') {
            config.openAmount();
            ElMessage.success(config.successMsg);
          } else if (config.code === 'displayProcessCard') {
            config.displayProcess();
            ElMessage.success(config.successMsg);
          } else if (config.code === 'hideProcessCard') {
            config.hideProcess();
            ElMessage.success(config.successMsg);
          } else if (['setShape', 'safeDXF', 'exportOPTIMA'].includes(config.code)) {
            config.showMessage();
          }
        }).catch(() => {
          // 用户点击取消后执行的逻辑
          ElMessage.info('已取消操作');
        });
      } else {
        console.error(`未找到操作选项 ${menu.code} 对应的配置,请检查配置项`);
      }
    }
  },
};
 
const handleCommand = async (command) => {
  if (command === 3) {
    // 执行模拟计算
    await emit('changeDialog', command);
 
  } else {
    // 其他命令直接执行
    await emit('changeDialog', command);
  }
};
 
let originalFilm=ref(true)
let surplusMaterial=ref(false)
 
//优化计算
const dialogVisible = ref({});
 
const optimizeData = ref({
  projectNo:null,
  allowRotate:null,
  cutOrigin:null,
  minCutDistance :null,
  optimizeMode:null,
  travType:null,
  rackCycleQty:null,
  glassThickness:null,
  glassType:null,
  glassDetails :[],
  materialDetails:[]
});
 
 
const openDialog = (index) => {
  if(index===4){
    if(parseInt(optimizeState.value)===1){
      ElMessage.warning("该工程已优化")
      return;
    }
    emit('getSmallPieceData', 1);
    optimizeData.value.glassDetails = [];
    // 从表格中获取 glassDetail 数据,而不是从后端接口读取
    const tableData = xGrid.value.getTableData().fullData;
    const glassDetailData = tableData.map(item => {
      let rackNoValue = 0;
      if (item.rackNo !== undefined && item.rackNo !== null && item.rackNo !== '') {
        rackNoValue = item.rackNo;
      }
      return {
        width: parseFloat(item.width) || 0,
        height: parseFloat(item.height) || 0,
        processId: item.processId,
        layer: item.layer,
        totalLayer: item.totalLayer,
        orderSort: item.order_number,
        markIcon: item.markIcon,
        quantity: parseInt(item.quantity) || 0,
        patchState: item.patchState,
        upGrind: item.longGrind1,
        downGrind: item.longGrind2,
        leftGrind: item.shortGrind1,
        rightGrind: item.shortGrind2,
        heatLayoutId: item.heatLayoutId,
        process: item.process,
        orderNo: item.orderNo,
        customerName: item.customerName,
        processingNote: item.processingNote,
        projectName: item.projectName,
        productName: item.productName,
        buildingNumber: item.buildingNumber,
        rackNo: rackNoValue
      };
    });
 
    // 更新 optimizeData 中的 glassDetails
    optimizeData.value.glassDetails = glassDetailData;
 
    // 打开优化对话框
    dialogVisible.value[4] = true;
 
  }else{
    dialogVisible.value[index] = true;
  }
};
 
//关闭弹窗
const closeDialog = (index) => {
  dialogVisible.value[index] = false;
};
 
//右键菜单统一修边
const props = defineProps({
  TrimmingDialogVisible: {
    type: [Boolean, Object],
    required: false,
    default: null
  },
  CheckboxChangeData: {
    type: Array,
    required: false,
    default: null
  }
});
 
 
const selectedGlassDataForTrimming = ref([]);
 
/*watch(() => props.TrimmingDialogVisible, (newValue) => {
  if (newValue === true) {
    dialogVisible.value[3] = newValue;
  }
});*/
 
watch(
    () => props.TrimmingDialogVisible,
    (newVal, oldVal) => {
      // 处理打开修边对话框的逻辑
      if (newVal != null && typeof newVal === 'object' && newVal.action === 'open-trimming-dialog') {
        dialogVisible.value[3] = true;
 
        // 更新选中的玻璃数据
        if (newVal.selectedData && newVal.selectedData.length > 0) {
          selectedGlassDataForTrimming.value = newVal.selectedData;
        } else {
          selectedGlassDataForTrimming.value = [];
        }
      }
    }
);
// 单独处理选中原片数据的逻辑
watch(
    () => props.CheckboxChangeData,
    (newData, oldData) => {
      // 只有当有选中数据时才处理
      if (newData != null && newData.length > 0) {
        optimizeData.value.materialDetails = [];
        newData.forEach(items => {
          const detail = {
            width: null,
            height: null,
            stockCode: null,
            quantity: null,
            upTrim: null,
            downTrim: null,
            leftTrim: null,
            rightTrim: null,
            priority: 0
          }
          detail.width = items.width
          detail.height = items.height
          detail.stockCode = items.id
          detail.quantity = items.available_quantity
          detail.upTrim = items.upTrim
          detail.downTrim = items.downTrim
          detail.leftTrim = items.leftTrim
          detail.rightTrim = items.rightTrim
 
          optimizeData.value.materialDetails.push(detail)
        })
        dialogVisible.value[4] = true;
      } else if (newData !== null && newData.length === 0) {
        // 只有当明确传入空数组时才提示选择原片
        ElMessage.warning('请选择原片');
      }
    }
);
 
 
const route = useRoute();
//工程号
const projectNo = ref(route.params.projectNo);
provide('projectNo', projectNo);
const projectName = ref('');
const thickNess = ref(route.params.thickNess);
const model = ref(route.params.model);
const quantitys = ref();
const areas = ref();
const optimizeState = ref(route.params.optimizeState);
onBeforeUnmount(() => {
  localStorage.setItem('projectNo', projectNo.value);
});
 
const saveOptimizeData = async () => {
  try {
    // 先从后端查询工程状态
    const stateRes = await request.post(`/glassOptimize/getProjectState/${projectNo.value}`);
    if (Number(stateRes.code) === 200) {
      const projectData = stateRes.data.data;
 
      // 检查 optimize_state 状态
      if (projectData.optimize_state === 1) {
        // 如果已完成优化,提示用户并阻止继续执行
        ElMessage.warning('已完成优化保存,不允许重复提交');
        return;
      }
    } else {
      ElMessage.warning(stateRes.msg);
      return;
    }
    if(orderInfo.optimizeData!==null){
      if(quantitys.value===orderInfo.optimizeData.optimalResults.glassTotalQuantity){
        console.log("保存数据1",orderInfo.optimizeData)
        request.post(`/glassOptimize/saveOptimizeData/${projectNo.value}`,orderInfo.optimizeData).then((res) => {
          if ((Number(res.code) === 200)) {
            ElMessage.success("保存成功");
          } else {
            ElMessage.warning(res.msg);
          }
        }).catch((error) => {
          console.error("获取数据出错:", error);
        });
      }else{
        ElMessage.warning("原片不足,小片未全部优化");
      }
    }else {
      ElMessage.warning("数据未优化");
    }
  } catch (error) {
    ElMessage.error('检查工程状态失败,请稍后重试');
    console.error('检查工程状态失败:', error);
  }
}
 
const fetchData = () => {
  //启用表格拖动选中
  addListener(xGrid.value,gridOptions,cellArea.value)
  request.post(`/glassOptimize/optimizeInfo/${projectNo.value}/${username}`).then((res) => {
    if ((Number(res.code) === 200)) {
      let data = res.data.data;
      const grindingTrimming = res.data.grindingTrimming;
      optimizeState.value=res.data.optimizeState;
 
      // 处理 grindingTrimming 数据(如果存在)
      let processedGrindConfig = null;
      if(grindingTrimming!==null && grindingTrimming.length > 0){
        // 处理 grindingTrimming 数据,去除双引号
        const formattedData = grindingTrimming.map(item => {
          const formattedItem = {};
          for (const key in item) {
            if (typeof item[key] === 'string') {
              //去除字符串属性值开头和结尾的双引号
              formattedItem[key] = item[key].replace(/^\"|\"$/g, '');
            } else {
              formattedItem[key] = item[key];
            }
          }
          return formattedItem;
        });
        processedGrindConfig = formattedData[0];
      }
 
      data = data.map(item => {
        // 直接将 grindingTrimming 中的磨量信息写到表中
        if (processedGrindConfig) {
          // 使用 grindingTrimming 中的配置设置磨量
          const leftEdge = parseFloat(processedGrindConfig.leftEdge) || 0;
          const rightEdge = parseFloat(processedGrindConfig.rightEdge) || 0;
          const upEdge = parseFloat(processedGrindConfig.upEdge) || 0;
          const downEdge = parseFloat(processedGrindConfig.downEdge) || 0;
 
          item.longGrind1 = leftEdge;   // 长磨1
          item.longGrind2 = rightEdge;  // 长磨2
          item.shortGrind1 = upEdge;    // 短磨1
          item.shortGrind2 = downEdge;  // 短磨2
 
          // 如果启用了自动填充功能,根据尺寸判断是否应用磨量
          if(processedGrindConfig.autoFillEdge === "true"){
            const minAutoLength = parseFloat(processedGrindConfig.minAutoLenght) || 0;
 
            // 如果宽度小于最小自动长度,不应用左右磨量
            if(item.width < minAutoLength){
              item.longGrind1 = 0;
              item.longGrind2 = 0;
            }
 
            // 如果高度小于最小自动长度,不应用上下磨量
            if(item.height < minAutoLength){
              item.shortGrind1 = 0;
              item.shortGrind2 = 0;
            }
          }
        } else {
          // 如果没有 grindingTrimming 数据,初始化为0
          item.longGrind1 = item.longGrind1 !== undefined && item.longGrind1 !== null ?
              parseFloat(item.longGrind1) : 0;
          item.longGrind2 = item.longGrind2 !== undefined && item.longGrind2 !== null ?
              parseFloat(item.longGrind2) : 0;
          item.shortGrind1 = item.shortGrind1 !== undefined && item.shortGrind1 !== null ?
              parseFloat(item.shortGrind1) : 0;
          item.shortGrind2 = item.shortGrind2 !== undefined && item.shortGrind2 !== null ?
              parseFloat(item.shortGrind2) : 0;
        }
 
        item.height=parseFloat(item.height.toFixed(2))
        item.width=parseFloat(item.width.toFixed(2))
 
        return item;
      });
 
      xGrid.value.loadData(data);
      gridOptions.data = data;
      projectName.value = data[0].project_name;
      quantitys.value=res.data.project.glass_total
      areas.value=res.data.project.glass_total_area
 
      // 更新 optimizeData 中的磨量配置
      updateOptimizeDataWithGrindingConfig(processedGrindConfig);
    } else {
      ElMessage.warning(res.msg);
    }
  }).catch((error) => {
    console.error("获取数据出错:", error);
  });
};
 
const updateOptimizeDataWithGrindingConfig = (grindConfig) => {
  if (grindConfig) {
    // 更新 optimizeData 中的磨量配置
    optimizeData.value.grindingConfig = {
      leftEdge: parseFloat(grindConfig.leftEdge) || 0,
      upEdge: parseFloat(grindConfig.upEdge) || 0,
      rightEdge: parseFloat(grindConfig.rightEdge) || 0,
      downEdge: parseFloat(grindConfig.downEdge) || 0,
      autoFillEdge: grindConfig.autoFillEdge === "true",
      minAutoLength: parseFloat(grindConfig.minAutoLenght) || 0
    };
  }
};
 
const firstLoading = async() => {
  request.post(`/glassOptimize/selectOptimizeParms/${username}`).then((res) => {
    if (res.code == "200") {
      const parsedData = JSON.parse(res.data);
      optimizeData.value.projectNo=projectNo.value
      optimizeData.value.glassType=model.value
      optimizeData.value.glassThickness=thickNess.value
      optimizeData.value.allowRotate=parsedData.optimization.smallPieceRotationProhibited
      optimizeData.value.optimizeMode=parsedData.optimization.optimizationMethod
      optimizeData.value.minCutDistance=parsedData.optimization.bendEdgeDistance
      optimizeData.value.cutOrigin=parsedData.optimization.cutterOriginPosition
      optimizeData.value.travType=parsedData.optimization.travType
      optimizeData.value.rackCycleQty=parsedData.optimization.rackCycleQty
    } else {
      ElMessage.warning(res.msg)
    }
  })
 
}
 
onMounted(() => {
  if (projectNo.value) {
    localStorage.setItem('currentProjectNo', projectNo.value);
    orderInfo.projectNo=route.params
    fetchData();
    firstLoading();
    checkAutoRedirectToOptimize();
  }else if(orderInfo.projectNo!==null){
    projectNo.value=orderInfo.projectNo.projectNo
    model.value=orderInfo.projectNo.model
    thickNess.value=orderInfo.projectNo.thickNess
    fetchData();
    firstLoading();
    checkAutoRedirectToOptimize();
  }
});
 
// 流程卡 宽度
const leftTableWidth = ref(100);
const showProcessCardTable = ref(false);
// 用于存储流程卡数据
const processCardData = ref(null);
//流程卡
const getProcessCard = () => {
  request.post(`/glassOptimize/getProcessCard/${projectNo.value}`).then((res) => {
    if (Number(res.code) === 200) {
      processCardData.value = res.data.data;
    } else {
      ElMessage.warning(res.msg);
    }
  });
};
 
 
// 从子组件SetAmount获取磨量值,并更新表格数据
const Amount = (amountData) => {
  // fetchData()
  const data = gridOptions.data;
  if (data) {
    const updatedData = data.map(item => ({
      ...item,
      longGrind1: Number(amountData.quicksetTop),
      longGrind2: Number(amountData.quicksetRight),
      shortGrind1: Number(amountData.quicksetBottom),
      shortGrind2: Number(amountData.quicksetLeft)
    }));
    gridOptions.data = updatedData;
    xGrid.value.loadData(updatedData);
  }
  /*nextTick(() => {
    const data = gridOptions.data;
    if (data) {
      try {
        const updatedData = [];
        for (let i = 0; i < data.length; i++) {
          const item = data[i];
          const updatedItem = {
            ...item,
            longGrind1: Number(amountData.quicksetTop),
            longGrind2: Number(amountData.quicksetRight),
            shortGrind1: Number(amountData.quicksetBottom),
            shortGrind2: Number(amountData.quicksetLeft)
          };
          updatedData.push(updatedItem);
        }
        gridOptions.data = updatedData;
        xGrid.value.loadData(updatedData);
      } catch (error) {
        console.error('更新表格数据时出错:', error);
        // 这里可以根据实际需求添加一些回滚操作或者提示用户的逻辑,比如显示一个错误提示框等
        ElMessage.error('更新磨量数据时出现错误,请检查输入或联系管理员');
      }
    } else {
      console.warn('表格数据为空,无法更新磨量值');
    }
  });*/
};
 
const grindingConfig = ref(null);
 
const loadGrindingConfiguration = async () => {
  return new Promise((resolve) => {
    request.post(`/glassOptimize/getConfiguration/磨量/${username}`).then((res) => {
      if (res.code == "200") {
        const rawData = res.data.data;
        if (Array.isArray(rawData) && rawData.length > 0) {
          const formattedData = rawData.map(item => {
            const formattedItem = {};
            for (const key in item) {
              if (typeof item[key] === 'string') {
                //去除字符串属性值开头和结尾的双引号
                formattedItem[key] = item[key].replace(/^\"|\"$/g, '');
              } else {
                formattedItem[key] = item[key];
              }
            }
            return formattedItem;
          });
          // 保存磨量配置
          grindingConfig.value = formattedData[0];
          resolve(formattedData[0]);
        } else {
          const defaultConfig = {
            leftEdge: '0',
            upEdge: '0',
            rightEdge: '0',
            downEdge: '0',
            quickEdge: '1',
            autoFillEdge: 'false',
            minAutoLenght: '0'
          };
          grindingConfig.value = defaultConfig;
          resolve(defaultConfig);
        }
      } else {
        ElMessage.warning(res.msg);
        const defaultConfig = {
          leftEdge: '0',
          upEdge: '0',
          rightEdge: '0',
          downEdge: '0',
          quickEdge: '1',
          autoFillEdge: 'false',
          minAutoLenght: '0'
        };
        grindingConfig.value = defaultConfig;
        resolve(defaultConfig);
      }
    }).catch(() => {
      const defaultConfig = {
        leftEdge: '0',
        upEdge: '0',
        rightEdge: '0',
        downEdge: '0',
        quickEdge: '1',
        autoFillEdge: 'false',
        minAutoLenght: '0'
      };
      grindingConfig.value = defaultConfig;
      resolve(defaultConfig);
    });
  });
};
 
//中转站接受SetTrimming的值(设置修边)
const emit = defineEmits([
  'changeDialog',
  'forward-data-to-grandparent',
  'send-inventory-to-op'
]);
 
const handleTrimmingData = (data) => {
  emit('forward-data-to-grandparent', data);
};
 
//中转站接受CheckInventory的值(查询库存)
const handleInventory = (selectedLabel1, selectedLabel2) => {
  let type=0;
  if(originalFilm.value===true&&surplusMaterial.value===true){
    type=3
  }else if(originalFilm.value===true&&surplusMaterial.value===false){
    type=1
  }else if(originalFilm.value===false&&surplusMaterial.value===true){
    type=2
  }else{
    type=1
  }
  emit('send-inventory-to-op', selectedLabel1, selectedLabel2,type);
}
 
</script>
 
<template>
  <div style="width: 100%;height: 85%;">
    <!-- 头部 -->
    <div id="header" >
      <!--工程文件菜单-->
      <el-dropdown @command="handleCommand">
        <el-button type="primary" :icon="Folder" style="margin-top: 8px; margin-left: 5px">
          工程文件
        </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item :command="1" :icon="Plus">创建工程</el-dropdown-item>
            <el-dropdown-item :command="2" :icon="Setting">工程管理</el-dropdown-item>
            <el-dropdown-item :command="3" :icon="Operation">模拟计算</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
 
      <div id="title">
        <span>工程编号:</span>
        <el-input readonly placeholder="" style="width: 150px" v-model="projectNo"></el-input>&nbsp;
        <span>工程名称:</span>
        <el-input readonly placeholder="" style="width: 150px; margin-right: 140px;" v-model="projectName" ></el-input>
        原片<el-checkbox v-model="originalFilm" ></el-checkbox>
        余料<el-checkbox v-model="surplusMaterial" ></el-checkbox>&nbsp;&nbsp;
        <el-button id="checkinventory" type="primary" @click="openDialog(1)">查询库存</el-button>
        <el-dialog v-model="dialogVisible[1]" title="查询库存" destroy-on-close style="width: 35%;height:35%;">
          <check-inventory :closeDialog="closeDialog" :thickNess="thickNess" :model="model"
                           @send-data-inventory="handleInventory"/>
        </el-dialog>
        <el-button id="button" type="primary" @click="openDialog(2)">设置磨量</el-button>
        <el-dialog v-model="dialogVisible[2]" title="设置磨量(mm)" destroy-on-close
                   style="width: 35%;height:80%;margin-top: 3vh;">
          <set-amount :closeDialog="closeDialog" @set-amount="Amount"/>
        </el-dialog>
        <el-button id="button" type="primary" @click="openDialog(3)">设置修边</el-button>
        <el-dialog v-model="dialogVisible[3]" title="设置修边(mm)" destroy-on-close
                   style="width: 35%;height:80%;margin-top: 3vh;">
          <set-trimming
              :closeDialog="closeDialog"
              :selected-glass-data="selectedGlassDataForTrimming"
              @send-data-event="handleTrimmingData"/>
        </el-dialog>
        <el-button id="button" type="primary" @click="saveOptimizeData()">保存</el-button>
        <el-button id="button" type="primary" @click="openDialog(4)">优化</el-button>
        <el-dialog v-model="dialogVisible[4]" title="优化计算" destroy-on-close
                   style="width: 75%;height:90%;margin-top: 3vh;">
          <optimize-compute :quantity="quantitys" :area="areas" :optimizeData="optimizeData"
                            @send-data-event="handleTrimmingData"/>
        </el-dialog>
      </div>
    </div>
 
    <!-- 表格容器 -->
    <div class="table-container">
      <vxe-grid
          class="left-table"
          @filter-change="filterChanged"
          height="100%"
          ref="xGrid"
          v-bind="gridOptions"
          v-on="gridEvents"
          v-bind:style="{ width: leftTableWidth + '%' }"
      >
        <template #num2_filter="{ column, $panel }">
          <div>
            <div v-for="(option, index) in column.filters" :key="index">
              <vxe-select v-model="option.data" :placeholder="$t('processCard.pleaseSelect')"
                          @change="changeFilterEvent($event, option, $panel)">
                <vxe-option value="0" :label="$t('basicData.unchecked')"></vxe-option>
                <vxe-option value="1" :label="$t('basicData.selected')"></vxe-option>
              </vxe-select>
            </div>
          </div>
        </template>
        <template #num1_filter="{ column, $panel }">
          <div>
            <div v-for="(option, index) in column.filters" :key="index">
              <input
                  type="type"
                  v-model="option.data"
                  @keyup.enter.native="$panel.confirmFilter()"
                  @input="changeFilterEvent($event, option, $panel)"/>
            </div>
          </div>
        </template>
      </vxe-grid>
 
      <!-- 流程卡表格 -->
      <vxe-grid
          height="100%"
          class="right-table"
          :data="processCardData"
          v-bind="processCardColumns"
          v-if="showProcessCardTable"
          :header-cell-style="{'height': '51.9px'}"
      >
      </vxe-grid>
 
    </div>
    <div class="vxe-table--cell-area" ref="cellArea" >
      <span  class="vxe-table--cell-main-area"  ></span>
 
      <span class="vxe-table--cell-active-area"  ></span>
    </div>
  </div>
</template>
 
<style scoped>
.table-container {
  width: 100%;
  height: 100%;
  flex: 1;
  display: flex;
}
 
.left-table {
  float: left;
}
 
.right-table {
  width: 40%;
}
 
:deep(.vxe-toolbar){
  height: 40px;
}
 
#header {
  height: 50px;
  display: flex;
 
}
 
#title {
  margin: 8px 5px;
  width: 1240px;
}
 
#button {
  margin-left: 10px;
}
 
.vxe-grid {
  /* 禁用浏览器默认选中 */
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}
 
</style>