张诺
11 小时以前 7c86b549b27bd54f6bd5de81c13f8242f91c87ff
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
<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogType === 'add' ? '新增生产加工' : '编辑生产加工'"
    width="1200px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-row :gutter="10" style="margin-bottom: 10px">
      <el-col :span="3">
        <el-button type="primary" @click="handlData"
          ><el-icon>
            <Plus /> </el-icon
          >选择数据</el-button
        >
      </el-col>
      <el-col :span="4">
        <el-button
          type="danger"
          @click="removeSelectedData"
          :disabled="tableData.length === 0"
        >
          <el-icon>
            <Delete />
          </el-icon>
          清空已选
        </el-button>
      </el-col>
      <el-col :span="17" style="text-align: right; line-height: 32px">
        <el-text type="info" size="small">
          已选择 {{ tableData.length }} 项数据
          <span v-if="tableData.length > 0">
            ,总使用量: {{ totalUsedQuantity.toFixed(2) }}
          </span>
        </el-text>
      </el-col>
    </el-row>
    <ETableModify
      :columns="columns"
      :showOperations="false"
      height="200"
      @cell-edit="handleCellEdit"
      :tableData="tableData"
      :showOverflowTooltip="false"
      @row-click="handleRowClick"
      :editableColumns="['usedQuantity']"
      @delete="handleRemoveItem"
    />
    <div class="empty-table">
      <h1>生产明细</h1>
      <el-row :gutter="10">
        <el-col :span="2">
          <el-button type="primary" @click="addNewRow">
            <el-icon>
              <Plus />
            </el-icon>
            新增
          </el-button>
        </el-col>
        <el-col :span="2">
          <el-button type="danger" @click="clearAllRows">
            <el-icon>
              <Delete />
            </el-icon>
            清空
          </el-button>
        </el-col>
        <!-- <el-col :span="2">
        <el-button type="warning" @click="calculateAllCosts">
          <el-icon>
            <Warning />
          </el-icon> 重新计算
        </el-button>
      </el-col> -->
      </el-row>
      <ProductionDetailsTable
        v-model="detailsTableData"
        :border="false"
        :show-operations="true"
        :auto-calculate="true"
        @input-change="handleDetailsChange"
        @delete-row="handleDeleteRow"
      />
    </div>
 
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose" v-if="dialogType === 'add'"
          >取 消</el-button
        >
        <el-button @click="handleReset" v-if="dialogType === 'edit'"
          >重 置</el-button
        >
        <el-button type="primary" :loading="loading" @click="handleSubmit"
          >确 定</el-button
        >
      </div>
    </template>
  </el-dialog>
  <el-dialog
    v-model="innerVisible"
    width="1000"
    title="选择配置数据"
    center
    append-to-body
  >
    <div style="margin-bottom: 10px">
      <el-alert
        v-if="tableData.length > 0"
        :title="`当前已选择 ${tableData.length} 条数据`"
        type="info"
        :closable="false"
        show-icon
      />
    </div>
    <ETable
      @selection-change="handleSelectionChange"
      :showOperations="false"
      ref="etableRef"
      :columns="formalDatabaseColumns"
      :tableData="formalDatabaseData"
      :defaultSelectedIds="selectedIds"
      :rowKey="'id'"
      height="400"
      @cell-edit="handleCellEdit"
      :show-selection="true"
    />
    <el-row :gutter="24" style="margin-top: 15px">
      <el-col :span="12">
        <el-text type="info">
          已选择 {{ formalDatabaseSelectedData.length }} 条数据
        </el-text>
      </el-col>
      <el-col :span="12" style="text-align: right">
        <el-button @click="innerVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="handleSelectData"
          :disabled="formalDatabaseSelectedData.length === 0"
        >
          确定添加
        </el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>
 
<script setup>
import { ref, reactive, watch, onMounted, nextTick, computed } from "vue";
import ETable from "@/components/Table/ETable.vue";
import ETableModify from "@/components/Table/EtableModify.vue";
import ProductionDetailsTable from "./ProductionDetailsTable.vue";
import { ElMessage, ElMessageBox, ElAlert, ElText } from "element-plus";
import { Delete, Warning, Plus } from "@element-plus/icons-vue";
import { getOfficialAll, addOrEditPM } from "@/api/production/index.js";
import { getCurrentInstance } from "vue";
 
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  type: {
    type: String,
    default: "add", // 'add' 或 'edit'
  },
  rowData: {
    type: Object,
    default: () => ({}),
  },
});
const dialogVisible = defineModel("visible", {
  type: Boolean,
  default: false,
});
const emit = defineEmits(["update:visible", "success"]);
 
const innerVisible = ref(false);
const dialogType = ref("add");
const loading = ref(false);
const formRef = ref(null);
const tableData = ref([]);
const currentRow = ref(null);
const columns = [
  { label: "煤种", prop: "coal", minwidth: 120 },
  { label: "库存数量", prop: "inventoryQuantity", minwidth: 100 },
  {
    label: "使用数量",
    prop: "usedQuantity",
    editable: true,
    minwidth: 120,
    editType: "number",
  },
];
const etableRef = ref(null);
const selectedIds = ref([]); // 默认选中的ID数组
// 调试函数:验证ID匹配逻辑
const debugIdMatching = () => {
  if (formalDatabaseData.value.length > 0 && selectedIds.value.length > 0) {
    const matchedRows = formalDatabaseData.value.filter((row) =>
      selectedIds.value.includes(row.id)
    );
  }
};
const detailsTableData = ref([]);
const handleRowClick = (row) => {
  currentRow.value = row;
};
const formalDatabaseColumns = ref([
  { prop: "supplierName", label: "供应商名称", minwidth: 150 },
  { prop: "coal", label: "煤种类型", minwidth: 60 },
  { prop: "inventoryQuantity", label: "库存数量", minwidth: 80 },
  { prop: "unit", label: "单位", minwidth: 100 },
  { prop: "priceExcludingTax", label: "单价(不含税)", minwidth: 80 },
  { prop: "createTime", label: "登记日期", minwidth: 400 },
]);
// 表单数据
const formData = reactive({
  category: "",
  unit: "",
  productionVolume: 0,
  laborCost: 0,
  materialCost: 0,
  equipmentCost: 0,
  totalCost: 0,
  totalPrice: 0,
  profit: 0,
  reviewer: "",
  date: "",
});
const handlData = async () => {
  innerVisible.value = true;
  let res = await getOfficialAll();
  if (res.code === 200) {
    formalDatabaseData.value = res.data;
    const existingOfficialIds = tableData.value
      .map((item) => item.officialId)
      .filter((id) => id);
    selectedIds.value = existingOfficialIds;
    debugIdMatching();
    nextTick(() => {
      setTimeout(() => {
        if (etableRef.value && existingOfficialIds.length > 0) {
          etableRef.value.setDefaultSelection();
        }
      }, 100);
    });
  } else {
    ElMessage.error("获取配置数据失败");
  }
};
// 手动设置表格选中状态
const setTableSelection = (ids) => {
  if (!etableRef.value || !Array.isArray(ids) || ids.length === 0) {
    return;
  }
 
  nextTick(() => {
    setTimeout(() => {
      try {
        // 先清除所有选中
        etableRef.value.clearSelection();
 
        // 找到需要选中的行并设置选中状态
        // 注意:ids中是officialId,需要匹配formalDatabaseData中的id字段
        const rowsToSelect = formalDatabaseData.value.filter((row) =>
          ids.includes(row.id)
        );
        if (rowsToSelect.length > 0) {
          etableRef.value.setRowsSelection(rowsToSelect, true);
          console.log("选中状态设置完成");
        } else {
        }
      } catch (error) {
        console.error("设置选中状态失败:", error);
      }
    }, 150);
  });
};
 
const formalDatabaseData = ref([]);
const formalDatabaseSelectedData = ref([]);
formalDatabaseData.value = [];
// 初始化
const Initialization = () => {
  tableData.value = [];
  detailsTableData.value = [];
  copyForm.value = null;
  dialogType.value = "add";
};
const copyForm = ref(null);
const editInitialization = (data) => {
  copyForm.value = { ...data }; // 深拷贝数据
  tableData.value = data.productionInventoryList || [];
  detailsTableData.value = data.productionList || [];
  dialogType.value = "edit";
 
  // 设置默认选中的ID,使用officialId来匹配
  const existingOfficialIds = tableData.value
    .map((item) => item.officialId)
    .filter((id) => id);
  selectedIds.value = existingOfficialIds;
};
// 监听对话框状态,在打开时设置选中状态
watch(innerVisible, (newVal) => {
  if (newVal && selectedIds.value.length > 0) {
    console.log("对话框打开,设置选中状态");
    setTimeout(() => setTableSelection(selectedIds.value), 200);
  }
  // 对话框关闭时清空选择状态
  if (!newVal) {
    formalDatabaseSelectedData.value = [];
  }
});
 
defineExpose({
  Initialization,
  editInitialization,
});
const handleSelectData = (row) => {
  tableData.value = [];
  if (!innerVisible.value) return;
  const selectedData = formalDatabaseSelectedData.value;
  if (selectedData.length === 0) {
    ElMessage.warning("请至少选择一条数据");
    return;
  }
  let addedCount = 0;
  let duplicateCount = 0;
  selectedData.forEach((item) => {
    const newItem = {
      ...item, // 复制所有原始数据
      officialId: item.id, // 保存原始的id作为officialId
      usedQuantity: 0, // 初始使用数量为0
      // 可以根据需要添加其他字段
    };
    tableData.value.push(newItem);
    addedCount++;
  });
 
  // 更新selectedIds,确保包含所有当前tableData中的officialId
  const allOfficialIds = tableData.value
    .map((item) => item.officialId)
    .filter((id) => id);
  selectedIds.value = allOfficialIds;
 
  console.log("更新后的表格数据:", tableData.value);
  console.log("更新后的选中ID:", selectedIds.value);
 
  // 关闭选择对话框
  innerVisible.value = false;
 
  // 显示结果消息
  let message = "";
  if (addedCount > 0) {
    message += `成功添加 ${addedCount} 条数据`;
  }
  if (duplicateCount > 0) {
    message += (message ? "," : "") + `跳过 ${duplicateCount} 条重复数据`;
  }
  if (message) {
    ElMessage.success(message);
  } else {
    ElMessage.info("没有新数据被添加");
  }
};
const handleSelectionChange = (selection) => {
  formalDatabaseSelectedData.value = selection;
};
const handleReset = () => {
  console.log(copyForm.value);
  tableData.value =
    JSON.parse(JSON.stringify(copyForm.value.productionInventoryList)) || [];
  detailsTableData.value =
    JSON.parse(JSON.stringify(copyForm.value.productionList)) || [];
};
// 提交表单
const handleSubmit = async () => {
  let data = {
    productionList: detailsTableData.value,
    productionInventoryList: tableData.value,
    ...copyForm.value,
  };
  let res = await addOrEditPM(data);
  if (res.code === 200) {
    dialogVisible.value = false;
    emit("success");
  } else {
    ElMessage.error("提交失败");
  }
};
 
// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false;
  formRef.value?.resetFields();
  Object.assign(formData, {
    category: "",
    unit: "",
    productionVolume: 0,
    laborCost: 0,
    materialCost: 0,
    equipmentCost: 0,
    totalCost: 0,
    totalPrice: 0,
    profit: 0,
    reviewer: "",
    date: "",
  });
};
 
// 添加单元格编辑处理函数
const handleCellEdit = (row, prop, value) => {
  if (prop === "usedQuantity") {
    const numValue = Number(value);
    const inventory = Number(row.inventoryQuantity);
 
    // 验证输入值
    if (isNaN(numValue) || numValue < 0) {
      ElMessage.warning("使用数量必须是非负数!");
      row.usedQuantity = 0;
      return;
    }
 
    if (numValue > inventory) {
      ElMessage.warning(`使用数量不能大于库存数量(${inventory})!`);
      row.usedQuantity = inventory;
      return;
    }
 
    // 更新值
    row.usedQuantity = numValue;
    console.log(`更新 ${row.coal} 的使用数量为: ${numValue}`);
  }
};
 
// 处理生产明细表格的操作
const addNewRow = () => {
  detailsTableData.value.push({
    coal: "",
    productionQuantity: "",
    laborCost: "",
    energyConsumptionCost: "",
    equipmentDepreciation: "",
    purchasePrice: "",
    autoCalculate: "0.00",
    producer: "",
  });
};
 
const clearAllRows = () => {
  detailsTableData.value = [];
  ElMessage.success("已清空所有数据");
};
 
const handleDetailsChange = (data) => {
  console.log("生产明细数据变化:", data);
};
 
const handleDeleteRow = (index) => {
  ElMessage.success(`已删除第 ${index + 1} 行数据`);
};
 
// 删除单个已选数据项
const handleRemoveItem = (row) => {
  console.log("删除项:", row);
  const index = tableData.value.findIndex(
    (item) => item.officialId === row.officialId
  );
  if (index > -1) {
    tableData.value.splice(index, 1);
 
    // 更新selectedIds
    const updatedOfficialIds = tableData.value
      .map((item) => item.officialId)
      .filter((id) => id);
    selectedIds.value = updatedOfficialIds;
 
    console.log("删除后的表格数据:", tableData.value);
    console.log("更新后的选中ID:", selectedIds.value);
 
    ElMessage.success("已删除选中项");
  }
};
 
// 清空所有已选数据
const removeSelectedData = () => {
  if (tableData.value.length === 0) {
    ElMessage.warning("没有可清空的数据");
    return;
  }
 
  ElMessageBox.confirm("确认清空所有已选择的数据吗?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      tableData.value = [];
      selectedIds.value = [];
      console.log("已清空所有已选数据");
      ElMessage.success("已清空所有数据");
    })
    .catch(() => {
      console.log("取消清空操作");
    });
};
 
// 计算总使用量
const totalUsedQuantity = computed(() => {
  return tableData.value.reduce((total, item) => {
    const usedQty = Number(item.usedQuantity) || 0;
    return total + usedQty;
  }, 0);
});
</script>
 
<style scoped lang="scss">
.el-form {
  .el-row {
    padding-top: 20px;
    background: rgba($color: #f8fafb, $alpha: 0.5);
  }
}
 
.el-row > .el-col > h1 {
  font-weight: bolder;
}
.empty-table > .el-row {
  margin-bottom: 12px;
}
</style>