张诺
23 小时以前 7619d415522ab3dc3299d6a2a9f5c9964a692d3f
src/views/production/components/ProductionDialog.vue
@@ -9,9 +9,7 @@
    <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-icon> <Plus /> </el-icon>选择数据</el-button
        >
      </el-col>
      <el-col :span="4">
@@ -57,21 +55,14 @@
            新增
          </el-button>
        </el-col>
        <el-col :span="2">
        <!-- <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-col> -->
      </el-row>
      <ProductionDetailsTable
        v-model="detailsTableData"
@@ -85,12 +76,14 @@
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose" v-if="dialogType === 'add'"
        <el-button
          @click="handleClose"
          v-if="dialogType === 'add' || dialogType === 'edit'"
          >取 消</el-button
        >
        <el-button @click="handleReset" v-if="dialogType === 'edit'"
        <!-- <el-button @click="handleReset" v-if="dialogType === 'edit'"
          >重 置</el-button
        >
        > -->
        <el-button type="primary" :loading="loading" @click="handleSubmit"
          >确 定</el-button
        >
@@ -114,6 +107,8 @@
      />
    </div>
    <ETable
      :showIndex="false"
      :showOverflowTooltip="false"
      @selection-change="handleSelectionChange"
      :showOperations="false"
      ref="etableRef"
@@ -152,35 +147,45 @@
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";
import {
  getOfficialAll,
  addOrEditPM,
  deleteProductionInventory,
} from "@/api/production/index.js";
import { validateFormData, validateNumber, deepClone, createDefaultProductionRow } from "@/utils/production";
import { useCoalData } from "./useCoalData";
import useUserStore from "@/store/modules/user";
// Props 和 Emits
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  type: {
    type: String,
    default: "add", // 'add' 或 'edit'
  },
  rowData: {
    type: Object,
    default: () => ({}),
  },
  visible: { type: Boolean, default: false },
  type: { type: String, default: "add" },
  rowData: { type: Object, default: () => ({}) },
});
const dialogVisible = defineModel("visible", {
  type: Boolean,
  default: false,
});
const emit = defineEmits(["update:visible", "success"]);
const dialogVisible = defineModel("visible", { type: Boolean, default: false });
const emit = defineEmits(["update:visible", "success", "update:productionAndProcessing"]);
// 用户信息和煤种数据
const userStore = useUserStore();
const { getCoalNameById } = useCoalData();
let userInfo;
// 对话框状态
const innerVisible = ref(false);
const dialogType = ref("add");
const loading = ref(false);
const formRef = ref(null);
const etableRef = ref(null);
// 数据状态
const tableData = ref([]);
const detailsTableData = ref([]);
const formalDatabaseData = ref([]);
const formalDatabaseSelectedData = ref([]);
const selectedIds = ref([]);
const currentRow = ref(null);
const copyForm = ref(null);
// 表格列配置
const columns = [
  { label: "煤种", prop: "coal", minwidth: 120 },
  { label: "库存数量", prop: "inventoryQuantity", minwidth: 100 },
@@ -192,9 +197,16 @@
    editType: "number",
  },
];
const etableRef = ref(null);
const selectedIds = ref([]); // 默认选中的ID数组
// 调试函数:验证ID匹配逻辑
const formalDatabaseColumns = ref([
  { prop: "supplierName", label: "供应商名称", minwidth: 150 },
  { prop: "coal", label: "煤种类型", minwidth: 60 },
  { prop: "inventoryQuantity", label: "库存数量", minwidth: 80 },
  { prop: "unit", label: "单位", minwidth: 20 },
  { prop: "priceExcludingTax", label: "单价(不含税)", minwidth: 80 },
  { prop: "createTime", label: "登记日期", width: 200 },
]);
// 工具函数
const debugIdMatching = () => {
  if (formalDatabaseData.value.length > 0 && selectedIds.value.length > 0) {
    const matchedRows = formalDatabaseData.value.filter((row) =>
@@ -202,32 +214,12 @@
    );
  }
};
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();
@@ -258,44 +250,32 @@
  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 }; // 深拷贝数据
  copyForm.value = deepClone(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);
@@ -304,7 +284,6 @@
// 监听对话框状态,在打开时设置选中状态
watch(innerVisible, (newVal) => {
  if (newVal && selectedIds.value.length > 0) {
    console.log("对话框打开,设置选中状态");
    setTimeout(() => setTableSelection(selectedIds.value), 200);
  }
  // 对话框关闭时清空选择状态
@@ -344,9 +323,6 @@
    .filter((id) => id);
  selectedIds.value = allOfficialIds;
  console.log("更新后的表格数据:", tableData.value);
  console.log("更新后的选中ID:", selectedIds.value);
  // 关闭选择对话框
  innerVisible.value = false;
@@ -367,94 +343,99 @@
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 detailsValidation = validateFormData(detailsTableData.value, [
    "coal",
    "productionQuantity",
    "laborCost",
    "energyConsumptionCost",
    "equipmentDepreciation",
    "purchasePrice"
  ]);
  if (!detailsValidation.isValid) {
    ElMessage.warning(detailsValidation.message);
    return;
  }
  // 验证库存使用数据
  if (tableData.value.length === 0) {
    ElMessage.warning("请添加生产加工数据");
    return;
  }
  for (let i = 0; i < tableData.value.length; i++) {
    const element = tableData.value[i];
    if (element.usedQuantity == 0 || element.usedQuantity === null) {
      ElMessage.warning(`请填写使用数量: ${element.coal}`);
      return;
    }
  }
  try {
    const data = {
      ...copyForm.value,
      productionList: detailsTableData.value,
      productionInventoryList: tableData.value,
    };
    const res = await addOrEditPM(data);
    if (res.code === 200) {
      dialogVisible.value = false;
      emit("success");
    } else {
      ElMessage.error("提交失败");
    }
  } catch (error) {
    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;
    const validation = validateNumber(value, 0, Number(row.inventoryQuantity));
    if (!validation.isValid) {
      ElMessage.warning(validation.message);
      row.usedQuantity = validation.value;
      return;
    }
    if (numValue > inventory) {
      ElMessage.warning(`使用数量不能大于库存数量(${inventory})!`);
      row.usedQuantity = inventory;
      return;
    }
    // 更新值
    row.usedQuantity = numValue;
    console.log(`更新 ${row.coal} 的使用数量为: ${numValue}`);
    row.usedQuantity = validation.value;
  }
};
// 处理生产明细表格的操作
// 处理生产明细表格的操作 - 使用工具函数
const addNewRow = () => {
  detailsTableData.value.push({
    coal: "",
    productionQuantity: "",
    laborCost: "",
    energyConsumptionCost: "",
    equipmentDepreciation: "",
    purchasePrice: "",
    autoCalculate: "0.00",
    producer: "",
  });
  const newRow = createDefaultProductionRow(userInfo);
  detailsTableData.value.push(newRow);
};
const clearAllRows = () => {
  detailsTableData.value = [];
  ElMessage.success("已清空所有数据");
// 重置数据 - 使用深拷贝
const handleReset = () => {
  if (copyForm.value) {
    tableData.value = deepClone(copyForm.value.productionInventoryList) || [];
    detailsTableData.value = deepClone(copyForm.value.productionList) || [];
  }
};
// 获取用户信息
onMounted(async () => {
  try {
    userInfo = await userStore.getInfo();
  } catch (error) {
    ElMessage.error("获取用户信息失败,请重试");
  }
});
// 简化的事件处理函数
const handleDetailsChange = (data) => {
  console.log("生产明细数据变化:", data);
};
const handleDeleteRow = (index) => {
@@ -463,7 +444,6 @@
// 删除单个已选数据项
const handleRemoveItem = (row) => {
  console.log("删除项:", row);
  const index = tableData.value.findIndex(
    (item) => item.officialId === row.officialId
  );
@@ -475,10 +455,6 @@
      .map((item) => item.officialId)
      .filter((id) => id);
    selectedIds.value = updatedOfficialIds;
    console.log("删除后的表格数据:", tableData.value);
    console.log("更新后的选中ID:", selectedIds.value);
    ElMessage.success("已删除选中项");
  }
};
@@ -489,21 +465,26 @@
    ElMessage.warning("没有可清空的数据");
    return;
  }
  ElMessageBox.confirm("确认清空所有已选择的数据吗?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
    .then(async () => {
      if (dialogType.value === "edit") {
        let res = await deleteProductionInventory({
          productionInventoryList: tableData.value,
        });
        emit("update:productionAndProcessing", tableData.value, copyForm.value);
      }
      // [Vue warn]: Component emitted event "update:productionAndProcessing" but it is neither declared in the emits option nor as an "onUpdate:productionAndProcessing" prop.
      formalDatabaseSelectedData.value = [];
      tableData.value = [];
      selectedIds.value = [];
      console.log("已清空所有已选数据");
      ElMessage.success("已清空所有数据");
    })
    .catch(() => {
      console.log("取消清空操作");
    });
    .catch(() => {});
};
// 计算总使用量