<template>
  <div class="cattle-management">
    <a-card title="牛只档案管理" :bordered="false">
      <!-- 操作按钮 -->
      <template #extra>
        <a-space>
          <a-button type="primary" @click="showAddModal = true">
            <template #icon><PlusOutlined /></template>
            添加牛只
          </a-button>
          <a-button @click="loadCattle">
            <template #icon><ReloadOutlined /></template>
            刷新
          </a-button>
          <a-button @click="exportData">
            <template #icon><ExportOutlined /></template>
            导出
          </a-button>
        </a-space>
      </template>

      <!-- 统计卡片 -->
      <div class="stats-section">
        <a-row :gutter="16" style="margin-bottom: 24px;">
          <a-col :span="6">
            <a-card :bordered="false" class="stat-card">
              <a-statistic
                title="总牛只数量"
                :value="stats.total"
                suffix="头"
                :value-style="{ color: '#3f8600' }"
              />
            </a-card>
          </a-col>
          <a-col :span="6">
            <a-card :bordered="false" class="stat-card">
              <a-statistic
                title="健康牛只"
                :value="stats.healthy"
                suffix="头"
                :value-style="{ color: '#52c41a' }"
              />
            </a-card>
          </a-col>
          <a-col :span="6">
            <a-card :bordered="false" class="stat-card">
              <a-statistic
                title="平均体重"
                :value="stats.avgWeight"
                suffix="kg"
                :value-style="{ color: '#1890ff' }"
              />
            </a-card>
          </a-col>
          <a-col :span="6">
            <a-card :bordered="false" class="stat-card">
              <a-statistic
                title="本月新增"
                :value="stats.monthlyNew"
                suffix="头"
                :value-style="{ color: '#722ed1' }"
              />
            </a-card>
          </a-col>
        </a-row>
      </div>

      <!-- 搜索表单 -->
      <div class="search-form">
        <a-form layout="inline" :model="searchForm" @finish="handleSearch">
          <a-form-item label="耳标号">
            <a-input v-model:value="searchForm.ear_tag" placeholder="请输入耳标号" />
          </a-form-item>
          <a-form-item label="品种">
            <a-select v-model:value="searchForm.breed" placeholder="请选择品种" style="width: 150px;">
              <a-select-option value="">全部品种</a-select-option>
              <a-select-option value="西门塔尔牛">西门塔尔牛</a-select-option>
              <a-select-option value="安格斯牛">安格斯牛</a-select-option>
              <a-select-option value="夏洛莱牛">夏洛莱牛</a-select-option>
              <a-select-option value="利木赞牛">利木赞牛</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="健康状态">
            <a-select v-model:value="searchForm.health_status" placeholder="请选择状态" style="width: 120px;">
              <a-select-option value="">全部状态</a-select-option>
              <a-select-option value="healthy">健康</a-select-option>
              <a-select-option value="sick">生病</a-select-option>
              <a-select-option value="quarantine">隔离</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="所有者">
            <a-input v-model:value="searchForm.owner_name" placeholder="请输入所有者" />
          </a-form-item>
          <a-form-item>
            <a-button type="primary" html-type="submit">搜索</a-button>
            <a-button style="margin-left: 8px;" @click="resetSearch">重置</a-button>
          </a-form-item>
        </a-form>
      </div>

      <!-- 牛只表格 -->
      <a-table
        :columns="columns"
        :data-source="cattle"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        row-key="id"
        :scroll="{ x: 1500 }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'ear_tag'">
            <a-tag color="blue">{{ record.ear_tag }}</a-tag>
          </template>
          <template v-else-if="column.key === 'health_status'">
            <a-tag :color="getHealthStatusColor(record.health_status)">
              {{ getHealthStatusText(record.health_status) }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'gender'">
            <a-tag :color="record.gender === 'male' ? 'blue' : 'pink'">
              {{ record.gender === 'male' ? '公牛' : '母牛' }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'age'">
            {{ calculateAge(record.birth_date) }}个月
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button type="link" size="small" @click="viewCattle(record)">查看</a-button>
              <a-button type="link" size="small" @click="editCattle(record)">编辑</a-button>
              <a-button type="link" size="small" @click="viewFeedingRecords(record)">饲养记录</a-button>
              <a-popconfirm
                title="确定要删除这头牛只吗？"
                @confirm="deleteCattle(record.id)"
              >
                <a-button type="link" size="small" danger>删除</a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 添加/编辑牛只模态框 -->
    <a-modal
      v-model:open="showAddModal"
      :title="editingCattle ? '编辑牛只' : '添加牛只'"
      @ok="handleSaveCattle"
      @cancel="handleCancel"
      :confirm-loading="saving"
      width="800px"
    >
      <a-form :model="cattleForm" :rules="rules" ref="cattleFormRef" layout="vertical">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="耳标号" name="ear_tag">
              <a-input v-model:value="cattleForm.ear_tag" placeholder="请输入耳标号" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="名称" name="name">
              <a-input v-model:value="cattleForm.name" placeholder="请输入牛只名称" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="品种" name="breed">
              <a-select v-model:value="cattleForm.breed" placeholder="请选择品种">
                <a-select-option value="西门塔尔牛">西门塔尔牛</a-select-option>
                <a-select-option value="安格斯牛">安格斯牛</a-select-option>
                <a-select-option value="夏洛莱牛">夏洛莱牛</a-select-option>
                <a-select-option value="利木赞牛">利木赞牛</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="性别" name="gender">
              <a-radio-group v-model:value="cattleForm.gender">
                <a-radio value="male">公牛</a-radio>
                <a-radio value="female">母牛</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="出生日期" name="birth_date">
              <a-date-picker
                v-model:value="cattleForm.birth_date"
                style="width: 100%;"
                placeholder="请选择出生日期"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="毛色" name="color">
              <a-input v-model:value="cattleForm.color" placeholder="请输入毛色" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="体重(kg)" name="weight">
              <a-input-number
                v-model:value="cattleForm.weight"
                :min="0"
                :max="2000"
                style="width: 100%;"
                placeholder="请输入体重"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="健康状态" name="health_status">
              <a-select v-model:value="cattleForm.health_status" placeholder="请选择健康状态">
                <a-select-option value="healthy">健康</a-select-option>
                <a-select-option value="sick">生病</a-select-option>
                <a-select-option value="quarantine">隔离</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-form-item label="牧场位置" name="farm_location">
          <a-input v-model:value="cattleForm.farm_location" placeholder="请输入牧场位置" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 查看牛只详情模态框 -->
    <a-modal
      v-model:open="showDetailModal"
      title="牛只详细信息"
      :footer="null"
      width="900px"
    >
      <div v-if="selectedCattle" class="cattle-detail">
        <a-descriptions title="基本信息" :column="2" bordered>
          <a-descriptions-item label="耳标号">
            <a-tag color="blue">{{ selectedCattle.ear_tag }}</a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="名称">{{ selectedCattle.name }}</a-descriptions-item>
          <a-descriptions-item label="品种">{{ selectedCattle.breed }}</a-descriptions-item>
          <a-descriptions-item label="性别">
            <a-tag :color="selectedCattle.gender === 'male' ? 'blue' : 'pink'">
              {{ selectedCattle.gender === 'male' ? '公牛' : '母牛' }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="出生日期">{{ selectedCattle.birth_date }}</a-descriptions-item>
          <a-descriptions-item label="年龄">{{ calculateAge(selectedCattle.birth_date) }}个月</a-descriptions-item>
          <a-descriptions-item label="毛色">{{ selectedCattle.color }}</a-descriptions-item>
          <a-descriptions-item label="体重">{{ selectedCattle.weight }}kg</a-descriptions-item>
          <a-descriptions-item label="健康状态">
            <a-tag :color="getHealthStatusColor(selectedCattle.health_status)">
              {{ getHealthStatusText(selectedCattle.health_status) }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="牧场位置">{{ selectedCattle.farm_location }}</a-descriptions-item>
          <a-descriptions-item label="创建时间">{{ selectedCattle.created_at }}</a-descriptions-item>
          <a-descriptions-item label="更新时间">{{ selectedCattle.updated_at }}</a-descriptions-item>
        </a-descriptions>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { PlusOutlined, ReloadOutlined, ExportOutlined } from '@ant-design/icons-vue';
import { cattleAPI } from '../services/api.js';
import dayjs from 'dayjs';

// 响应式数据
const cattle = ref([]);
const loading = ref(false);
const saving = ref(false);
const showAddModal = ref(false);
const showDetailModal = ref(false);
const editingCattle = ref(null);
const selectedCattle = ref(null);
const cattleFormRef = ref();

// 统计数据
const stats = ref({
  total: 0,
  healthy: 0,
  avgWeight: 0,
  monthlyNew: 0,
});

// 搜索表单
const searchForm = reactive({
  ear_tag: '',
  breed: '',
  health_status: '',
  owner_name: '',
});

// 牛只表单
const cattleForm = reactive({
  ear_tag: '',
  name: '',
  breed: '',
  gender: '',
  birth_date: null,
  color: '',
  weight: null,
  health_status: 'healthy',
  farm_location: '',
});

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total) => `共 ${total} 条记录`,
});

// 表格列配置
const columns = [
  { title: '耳标号', dataIndex: 'ear_tag', key: 'ear_tag', width: 120, fixed: 'left' },
  { title: '名称', dataIndex: 'name', key: 'name', width: 100 },
  { title: '品种', dataIndex: 'breed', key: 'breed', width: 120 },
  { title: '性别', dataIndex: 'gender', key: 'gender', width: 80 },
  { title: '年龄', key: 'age', width: 80 },
  { title: '体重(kg)', dataIndex: 'weight', key: 'weight', width: 100 },
  { title: '毛色', dataIndex: 'color', key: 'color', width: 80 },
  { title: '健康状态', dataIndex: 'health_status', key: 'health_status', width: 120 },
  { title: '牧场位置', dataIndex: 'farm_location', key: 'farm_location', width: 200 },
  { title: '创建时间', dataIndex: 'created_at', key: 'created_at', width: 160 },
  { title: '操作', key: 'action', width: 250, fixed: 'right' },
];

// 表单验证规则
const rules = {
  ear_tag: [{ required: true, message: '请输入耳标号' }],
  name: [{ required: true, message: '请输入牛只名称' }],
  breed: [{ required: true, message: '请选择品种' }],
  gender: [{ required: true, message: '请选择性别' }],
  birth_date: [{ required: true, message: '请选择出生日期' }],
  weight: [{ required: true, message: '请输入体重' }],
  health_status: [{ required: true, message: '请选择健康状态' }],
};

// 加载牛只列表
const loadCattle = async () => {
  loading.value = true;
  try {
    const params = {
      page: pagination.current,
      limit: pagination.pageSize,
      ...searchForm,
    };
    
    const response = await cattleAPI.getCattle(params);
    
    if (response.success) {
      cattle.value = response.data.cattle || [];
      pagination.total = response.data.pagination?.total || 0;
    } else {
      message.error(response.message || '获取牛只列表失败');
    }
  } catch (error) {
    console.error('获取牛只列表失败:', error);
    message.error('获取牛只列表失败');
  } finally {
    loading.value = false;
  }
};

// 加载统计数据
const loadStats = async () => {
  try {
    const response = await cattleAPI.getStatistics();
    if (response.success) {
      stats.value = response.data;
    }
  } catch (error) {
    console.error('获取统计数据失败:', error);
  }
};

// 计算年龄（月份）
const calculateAge = (birthDate) => {
  if (!birthDate) return 0;
  return dayjs().diff(dayjs(birthDate), 'month');
};

// 获取健康状态颜色
const getHealthStatusColor = (status) => {
  const colors = {
    healthy: 'green',
    sick: 'red',
    quarantine: 'orange',
  };
  return colors[status] || 'default';
};

// 获取健康状态文本
const getHealthStatusText = (status) => {
  const texts = {
    healthy: '健康',
    sick: '生病',
    quarantine: '隔离',
  };
  return texts[status] || status;
};

// 表格变化处理
const handleTableChange = (pag) => {
  pagination.current = pag.current;
  pagination.pageSize = pag.pageSize;
  loadCattle();
};

// 搜索处理
const handleSearch = () => {
  pagination.current = 1;
  loadCattle();
};

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    ear_tag: '',
    breed: '',
    health_status: '',
    owner_name: '',
  });
  pagination.current = 1;
  loadCattle();
};

// 查看牛只详情
const viewCattle = (record) => {
  selectedCattle.value = record;
  showDetailModal.value = true;
};

// 编辑牛只
const editCattle = (record) => {
  editingCattle.value = record;
  Object.assign(cattleForm, {
    ...record,
    birth_date: record.birth_date ? dayjs(record.birth_date) : null,
  });
  showAddModal.value = true;
};

// 查看饲养记录
const viewFeedingRecords = (record) => {
  message.info(`查看 ${record.name} 的饲养记录`);
  // TODO: 实现饲养记录查看
};

// 删除牛只
const deleteCattle = async (id) => {
  try {
    const response = await cattleAPI.deleteCattle(id);
    if (response.success) {
      message.success('删除成功');
      loadCattle();
      loadStats();
    } else {
      message.error(response.message || '删除失败');
    }
  } catch (error) {
    console.error('删除牛只失败:', error);
    message.error('删除失败');
  }
};

// 保存牛只
const handleSaveCattle = async () => {
  try {
    await cattleFormRef.value.validate();
    saving.value = true;

    const formData = {
      ...cattleForm,
      birth_date: cattleForm.birth_date ? cattleForm.birth_date.format('YYYY-MM-DD') : null,
    };

    let response;
    if (editingCattle.value) {
      response = await cattleAPI.updateCattle(editingCattle.value.id, formData);
    } else {
      response = await cattleAPI.createCattle(formData);
    }

    if (response.success) {
      message.success(editingCattle.value ? '更新成功' : '创建成功');
      showAddModal.value = false;
      loadCattle();
      loadStats();
    } else {
      message.error(response.message || '保存失败');
    }
  } catch (error) {
    console.error('保存牛只失败:', error);
    message.error('保存失败');
  } finally {
    saving.value = false;
  }
};

// 取消操作
const handleCancel = () => {
  showAddModal.value = false;
  editingCattle.value = null;
  cattleFormRef.value?.resetFields();
};

// 导出数据
const exportData = () => {
  message.success('导出功能开发中');
};

// 组件挂载时加载数据
onMounted(() => {
  loadCattle();
  loadStats();
});
</script>

<style scoped>
.cattle-management {
  padding: 24px;
}

.search-form {
  margin-bottom: 16px;
  padding: 16px;
  background: #fafafa;
  border-radius: 6px;
}

.stat-card {
  text-align: center;
}

.cattle-detail {
  max-height: 600px;
  overflow-y: auto;
}
</style>