<template>
  <div>
    <!-- 搜索区域 -->
    <div style="margin-bottom: 20px; display: flex; align-items: center; gap: 10px;">
      <el-input
          v-model="searchKeyword"
          placeholder="请输入猪品种名称"
          clearable
          style="width: 300px;"
          @keyup.enter="handleSearch"
      ></el-input>
      <el-button type="primary" @click="handleSearch">搜索</el-button>
    </div>

    <!-- 猪品种列表 -->
    <el-table :data="tableData" style="width: 100%" v-loading="loading" row-key="id"
              :expand-row-keys="expandRowKeys" @expand-change="handleExpandChange">
      <el-table-column type="expand">
        <template #default="props">
          <div style="padding: 10px 20px;">
            <h4>该品种下的年龄阶段简介</h4>
            <el-table :data="props.row.pig_types" border>
              <el-table-column prop="age_stage_name" label="年龄阶段"></el-table-column>
              <el-table-column prop="description" label="描述"></el-table-column>
              <el-table-column prop="min_days" label="最小天数"></el-table-column>
              <el-table-column prop="max_days" label="最大天数"></el-table-column>
              <el-table-column prop="min_weight" label="最小体重(kg)" :formatter="weightFormatter"></el-table-column>
              <el-table-column prop="max_weight" label="最大体重(kg)" :formatter="weightFormatter"></el-table-column>
              <el-table-column prop="daily_gain_weight" label="日增重(kg)" :formatter="weightFormatter"></el-table-column>
              <el-table-column prop="daily_feed_intake" label="日采食量(kg)" :formatter="weightFormatter"></el-table-column>
            </el-table>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="品种名称"></el-table-column>
      <el-table-column prop="description" label="描述"></el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        style="margin-top: 20px;"
        :current-page="pagination.page"
        :page-size="pagination.page_size"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    ></el-pagination>
  </div>
</template>

<script>
import {ref, onMounted} from 'vue';
import {FeedApi} from '../../api/feed';
import {ElMessageBox, ElMessage} from 'element-plus';

export default {
  name: 'PigBreedTable',
  emits: ['edit'], // 声明触发的事件
  setup(props, { emit }) {
    const tableData = ref([]);
    const loading = ref(false);
    const searchKeyword = ref('');
    const expandRowKeys = ref([]); // 用于控制展开行

    const pagination = ref({
      page: 1,
      page_size: 10,
      total: 0,
    });

    const fetchPigBreeds = async () => {
      loading.value = true;
      try {
        const params = {
          page: pagination.value.page,
          page_size: pagination.value.page_size,
          order_by: 'id ASC', // 默认按 ID 升序排序
        };

        if (searchKeyword.value) {
          params.name = searchKeyword.value; // 按名称模糊查询
        }

        const response = await FeedApi.getPigBreeds(params);

        if (response.data) {
          tableData.value = response.data.list;
          pagination.value.total = response.data.pagination.total;
        }
      } catch (error) {
        console.error('获取猪品种列表失败:', error);
        ElMessage.error('获取猪品种列表失败');
      } finally {
        loading.value = false;
      }
    };

    const handleSearch = () => {
      pagination.value.page = 1;
      fetchPigBreeds();
    };

    const handleSizeChange = (size) => {
      pagination.value.page_size = size;
      fetchPigBreeds();
    };

    const handleCurrentChange = (page) => {
      pagination.value.page = page;
      fetchPigBreeds();
    };

    // 处理行展开/折叠事件
    const handleExpandChange = async (row, expandedRows) => {
      const isExpanded = expandedRows.some(r => r.id === row.id);
      // 优化：仅在展开时且数据未加载时才请求
      // 注意：PigBreedResponse 默认不包含 pig_types 字段，需要单独请求
      if (isExpanded && (!row.pig_types || row.pig_types.length === 0)) {
        try {
          // 调用 getPigTypes 接口，按 breed_id 筛选
          const response = await FeedApi.getPigTypes({ breed_id: row.id, page: 1, page_size: 999 }); // 获取所有相关猪类型
          if (response.data && response.data.list) {
            const index = tableData.value.findIndex(item => item.id === row.id);
            if (index !== -1) {
              tableData.value[index].pig_types = response.data.list;
            }
          }
        } catch (error) {
          console.error('获取该品种下的猪类型失败:', error);
          ElMessage.error('获取猪类型失败');
        }
      }
    };

    // 将克转换为公斤并格式化，只返回数值
    const weightFormatter = (row, column, cellValue) => {
      if (typeof cellValue === 'number') {
        return (cellValue / 1000).toFixed(2);
      }
      return cellValue;
    };

    const handleEdit = (row) => {
      emit('edit', row); // 触发 edit 事件，并传递当前行数据
    };

    const handleDelete = (row) => {
      ElMessageBox.confirm(
          `确定要删除猪品种 "${row.name}" 吗？`,
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
      ).then(async () => {
        try {
          await FeedApi.deletePigBreed(row.id);
          ElMessage.success('删除成功');
          await fetchPigBreeds();
        } catch (error) {
          ElMessage.error('删除失败: ' + (error.message || '未知错误'));
        }
      }).catch(() => {
        // 用户取消操作
      });
    };

    onMounted(() => {
      fetchPigBreeds();
    });

    return {
      tableData,
      loading,
      searchKeyword,
      expandRowKeys,
      pagination,
      handleSearch,
      handleSizeChange,
      handleCurrentChange,
      handleExpandChange,
      weightFormatter, // 暴露给模板
      handleEdit,
      handleDelete,
      fetchPigBreeds, // 将方法暴露出去
    };
  },
};
</script>

<style scoped>
</style>
