支持编辑配方

This commit is contained in:
2025-11-24 15:11:42 +08:00
parent 3505fcb250
commit 985f84ad79

View File

@@ -1,7 +1,7 @@
<template> <template>
<el-dialog <el-dialog
:model-value="visible" :model-value="visible"
:title="`配方详情: ${recipe ? recipe.name : ''}`" :title="`配方详情: ${recipe ? recipe.name : ''}` + (isEditing ? ' (编辑中)' : '')"
@close="handleClose" @close="handleClose"
width="70%" width="70%"
top="5vh" top="5vh"
@@ -20,14 +20,37 @@
</div> </div>
<el-tabs v-else v-model="activeTab"> <el-tabs v-else v-model="activeTab">
<el-tab-pane label="原料列表" name="ingredients"> <el-tab-pane label="原料列表" name="ingredients">
<el-table :data="ingredientDetails" style="width: 100%"> <div v-if="!isEditing">
<el-table-column prop="name" label="原料名称" /> <el-table :data="ingredientDetails" style="width: 100%">
<el-table-column prop="percentage" label="占比"> <el-table-column prop="name" label="原料名称" />
<template #default="scope"> <el-table-column prop="percentage" label="占比">
{{ (scope.row.percentage * 100).toFixed(2) }}% <template #default="scope">
</template> {{ (scope.row.percentage * 100).toFixed(2) }}%
</el-table-column> </template>
</el-table> </el-table-column>
</el-table>
</div>
<div v-else>
<el-table :data="localIngredientDetails" style="width: 100%">
<el-table-column prop="name" label="原料名称" />
<el-table-column label="占比">
<template #default="scope">
<el-input-number v-model="scope.row.percentage" :min="0" :max="1" :step="0.01" :precision="2" @change="updateNutrientSummary"></el-input-number>
</template>
</el-table-column>
<el-table-column label="操作">
<template #default="scope">
<el-button type="danger" :icon="Delete" circle @click="removeIngredient(scope.$index)"></el-button>
</template>
</el-table-column>
</el-table>
<div class="add-ingredient-section">
<el-select v-model="newIngredientId" placeholder="选择要添加的原料" filterable style="flex-grow: 1;">
<el-option v-for="item in availableRawMaterials" :key="item.id" :label="item.name" :value="item.id"></el-option>
</el-select>
<el-button type="primary" @click="addIngredient" style="margin-left: 10px;">添加原料</el-button>
</div>
</div>
</el-tab-pane> </el-tab-pane>
<el-tab-pane label="营养成分汇总" name="nutrients"> <el-tab-pane label="营养成分汇总" name="nutrients">
<el-table :data="nutrientSummary" style="width: 100%" ref="nutrientTableRef"> <el-table :data="nutrientSummary" style="width: 100%" ref="nutrientTableRef">
@@ -42,15 +65,20 @@
</el-tabs> </el-tabs>
<template #footer> <template #footer>
<span class="dialog-footer"> <span class="dialog-footer">
<el-button @click="handleClose">关闭</el-button> <el-button v-if="!isEditing" @click="handleEdit">编辑配方</el-button>
<el-button v-else @click="handleCancelEdit">取消</el-button>
<el-button v-if="isEditing" type="primary" @click="handleSaveRecipe">保存</el-button>
<el-button v-else @click="handleClose">关闭</el-button>
</span> </span>
</template> </template>
</el-dialog> </el-dialog>
</template> </template>
<script> <script>
import { ref, watch, nextTick } from 'vue'; import { ref, watch, nextTick, computed } from 'vue';
import { getRawMaterialById } from '../../api/feed'; import { getRawMaterialById, getRawMaterials, updateRecipe } from '../../api/feed';
import { ElMessage } from 'element-plus';
import { Delete } from '@element-plus/icons-vue';
export default { export default {
name: 'RecipeDetailDialog', name: 'RecipeDetailDialog',
@@ -61,14 +89,18 @@ export default {
default: () => null, default: () => null,
}, },
}, },
emits: ['update:visible'], emits: ['update:visible', 'recipe-updated'], // 添加 recipe-updated 事件
setup(props, { emit }) { setup(props, { emit }) {
const isEditing = ref(false); // 控制是否处于编辑模式
const activeTab = ref('ingredients'); const activeTab = ref('ingredients');
const loading = ref(false); const loading = ref(false);
const error = ref(null); const error = ref(null);
const ingredientDetails = ref([]); const ingredientDetails = ref([]); // 显示模式下的原料详情
const localIngredientDetails = ref([]); // 编辑模式下的原料详情
const nutrientSummary = ref([]); const nutrientSummary = ref([]);
const nutrientTableRef = ref(null); const nutrientTableRef = ref(null);
const allRawMaterials = ref([]); // 所有可用原料列表
const newIngredientId = ref(null); // 待添加的新原料ID
const handleClose = () => { const handleClose = () => {
emit('update:visible', false); emit('update:visible', false);
@@ -91,6 +123,12 @@ export default {
return Array.from(summary, ([name, value]) => ({ name, value })); return Array.from(summary, ([name, value]) => ({ name, value }));
}; };
// 计算属性,用于过滤掉已经存在的原料
const availableRawMaterials = computed(() => {
const existingIngredientIds = new Set(localIngredientDetails.value.map(ing => ing.id));
return allRawMaterials.value.filter(material => !existingIngredientIds.has(material.id));
});
watch(() => props.visible, async (newVal) => { watch(() => props.visible, async (newVal) => {
if (newVal && props.recipe) { if (newVal && props.recipe) {
loading.value = true; loading.value = true;
@@ -104,7 +142,9 @@ export default {
percentage: props.recipe.recipe_ingredients[index].percentage, percentage: props.recipe.recipe_ingredients[index].percentage,
})); }));
ingredientDetails.value = details; ingredientDetails.value = details; // 用于显示模式
localIngredientDetails.value = JSON.parse(JSON.stringify(details)); // 用于编辑模式,深拷贝
nutrientSummary.value = calculateNutrientSummary(details); nutrientSummary.value = calculateNutrientSummary(details);
} catch (err) { } catch (err) {
@@ -116,8 +156,10 @@ export default {
} else { } else {
// 重置数据 // 重置数据
ingredientDetails.value = []; ingredientDetails.value = [];
localIngredientDetails.value = [];
nutrientSummary.value = []; nutrientSummary.value = [];
activeTab.value = 'ingredients'; activeTab.value = 'ingredients';
isEditing.value = false; // 关闭对话框时重置编辑状态
} }
}); });
@@ -131,14 +173,105 @@ export default {
} }
}); });
// 实时更新营养成分汇总
const updateNutrientSummary = () => {
nutrientSummary.value = calculateNutrientSummary(localIngredientDetails.value);
};
// 进入编辑模式
const handleEdit = async () => {
isEditing.value = true;
// 获取所有原料列表
try {
const response = await getRawMaterials({ page_size: 999 });
if (response.data && response.data.list) {
allRawMaterials.value = response.data.list;
}
} catch (err) {
ElMessage.error('获取所有原料失败: ' + (err.message || '未知错误'));
}
};
// 取消编辑
const handleCancelEdit = () => {
isEditing.value = false;
// 恢复到原始数据
localIngredientDetails.value = JSON.parse(JSON.stringify(ingredientDetails.value));
updateNutrientSummary(); // 重新计算营养成分
};
// 保存配方
const handleSaveRecipe = async () => {
// 验证占比总和是否为1
const totalPercentage = localIngredientDetails.value.reduce((sum, ing) => sum + ing.percentage, 0);
if (Math.abs(totalPercentage - 1) > 0.001) { // 允许浮点数误差
ElMessage.error(`原料总占比必须为100%,当前为${(totalPercentage * 100).toFixed(2)}%`);
return;
}
// 构造保存数据
const recipeToSave = {
id: props.recipe.id,
name: props.recipe.name, // 名称不变
description: props.recipe.description, // 描述不变
recipe_ingredients: localIngredientDetails.value.map(ing => ({
raw_material_id: ing.id,
percentage: ing.percentage,
})),
};
try {
await updateRecipe(recipeToSave.id, recipeToSave);
ElMessage.success('配方更新成功');
isEditing.value = false;
emit('recipe-updated'); // 通知父组件配方已更新
} catch (err) {
ElMessage.error('保存配方失败: ' + (err.message || '未知错误'));
}
};
// 移除原料
const removeIngredient = (index) => {
localIngredientDetails.value.splice(index, 1);
updateNutrientSummary();
};
// 添加原料
const addIngredient = () => {
if (!newIngredientId.value) {
ElMessage.warning('请选择要添加的原料');
return;
}
const materialToAdd = allRawMaterials.value.find(m => m.id === newIngredientId.value);
if (materialToAdd && !localIngredientDetails.value.some(ing => ing.id === materialToAdd.id)) {
localIngredientDetails.value.push({ ...materialToAdd, percentage: 0 }); // 默认占比0
newIngredientId.value = null;
updateNutrientSummary();
} else if (localIngredientDetails.value.some(ing => ing.id === materialToAdd.id)) {
ElMessage.warning('该原料已存在于配方中');
}
};
return { return {
activeTab, activeTab,
loading, loading,
error, error,
ingredientDetails, ingredientDetails,
localIngredientDetails,
nutrientSummary, nutrientSummary,
nutrientTableRef, nutrientTableRef,
handleClose, handleClose,
isEditing,
handleEdit,
handleCancelEdit,
handleSaveRecipe,
removeIngredient,
addIngredient,
availableRawMaterials,
newIngredientId,
updateNutrientSummary,
Delete, // 暴露 Delete 图标组件
}; };
}, },
}; };
@@ -152,4 +285,9 @@ export default {
.dialog-footer { .dialog-footer {
text-align: right; text-align: right;
} }
.add-ingredient-section {
margin-top: 20px;
display: flex;
align-items: center;
}
</style> </style>