<template>
  <div class="pig-nutrient-requirements-display">
    <div v-if="!isEditing">
      <div class="edit-button-container">
        <el-button type="primary" @click="handleEdit">编辑营养需求</el-button>
      </div>
      <el-table :data="nutrientRequirements" border style="width: 100%; max-height: 300px; overflow-y: auto;">
        <el-table-column prop="nutrient_name" label="营养素名称"></el-table-column>
        <el-table-column prop="min_requirement" label="最小需求量"></el-table-column>
        <el-table-column prop="max_requirement" label="最大需求量"></el-table-column>
      </el-table>
      <div v-if="nutrientRequirements.length === 0" class="no-data-message">
        暂无该品种该年龄阶段的营养需求数据。
      </div>
    </div>

    <PigNutrientRequirementsEditor
      v-else
      :initialNutrientRequirements="nutrientRequirements"
      :pigTypeId="pigTypeId"
      @save="handleSave"
      @cancel="handleCancel"
    ></PigNutrientRequirementsEditor>
  </div>
</template>

<script>
import { defineComponent, ref } from 'vue';
import PigNutrientRequirementsEditor from './PigNutrientRequirementsEditor.vue';

export default defineComponent({
  name: 'PigNutrientRequirementsDisplay',
  components: {
    PigNutrientRequirementsEditor,
  },
  props: {
    nutrientRequirements: {
      type: Array,
      default: () => [],
    },
    pigTypeId: { // 猪类型ID，用于传递给编辑器组件
      type: Number,
      required: true,
    },
  },
  emits: ['refresh'], // 声明触发的事件，用于通知父组件刷新数据
  setup(props, { emit }) {
    const isEditing = ref(false); // 控制显示展示模式还是编辑模式

    const handleEdit = () => {
      isEditing.value = true;
    };

    const handleSave = () => {
      isEditing.value = false;
      emit('refresh'); // 通知父组件刷新数据
    };

    const handleCancel = () => {
      isEditing.value = false;
    };

    return {
      isEditing,
      handleEdit,
      handleSave,
      handleCancel,
    };
  },
});
</script>

<style scoped>
.pig-nutrient-requirements-display {
  padding: 10px;
}

.no-data-message {
  text-align: center;
  color: #909399;
  margin-top: 20px;
}
.edit-button-container {
  margin-bottom: 20px; /* 调整按钮与表格之间的间距 */
  text-align: right;
}
</style>
