cuilei
4 天以前 4dfa438cbd4f3f475c97a2233688d1fe3628099c
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
<template>
  <j-modal
    :title="title"
    :width="width"
    :visible="visible"
    :fullscreen="true"
    switchFullscreen
    @ok="handleOk"
    :okButtonProps="{ class:{'jee-hidden': disableSubmit} }"
    @cancel="handleCancel"
    cancelText="关闭">
 
    <a-row :gutter="{ xs: 4, sm: 8, md: 16}">
      <a-col :span="12">
        <a-card :bordered="false">
          <!-- 查询区域 -->
          <div class="table-page-search-wrapper">
            <a-form layout="inline" @keyup.enter.native="searchQuery">
              <a-row :gutter="12">
                <a-col :span="7">
                  <a-form-item label="产线" :label-col="{span: 6}" :wrapper-col="{span: 18}">
                    <j-tree-select dict="base_factory,factory_name,id" pid-field="parent_id"
                                   v-model="queryParam.factoryId" style="width: 100%"></j-tree-select>
                  </a-form-item>
                </a-col>
                <a-col :span="9">
                  <a-form-item label="日期" :label-col="{span: 4}" :wrapper-col="{span: 20}">
                    <a-range-picker
                      style="width: 100%"
                      @change="dateRangeChange"
                      :value="dateRange"
                      :disabledDate="disabledDate"
                      @openChange="onOpenChange"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <span style="float: left;overflow: hidden;white-space: nowrap;" class="table-page-search-submitButtons">
                    <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
                    <a-button type="info" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
                  </span>
                </a-col>
              </a-row>
              <a-row :gutter="12" style="margin-top: 8px;">
                <a-col :span="24">
                  <a-button type="primary" @click="generatePlan" icon="retweet">生成排产计划</a-button>
                </a-col>
              </a-row>
            </a-form>
          </div>
 
          <div class="table-operator">
            <a-dropdown v-if="selectedRowKeys.length > 0">
              <a-menu slot="overlay">
                <a-menu-item key="1" @click="batchDel">
                  <a-icon type="delete" />
                  删除
                </a-menu-item>
              </a-menu>
              <a-button style="margin-left: 8px"> 批量操作
                <a-icon type="down" />
              </a-button>
            </a-dropdown>
          </div>
<!--          <div>-->
<!--            <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">-->
<!--              <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a-->
<!--              style="font-weight: 600">{{ selectedRowKeys.length }}</a>项-->
<!--              <a style="margin-left: 24px" @click="onClearSelected">清空</a>-->
<!--            </div>-->
 
            <vxe-table
              ref="table"
              border
              show-overflow
              show-header-overflow
              :scroll-x="{enabled: true}"
              :data="dataSource"
              :edit-config="{trigger: 'click', mode: 'cell', activeMethod: isRowEditable}"
              :edit-rules="editRules"
            >
<!--              <vxe-table-column type="checkbox" width="40" fixed="left"></vxe-table-column>-->
              <vxe-table-column type="seq" width="40" />
              <vxe-table-column width="100" title="工单号" field="workOrderCode">
                <template #default="{ row }">
                  <span v-if="row.workOrderCode">{{ row.workOrderCode }}</span>
                  <span v-else class="placeholder-text">系统自动生成</span>
                </template>
              </vxe-table-column>
              <vxe-table-column
                title="物料编号"
                field="materialNumber"
                width="120"
                :edit-render="{name: '$select', options: materialOptions, events: {change: handleMaterialChange}}">
                <template #default="{ row }">
                  <span v-if="row.materialNumber">{{ row.materialNumber }}</span>
                  <span v-else class="placeholder-text">请选择物料编号</span>
                </template>
              </vxe-table-column>
              <vxe-table-column title="物料名称" field="materialName" width="100">
                <template #default="{ row }">
                  <span v-if="row.materialName">{{ row.materialName }}</span>
                  <span v-else class="placeholder-text">物料名称自动填充</span>
                </template>
              </vxe-table-column>
              <vxe-table-column title="班组id" :visible="false" field="groupId"></vxe-table-column>
              <vxe-table-column
                title="班次"
                width="100"
                field="shiftId"
                :edit-render="{name: '$select', options: shiftOptions, events: {change: handleShiftChange}}">
                <template #default="{ row }">
                  <span v-if="row.shiftId">{{ row.shiftName || row.shiftId_dictText }}</span>
                  <span v-else class="placeholder-text">请选择班次</span>
                </template>
              </vxe-table-column>
              <vxe-table-column
                title="排产日期"
                field="workOrderDate"
                width="120"
                :edit-render="{name: '$select', options: workOrderDateOptions, events: {change: handleWorkOrderDateChange}}">
                <template #default="{ row }">
                  <span v-if="row.workOrderDate">{{ row.workOrderDate }}</span>
                  <span v-else class="placeholder-text">请选择排产日期</span>
                </template>
              </vxe-table-column>
              <vxe-table-column
                title="计划生产数量"
                field="planQuantity"
                width="100"
                :edit-render="{name: '$input'}">
                <template #default="{ row }">
                  <span v-if="row.planQuantity">{{ row.planQuantity }}</span>
                  <span v-else class="placeholder-text">请填写计划生产数量</span>
                </template>
              </vxe-table-column>
              <vxe-table-column title="" width="40" fixed="right">
                <template #default="{ row }">
                  <span v-if="row.workOrderStatus === 'NEW' || !row.workOrderStatus">
                    <i class="vxe-icon--remove" @click="handleRemove(row)"></i>
                  </span>
                </template>
              </vxe-table-column>
            </vxe-table>
            <a-button
              :disabled="addScheduleFlag"
              style="width: 100%; margin-top: 16px; margin-bottom: 8px"
              type="dashed"
              icon="plus"
              @click="addSchedulePlan"
            >新增排产计划
            </a-button>
<!--            <vxe-pager-->
<!--              :current-page="pagination.current"-->
<!--              :page-size="pagination.pageSize"-->
<!--              :total="pagination.total"-->
<!--              :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']"-->
<!--              @page-change="handlePageChange">-->
<!--            </vxe-pager>-->
          </div>
        </a-card>
      </a-col>
      <a-col :span="12">
        <a-card :bordered="false">
          <MesProductionWeekCalendar
            ref="weekCalendar"
            :start-date="calendarStartDate"
            :show-navigation="false"
            :show-today-button="false"
            :show-today-highlight="false"
            :show-first-day-highlight="false"
            @select="onDateSelect"
            @change="onCalendarChange"
          >
            <template #dateCell="{ date, isSelected, isToday }">
              <div class="custom-date-content">
                <div
                  v-for="(workOrder, index) in getWorkOrdersForDate(date)"
                  :key="workOrder.id"
                  class="work-order-item"
                  :class="getColorClass(index)"
                >
                  <span class="work-order-shift">{{ workOrder.shiftCode }}</span>
                  <span class="work-order-material">{{ workOrder.materialName }}</span>
                  <span class="work-order-quantity">{{ workOrder.planQuantity }}</span>
                </div>
              </div>
            </template>
          </MesProductionWeekCalendar>
        </a-card>
      </a-col>
    </a-row>
 
  </j-modal>
 
 
</template>
 
<script>
 
import '@/assets/less/TableExpand.less'
import MesProductionWeekCalendar from '@views/mes/modules/MesProductionWeekCalendar.vue'
import moment from 'moment'
import { getAction, postAction, requestPut } from '@api/manage'
import { ajaxGetDictItems } from '@api/api'
 
export default {
  name: 'MesProductionWorkOrderScheduleModal',
  components: {
    MesProductionWeekCalendar
  },
  data() {
    return {
      title: '排产管理页面',
      width: 600,
      visible: false,
      disableSubmit: false,
      addScheduleFlag: false,
      queryParam: {},
      dataSource: [],
      shiftOptions: [],
      groupShiftMap: {},
      materialOptions: [],
      materNumberNameMap: {},
      workOrderDateOptions: [],
      selectedRowKeys: [],
      selectionRows: [],
      /* 分页参数 */
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0
      },
      // 表头
      url: {
        list: '/mesproductionworkorder/mesProductionWorkOrder/list',
        delete: '/mesproductionworkorder/mesProductionWorkOrder/delete',
        deleteBatch: '/mesproductionworkorder/mesProductionWorkOrder/deleteBatch',
        exportXlsUrl: '/mesproductionworkorder/mesProductionWorkOrder/exportXls',
        importExcelUrl: 'mesproductionworkorder/mesProductionWorkOrder/importExcel',
        listProductionLinesOption: '/base/factory/queryIdTree',
        queryShiftGroupByFactoryId: '/base/shiftGroup/queryShiftGroupByFactoryId',
        queryFactoryById: '/base/factory/queryById',
        schedule: '/mesproductionworkorder/mesProductionWorkOrder/schedule',
        addSchedulePlan: '/mesproductionworkorder/mesProductionWorkOrder/addSchedulePlan'
      },
      editRules: {
        materialNumber: [
          { required: true, message: '物料编号必须选择' }
        ],
        shiftId: [
          { required: true, message: '班次必须选择' }
        ],
        workOrderDate: [
          { required: true, message: '排产日期必须选择' }
        ],
        planQuantity: [
          { required: true, message: '计划生产数量为必填' }
        ]
      },
      dictOptions: {},
      superFieldList: [],
      // 用于演示的工单数据
      workOrdersByDate: {},
      // 日历起始日期
      calendarStartDate: moment().startOf('week'), // 默认显示当前周的周一
      productionLineData: [],
      dateRange: [],
      tempStartDate: null, // 临时存储开始日期
      hoveredDate: null    // 存储鼠标悬停的日期
    }
  },
  created() {
  },
  watch: {
    dataSource: {
      handler() {
        // 使用 nextTick 确保在 DOM 更新后再更新日历
        this.$nextTick(() => {
          this.updateCalendarWorkOrders()
        })
      },
      deep: true
    }
  },
  computed: {
    importExcelUrl: function() {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    }
  },
  methods: {
    isRowEditable({row, rowIndex}) {
      return row.workOrderStatus === 'NEW' || !row.workOrderStatus
    },
    getColorClass(index) {
      return index % 2 === 0 ? 'blue-item' : 'red-item';
    },
    scheduleOpen() {
      this.visible = true
    },
    close() {
      this.$emit('close')
      this.visible = false
    },
    handleOk() {
      // 表格全表校验
      this.$refs.table.validate((valid) => {
        if (valid) {
          this.$message.error("请完成所有必填信息后再提交!")
        } else {
          let tableData = this.$refs.table.getTableData().fullData
          postAction(this.url.addSchedulePlan, tableData).then(res=> {
            if (res.success) {
              this.$message.success(res.message)
              this.submitCallback()
            } else {
              this.$message.warning(res.message)
            }
          })
        }
      })
    },
    submitCallback() {
      this.$emit('ok')
      this.queryParam = {}
      this.dateRange = []
      this.workOrdersByDate = {}
      this.dataSource = []
      this.visible = false
    },
    handleCancel() {
      this.queryParam = {}
      this.dateRange = []
      this.workOrdersByDate = {}
      this.dataSource = []
      this.pagination.current = 1
      this.pagination.pageSize = 10
      this.pagination.total = 0
      this.close()
    },
    onClearSelected() {
      this.selectedRowKeys = []
      this.selectionRows = []
    },
    loadData(arg) {
      return new Promise((resolve, reject) => {
        //加载数据 若传入参数1则加载第一页的内容
        if (arg === 1) {
          this.pagination.current = 1
        }
        var params = Object.assign({}, this.queryParam, {
          pageNo: this.pagination.current,
          pageSize: this.pagination.pageSize
        })
        console.log('params', params)
        if (!params) {
          reject(new Error('查询参数无效'))
          return false
        }
        this.loading = true
        getAction(this.url.list, params).then((res) => {
          if (res.success) {
            this.dataSource = res.result.records || res.result
            if (res.result.total) {
              this.pagination.total = res.result.total
            } else {
              this.pagination.total = 0
            }
            resolve(res)
          } else {
            this.$message.warning(res.message)
            reject(new Error(res.message))
          }
        }).catch(error => {
          reject(error)
        }).finally(() => {
          this.loading = false
        })
      })
    },
    handlePageChange({ currentPage, pageSize }) {
      this.pagination.current = currentPage
      this.pagination.pageSize = pageSize
      this.loadData()
    },
    searchQuery() {
      if (!this.queryParam.factoryId || this.dateRange.length === 0) {
        this.$message.warning('请选择产线及排产日期范围!')
        return
      }
      this.queryParam = Object.assign(this.queryParam, this.dateRange)
      this.loadData(1).then(() => {
        this.initTableData(null, this.dateRange)
        // 设置日历显示为查询日期范围内的第一周
        if (this.dateRange[0]) {
          this.calendarStartDate = this.dateRange[0].clone().startOf('week');
        }
      })
    },
    searchReset() {
      this.queryParam = {}
      this.dateRange = []
      this.workOrdersByDate = {}
      this.dataSource = []
      this.pagination.total = 0
    },
    // 生成工单号的方法
    generateWorkOrderCode(row) {
      // 获取各个字段的值
      const factoryCode = row.factoryCode || '';
      const materialNumber = row.materialNumber || '';
      const workDate = row.workOrderDate || '';
      const shiftCode = row.shiftCode || '';
 
      let formattedDate = workDate;
      if (workDate && workDate.length >= 10) {
        // 如果是完整日期格式,提取 YYYY-MM-DD 部分
        formattedDate = workDate.substring(0, 10).replace(/-/g, '');
      }
      return `${factoryCode}${materialNumber}${formattedDate}${shiftCode}`;
    },
    updateWorkOrderCode(row) {
      row.workOrderCode = this.generateWorkOrderCode(row);
    },
    // 格式化日期为 YYYY-MM-DD
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    // 生成日期范围数组
    generateDateRangeOptions(startDate, endDate) {
      const dateOptions = [];
      const start = new Date(startDate);
      const end = new Date(endDate);
 
      // 设置时间为每天的0点
      start.setHours(0, 0, 0, 0);
      end.setHours(0, 0, 0, 0);
 
      // 生成日期范围内的所有日期
      for (let date = new Date(start); date <= end; date.setDate(date.getDate() + 1)) {
        const formattedDate = this.formatDate(date);
        dateOptions.push({
          value: formattedDate,
          label: formattedDate
        });
      }
      return dateOptions;
    },
    initDictSelectOptions(record) {
      return new Promise((resolve) => {
        // 并行执行多个异步请求
        const promises = [];
 
        let factoryId
        if (record && record.length > 0) {
          factoryId = record[0].factoryId
        } else {
          factoryId = this.queryParam.factoryId
        }
 
        const shiftGroupPromise = getAction(this.url.queryShiftGroupByFactoryId, { factoryId: factoryId }).then(res => {
          if (res.success) {
            this.shiftOptions = res.result.map(item => {
              return {
                value: item.shiftId,
                label: item.shiftId_dictText
              }
            })
            this.groupShiftMap = res.result.reduce((map, item) => {
              map[item.shiftId] = {
                groupId: item.id,
                shiftCode: item.shiftCode_dictText,
                shiftName: item.shiftId_dictText
              }
              return map
            }, {})
          }
        }).catch(() => {
        });
        promises.push(shiftGroupPromise);
 
        const materialNumberPromise = ajaxGetDictItems("lsw_material,material_name,material_number,del_flag!='1' order by material_number asc", null).then(res => {
          if (res.success) {
            this.materialOptions = res.result.map(item => {
              return {
                value: item.value,
                label: item.value
              }
            });
            this.materNumberNameMap = res.result.reduce((map, item) => {
              map[item.value] = item.text
              return map
            }, {})
          }
        }).catch(() => {
        });
        promises.push(materialNumberPromise);
 
        // 等待所有请求完成
        Promise.all(promises).then(() => {
          resolve();
        });
      })
    },
    generatePlan() {
      if (!this.queryParam.factoryId || this.dateRange.length === 0) {
        this.$message.warning('请选择产线及排产日期范围!')
        return
      }
      getAction(this.url.schedule, {
        factoryId: this.queryParam.factoryId,
        startDate: this.dateRange[0].format('YYYY-MM-DD'),
        endDate: this.dateRange[1].format('YYYY-MM-DD')
      }).then(res => {
        if (res.success) {
          const record = res.result
          this.initTableData(record, this.dateRange)
          // 设置日历显示为生成计划日期范围内的第一周
          if (this.dateRange[0]) {
            this.calendarStartDate = this.dateRange[0].clone().startOf('week');
          }
        }
      })
    },
    initTableData(record, dateRange) {
      // 先加载字典数据,再初始化表单
      this.initDictSelectOptions(record).then(() => {
        this.$nextTick(() => {
          // 根据日期范围生成排产日期选项
          if (dateRange && dateRange.length === 2) {
            this.workOrderDateOptions = this.generateDateRangeOptions(dateRange[0], dateRange[1]);
          }
 
          // 为每条记录生成工单号
          if (record && record.length > 0) {
            record.forEach(row => {
              if (!row.workOrderCode) {
                this.updateWorkOrderCode(row);
              }
            });
            this.dataSource.push(...record)
          }
          this.pagination.total = this.dataSource.length
          this.$nextTick(() => {
            if (this.$refs.table && this.dataSource.length > 0) {
              // 激活第一行进入编辑状态
              this.$refs.table.setActiveRow(this.dataSource[0])
            }
          })
        });
      })
    },
    handleWorkOrderDateChange($event, value) {
      $event.row.workOrderDate = value.value;
      this.updateWorkOrderCode($event.row)
    },
    handleMaterialChange($event, value) {
      const key = value.value
      if (key && this.materNumberNameMap[key]) {
        $event.row.materialName = this.materNumberNameMap[key]
      } else {
        $event.row.materialName = '';
      }
      // 更新物料编号
      $event.row.materialNumber = key;
      // 重新生成工单号
      this.updateWorkOrderCode($event.row);
    },
    handleShiftChange($event, value) {
      const key = value.value
      // 从 groupShiftMap 中获取对应的班组id
      if (key && this.groupShiftMap[key]) {
        // 更新当前行的班组id、班次编码(拼接工单号用)字段
        $event.row.groupId = this.groupShiftMap[key].groupId
        $event.row.shiftCode = this.groupShiftMap[key].shiftCode
        $event.row.shiftName = this.groupShiftMap[key].shiftName
      } else {
        // 如果没有匹配的班组,则清空
        $event.row.groupId = ''
        $event.row.shiftCode = ''
        $event.row.shiftName = ''
      }
      // 重新生成工单号
      this.updateWorkOrderCode($event.row);
    },
    async addSchedulePlan() {
      if (!this.queryParam.factoryId || this.dateRange.length === 0) {
        this.$message.warning('请先选择产线及排产日期范围!')
        return
      }
      let factoryCode = ''
      if (this.dataSource.length === 0) {
        const res = await getAction(this.url.queryFactoryById, {id: this.queryParam.factoryId})
        if (res.success) {
          factoryCode = res.result.factoryCode
        }
      } else {
        factoryCode = this.dataSource[0].factoryCode
      }
      // 创建新行数据
      const newRow = {
        workOrderCode: factoryCode,
        materialNumber: '',
        materialName: '',
        factoryId: this.dataSource.length > 0 ? this.dataSource[0].factoryId : this.queryParam.factoryId,
        factoryCode: factoryCode,
        groupId: '',
        shiftId: '',
        shiftCode: '',
        shiftName: '',
        workOrderDate: '',
        planQuantity: ''
      }
      this.initDictSelectOptions(null).then(() => {
        // 根据日期范围生成排产日期选项
        if (this.dateRange && this.dateRange.length === 2) {
          this.workOrderDateOptions = this.generateDateRangeOptions(this.dateRange[0], this.dateRange[1]);
        }
        this.dataSource.push(newRow)
        this.pagination.total += 1
        // 激活新增的行进入编辑状态
        this.$nextTick(() => {
          if (this.$refs.table) {
            this.$refs.table.setActiveRow(newRow)
          }
        })
      })
    },
    handleRemove(row) {
      let table = this.$refs.table
      this.$confirm({
        title: '提示',
        content: '确认要删除吗?',
        okText: '确定',
        cancelText: '取消',
        onOk: () => {
          const index = this.dataSource.indexOf(row)
          if (index > -1) {
            this.dataSource.splice(index, 1)
            this.pagination.total -= 1
          }
          // 删除行
          table.remove(row)
        }
      })
    },
    onOpenChange(open) {
      if (!open) {
        // 关闭选择器时重置状态
        this.tempStartDate = null
        this.hoveredDate = null
      }
    },
    disabledDate(current) {
      // 如果有临时开始日期,则限制结束日期范围
      if (this.tempStartDate) {
        const startDate = this.tempStartDate.clone().startOf('day')
        const maxDate = startDate.clone().add(6, 'days').endOf('day') // 7天包括起始日
        const minDate = startDate.clone().subtract(6, 'days').startOf('day') // 也可以向前选6天
        // 禁用超出7天范围的日期
        return current && (current < minDate || current > maxDate)
      }
      // 默认不禁用
      return false
    },
    dateRangeChange(dates, dateStrings) {
      this.dateRange = dates
      if (dates && dates.length > 0) {
        if (dates.length === 1) {
          // 选择了开始日期,保存到临时变量
          this.tempStartDate = dates[0]
          this.hoveredDate = dates[0]
        } else if (dates.length === 2) {
          // 选择了结束日期,验证范围
          const startDate = dates[0]
          const endDate = dates[1]
          const diffDays = endDate.diff(startDate, 'days') + 1
 
          if (diffDays > 7) {
            this.$message.warning('日期范围不能超过7天')
            // 自动调整为7天范围
            const adjustedEndDate = startDate.clone().add(6, 'days')
            this.dateRange = [startDate, adjustedEndDate]
            this.queryParam.startDate = startDate.format('YYYY-MM-DD')
            this.queryParam.endDate = adjustedEndDate.format('YYYY-MM-DD')
          } else {
            this.queryParam.startDate = dateStrings[0]
            this.queryParam.endDate = dateStrings[1]
          }
          // 重置临时状态
          this.tempStartDate = null
          this.hoveredDate = null
        }
 
        // 更新日历显示为选中日期所在周
        if (dates[0]) {
          this.calendarStartDate = dates[0].clone().startOf('week');
        }
      } else {
        // 清除了选择
        this.queryParam.startDate = null
        this.queryParam.endDate = null
        this.tempStartDate = null
        this.hoveredDate = null
        // 重置日历为当前周
        this.calendarStartDate = moment().startOf('week');
      }
    },
    // 处理日期选择事件 - 更新日历显示为选中日期所在周
    onDateSelect(date) {
      console.log('Selected date:', date.format('YYYY-MM-DD'))
      // 更新日历显示为选中日期所在周
      this.calendarStartDate = date.clone().startOf('week');
    },
 
    // 处理日历周变化事件
    onCalendarChange(date) {
      console.log('Calendar week changed:', date.format('YYYY-MM-DD'))
      // 日历周变化时更新 startDate
      this.calendarStartDate = date.clone().startOf('week');
    },
    // 更新日历中的工单数据
    updateCalendarWorkOrders() {
      const workOrdersByDate = {}
      this.dataSource.forEach(workOrder => {
        const workOrderDate = workOrder.workOrderDate
        if (workOrderDate) {
          if (!workOrdersByDate[workOrderDate]) {
            workOrdersByDate[workOrderDate] = []
          }
          workOrdersByDate[workOrderDate].push({
            id: workOrder.id,
            shiftCode: workOrder.shiftCode || '',
            materialName: workOrder.materialName || '',
            planQuantity: workOrder.planQuantity || 0
          })
        }
      })
      this.workOrdersByDate = workOrdersByDate
    },
    // 获取指定日期的工单
    getWorkOrdersForDate(date) {
      const dateStr = date.format('YYYY-MM-DD')
      return this.workOrdersByDate[dateStr] || []
    }
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
 
.placeholder-text {
  font-style: italic;
  color: #999;
}
 
.work-order-item {
  font-size: 12px;
  padding: 2px 4px;
  margin-bottom: 2px;
  background-color: #f0f0f0;
  border-radius: 2px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
 
.work-order-item.blue-item {
  background-color: #e6f7ff;
  border-left: 2px solid #1890ff;
}
 
.work-order-item.red-item {
  background-color: #fff1f0;
  border-left: 2px solid #f5222d;
}
 
.work-order-shift {
  font-weight: bold;
  margin-right: 4px;
}
 
.work-order-material {
  margin-right: 4px;
}
 
.work-order-quantity {
  float: right;
}
</style>