<template>
  <div class="cattle-pens">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">栏舍设置</h1>
    </div>

    <!-- 操作按钮区域 -->
    <div class="action-bar">
      <div class="action-buttons">
        <a-button type="primary" @click="handleAdd">
          <template #icon>
            <PlusOutlined />
          </template>
          新增栏舍
        </a-button>
        <a-button @click="handleBatchDelete" :disabled="selectedRowKeys.length === 0">
          <template #icon>
            <DeleteOutlined />
          </template>
          批量删除
        </a-button>
        <a-button @click="handleExport">
          <template #icon>
            <ExportOutlined />
          </template>
          导出数据
        </a-button>
      </div>
      
      <!-- 搜索框 -->
      <div class="search-container">
        <a-input
          v-model="searchValue"
          placeholder="请输入栏舍名称(精确匹配)"
          class="search-input"
          @pressEnter="handleSearch"
          @input="handleSearchInput"
        >
          <template #suffix>
            <SearchOutlined @click="handleSearch" />
          </template>
        </a-input>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <a-table
        :columns="columns"
        :data-source="tableData"
        :pagination="pagination"
        :loading="loading"
        :row-selection="rowSelection"
        class="pens-table"
        size="middle"
      >
        <!-- 状态列 -->
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <a-tag :color="record.status === '启用' ? 'green' : 'red'">
              {{ record.status }}
            </a-tag>
          </template>
          <template v-if="column.key === 'action'">
            <a-space>
              <a-button type="link" size="small" @click="handleEdit(record)">
                编辑
              </a-button>
              <a-button type="link" size="small" @click="handleViewAnimals(record)">
                查看牛只
              </a-button>
              <a-button type="link" size="small" danger @click="handleDelete(record)">
                删除
              </a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </div>

    <!-- 新增/编辑弹窗 -->
    <a-modal
      :open="modalVisible"
      @update:open="modalVisible = $event"
      :title="modalTitle"
      width="600px"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
    >
      <a-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
      >
        <a-form-item label="栏舍名称" name="name">
          <a-input 
            v-model:value="formData.name" 
            placeholder="请输入栏舍名称"
          />
        </a-form-item>
        
        <a-form-item label="栏舍编号" name="code">
          <a-input 
            v-model:value="formData.code" 
            placeholder="请输入栏舍编号"
          />
        </a-form-item>
        
        <a-form-item label="栏舍类型" name="type">
          <a-select 
            v-model:value="formData.type" 
            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-option value="治疗栏">治疗栏</a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item label="容量" name="capacity">
          <a-input-number 
            v-model:value="formData.capacity" 
            :min="1" 
            :max="1000"
            style="width: 100%" 
            placeholder="请输入栏舍容量"
          />
        </a-form-item>
        
        <a-form-item label="当前牛只数量" name="currentCount">
          <a-input-number 
            v-model:value="formData.currentCount" 
            :min="0" 
            :max="formData.capacity || 1000"
            style="width: 100%" 
            placeholder="当前牛只数量"
          />
        </a-form-item>
        
        <a-form-item label="面积(平方米)" name="area">
          <a-input-number 
            v-model:value="formData.area" 
            :min="0" 
            :precision="2"
            style="width: 100%" 
            placeholder="请输入栏舍面积"
          />
        </a-form-item>
        
        <a-form-item label="位置描述" name="location">
          <a-textarea 
            v-model:value="formData.location" 
            :rows="3" 
            placeholder="请输入栏舍位置描述"
          />
        </a-form-item>
        
        <a-form-item label="状态" name="status">
          <a-radio-group 
            v-model:value="formData.status"
          >
            <a-radio value="启用">启用</a-radio>
            <a-radio value="停用">停用</a-radio>
          </a-radio-group>
        </a-form-item>
        
        <a-form-item label="备注" name="remark">
          <a-textarea 
            v-model:value="formData.remark" 
            :rows="3" 
            placeholder="请输入备注信息"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 查看牛只弹窗 -->
    <a-modal
      :open="animalsModalVisible"
      @update:open="animalsModalVisible = $event"
      title="栏舍牛只信息"
      width="800px"
      :footer="null"
    >
      <a-table
        :columns="animalColumns"
        :data-source="currentPenAnimals"
        :pagination="{
          current: animalsPagination.current,
          pageSize: animalsPagination.pageSize,
          total: animalsPagination.total,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
        }"
        @change="handleAnimalsTableChange"
        size="small"
      />
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import { message, Modal } from 'ant-design-vue'
import {
  PlusOutlined,
  DeleteOutlined,
  SearchOutlined,
  ExportOutlined
} from '@ant-design/icons-vue'
import { ExportUtils } from '../utils/exportUtils'
import { api } from '../utils/api'
import dayjs from 'dayjs'
import { getBreedName } from '../utils/fieldMappings'

// 响应式数据
const loading = ref(false)
const searchValue = ref('')
const modalVisible = ref(false)
const animalsModalVisible = ref(false)
const modalTitle = ref('新增栏舍')
const formRef = ref()
const selectedRowKeys = ref([])

// 表格数据
const tableData = ref([])

// 当前栏舍的牛只数据
const currentPenAnimals = ref([])
const currentPenId = ref(null)
const animalsPagination = ref({
  current: 1,
  pageSize: 10,
  total: 0
})

// 表格列配置
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: 80,
    align: 'center'
  },
  {
    title: '栏舍名称',
    dataIndex: 'name',
    key: 'name',
    width: 150
  },
  {
    title: '栏舍编号',
    dataIndex: 'code',
    key: 'code',
    width: 120
  },
  {
    title: '栏舍类型',
    dataIndex: 'type',
    key: 'type',
    width: 100
  },
  {
    title: '容量',
    dataIndex: 'capacity',
    key: 'capacity',
    width: 80
  },
  {
    title: '当前牛只数量',
    dataIndex: 'currentCount',
    key: 'currentCount',
    width: 120
  },
  {
    title: '面积(平方米)',
    dataIndex: 'area',
    key: 'area',
    width: 120
  },
  {
    title: '位置描述',
    dataIndex: 'location',
    key: 'location',
    width: 200
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 80
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    width: 150
  },
  {
    title: '操作',
    key: 'action',
    width: 180,
    fixed: 'right'
  }
]

// 牛只表格列配置
const animalColumns = [
  {
    title: '耳号',
    dataIndex: 'earTag',
    key: 'earTag'
  },
  {
    title: '品种',
    dataIndex: 'breed',
    key: 'breed'
  },
  {
    title: '性别',
    dataIndex: 'gender',
    key: 'gender'
  },
  {
    title: '月龄',
    dataIndex: 'ageInMonths',
    key: 'ageInMonths'
  },
  {
    title: '生理阶段',
    dataIndex: 'physiologicalStage',
    key: 'physiologicalStage'
  }
]

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条/共 ${total} 条`
})

// 行选择配置
const rowSelection = {
  selectedRowKeys: selectedRowKeys,
  onChange: (keys) => {
    selectedRowKeys.value = keys
  }
}

// 表单数据
const formData = reactive({
  name: '',
  code: '',
  type: '',
  capacity: null,
  currentCount: null,
  area: null,
  location: '',
  status: '启用',
  remark: ''
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入栏舍名称', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入栏舍编号', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择栏舍类型', trigger: 'change' }
  ],
  capacity: [
    { required: true, message: '请输入栏舍容量', trigger: 'blur' }
  ],
  area: [
    { required: true, message: '请输入栏舍面积', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 方法
const loadData = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.current,
      pageSize: pagination.pageSize
    }
    
    // 搜索关键词（后端使用 search 参数）
    if (searchValue.value && searchValue.value.trim()) {
      params.search = searchValue.value.trim()
    }
    
    console.log('📤 [栏舍设置] 发送请求参数:', params)
    
    const response = await api.cattlePens.getList(params)
    console.log('📥 [栏舍设置] 接收到的响应数据:', response)
    
    if (response.success) {
      console.log('📊 [栏舍设置] 原始列表数据:', response.data.list)
      
      tableData.value = response.data.list.map(item => ({
        ...item,
        key: item.id,
        createTime: item.created_at ? dayjs(item.created_at).format('YYYY-MM-DD HH:mm:ss') : '-'
      }))
      
      console.log('📊 [栏舍设置] 格式化后的表格数据:', tableData.value)
      pagination.total = response.data.total
      console.log('📊 [栏舍设置] 总记录数:', response.data.total)
    } else {
      console.warn('⚠️ [栏舍设置] 请求成功但返回失败状态:', response.message)
    }
  } catch (error) {
    console.error('❌ [栏舍设置] 加载数据失败:', error)
    message.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

const handleAdd = () => {
  modalTitle.value = '新增栏舍'
  resetForm()
  modalVisible.value = true
}

const handleEdit = async (record) => {
  console.log('🔄 [栏舍设置] 开始编辑操作')
  console.log('📋 [栏舍设置] 原始记录数据:', {
    id: record.id,
    name: record.name,
    type: record.type,
    status: record.status,
    capacity: record.capacity,
    area: record.area,
    location: record.location,
    description: record.description,
    remark: record.remark,
    farmId: record.farmId,
    farmName: record.farm?.name
  })
  
  modalTitle.value = '编辑栏舍'
  
  // 填充表单数据 - 使用直接赋值确保响应式更新
  formData.id = record.id || null
  formData.name = record.name || ''
  formData.code = record.code || ''
  formData.type = record.type || ''
  formData.capacity = record.capacity || 0
  formData.currentCount = record.currentCount || 0
  formData.area = record.area || null
  formData.location = record.location || ''
  formData.status = record.status || '启用'
  formData.remark = record.remark || ''
  formData.farmId = record.farmId || record.farm_id || null
  
  console.log('📝 [栏舍设置] 表单数据已填充:', formData)
  
  // 打开模态框
  modalVisible.value = true
  
  // 等待模态框和表单渲染完成
  await nextTick()
  await new Promise(resolve => setTimeout(resolve, 200))
  
  console.log('✅ [栏舍设置] 模态框已打开，表单应该已填充')
}

const handleDelete = (record) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除栏舍"${record.name}"吗？`,
    async onOk() {
      try {
        await api.cattlePens.delete(record.id)
        message.success('删除成功')
        loadData()
      } catch (error) {
        console.error('删除失败:', error)
        message.error('删除失败')
      }
    }
  })
}

const handleBatchDelete = () => {
  Modal.confirm({
    title: '确认批量删除',
    content: `确定要删除选中的 ${selectedRowKeys.value.length} 个栏舍吗？`,
    async onOk() {
      try {
        await api.cattlePens.batchDelete(selectedRowKeys.value)
        message.success('批量删除成功')
        selectedRowKeys.value = []
        loadData()
      } catch (error) {
        console.error('批量删除失败:', error)
        message.error('批量删除失败')
      }
    }
  })
}

const handleViewAnimals = async (record) => {
  try {
    console.log('🚀 开始获取栏舍牛只数据');
    console.log('📋 栏舍信息:', {
      id: record.id,
      name: record.name,
      currentAnimalCount: record.currentAnimalCount
    });
    
    currentPenId.value = record.id
    animalsPagination.value.current = 1
    animalsPagination.value.total = 0
    
    await loadPenAnimals(record.id, 1, 10)
    animalsModalVisible.value = true
  } catch (error) {
    console.error('获取栏舍牛只失败:', error)
    message.error('获取栏舍牛只失败')
  }
}

// 加载栏舍牛只数据
const loadPenAnimals = async (penId, page = 1, pageSize = 10) => {
  try {
    console.log(`🔍 加载栏舍${penId}第${page}页数据，每页${pageSize}条`);
    
    const response = await api.cattlePens.getAnimals(penId, { page, pageSize })
    console.log('✅ API响应:', response);
    
    if (response.success) {
      console.log(`🐄 获取到的牛只数量: ${response.data.list.length}`);
      console.log(`📊 总记录数: ${response.data.total}`);
      
      currentPenAnimals.value = response.data.list.map(item => ({
        ...item,
        key: item.id,
        breed: getBreedName(item.varieties || item.breed || '')
      }))
      
      // 更新分页信息
      animalsPagination.value = {
        current: response.data.page,
        pageSize: response.data.pageSize,
        total: response.data.total
      }
      
      console.log('📊 更新后的分页信息:', animalsPagination.value);
    }
  } catch (error) {
    console.error('加载栏舍牛只失败:', error)
    message.error('加载栏舍牛只失败')
  }
}

// 处理牛只表格分页变化
const handleAnimalsTableChange = (pagination) => {
  console.log('🔄 牛只表格分页变化:', pagination);
  if (currentPenId.value) {
    loadPenAnimals(currentPenId.value, pagination.current, pagination.pageSize)
  }
}

const handleExport = async () => {
  try {
    console.log('=== 开始导出栏舍数据 ===')
    console.log('tableData.value长度:', tableData.value.length)
    console.log('tableData.value示例:', tableData.value[0])
    
    if (!tableData.value || tableData.value.length === 0) {
      message.warning('没有数据可导出')
      return
    }
    
    message.loading('正在导出数据...', 0)
    
    // 转换数据格式以匹配导出工具类的列配置
    const exportData = tableData.value.map(item => {
      console.log('转换前栏舍数据项:', item)
      return {
        id: item.id,
        name: item.name || '',
        animal_type: item.animalType || item.animal_type || '牛', // 默认动物类型为牛
        pen_type: item.type || item.penType || item.pen_type || '', // 使用type字段
        responsible: item.responsible || item.manager || item.managerName || '',
        capacity: item.capacity || 0,
        status: item.status || '启用',
        creator: item.creator || item.created_by || item.creatorName || '',
        created_at: item.created_at || item.createTime || ''
      }
    })
    
    console.log('转换后栏舍数据示例:', exportData[0])
    console.log('转换后栏舍数据总数:', exportData.length)
    
    const result = ExportUtils.exportPenData(exportData)
    
    if (result.success) {
      message.destroy()
      message.success(`导出成功！文件：${result.filename}`)
    } else {
      message.destroy()
      message.error(result.message)
    }
  } catch (error) {
    message.destroy()
    console.error('导出失败:', error)
    message.error('导出失败，请重试')
  }
}

// 监听搜索输入变化
const handleSearchInput = (e) => {
  console.log('🔍 [栏舍设置] 搜索输入变化:', e.target.value)
  // 确保searchValue被正确更新
  searchValue.value = e.target.value
  
  // 实时过滤表格数据
  debounceSearch()
}

// 使用防抖函数处理实时搜索，避免频繁请求
const debounceSearch = (() => {
  let timer = null
  return () => {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      console.log('🔍 [栏舍设置] 执行实时搜索，搜索值:', searchValue.value)
      pagination.current = 1
      loadData()
    }, 300) // 300ms防抖延迟
  }
})()

const handleSearch = () => {
  console.log('🔍 [栏舍设置] 执行搜索操作，搜索值:', searchValue.value)
  pagination.current = 1
  loadData()
}

// 字段变化监听方法
const handleFieldChange = (fieldName, value) => {
  console.log(`📝 [栏舍设置] 字段变化监听: ${fieldName} = ${value}`)
  console.log(`📝 [栏舍设置] 当前表单数据:`, formData)
  
  // 确保数据同步到formData
  if (formData[fieldName] !== value) {
    formData[fieldName] = value
    console.log(`✅ [栏舍设置] 字段 ${fieldName} 已更新为: ${value}`)
  }
}

const handleModalOk = async () => {
  try {
    console.log('💾 [栏舍设置] 开始保存操作')
    console.log('📝 [栏舍设置] 用户输入的表单数据:', {
      id: formData.id,
      name: formData.name,
      code: formData.code,
      type: formData.type,
      status: formData.status,
      capacity: formData.capacity,
      currentCount: formData.currentCount,
      area: formData.area,
      location: formData.location,
      remark: formData.remark,
      farmId: formData.farmId
    })
    
    await formRef.value.validate()
    console.log('✅ [栏舍设置] 表单验证通过')
    
    // 准备发送给后端的数据，转换数字格式
    const submitData = {
      name: formData.name,
      code: formData.code,
      type: formData.type,
      status: formData.status,
      capacity: formData.capacity ? Number(formData.capacity) : null,
      currentCount: formData.currentCount ? Number(formData.currentCount) : 0,
      area: formData.area ? Number(formData.area) : null,
      location: formData.location || '',
      remark: formData.remark || '',
      farmId: formData.farmId || 1
    }
    
    console.log('📤 [栏舍设置] 准备发送的数据:', submitData)
    
    if (modalTitle.value === '新增栏舍') {
      console.log('🆕 [栏舍设置] 执行创建操作')
      await api.cattlePens.create(submitData)
      console.log('✅ [栏舍设置] 创建成功')
      message.success('创建成功')
    } else {
      console.log('🔄 [栏舍设置] 执行更新操作，记录ID:', formData.id)
      const response = await api.cattlePens.update(formData.id, submitData)
      console.log('✅ [栏舍设置] 更新成功，服务器响应:', response)
      message.success('更新成功')
    }
    
    modalVisible.value = false
    resetForm()
    loadData()
  } catch (error) {
    console.error('❌ [栏舍设置] 操作失败:', error)
    message.error('操作失败')
  }
}

const handleModalCancel = () => {
  modalVisible.value = false
  resetForm()
}

const resetForm = () => {
  Object.keys(formData).forEach(key => {
    if (key === 'capacity' || key === 'currentCount' || key === 'area') {
      formData[key] = null
    } else {
      formData[key] = ''
    }
  })
  formData.status = '启用'
  formRef.value?.resetFields()
}

// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.cattle-pens {
  padding: 24px;
  background: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 24px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #262626;
  margin: 0;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 16px 24px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.search-container {
  width: 300px;
}

.search-input {
  height: 40px;
  border-radius: 6px;
}

.table-container {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.pens-table {
  font-size: 14px;
}

.pens-table :deep(.ant-table-thead > tr > th) {
  background: #fafafa;
  font-weight: 600;
  color: #262626;
  border-bottom: 1px solid #f0f0f0;
}

.pens-table :deep(.ant-table-tbody > tr > td) {
  border-bottom: 1px solid #f0f0f0;
}

.pens-table :deep(.ant-table-tbody > tr:hover > td) {
  background: #f5f5f5;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .action-bar {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .search-container {
    width: 100%;
  }
}

@media (max-width: 768px) {
  .cattle-pens {
    padding: 16px;
  }
  
  .action-buttons {
    flex-direction: column;
    gap: 8px;
  }
}
</style>
