于杰
9 天以前 9599b7f0354e0654d522fe4303ade7dd7aaa3680
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
<script setup>
import {computed, nextTick, reactive, ref} from "vue";
import {useI18n} from "vue-i18n";
import deepClone from "@/utils/deepClone"
import {Search} from "@element-plus/icons-vue";
import request from "@/utils/request";
import {ElDatePicker, ElMessage, ElMessageBox} from "element-plus";
import useOrderInfoStore from "@/stores/sd/order/orderInfo";
import useUserInfoStore from "@/stores/userInfo";
import userInfo from "@/stores/userInfo";
import {useRouter} from 'vue-router';
import {defineEmits} from 'vue';
import {changeFilterEvent, filterChanged} from "@/hook";
 
 
const {t} = useI18n()
const userStore = useUserInfoStore()
const user = userInfo()
const orderInfo = useOrderInfoStore()
 
const router = useRouter();
 
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: 'ProjectMange',
  scrollX: {enabled: true},
  scrollY: {enabled: true, gt: 0},//开启虚拟滚动
  showOverflow: true,
  columnConfig: {
    resizable: true,
    useKey: true
  },
  filterConfig: {   //筛选配置项
    //remote: true
  },
  customConfig: {
    storage: true
  },
  editConfig: {
    trigger: 'click',
    mode: 'row',
    showStatus: true
  },
 
  columns: [
    {type: 'seq', title: t('basicData.Number'), width: 80},
    {field: 'projectNumber', width: 100, title: '工程号',sortable: true,showOverflow:'ellipsis' ,filters:[{ data: '' }],slots: { filter: 'num1_filter' },filterMethod:filterChanged},
    {field: 'projectName', width: 50, title: '名称',},
    {field: 'glassType', width: 50, title: '膜系',},
    {field: 'thickness', width: 50, title: '厚度',},
    {field: 'type', width: 50, title: '类型',},
    {field: 'state', width: 50, title: '状态',},
    {field: 'temperingState', width: 50, title: '钢化模拟', filters: [{data: ''}], slots: {filter: 'select_filter1'},
      filterMethod:filterChanged, formatter: ({ cellValue }) => cellValue === 1 ? '是' : (cellValue === 0 ? '否' : cellValue)},
    {field: 'optimizeState', width: 50, title: '优化计算', filters: [{data: ''}], slots: {filter: 'select_filter1'},
      filterMethod:filterChanged, formatter: ({ cellValue }) => cellValue === 1 ? '是' : (cellValue === 0 ? '否' : cellValue)},
    {field: 'quantity', width: 50, title: '数量',},
    {field: 'area', width: 50, title: '面积',},
    {field: 'processCardQuantity', width: 100, title: '流程卡数量',},
    {field: 'usingQuantity', width: 100, title: '原片使用数',},
    {field: 'processCardCollection', width: 70, title: '流程卡',filters: [{data: ''}], slots: {filter: 'num1_filter'},filterMethod:filterChanged},
    {field: 'temperedLoadingRate', width: 100, title: '钢化装载率',},
    {field: 'numberOfTemperingFurnaces', width: 100, title: '钢化炉数',},
    {field: 'averageCuttingRate', width: 100, title: '平均切裁率',},
    {field: 'effectiveCuttingRate', width: 100, title: '有效切裁率',},
    {field: 'residueGlassCuttingRate', width: 100, title: '尾片切裁率',},
    {field: 'amountOfOriginalGlassUsage1', width: 100, title: '原料使用数',},
    // {field: 'averageCuttingRate1', width: 100, title: '平均切裁率',},
    {field: 'notes', width: 50, title: '备注',},
    {field: 'creator', width: 100, title: '创建人',},
    {field: 'createTime', width: 100, title: '创建时间',},
    {field: 'modifyTime', width: 100, title: '修改时间',},
  ],//表头参数
  data: null,//表格数据
  toolbarConfig: {
    buttons: [
    ],
    import: false,
    // export: true,
    // print: true,
    zoom: true,
    custom: true
  },
  //右键菜单选项
  menuConfig: {
    body: {
      options: [
        [
          {code: 'openProject', name: '打开工程', prefixIcon: 'vxe-icon-folder-open'},
          {code: 'compute', name: '模拟计算', prefixIcon: 'vxe-icon-subtable'},
          //{code: 'optimizeTypography', name: '优化排版', prefixIcon: 'vxe-icon-menu'},
          {code: 'production', name: '确认生产', prefixIcon: 'vxe-icon-square-checked'},
          {code: 'novisible', name: '取消生产', prefixIcon: 'vxe-icon-eye-fill-close'},
          {code: 'copyproject', name: '复刻工程', prefixIcon: 'vxe-icon-copy'},
          {code: 'undoOptimize', name: '撤销优化', prefixIcon: 'vxe-icon-error-circle-fill'},
          {code: 'undoCompute', name: '撤销模拟计算', prefixIcon: 'vxe-icon-error-circle-fill'},
          {code: 'InitializeProject', name: '初始化工程', prefixIcon: 'vxe-icon-undo'},
          {code: 'delProject', name: '删除工程', prefixIcon: 'vxe-icon-delete'},
          {code: 'viewTempered', name: '查看钢化版图', prefixIcon: 'vxe-icon-custom-column'},
          {code: 'viewOptimize', name: '查看优化版图', prefixIcon: 'vxe-icon-layout'},
          {code: 'Export', name: '数据导出', prefixIcon: 'vxe-icon-download', visible: true, disabled: false},
          {code: 'print', name: '打印优化报告', prefixIcon: 'vxe-icon-layout'},
          {code: 'print2', name: '打印优化版图报告', prefixIcon: 'vxe-icon-layout'},
 
        ],
        []
      ]
    },
  },
})
// 定义操作配置对象数组,集中管理不同操作选项对应的参数
const operationConfigs = [
  {
    code: 'openProject', // 打开工程
    initialState: ['1', '100', '200'], //
    targetState: null,
    successMsg: '已打开!',
    checkMessage: '当前工程状态不符合条件,请确认工程状态后再操作!',
    requiresRow: true,
    openFile: async ({row}) => {
      orderInfo.optimizeData.optimalResults=null
      orderInfo.optimizeData.originalFilm=null
      const projectNumber = row.projectNumber;
      const thickness = row.thickness;
      const glassType = row.glassType;
      const quantity = row.quantity;
      const area = row.area;
      const optimizeState = row.optimizeState;
      await router.push({
        name: 'optimizeInfo',
        params: {
          projectNo: projectNumber,
          thickNess: thickness,
          model: glassType,
          quantity: quantity,
          area: area,
          optimizeState:optimizeState
        }
      });
    }
  },
  {
    code: 'compute', // 打开模拟计算操作
    initialState: '1',
    temperingState: '0',
    targetState: null,
    successMsg: '模拟计算已启动!',
    checkMessage: '当前工程状态不符合模拟计算条件,请确认工程状态后再操作!',
    requiresRow: true,
    actionFunction: async ({row}) => {
      const projectNo = row.projectNumber;
      emit('switch-dialog', row);
    }
  },
  {
    code: 'print', // 打印
    initialState: '1',
    temperingState: '0',
    targetState: null,
    successMsg: '模拟计算已启动!',
    checkMessage: '当前工程状态不符合模拟计算条件,请确认工程状态后再操作!',
    requiresRow: true,
    actionFunction: async ({row}) => {
      const projectNo = row.projectNumber;
      emit('switch-dialog-print', row);
    }
  },
  {
    code: 'print2', // 打印
    initialState: '1',
    temperingState: '0',
    targetState: null,
    successMsg: '模拟计算已启动!',
    checkMessage: '当前工程状态不符合模拟计算条件,请确认工程状态后再操作!',
    requiresRow: true,
    actionFunction: async ({row}) => {
      const projectNo = row.projectNumber;
      emit('switch-dialog-print2', row);
    }
  },
  {
    code: 'optimizeTypography',
    initialState: ['1','100'], //
    targetState: null,
    successMsg: '优化排版已启动!',
    checkMessage: '当前工程状态不符合优化排版条件,请确认工程状态后再操作!',
    requiresRow: true,
    Typography: async ({row}) => {
      const projectNumber = row.projectNumber;
      const thickness = row.thickness;
      const glassType = row.glassType;
      const quantity = row.quantity;
      const area = row.area;
      const optimizeState = row.optimizeState;
      await router.push({
        name: 'optimizeInfo',
        params: {
          projectNo: projectNumber,
          thickNess: thickness,
          model: glassType,
          quantity: quantity,
          area: area,
          optimizeState:optimizeState
        }
      });
    }
  },
  {
    code: 'undoCompute',
    initialState: 1,
    temperingState: 1,
    targetState: 0,
    targetStates: 0,
    successMsg: '撤销模拟计算成功,数据已更新!',
    checkMessage: '当前工程状态不符合撤销模拟计算条件,请确认工程状态后再操作!',
    requiresRow: true,
  },
  {
    code: 'undoOptimize',
    initialState: 1,
    optimizeState: 1,
    targetState: 0,
    targetStates: 0,
    successMsg: '撤销优化成功,数据已更新!',
    checkMessage: '当前工程状态不符合撤销优化条件,请确认工程状态后再操作!',
    requiresRow: true,
  },
  {
    code: 'production',
    initialState: 1,
    // temperingState: 1,
    optimizeState: 1,
    targetState: 100,
    targetStates: 0,
    successMsg: '设置成功,允许生产!',
    checkMessage: '当前工程状态不符合允许生产条件,请确认工程状态后再操作!',
    requiresRow: true,
  },
  {
    code: 'novisible',
    initialState: 100,
    // temperingState: 1,
    optimizeState: 1,
    targetState: 1,
    targetStates: 0,
    successMsg: '设置成功,生产不可见!',
    checkMessage: '当前工程状态不符合生产不可见条件,请确认工程状态后再操作!',
    requiresRow: true,
  },
  {
    code: 'InitializeProject',
    initialState: '2',
    targetState: 1,
    successMsg: '初始化工程成功!',
    checkMessage: '当前工程状态不符合初始化条件,请确认工程状态后再操作!',
    requiresRow: true,
  },
  {
    code: 'delProject',
    initialState: ['1', '100'],
    targetState: null,
    successMsg: '工程删除成功!',
    checkMessage: '当前工程状态不符合删除条件,请确认工程状态后再操作!',
  },
  {
    code: 'Export', // 导出文件操作的配置
    initialState: [],
    targetState: null,
    successMsg: '文件导出成功!',
    gridRef: xGrid,
    requiresRow: false,
  },
  {
    code: 'viewTempered',
    initialState: [],
    targetState: null,
    successMsg: '钢化版图已打开!',
    failureMsg: '工程删除失败,请联系管理员!',
    requiresRow: true,
  },
  {
    code: 'viewOptimize',
    initialState: [],
    targetState: null,
    successMsg: '优化版图已打开!',
    failureMsg: '工程删除失败,请联系管理员!',
    requiresRow: true,
  }
];
 
function getOriginalState(targetState) {
  // 根据工程状态返回对应的原始状态
  const stateMapping = {
    1: '100',
    100: '1'
  };
  return stateMapping[targetState] || targetState;
}
 
//右键菜单条件判断
function checkOperationCondition(config, row) {
  if (!config.requiresRow || !row) {
    return false;
  }
  if (Array.isArray(config.initialState)) {
    return config.initialState.includes(String(row.state));
  }
  return config.initialState === String(row.state);
}
 
// 右键菜单点击事件
const gridEvents = {
  menuClick({menu, row}) {
    const $grid = xGrid.value;
    if ($grid) {
      const config = operationConfigs.find(c => c.code === menu.code);
      if (config) {
        if (config.requiresRow && !row) {
          ElMessage.warning('未选中工程,请选中工程后再进行当前操作!');
          return;
        }
        if (config.code === 'Export') {
          config.gridRef.value.exportData();
          ElMessage.success(config.successMsg);
          return;
        }
        if (config.code === 'compute') {
          // 增加逻辑:检查钢化模拟列是否已经是"是"
          if (row.temperingState === 1) {
            ElMessage.warning('该项目已模拟计算');
            return;
          }
          if(row.state===1 && row.temperingState===0){
            config.actionFunction({row});
          }else{
            ElMessage.warning(config.checkMessage);
          }
          return;
        }
        if (config.code === 'print') {
          if(row.optimizeState===1 ){
            config.actionFunction({row});
          }else{
            ElMessage.warning(config.checkMessage);
          }
          return;
        }
        if (config.code === 'print2') {
          if(row.optimizeState===1 ){
            config.actionFunction({row});
          }else{
            ElMessage.warning(config.checkMessage);
          }
          return;
        }
        else if (config.code === 'openProject') {
          handleSameDataOperation(row).then(({isRoutesEqual}) => {
            if (!isRoutesEqual) {
              config.openFile({row});
              ElMessage.success(config.successMsg);
 
            }
          });
          return;
        }
        // 添加确认提示弹窗,询问用户是否进行当前操作
        ElMessageBox.confirm('是否进行当前操作?', '确认操作', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if (config.code === 'viewTempered') {
            ElMessageBox.alert('当前点击的是查看钢化版图功能,目前暂时仅做提示,暂无实际查看操作!', '功能提示', {
              confirmButtonText: '我知道了'
            });
            return;
          }
          if (config.code === 'viewOptimize') {
            (async () => {
              if (!row) {
                ElMessage.warning('请选择要查看的工程');
                return;
              }
 
              try {
                await router.push({
                  name: 'optimizeInfo',
                  params: {
                    projectNo: row.projectNumber,
                    thickNess: row.thickness,
                    model: row.glassType,
                    quantity: row.quantity,
                    area: row.area,
                    optimizeState: row.optimizeState
                  },
                  query: {
                    redirect: 'optimizeControl' // 添加跳转标识
                  }
                });
 
                // 同时保存 projectNo 到 localStorage 供后续页面使用
                localStorage.setItem('projectNo', row.projectNumber);
                console.log("projectNo:", row.projectNumber);
              } catch (error) {
                console.error('路由跳转失败:', error);
                ElMessage.error('页面跳转失败');
              }
            })();
            return;
          }
          if (config.code === 'delProject') {
            if (!row) {
              ElMessage.warning(config.checkMessage);
              return;
            }
            const isInitialStateMatched = config.initialState.includes(String(row.state));
            if (!isInitialStateMatched) {
              ElMessage.warning(config.checkMessage);
              return;
            }
            deleteProject(row.projectNumber, config);
          }else {
            if (config.code === 'optimizeTypography') {
              handleSameDataOperation(row).then(({isRoutesEqual}) => {
                if (!isRoutesEqual) {
                  config.Typography({row});
                  ElMessage.success(config.successMsg);
                  return;
                }
              });
            }
            else {
              let code=0
 
              if(config.code === 'undoCompute'){
                if(row.temperingState==1&&row.state===1){
                  row.temperingState = config.targetStates;
                  code=1
                }else{
                  ElMessage.warning(config.checkMessage);
                  return;
                }
              }else if(config.code === 'undoOptimize'){
                if(row.optimizeState==1&&row.state===1){
                  // 先更新前端显示的状态
                  row.optimizeState = config.targetStates;
                  code=2;
 
                  // 更新列表中的数据以刷新显示
                  const index = produceList.value.findIndex(item => item === row);
                  if (index !== -1) {
                    produceList.value.splice(index, 1, {...row});
                    xGrid.value.reloadData(produceList.value);
                  }
 
                }else{
                  ElMessage.warning(config.checkMessage);
                  return;
                }
              }
              else if(config.code === 'production'){
                if(row.optimizeState===1&&row.state===1){
                  row.state = config.targetState;
                  code=3
                }else{
                  ElMessage.warning(config.checkMessage);
                  return;
                }
              }
              else if(config.code === 'novisible'){
                if(row.state===100){
                  row.state = config.targetState;
                  code=4
                }else{
                  ElMessage.warning(config.checkMessage);
                  return;
                }
              }
              const index = produceList.value.findIndex(item => item === row);
              if (index !== -1) {
                produceList.value.splice(index, 1, {...row});
                xGrid.value.reloadData(produceList.value);
              }
              updateProjectStateAndHandleResponse(row, row.projectNumber, config.targetState,config.targetStates,code, config.successMsg);
            }
          }
        }).catch(() => {
          // 用户点击取消后执行的逻辑
          ElMessage.info('已取消操作');
        });
      } else {
        console.error(`未找到操作选项 ${menu.code} 对应的配置,请检查配置项`);
      }
    }
  },
  cellDblclick: ({row}) => {
    const menu = {code: 'openProject'};
    nextTick(() => {
      handleSameDataOperation(row).then(({isRoutesEqual}) => {
        if (!isRoutesEqual) {
          gridEvents.menuClick({menu, row});
        }
      });
    });
  },
};
 
// 公共处理函数,处理相同数据时的操作,并返回targetRoute对象(右键菜单和双击打开)
const handleSameDataOperation = async ({projectNumber, thickness, glassType,quantity,area,optimizeState}) => {
  const targetRoute = {
    name: 'optimizeInfo',
    params: {
      projectNo: projectNumber,
      thickNess: String(thickness),
      model: glassType,
      quantity: quantity,
      area: area,
      optimizeState:optimizeState
    }
  };
  const currentRoute = router.currentRoute.value;
  console.log(router.currentRoute.value)
  console.log(targetRoute)
  const isRoutesEqual = currentRoute.name === targetRoute.name &&
      currentRoute.params.projectNo === targetRoute.params.projectNo &&
      parseFloat(currentRoute.params.thickNess) === parseFloat(targetRoute.params.thickNess) &&
      currentRoute.params.model === targetRoute.params.model &&
      parseInt(currentRoute.params.quantity) === parseInt(targetRoute.params.quantity) &&
      parseFloat(currentRoute.params.area) === parseFloat(targetRoute.params.area)&&
      parseFloat(currentRoute.params.optimizeState) === parseFloat(targetRoute.params.optimizeState);
  if (isRoutesEqual) {
    handleConfirm();
  }
  return {isRoutesEqual};
};
//选中相同数据时弹窗提示
const handleConfirm = () => {
  const currentRoute = router.currentRoute.value;
  const projectNumber = currentRoute.params.projectNo;
  ElMessageBox.confirm(`当前工程(工程号:${projectNumber})已打开,是否重新打开?`, '确认操作', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
      .then(() => {
        emit('close-detail-page');
        ElMessage.success('已打开!');
      })
      .catch(() => {
        ElMessage.info('已取消操作');
      });
};
 
 
// 封装发送右键菜单请求、处理响应以及错误回滚等逻辑的函数
function rollbackStateAndReloadGrid(row, targetState) {
  row.state = getOriginalState(targetState);
  const rollbackIndex = produceList.value.findIndex(item => item === row);
  if (rollbackIndex !== -1) {
    produceList.value.splice(rollbackIndex, 1, {...row});
    xGrid.value.reloadData(produceList.value);
  }
}
 
function updateProjectStateAndHandleResponse(row, projectNumber, targetState, targetStates, code, successMsg) {
  const updateParams = {
    projectNumber: projectNumber,
    stateToUpdate: targetState,
    targetStates: targetStates
  };
  request.post(`/glassOptimize/updateProjectState/${projectNumber}/${targetState}/${targetStates}/${code}`, updateParams, {
    headers: {
      'Content-Type': 'application/json'
    }
  }).then((res) => {
    // 检查业务状态码,如果是201则抛出错误以在catch中处理
    if (Number(res.code) === 201) {
      // 抛出自定义错误对象,包含后端返回的msg信息
      throw new Error(res.msg || '操作失败');
    }
    if (Number(res.code) === 200 && (res.msg === "" || res.msg === null)) {
      ElMessage.success(successMsg);
    } else {
      console.log('res.code 的值:', res.code, ', 类型:', typeof res.code);
      console.log('res.msg 的值:', res.msg, ', 类型:', typeof res.msg);
      const errorMsg = res.data ? res.data.errorMessage : '操作失败,未获取到具体原因,请联系管理员';
      ElMessage.error(`操作失败,原因: ${errorMsg}`);
      rollbackStateAndReloadGrid(row, targetState); // 调用回滚函数
    }
  }).catch((error) => {
    console.error('请求出错,操作未完成,详细错误信息:', error);
    //const errorMsg = (res.data && res.data.errorMessage) ? res.data.errorMessage : '操作失败,未获取到具体原因,请联系管理员';
    ElMessage.error(`请求出错,操作未完成  `+error);
    rollbackStateAndReloadGrid(row, targetState); // 调用回滚函数
  });
}
 
//删除工程
function deleteProject(projectNumber, config) {
  request.post(`/glassOptimize/deleteProject/${projectNumber}`, {
    headers: {
      'Content-Type': 'application/json'
    }
  }).then((res) => {
    if (res.code==200 && res.data===true) {
      ElMessage.success(config.successMsg);
      // 从列表中移除已删除的工程数据
      const index = produceList.value.findIndex(item => item.projectNumber === projectNumber);
      if (index !== -1) {
        produceList.value.splice(index, 1);
        xGrid.value.reloadData(produceList.value);
      }
    } else {
      console.log('res.code 的值:', res.code, ', 类型:', typeof res.code);
      console.log('res.msg 的值:', res.msg, ', 类型:', typeof res.msg);
      const errorMsg = res.data ? res.data.errorMessage : config.failureMsg;
      ElMessage.error(`操作失败,原因: ${errorMsg}`);
    }
  }).catch((error) => {
    console.error('请求出错,工程删除未完成,详细错误信息:', error);
    const errorMsg = (res.data && res.data.errorMessage) ? res.data.errorMessage : config.failureMsg;
    ElMessage.error(`请求出错,工程删除未完成,原因: ${errorMsg}`);
  });
}
 
//定义切换模拟计算弹窗
const emit = defineEmits(['switch-dialog', 'close-detail-page','switch-dialog-print','switch-dialog-print2']);
 
//定义工程状态
const optionVal = ref('all')
const options = [
  {
    value: 'all',
    label: '全部',
  },
  {
    value: '1',
    label: '初始状态,1',
  },
  /*{
    value: '2',
    label: '第一次优化,2',
  },
  {
    value: '10',
    label: '模拟计算,10',
  },
  {
    value: '20',
    label: '优化完成,20',
  },*/
  {
    value: '100',
    label: '生产可见,100',
  },
  {
    value: '200',
    label: '生产领取,200',
  },
]
 
//工程状态函数
function handleOptionChange() {
  if (optionVal.value === 'all') {
    // 清空工程状态相关的已有筛选条件
    delete filterData.value['state'];
  } else {
    filterData.value['state'] = optionVal.value; // 明确添加选择的工程状态值到筛选条件中
  }
  getWorkOrder();
}
 
//公共函数
function buildRequestParams() {
  let startSelectTime = orderInfo.workOrderDate[0];
  let endSelectTime = orderInfo.workOrderDate[1];
 
  const params = {
    startSelectTime,
    endSelectTime,
  };
 
  return params;
}
 
//筛选条件
let filterData = ref({
  projectNumber: '',
})
// 定义数据返回结果,使用ref创建响应式数据,初始化为空数组
let produceList = ref([])
 
// 获取15天前到当前时间
function getNowTime() {
  const start = new Date(new Date().getTime() - 3600 * 1000 * 24 * 70)
      .toISOString()
      .replace('T', ' ')
      .slice(0, 10) //默认开始时间15天前
  const end = new Date(new Date().getTime())
      .toISOString()
      .replace('T', ' ')
      .slice(0, 10)//默认结束时间当前时间
  return [start, end]
}
 
// 初始化时间范围,若为空则设为近15天时间
if (orderInfo.workOrderDate[0] === "" && orderInfo.workOrderDate[1] === "") {
  orderInfo.workOrderDate = getNowTime();
}
//获取选中时间
let startSelectTime = orderInfo.workOrderDate[0]
let endSelectTime = orderInfo.workOrderDate[1]
// 首次加载数据
request.post(`/glassOptimize/optimizeProjectMange/${startSelectTime}/${endSelectTime}`, filterData.value).then((res) => {
  if (res.code == 200) {
    produceList.value = produceList.value.concat(deepClone(res.data.data))
    xGrid.value.reloadData(produceList.value);
    gridOptions.loading = false;
    console.log('工程管理表格数据',produceList.value);
  } else {
    ElMessage.warning(res.msg);
  }
})
 
/*使用筛选,后端获取数据*/
/*const changeFilterEvent = (event, option, $panel,) => {
  // 手动触发筛选
  $panel.changeOption(event, !!option.data, option)
}
 
function filterChanged(column) {
  gridOptions.loading = true;
  //筛选条件发生变化条件发生变化
  let value = column.datas[0] != undefined ? column.datas[0] : ''
  value = value.trim();
  //判断是否为工程状态列的筛选改变(假设工程状态字段名为'state',可根据实际情况调整)
  if (column.property === 'state') {
    if (value === 'all') {
      // 如果选择的是全部,从筛选数据中删除此条件,避免传递给后端干扰获取全部数据
      delete filterData.value['state'];
    } else {
      filterData.value['state'] = value;
    }
  } else {
    //判断是否存在外键
    if (column.property.indexOf('.') > -1) {
      const columnArr = column.property.split('.');
      filterData.value[columnArr[0]] = {
        [columnArr[1]]: value,
      };
    } else {
      filterData.value[column.property] = value;
    }
  }
 
  const params = buildRequestParams();
  request.post(`/glassOptimize/optimizeProjectMange/${params.startSelectTime}/${params.endSelectTime}`, filterData.value).then((res) => {
    if (res.code == 200) {
      produceList.value = deepClone(res.data.data);
      xGrid.value.reloadData(produceList)
      gridOptions.loading = false
    } else {
      ElMessage.warning(res.msg)
    }
  });
}*/
 
// 点击查询按钮触发的函数,根据当前筛选条件获取数据并加载到表格
const getWorkOrder = () => {
  const params = buildRequestParams();
  request.post(`/glassOptimize/optimizeProjectMange/${params.startSelectTime}/${params.endSelectTime}`, filterData.value).then((res) => {
    if (res.code == 200) {
      console.log(res.data.data)
      produceList.value = deepClone(res.data.data);
      gridOptions.data = produceList.value;
      xGrid.value.loadData(produceList.value);
      gridOptions.loading = false;
    } else {
      ElMessage.warning(res.msg);
    }
  });
};
// 计算小片数量
const smallPieceQuantityInput = computed(() => {
  return produceList.value.reduce((acc, item) => acc + item.quantity, 0);
});
// 计算小片面积
const smallPieceAreaInput = computed(() => {
  const sum = produceList.value.reduce((acc, item) => acc + item.area, 0);
  return Number(sum.toFixed(2)); // 先使用toFixed保留两位小数,再转换回数值类型(因为toFixed返回字符串)
});
 
// 计算原片数量
const originalPieceQuantityInput = computed(() => {
  return produceList.value.reduce((acc, item) => acc + item.usingQuantity, 0);
});
 
// 原片面积固定为0,直接返回0
const originalPieceAreaInput = 0;
 
//日期左侧栏快捷选项
const shortcuts = [
  {
    text: '当日',
    value: () => {
      const end = new Date()
      const start = new Date(end)
      start.setHours(0, 0, 0, 0) // 设置为当天的凌晨 00:00:00
      return [start, end]
    }
  },
  {
    text: '近1周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setDate(start.getDate() - 7)
      return [start, end]
    }
  },
 
  {
    text: '近1个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setMonth(start.getMonth() - 1)
      return [start, end]
    }
  },
  {
    text: '近2个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setMonth(start.getMonth() - 2)
      return [start, end]
    }
  },
  {
    text: '近3个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setMonth(start.getMonth() - 3)
      return [start, end]
    }
  }
]
 
</script>
 
<template>
  <div id="mange">
    <div id="select" style="">
      <span>优化日期</span>
      <el-date-picker
          style="margin-left:10px; margin-top: -10px; "
          v-model="orderInfo.workOrderDate"
          :default-time="defaultTime"
          :start-placeholder="$t('basicData.startDate')"
          :end-placeholder="$t('basicData.endDate')"
          type="daterange"
          :shortcuts="shortcuts"
          showToday
          format="YYYY/MM/DD"
          value-format="YYYY-MM-DD"
      />
      <span class="input">工程状态</span>
      <el-select
          style="margin-left:10px; margin-top: -5px; width: 150px"
          :default-first-option="true"
          ref="getSelect"
          v-model="optionVal"
          clearable
          class="m-2"
          @change="handleOptionChange"
      >
        <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
        />
      </el-select>
      <!--查询-->
      <el-button
          style="margin-left:10px;margin-top: -5px"
          :icon="Search"
          type="primary"
          @click="getWorkOrder">{{ $t('basicData.search') }}
      </el-button>
    </div>
 
    <vxe-grid
        height="100%"
        class="mytable-scrollbar"
        ref="xGrid"
        v-bind="gridOptions"
        v-on="gridEvents"
    >
      <template #select_filter="{ column, $panel }">
        <div>
          <div v-for="(option, index) in column.filters" :key="index">
            <vxe-select v-model="option.data" @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 #select_filter1="{ column, $panel }">
        <div>
          <div v-for="(option, index) in column.filters" :key="index">
            <vxe-select v-model="option.data" @change="changeFilterEvent($event, option, $panel)">
              <vxe-option value="1" label="是"></vxe-option>
              <vxe-option value="0" label="否"></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>
    <div id="last">
      小片数量
      <el-input class="input" disabled v-model="smallPieceQuantityInput"></el-input>
      小片面积
      <el-input class="input" disabled v-model="smallPieceAreaInput"></el-input>
      原片数量
      <el-input class="input" disabled v-model="originalPieceQuantityInput"></el-input>
      原片面积
      <el-input class="input" disabled v-model="originalPieceAreaInput"></el-input>
    </div>
  </div>
</template>
 
<style scoped>
#mange {
  width: 100%;
  height: 85%;
}
 
:deep(.vxe-button.type--button.is--circle) {
  margin-top: -20px;
}
 
#last {
  margin-top: 10px;
}
 
.input {
  width: 80px;
  margin-left: 10px;
}
</style>