yuan
2 天以前 09ce99b6d33ec58d462da5b5fd65927d7ef98f60
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
<template>
  <div>
    <el-dialog
        v-model="dialogFormVisible"
        :title="operationType === 'add' ? '新增出厂检验' : '编辑出厂检验'"
        width="70%"
        @close="closeDia"
    >
      <el-form :model="form" label-width="140px" label-position="top" :rules="rules" ref="formRef">
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="产品名称:" prop="productId">
              <el-tree-select
                  v-model="form.productId"
                  placeholder="请选择"
                  clearable
                  check-strictly
                  @change="getModels"
                  :data="productOptions"
                  :render-after-expand="false"
                  :disabled="operationType === 'edit'"
                  style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规格型号:" prop="productModelId">
              <el-select v-model="form.productModelId" placeholder="请选择" clearable :disabled="operationType === 'edit'"
                         filterable readonly @change="handleChangeModel">
                <el-option v-for="item in modelOptions" :key="item.id" :label="item.model" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="指标选择:" prop="testStandardId">
              <el-select
                v-model="form.testStandardId"
                placeholder="请选择指标"
                clearable
                @change="handleTestStandardChange"
                style="width: 100%"
              >
                <el-option
                  v-for="item in testStandardOptions"
                  :key="item.id"
                  :label="item.standardName || item.standardNo"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位:" prop="unit">
              <el-input v-model="form.unit" placeholder="请输入" disabled/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="批号:" prop="batchNo">
              <el-input
                v-model="form.batchNo"
                placeholder="请输入"
                clearable
                :disabled="operationType === 'edit'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="UID码:" prop="uidNo">
              <el-input v-model="form.uidNo" placeholder="请输入" disabled/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="检品数量:" prop="inspectedQuantity">
              <el-input-number :step="0.01" :min="0" style="width: 100%" v-model="form.inspectedQuantity" placeholder="请输入" clearable :precision="2"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="总数量:" prop="quantity">
              <el-input-number :step="0.01" :min="0" style="width: 100%" v-model="form.quantity" placeholder="请输入" clearable :precision="2" :disabled="quantityDisabled"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
 
          <el-col :span="12">
            <el-form-item label="生产日期:" prop="productionDate">
              <el-date-picker
                  v-model="form.productionDate"
                  type="date"
                  placeholder="请选择日期"
                  value-format="YYYY-MM-DD"
                  format="YYYY-MM-DD"
                  clearable
                  style="width: 100%"
                  @change="calculateValidityDate"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="有效期:" prop="validityDate">
              <el-date-picker
                  v-model="form.validityDate"
                  type="date"
                  placeholder="自动计算或手动选择"
                  value-format="YYYY-MM-DD"
                  format="YYYY-MM-DD"
                  clearable
                  style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="检测单位:" prop="checkCompany">
              <el-input v-model="form.checkCompany" placeholder="请输入" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检测结果:" prop="checkResult">
              <el-select v-model="form.checkResult">
                <el-option label="合格" value="合格" />
                <el-option label="不合格" value="不合格" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="检验员:" prop="checkName">
                            <el-select v-model="form.checkName" placeholder="请选择" clearable>
                                <el-option v-for="item in userList" :key="item.nickName" :label="item.nickName"
                                                     :value="item.nickName"/>
                            </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检测日期:" prop="checkTime">
              <el-date-picker
                  v-model="form.checkTime"
                  type="date"
                  placeholder="请选择日期"
                  value-format="YYYY-MM-DD"
                  format="YYYY-MM-DD"
                  clearable
                  style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="6">
            <el-form-item label="检验用粉剂/液情况:" prop="inspectMaterialConditionId">
              <el-tree-select
                  v-model="form.inspectMaterialConditionId"
                  placeholder="请选择"
                  clearable
                  check-strictly
                  :data="productOptions"
                  :render-after-expand="false"
                  style="width: 100%"
                  @change="handleInspectMaterialChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="规格型号:" prop="inspectProductModelId">
              <el-select v-model="form.inspectProductModelId" placeholder="请选择" clearable
                         filterable readonly @change="handleChangeModels">
                <el-option v-for="item in inspectProductModel" :key="item.id" :label="item.model" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="批号(新):" prop="inspectBatchNo">
              <el-select
                  v-model="form.inspectBatchNo"
                  placeholder="请选择批号"
                  clearable
                  filterable
                  style="width: 100%"
                  @change="handleInspectBatchChange"
              >
                <el-option
                    v-for="item in inspectBatchOptions"
                    :key="item.batchNo"
                    :label="item.batchNo"
                    :value="item.batchNo"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="生产日期(新):" prop="inspectProductionDate">
              <el-input v-model="form.inspectProductionDate" placeholder="自动带出" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="有效期(新):" prop="inspectValidityDate">
              <el-input v-model="form.inspectValidityDate" placeholder="自动计算" disabled/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
            <PIMTable
                rowKey="id"
                :column="tableColumn"
                :tableData="tableData"
                :tableLoading="tableLoading"
                height="400"
            >
                <template #instrument="{ row }">
          <el-select
              v-model="row.instrument"
              placeholder="请选择或输入"
              filterable
              allow-create
              default-first-option
              clearable
              style="width: 100%"
              @change="handleInstrumentChange(row)"
          >
            <el-option label="目测" value="目测" />
            <el-option
                v-for="item in deviceList"
                :key="item.id"
                :label="item.deviceName + (item.deviceModel ? ' / ' + item.deviceModel : '')"
                :value="item.deviceName"
            />
          </el-select>
        </template>
        <template #deviceStatus="{ row }">
          <el-select
              v-model="row.deviceStatus"
              placeholder="请选择"
              default-first-option
              clearable
              style="width: 100%"
          >
            <el-option label="正常" value="正常" />
            <el-option label="停机" value="停机" />
            <el-option label="运行" value="运行" />
            <el-option label="维修" value="维修" />
            <el-option label="/" value="/" />
          </el-select>
        </template>
        <template #result="{ row }">
          <el-input v-model="row.result" placeholder="请输入" clearable />
        </template>
        <template #resultJudgment="{ row }">
          <el-select v-model="row.resultJudgment" placeholder="请选择" clearable style="width: 100%">
            <el-option label="合格" value="合格" />
            <el-option label="不合格" value="不合格" />
            <el-option label="/" value="/" />
          </el-select>
        </template>
            </PIMTable>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确认</el-button>
          <el-button @click="closeDia">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
 
<script setup>
import {ref, reactive, toRefs, computed, getCurrentInstance, nextTick} from "vue";
import {getOptions} from "@/api/procurementManagement/procurementLedger.js";
import {modelList, productTreeList} from "@/api/basicData/product.js";
import {qualityInspectAdd, qualityInspectUpdate} from "@/api/qualityManagement/rawMaterialInspection.js";
import {userListNoPage} from "@/api/system/user.js";
import { getStockInventoryListPage } from "@/api/inventoryManagement/stockInventory.js";
import {qualityInspectDetailByProductId, getQualityTestStandardParamByTestStandardId} from "@/api/qualityManagement/metricMaintenance.js";
import {qualityInspectParamInfo} from "@/api/qualityManagement/qualityInspectParam.js";
import {deviceList as qualityInspectParamDeviceList} from "@/api/energyManagement/index.js";
const { proxy } = getCurrentInstance()
const emit = defineEmits(['close'])
 
const dialogFormVisible = ref(false);
const operationType = ref('')
 
const validateBatchNo = (rule, value, callback) => {
  if (value === undefined || value === null || String(value).trim() === '') {
    callback(new Error('请输入批号'));
    return;
  }
  callback();
};
 
const data = reactive({
  form: {
    checkTime: "",
    process: "",
    checkName: "",
    productName: "",
    productId: "",
    productModelId: "",
    model: "",
    testStandardId: "",
    unit: "",
    uidNo: "",
    batchNo: "",
    inspectedQuantity: "",
    quantity: "",
    productionDate: "",
    validityDate: "",
    checkCompany: "",
    checkResult: "",
    // 检验用粉剂/液情况相关新字段
    inspectMaterialConditionId: "",
    inspectMaterialCondition: "",
    inspectProductModelId : "",
    inspectBatchNo: "",
    inspectProductModel: "",
    inspectProductionDate: "",
    inspectValidityDate: "",
    inspectValidityPeriod: "",
  },
  rules: {
    checkTime: [{ required: true, message: "请输入", trigger: "blur" },],
    process: [{ required: true, message: "请输入", trigger: "blur" }],
    checkName: [{ required: false, message: "请输入", trigger: "blur" }],
    productId: [{ required: true, message: "请输入", trigger: "blur" }],
    productModelId: [{ required: true, message: "请选择", trigger: "change" }],
    testStandardId: [{required: false, message: "请选择指标", trigger: "change"}],
    unit: [{ required: false, message: "请输入", trigger: "blur" }],
    inspectedQuantity: [
      { required: true, message: "请输入检品数量", trigger: "blur" },
      {
        validator: (rule, value, callback) => {
          if (value !== '' && value !== null && value !== undefined) {
            const qty = Number(form.value.quantity);
            const inspectedQty = Number(value);
            if (!isNaN(qty) && !isNaN(inspectedQty) && inspectedQty > qty) {
              callback(new Error("检品数量不能大于总数量"));
            } else {
              callback();
            }
          } else {
            callback();
          }
        },
        trigger: "blur"
      }
    ],
    quantity: [{ required: true, message: "请输入", trigger: "blur" }],
    checkCompany: [{ required: false, message: "请输入", trigger: "blur" }],
    batchNo: [{ required: true, validator: validateBatchNo, trigger: "blur" }],
    checkResult: [{ required: true, message: "请输入", trigger: "change" }],
  },
});
const { form, rules } = toRefs(data);
// 编辑时:productMainId 或 purchaseLedgerId 任一有值则数量置灰
const quantityDisabled = computed(() => {
  const v = form.value || {};
  return !!(v.productMainId != null || v.purchaseLedgerId != null);
});
const supplierList = ref([]);
const productOptions = ref([]);
const inspectProductModel = ref([]);
const tableColumn = ref([
    {
        label: "检测项目",
        prop: "parameterItem",
        width: 150
    },
    {
        label: "标准要求",
        prop: "standardValue",
        width: 180
    },
  {
    label: "单位",
    prop: "unit",
    width: 70
  },
  {
    label: "检测器具",
    prop: "instrument",
    dataType: 'slot',
    slot: 'instrument',
    width: 220
  },
  {
    label: "设备状态",
    prop: "deviceStatus",
    dataType: 'slot',
    slot: 'deviceStatus',
    width: 120
  },
  {
    label: "检测结果",
    prop: "result",
    dataType: 'slot',
    slot: 'result',
    width: 150
  },
    {
        label: "结果判断",
        prop: "resultJudgment",
        dataType: 'slot',
        slot: 'resultJudgment',
        width: 120
    },
]);
const tableData = ref([]);
const tableLoading = ref(false);
const userList = ref([]);
const currentProductId = ref(0);
const testStandardOptions = ref([]); // 指标选择下拉框数据
const modelOptions = ref([]);
const deviceList = ref([]);
const inspectBatchOptions = ref([]);
 
// 打开弹框
const openDialog = async (type, row) => {
  operationType.value = type;
  dialogFormVisible.value = true;
  // 先清空表单验证状态,避免闪烁
  await nextTick();
  proxy.$refs.formRef?.clearValidate();
  // 加载设备台账列表
  loadDeviceList();
 
  // 并行加载基础数据
  const [userListsRes] = await Promise.all([
    userListNoPage(),
    getProductOptions(),
    getOptions().then((res) => {
      supplierList.value = res.data;
    })
  ]);
  userList.value = userListsRes.data;
 
  form.value = {}
  testStandardOptions.value = [];
  tableData.value = [];
 
  if (operationType.value === 'edit') {
    // 先保存 testStandardId,避免被清空
    const savedTestStandardId = row.testStandardId;
    // 先设置表单数据,但暂时清空 testStandardId,等选项加载完成后再设置
    form.value = {...row, testStandardId: ''}
    currentProductId.value = row.productId || 0
    // 清空验证状态,避免数据加载过程中的校验闪烁
    nextTick(() => {
      proxy.$refs.formRef?.clearValidate();
    });
 
    // 编辑模式下,并行加载规格型号和指标选项
    if (currentProductId.value) {
      // 设置产品名称
      form.value.productName = findNodeById(productOptions.value, currentProductId.value);
 
      // 并行加载规格型号和指标选项
      const params = {
        productId: currentProductId.value,
        inspectType: 2
      };
 
      Promise.all([
        modelList({ id: currentProductId.value }),
        qualityInspectDetailByProductId(params)
      ]).then(([modelRes, testStandardRes]) => {
        // 设置规格型号选项
        modelOptions.value = modelRes || [];
        // 如果表单中已有 productModelId,设置对应的 model 和 unit
        if (form.value.productModelId && modelOptions.value.length > 0) {
          const selectedModel = modelOptions.value.find(item => item.id == form.value.productModelId);
          if (selectedModel) {
            form.value.model = selectedModel.model || '';
            form.value.unit = selectedModel.unit || '';
            form.value.uidNo = selectedModel.uidNo || '';
          }
        }
 
        // 设置指标选项
        testStandardOptions.value = testStandardRes.data || [];
 
        // 设置 testStandardId 并加载参数列表
        nextTick(() => {
          if (savedTestStandardId) {
            // 确保类型匹配(item.id 可能是数字或字符串)
            const matchedOption = testStandardOptions.value.find(item =>
              item.id == savedTestStandardId || String(item.id) === String(savedTestStandardId)
            );
            if (matchedOption) {
              // 确保使用匹配项的 id(保持类型一致)
              form.value.testStandardId = matchedOption.id;
            } else {
              // 如果找不到匹配项,尝试直接使用原值
              console.warn('未找到匹配的指标选项,testStandardId:', savedTestStandardId, '可用选项:', testStandardOptions.value);
              form.value.testStandardId = savedTestStandardId;
            }
          }
          // 编辑场景保留已有检验值,直接拉取原参数数据
          getQualityInspectParamList(row.id);
        });
 
        // 编辑模式下,加载检验用粉剂/液相关数据
        loadInspectMaterialData();
      });
    } else {
      getQualityInspectParamList(row.id);
      // 即使没有主产品,也尝试加载检验用粉剂/液数据
      loadInspectMaterialData();
    }
  }
}
const getProductOptions = () => {
  return productTreeList().then((res) => {
    productOptions.value = convertIdToValue(res);
  });
};
const getModels = (value) => {
  form.value.productModelId = undefined;
  form.value.unit = undefined;
  form.value.uidNo = undefined;
  form.value.batchNo = "";
  modelOptions.value = [];
  currentProductId.value = value
  form.value.productName = findNodeById(productOptions.value, value);
  modelList({ id: value }).then((res) => {
    modelOptions.value = res;
  })
  if (currentProductId.value) {
    getList();
  }
};
 
const handleChangeModel = (value) => {
  form.value.model = modelOptions.value.find(item => item.id == value)?.model || '';
  form.value.unit = modelOptions.value.find(item => item.id == value)?.unit || '';
  form.value.uidNo = modelOptions.value.find(item => item.id == value)?.uidNo || '';
  // 选择规格型号后,如果已有生产日期则重新计算有效期
  if (form.value.productionDate) {
    calculateValidityDate();
  }
}
 
const findNodeById = (nodes, productId) => {
  for (let i = 0; i < nodes.length; i++) {
    if (nodes[i].value === productId) {
      return nodes[i].label; // 找到节点,返回该节点
    }
    if (nodes[i].children && nodes[i].children.length > 0) {
      const foundNode = findNodeById(nodes[i].children, productId);
      if (foundNode) {
        return foundNode; // 在子节点中找到,返回该节点
      }
    }
  }
  return null; // 没有找到节点,返回null
};
function convertIdToValue(data) {
  return data.map((item) => {
    const { id, children, ...rest } = item;
    const newItem = {
      ...rest,
      value: id, // 将 id 改为 value
    };
    if (children && children.length > 0) {
      newItem.children = convertIdToValue(children);
    }
 
    return newItem;
  });
}
// 提交产品表单
const submitForm = () => {
  proxy.$refs.formRef.validate(valid => {
    if (valid) {
      form.value.inspectType = 2
            if (operationType.value === "add") {
                tableData.value.forEach((item) => {
                    delete item.id
                })
            }
            const data = {...form.value, qualityInspectParams: tableData.value}
      if (operationType.value === "add") {
        qualityInspectAdd(data).then(res => {
          proxy.$modal.msgSuccess("提交成功");
          closeDia();
        })
      } else {
        qualityInspectUpdate(data).then(res => {
          proxy.$modal.msgSuccess("提交成功");
          closeDia();
        })
      }
    }
  })
}
const getList = () => {
  if (!currentProductId.value) {
    testStandardOptions.value = [];
    tableData.value = [];
    return;
  }
  let params = {
    productId: currentProductId.value,
    inspectType: 2
  }
    qualityInspectDetailByProductId(params).then(res => {
        // 保存下拉框选项数据
        testStandardOptions.value = res.data || [];
        // 清空表格数据,等待用户选择指标
        tableData.value = [];
        // 清空指标选择
        form.value.testStandardId = '';
    })
}
 
// 指标选择变化处理
const handleTestStandardChange = (testStandardId) => {
  if (!testStandardId) {
    tableData.value = [];
    return;
  }
  tableLoading.value = true;
  getQualityTestStandardParamByTestStandardId(testStandardId).then(res => {
    tableData.value = res.data || [];
  }).catch(error => {
    console.error('获取标准参数失败:', error);
    tableData.value = [];
  }).finally(() => {
    tableLoading.value = false;
  })
}
const getQualityInspectParamList = (id) => {
    qualityInspectParamInfo(id).then(res => {
        tableData.value = (res.data || []).map(item => ({...item}));
    })
}
 
// 计算有效期(生产日期 + 规格型号中的有效期)
const calculateValidityDate = async () => {
  if (!form.value.productionDate) {
    form.value.validityDate = '';
    return;
  }
  // 获取规格型号的有效期
  const selectedModel = modelOptions.value.find(item => item.id == form.value.productModelId);
  if (selectedModel && selectedModel.validityPeriod) {
    const productionDate = new Date(form.value.productionDate);
    const validityPeriod = parseFloat(selectedModel.validityPeriod);
    const validityDate = new Date(productionDate);
    validityDate.setFullYear(validityDate.getFullYear() + Math.floor(validityPeriod));
    validityDate.setMonth(validityDate.getMonth() + Math.round((validityPeriod % 1) * 12));
    form.value.validityDate = validityDate.toISOString().split('T')[0];
  }
};
 
// 加载检验用粉剂/液情况相关数据(编辑模式回显用)
const loadInspectMaterialData = () => {
  // 如果有检验用粉剂/液产品ID,加载对应的规格型号
  if (form.value.inspectMaterialConditionId) {
    modelList({ id: form.value.inspectMaterialConditionId }).then((res) => {
      inspectProductModel.value = res || [];
      // 如果有规格型号ID,加载批号列表
      if (form.value.inspectProductModelId && inspectProductModel.value.length > 0) {
        const selectedModel = inspectProductModel.value.find(item => item.id == form.value.inspectProductModelId);
        if (selectedModel) {
          form.value.inspectProductModel = selectedModel.model || '';
        }
        // 根据规格型号查询批号列表
        getStockInventoryListPage({
          model: form.value.inspectProductModel,
          pageNum: 1,
          pageSize: -1
        }).then((res) => {
          inspectBatchOptions.value = res.data.records || [];
        });
      }
    });
  }
};
 
// 选择检验用粉剂/液情况后,根据产品ID查询库存批号列表
const handleInspectMaterialChange = (productId) => {
  inspectBatchOptions.value = [];
  form.value.inspectBatchNo = "";
  form.value.inspectProductModel = "";
  form.value.inspectProductModelId = "";
  form.value.inspectProductionDate = "";
  form.value.inspectValidityDate = "";
  form.value.inspectValidityPeriod = "";
  form.value.inspectMaterialCondition = findNodeById(productOptions.value, productId);
 
  modelList({ id: productId }).then((res) => {
    inspectProductModel.value = res;
  })
};
 
const handleChangeModels = (value) => {
  form.value.inspectProductModel = inspectProductModel.value.find(item => item.id == value)?.model || '';
 
  getStockInventoryListPage({
    model: form.value.inspectProductModel,
    pageNum: 1,
    pageSize: -1
  }).then(res => {
    inspectBatchOptions.value = res.data.records || []
    // 清空已选择的批号和新字段
    form.value.inspectBatchNo = "";
    form.value.inspectProductionDate = "";
    form.value.inspectValidityDate = "";
  });
  if (form.value.productionDate) {
    calculateInspectValidityDate();
  }
}
 
 
const calculateInspectValidityDate = () => {
  if (!form.value.inspectProductionDate) {
    form.value.inspectValidityDate = '';
    return;
  }
// 获取规格型号的有效期
  const selectedModel = inspectProductModel.value.find(item => item.id == form.value.inspectProductModelId);
  if (selectedModel && selectedModel.validityPeriod) {
    const inspectProductionDate = new Date(form.value.inspectProductionDate);
    const validityPeriod = parseFloat(selectedModel.validityPeriod);
    const validityDate = new Date(inspectProductionDate);
    validityDate.setFullYear(validityDate.getFullYear() + Math.floor(validityPeriod));
    validityDate.setMonth(validityDate.getMonth() + Math.round((validityPeriod % 1) * 12));
    form.value.inspectValidityDate = validityDate.toISOString().split('T')[0];
  }
}
 
const handleInspectBatchChange = (batchNo) => {
  if (!batchNo) {
    form.value.inspectProductionDate = "";
    form.value.inspectValidityDate = "";
    return;
  }
  const selectedBatch = inspectBatchOptions.value.find(item => item.batchNo === batchNo);
  if (selectedBatch) {
    // 带出规格型号和生产日期
    // form.value.inspectProductModel = selectedBatch.model || "";
    form.value.inspectProductionDate = selectedBatch.productionDate || "";
    calculateInspectValidityDate()
  }
};
 
// 获取设备台账列表
const loadDeviceList = () => {
    qualityInspectParamDeviceList().then(res => {
        deviceList.value = res.data || [];
    });
};
 
// 设备状态颜色映射
const getDeviceStatusType = (status) => {
    const map = {
        '正常': 'success',
        '运行': 'primary',
        '停机': 'warning',
        '维修': 'danger'
    };
    return map[status] || 'info';
};
 
// 检测器具变化时,自动填充设备状态
const handleInstrumentChange = (row) => {
    if (row.instrument === '目测') {
        row.deviceId = null;
        row.deviceName = '目测';
        row.deviceStatus = '';
        return;
    }
    const device = deviceList.value.find(d => d.deviceName === row.instrument);
    if (device) {
        row.deviceId = device.id;
        row.deviceName = device.deviceName;
        row.deviceStatus = device.status || '';
    } else {
        row.deviceId = null;
        row.deviceName = row.instrument || '';
        row.deviceStatus = '';
    }
};
 
// 关闭弹框
const closeDia = () => {
  proxy.resetForm("formRef");
  tableData.value = [];
  testStandardOptions.value = [];
  inspectBatchOptions.value = [];
  form.value.testStandardId = '';
  dialogFormVisible.value = false;
  emit('close')
};
defineExpose({
  openDialog,
});
</script>
 
<style scoped>
 
</style>