spring
20 小时以前 9aced09ef31ab77663e6ee052785d87ca3c671ba
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
<template>
  <el-dialog
    v-model="visible"
    title="领料"
    width="1400px"
    top="3vh"
    :close-on-click-modal="false"
    destroy-on-close
    class="material-requisition-dialog"
  >
    <div class="material-requisition-form">
        <!-- 原材料 Tab -->
        
          <div class="operation-bar">
            <el-button type="primary" @click="handleAdd">新增</el-button>
          </div>
          <el-table :data="materialList" border style="width: 100%" height="50vh">
            <el-table-column type="index" label="序号" width="60" align="center" />
            <el-table-column prop="productName" label="产品名称" min-width="150" />
            <el-table-column prop="model" label="型号" min-width="150" />
            <el-table-column prop="unit" label="单位" width="80" align="center" />
            <el-table-column prop="customer" label="供应商" min-width="160" show-overflow-tooltip />
            <el-table-column prop="batchNo" label="批号" min-width="180" show-overflow-tooltip />
            <el-table-column prop="requisitionQty" label="领用数量" width="120" align="center">
              <template #default="{ row }">
                <el-input-number
                  v-model="row.requisitionQty"
                  :min="0"
                  :max="row.qualitity || 0"
                  :precision="2"
                  :controls="false"
                  :disabled="!row.qualitity"
                  style="width: 100%"
                />
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" min-width="150">
              <template #default="{ row }">
                <el-input v-model="row.remark" placeholder="请输入备注" clearable />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80" align="center">
              <template #default="{ $index }">
                <el-button type="danger" link @click="handleDelete($index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
    </div>
 
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" :loading="saving" @click="handleConfirm">确 认</el-button>
        <el-button @click="handleCancel">取 消</el-button>
      </span>
    </template>
 
    <!-- 新增原材料弹窗 -->
    <el-dialog
      v-model="addDialogVisible"
      title="选择原材料"
      width="1000px"
      top="5vh"
      :close-on-click-modal="false"
      append-to-body
    >
      <div class="material-filter" style="margin-bottom: 20px;">
        <el-select
          v-model="filterSupplier"
          placeholder="供应商"
          clearable
          filterable
          style="width: 220px"
        >
          <el-option
            v-for="opt in supplierFilterOptions"
            :key="opt"
            :label="opt"
            :value="opt"
          />
        </el-select>
        <el-select
          v-model="filterBatchNo"
          placeholder="批号"
          clearable
          filterable
          style="width: 220px; margin-left: 12px"
        >
          <el-option
            v-for="opt in batchFilterOptions"
            :key="opt"
            :label="opt"
            :value="opt"
          />
        </el-select>
      </div>
      <el-table
        :data="filteredMaterials"
        border
        style="width: 100%"
        height="50vh"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="productName" label="产品名称" min-width="150" />
        <el-table-column prop="model" label="型号" min-width="150" />
        <el-table-column prop="unit" label="单位" width="80" align="center" />
        <el-table-column prop="customer" label="供应商" min-width="160" show-overflow-tooltip />
        <el-table-column prop="batchNo" label="批号" min-width="180" show-overflow-tooltip />
        <!-- <el-table-column prop="qualitity" label="可领用数量" width="100" align="center">
          <template #default="{ row }">
            {{ row.qualitity || 0 }}
          </template>
        </el-table-column> -->
      </el-table>
 
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="handleAddConfirm">确 定</el-button>
          <el-button @click="addDialogVisible = false">取 消</el-button>
        </span>
      </template>
    </el-dialog>
  </el-dialog>
</template>
 
<script setup>
import { ref, computed, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { drawMaterials } from '@/api/productionManagement/productionOrder.js';
import { getMaterials } from '@/api/inventoryManagement/stockInventory.js';
 
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  orderData: {
    type: Object,
    default: () => ({})
  }
});
 
const emit = defineEmits(['update:modelValue', 'confirm']);
 
const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
});
 
const loading = ref(false);
const saving = ref(false);
const activeTab = ref('material');
const materialList = ref([]);
 
// 新增弹窗相关
const addDialogVisible = ref(false);
const availableMaterials = ref([]);
const selectedMaterials = ref([]);
 
// 选择弹窗筛选条件(供应商/批号)
const filterSupplier = ref('');
const filterBatchNo = ref('');
 
// 将后端可能返回的字段做一下归一化:供应商/批号字段名可能不一致
const normalizeMaterial = (m) => {
  return {
    ...m,
    customer: m.customer ?? m.supplierName ?? '',
    batchNo: m.batchNo ?? m.batchNumber ?? m.batch_number ?? m.lotNo ?? '',
  };
};
 
const supplierFilterOptions = computed(() => {
  return Array.from(new Set(availableMaterials.value.map((m) => m.customer).filter(Boolean)));
});
 
const batchFilterOptions = computed(() => {
  const list = filterSupplier.value
    ? availableMaterials.value.filter((m) => m.customer === filterSupplier.value)
    : availableMaterials.value;
  return Array.from(new Set(list.map((m) => m.batchNo).filter(Boolean)));
});
 
const filteredMaterials = computed(() => {
  return availableMaterials.value.filter((m) => {
    if (filterSupplier.value && m.customer !== filterSupplier.value) return false;
    if (filterBatchNo.value && m.batchNo !== filterBatchNo.value) return false;
    return true;
  });
});
 
watch(filterSupplier, () => {
  // 如果当前“批号”不属于所选供应商,则清空
  if (filterBatchNo.value && !batchFilterOptions.value.includes(filterBatchNo.value)) {
    filterBatchNo.value = '';
  }
});
 
// 监听弹框打开,加载数据
watch(() => props.modelValue, (val) => {
  if (val && props.orderData) {
    loadMaterialList();
  }
});
 
const loadMaterialList = async () => {
  const order = props.orderData;
  const drawMaterialsData = order.drawMaterials;
  const bomId = order?.bomId;
 
  // 先获取getMaterials的最新数据
  let materialsFromApi = [];
  if (bomId) {
    try {
      const res = await getMaterials({ bomId });
      materialsFromApi = (res.data || []).map(normalizeMaterial);
    } catch (error) {
      console.error('查询原材料列表失败:', error);
    }
  }
 
  // 加载已保存的领料数据
  if (drawMaterialsData) {
    try {
      const list = typeof drawMaterialsData === 'string'
        ? JSON.parse(drawMaterialsData)
        : drawMaterialsData;
      // 合并数据:使用API的qualitity,使用保存的requisitionQty和remark
      materialList.value = list.map(savedItem => {
        const apiItem = materialsFromApi.find(m => m.id === savedItem.id || m.productModelId === savedItem.productModelId);
        return {
          ...savedItem,
          qualitity: apiItem?.qualitity ?? savedItem.qualitity ?? 0,
          requisitionQty: savedItem.requisitionQty || 0,
          customer: savedItem.customer ?? savedItem.supplierName ?? apiItem?.customer ?? '',
          batchNo: savedItem.batchNo ?? savedItem.batchNumber ?? apiItem?.batchNo ?? '',
        };
      });
    } catch (e) {
      console.error('解析领料数据失败:', e);
      materialList.value = [];
    }
  } else {
    materialList.value = [];
  }
};
 
// 打开新增弹窗
const handleAdd = async () => {
  const order = props.orderData;
  const bomId = order?.bomId;
  if (!bomId) {
    ElMessage.warning('当前订单缺少BOM信息');
    return;
  }
 
  loading.value = true;
  try {
    const res = await getMaterials({ bomId });
    console.log('getMaterials返回数据:', res.data);
    // 直接展示所有数据,不过滤
    availableMaterials.value = (res.data || []).map(normalizeMaterial);
    filterSupplier.value = '';
    filterBatchNo.value = '';
    selectedMaterials.value = [];
    addDialogVisible.value = true;
  } catch (error) {
    console.error('查询原材料列表失败:', error);
    ElMessage.error('查询原材料列表失败');
  } finally {
    loading.value = false;
  }
};
 
// 选择变化
const handleSelectionChange = (selection) => {
  selectedMaterials.value = selection;
};
 
// 确认添加
const handleAddConfirm = () => {
  if (selectedMaterials.value.length === 0) {
    ElMessage.warning('请选择至少一条记录');
    return;
  }
 
  // 过滤掉已存在的(通过id和productModelId判断)
  const existingIds = materialList.value.map(item => item.id);
  const existingProductModelIds = materialList.value.map(item => item.productModelId);
 
  const newItems = selectedMaterials.value
    .filter(item => !existingIds.includes(item.id) && !existingProductModelIds.includes(item.productModelId))
    .map(item => ({
      ...item,
      requisitionQty: 0,
      remark: '',
    }));
 
  if (newItems.length === 0) {
    ElMessage.warning('所选数据已存在,无需重复添加');
    return;
  }
 
  materialList.value = [...materialList.value, ...newItems];
  addDialogVisible.value = false;
  ElMessage.success(`成功添加 ${newItems.length} 条记录`);
};
 
// 删除
const handleDelete = (index) => {
  materialList.value.splice(index, 1);
};
 
const handleCancel = () => {
  visible.value = false;
  materialList.value = [];
  activeTab.value = 'material';
};
 
const handleConfirm = async () => {
  const orderId = props.orderData?.id;
  if (!orderId) {
    ElMessage.error('订单ID不存在');
    return;
  }
 
  const drawMaterialsList = materialList.value.map(item => ({
    ...item,
    requisitionQty: item.requisitionQty || 0
  }));
 
  const postData = {
    id: orderId,
    drawMaterials: JSON.stringify(drawMaterialsList)
  };
 
  saving.value = true;
  try {
    await drawMaterials(postData);
    ElMessage.success('领料保存成功');
    visible.value = false;
    materialList.value = [];
    activeTab.value = 'material';
    emit('confirm');
  } catch (error) {
    console.error('保存领料失败:', error);
    ElMessage.error('保存领料失败');
  } finally {
    saving.value = false;
  }
};
</script>
 
<style scoped lang="scss">
.material-requisition-form {
  .operation-bar {
    margin-bottom: 15px;
  }
 
  .el-tabs {
    height: 100%;
  }
 
  .el-table {
    margin-top: 10px;
  }
}
 
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
 
:deep(.el-dialog) {
  height: 85vh;
  margin-top: 3vh !important;
  display: flex;
  flex-direction: column;
}
 
:deep(.el-dialog__body) {
  flex: 1;
  overflow-y: auto;
  padding: 15px 20px;
}
 
:deep(.el-dialog__header) {
  padding: 15px 20px;
  border-bottom: 1px solid #e4e7ed;
}
 
:deep(.el-dialog__footer) {
  padding: 15px 20px;
  border-top: 1px solid #e4e7ed;
}
 
:deep(.el-tabs__content) {
  height: calc(100% - 55px);
}
 
:deep(.el-tab-pane) {
  height: 100%;
}
</style>