gaoluyang
2026-05-28 ca8dfc8a7dd8ba9b84d9a58c3c2a6d52a0c98a74
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
<template>
  <div>
    <el-dialog v-model="dialogVisible"
               title="领料台账"
               width="1400px"
               @close="handleClose">
      <div class="material-toolbar">
        <el-button type="primary"
                   @click="handleAddMaterialRow">新增</el-button>
      </div>
      <el-table v-loading="materialTableLoading"
                :data="materialTableData"
                border
                row-key="tempId">
        <el-table-column label="工序名称"
                         min-width="140">
          <template #default="{ row }">
            <span v-if="row.bom === true">{{ row.operationName || "-" }}</span>
            <el-select v-else
                       v-model="row.operationName"
                       placeholder="请选择工序"
                       clearable
                       filterable
                       style="width: 100%;"
                       @change="val => handleProcessNameChange(row, val)">
              <el-option v-for="item in processOptions"
                         :key="item.technologyOperationId"
                         :label="item.name"
                         :value="item.name" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="原料名称"
                         min-width="140">
          <template #default="{ row }">
            <span v-if="row.bom === true">{{ row.materialName || "-" }}</span>
            <el-button v-else
                       type="primary"
                       link
                       @click="openMaterialProductSelect(row)">
              {{ row.materialName || "选择原料" }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="原料型号"
                         min-width="140">
          <template #default="{ row }">
            {{ row.materialModel || "-" }}
          </template>
        </el-table-column>
        <!-- 批号多选 -->
        <el-table-column min-width="200"
                         label="批号">
          <template #default="{ row }">
            <el-select v-model="row.batchNo"
                       multiple
                       collapse-tags
                       collapse-tags-indicator
                       placeholder="请选择批号"
                       style="width: 100%;">
              <el-option v-for="item in row.batchNoList"
                         :key="item"
                         :label="item"
                         :value="item" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="库存数量"
                         min-width="120">
          <template #default="{ row }">
            <span :class="{ 'text-danger': isStockInsufficient(row) }">
              {{ row.stockQuantity ?? '-' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="需求数量"
                         min-width="120">
          <template #default="{ row }">
            <span v-if="row.bom === true" :class="{ 'text-danger': isStockInsufficient(row) }">{{ row.demandedQuantity ?? "-" }}</span>
            <el-input-number v-else
                             v-model="row.demandedQuantity"
                             :min="0"
                             :precision="3"
                             :step="1"
                             controls-position="right"
                             style="width: 100%;"
                             :class="{ 'is-stock-insufficient': isStockInsufficient(row) }"
                             @change="val => handleRequiredQtyChange(row, val)" />
          </template>
        </el-table-column>
        <el-table-column label="计量单位"
                         width="100">
          <template #default="{ row }">
            {{ row.unit || "-" }}
          </template>
        </el-table-column>
        <el-table-column label="领用数量"
                         min-width="120">
          <template #default="{ row }">
            <el-input-number v-model="row.pickQty"
                             :min="0"
                             :precision="3"
                             :step="1"
                             controls-position="right"
                             style="width: 100%;" />
          </template>
        </el-table-column>
        <el-table-column label="操作"
                         width="90"
                         fixed="right">
          <template #default="{ $index, row }">
            <el-button v-if="row.bom !== true"
                       type="danger"
                       link
                       @click="handleDeleteMaterialRow($index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <span class="dialog-footer">
          <el-button v-if="hasInsufficientStock"
                     type="warning"
                     @click="openPurchaseRequestDialog">采购申请</el-button>
          <el-button type="primary"
                     :loading="materialSaving"
                     :disabled="isSaveDisabled"
                     @click="handleMaterialSave">保存</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </span>
      </template>
    </el-dialog>
    <ProductSelectDialog v-model="materialProductDialogVisible"
                         @confirm="handleMaterialProductConfirm"
                         single />
    <PurchaseRequestDialog v-model="purchaseRequestDialogVisible"
                           :insufficient-items="insufficientStockItems"
                           :order-row="props.orderRow"
                           @saved="handlePurchaseRequestSaved" />
    <!-- request-url="/stockInventory/rawMaterials" -->
  </div>
</template>
 
<script setup>
  import { computed, ref, watch } from "vue";
  import { ElMessage } from "element-plus";
  import ProductSelectDialog from "@/views/basicData/product/ProductSelectDialog.vue";
  import PurchaseRequestDialog from "./PurchaseRequestDialog.vue";
  import {
    findProductProcessRouteItemList,
    listMain,
  } from "@/api/productionManagement/productProcessRoute.js";
  import {
    listMaterialPickingBom,
    saveMaterialPickingLedger,
    updateMaterialPickingLedger,
  } from "@/api/productionManagement/productionOrder.js";
  import { queryList2 } from "@/api/productionManagement/productStructure.js";
 
 
  const props = defineProps({
    modelValue: { type: Boolean, default: false },
    orderRow: { type: Object, default: null },
  });
  const emit = defineEmits(["update:modelValue", "saved"]);
 
  const dialogVisible = computed({
    get: () => props.modelValue,
    set: val => emit("update:modelValue", val),
  });
 
  const materialProductDialogVisible = ref(false);
  const materialTableLoading = ref(false);
  const materialSaving = ref(false);
  const materialTableData = ref([]);
  const purchaseRequestDialogVisible = ref(false);
 
  const isSaveDisabled = computed(() => {
    if (materialTableData.value.length === 0) return true;
    return !materialTableData.value.some(row => {
      // 检查是否有任何用户输入内容
      const hasBatch = Array.isArray(row.batchNo) && row.batchNo.length > 0;
      const hasPickQty =
        row.pickQty !== null && row.pickQty !== undefined && row.pickQty !== 0;
 
      if (row.bom) {
        // 对于来自BOM的行,输入框只有“批号”和“领用数量”
        return hasBatch || hasPickQty;
      } else {
        // 对于新增行,输入框包括“工序”、“原料”、“需求数量”、“批号”和“领用数量”
        const hasOperation = !!row.operationName;
        const hasMaterial = !!row.materialName;
        const hasDemanded =
          row.demandedQuantity !== null &&
          row.demandedQuantity !== undefined &&
          row.demandedQuantity !== 0;
        return (
          hasBatch || hasPickQty || hasOperation || hasMaterial || hasDemanded
        );
      }
    });
  });
 
  // 判断库存是否不足
  const isStockInsufficient = (row) => {
    const stockQuantity = Number(row.stockQuantity ?? 0);
    const demandedQty = Number(row.demandedQuantity ?? 0);
    return demandedQty > 0 && stockQuantity > 0 && demandedQty > stockQuantity;
  };
 
  // 库存不足的行
  const insufficientStockItems = computed(() => {
    return materialTableData.value.filter(row => isStockInsufficient(row));
  });
 
  // 是否有库存不足
  const hasInsufficientStock = computed(() => {
    return insufficientStockItems.value.length > 0;
  });
 
  const processOptions = ref([]);
  const currentMaterialSelectRowIndex = ref(-1);
  let materialTempId = 0;
 
  const createMaterialRow = (row = {}) => ({
    tempId: row.id || `temp_${++materialTempId}`,
    id: row.id,
    processId: row.processId || row.technologyOperationId,
    technologyOperationId: row.technologyOperationId || row.processId,
    operationName: row.operationName || "",
    bom: row.bom === true,
    materialModelId: row.materialModelId || row.productModelId,
    materialName: row.materialName || row.productName || "",
    materialModel: row.materialModel || row.model || "",
    demandedQuantity: Number(row.requiredQty ?? row.demandedQuantity ?? 0),
    unit: row.unit || "",
    pickQty: Number(row.pickQty ?? row.pickQuantity ?? 0),
    batchNo: row.batchNo
      ? typeof row.batchNo === "string"
        ? row.batchNo.split(",")
        : row.batchNo
      : [],
    batchNoList: row.batchNoList || [],
    stockQuantity: row.stockQuantity ?? row.stockQty ?? null,
  });
 
  const getProcessOptions = async () => {
    if (!props.orderRow?.id) return;
    const res = await findProductProcessRouteItemList({
      orderId: props.orderRow.id,
    });
    const routeList = Array.isArray(res?.data)
      ? res.data
      : res?.data?.records || [];
    const processMap = new Map();
    routeList.forEach(item => {
      const processId = item.technologyOperationId;
      const operationName = item.operationName;
      if (!processId || !operationName) return;
      const key = `${processId}_${operationName}`;
      if (!processMap.has(key)) {
        processMap.set(key, {
          id: processId,
          name: operationName,
        });
      }
    });
    processOptions.value = Array.from(processMap.values());
  };
  const isDetail = ref(true);
 
  const loadMaterialData = async () => {
    if (!props.orderRow?.id) return;
    materialTableLoading.value = true;
    materialTableData.value = [];
    await getProcessOptions();
    try {
      // 直接调用listMaterialPickingBom接口获取库存数量
      const bomRes = await listMaterialPickingBom(props.orderRow.id);
      const bomList = Array.isArray(bomRes?.data)
        ? bomRes.data
        : bomRes?.data?.records || [];
      if (bomList.length > 0) {
        isDetail.value = false;
        materialTableData.value = bomList.map(item => createMaterialRow(item));
      }
    } finally {
      materialTableLoading.value = false;
    }
  };
 
  watch(
    () => dialogVisible.value,
    visible => {
      if (visible) {
        loadMaterialData();
      }
    }
  );
 
  const handleClose = () => {
    materialTableData.value = [];
    currentMaterialSelectRowIndex.value = -1;
  };
 
  const handleAddMaterialRow = () => {
    materialTableData.value.push(createMaterialRow());
  };
 
  const handleDeleteMaterialRow = index => {
    materialTableData.value.splice(index, 1);
  };
 
  const handleProcessNameChange = (row, operationName) => {
    const process = processOptions.value.find(
      item => item.name === operationName
    );
    row.technologyOperationId = process?.technologyOperationId;
  };
 
  const handleRequiredQtyChange = (row, val) => {
    const required = Number(val ?? 0);
    row.demandedQuantity = required;
    if (!row.pickQty || Number(row.pickQty) === 0) {
      row.pickQty = required;
    }
  };
 
  const openMaterialProductSelect = row => {
    currentMaterialSelectRowIndex.value = materialTableData.value.findIndex(
      item => item.tempId === row.tempId
    );
    materialProductDialogVisible.value = true;
  };
 
  const handleMaterialProductConfirm = async (products) => {
    console.log(products, "products");
 
    if (!products || products.length === 0) return;
    const index = currentMaterialSelectRowIndex.value;
    if (index < 0 || !materialTableData.value[index]) return;
    const product = products[0];
    const row = materialTableData.value[index];
    row.materialModelId =
      product.materialModelId || product.modelId || product.id;
    row.materialName =
      product.materialName || product.productName || product.name || "";
    row.materialModel = product.materialModel || product.model || "";
    row.unit = product.unit || product.measureUnit || "";
    row.batchNoList = product.batchNoList;
    currentMaterialSelectRowIndex.value = -1;
    materialProductDialogVisible.value = false;
  };
 
  const validateMaterialRows = () => {
    if (materialTableData.value.length === 0) {
      return { valid: false, message: "请先新增领料数据" };
    }
    const invalidNewRow = materialTableData.value.find(
      item => item.bom !== true && (!item.operationName || !item.materialName)
    );
    if (invalidNewRow) {
      return { valid: false, message: "新增行的工序名称和原料名称为必填项" };
    }
    const invalidRow = materialTableData.value.find(
      item =>
        !item.operationName ||
        !item.materialName ||
        (Number(item.pickQty) > 0 &&
          (!item.batchNo || item.batchNo.length === 0)) ||
        (item.batchNo && item.batchNo.length > 0 && Number(item.pickQty) <= 0) ||
        item.demandedQuantity === null ||
        item.demandedQuantity === undefined ||
        item.pickQty === null ||
        item.pickQty === undefined
    );
    if (invalidRow) {
      if (
        invalidRow.batchNo &&
        invalidRow.batchNo.length > 0 &&
        Number(invalidRow.pickQty) <= 0
      ) {
        return { valid: false, message: "选择了批号时,领用数量必须大于零" };
      }
      return { valid: false, message: "请完善工序、原料、批号和数量后再保存" };
    }
    return { valid: true, message: "" };
  };
 
  const handleMaterialSave = async () => {
    if (!props.orderRow?.id) return;
    const validateResult = validateMaterialRows();
    if (!validateResult.valid) {
      ElMessage.warning(validateResult.message);
      return;
    }
    materialSaving.value = true;
    try {
      if (isDetail.value) {
        await updateMaterialPickingLedger({
          productionOrderId: props.orderRow.id,
          productionOrderPickDto: materialTableData.value.map(item => ({
            id: item.id,
            // processId: item.operationName,
            technologyOperationId: item.technologyOperationId,
            operationName: item.operationName,
            bom: item.bom === true,
            productModelId: item.materialModelId,
            // materialName: item.materialName,
            // materialModel: item.materialModel,
            demandedQuantity: item.demandedQuantity,
            unit: item.unit,
            pickQuantity: item.pickQty,
            batchNo: Array.isArray(item.batchNo)
              ? item.batchNo.join(",")
              : item.batchNo,
          })),
        });
      } else {
        await saveMaterialPickingLedger({
          productionOrderId: props.orderRow.id,
          productionOrderPickDto: materialTableData.value.map(item => ({
            id: item.id,
            // processId: item.operationName,
            technologyOperationId: item.technologyOperationId,
            operationName: item.operationName,
            bom: item.bom === true,
            productModelId: item.materialModelId,
            // materialName: item.materialName,
            // materialModel: item.materialModel,
            demandedQuantity: item.demandedQuantity,
            unit: item.unit,
            pickQuantity: item.pickQty,
            batchNo: Array.isArray(item.batchNo)
              ? item.batchNo.join(",")
              : item.batchNo,
          })),
        });
      }
 
      ElMessage({ message: "领料成功", type: "success" });
      emit("saved");
      dialogVisible.value = false;
    } finally {
      materialSaving.value = false;
    }
  };
 
  // 打开采购申请对话框
  const openPurchaseRequestDialog = () => {
    purchaseRequestDialogVisible.value = true;
  };
 
  // 采购申请保存回调
  const handlePurchaseRequestSaved = () => {
    // 采购申请保存成功后刷新数据
    loadMaterialData();
  };
</script>
 
<style scoped lang="scss">
  .material-toolbar {
    margin-bottom: 12px;
    text-align: right;
  }
 
  .text-danger {
    color: #f56c6c;
    font-weight: bold;
  }
 
  :deep(.is-stock-insufficient) {
    .el-input__wrapper {
      box-shadow: 0 0 0 1px #f56c6c inset;
    }
  }
</style>