<template>
  <div class="cattle-archives">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">牛档案</h1>
    </div>

    <!-- 操作按钮区域 -->
    <div class="action-bar">
      <div class="action-buttons">
        <a-button type="primary" class="action-btn">
          <template #icon>
            <PlusOutlined />
          </template>
          新增档案
        </a-button>
        <a-button class="action-btn" @click="() => { console.log('导出按钮被点击'); alert('导出按钮被点击'); testClick(); }">
          <template #icon>
            <ExportOutlined />
          </template>
          导出表格
        </a-button>
        <a-button type="primary" @click="() => alert('简单测试')">
          测试按钮
        </a-button>
        <a-button class="action-btn">
          <template #icon>
            <ImportOutlined />
          </template>
          导入牛档案
        </a-button>
      </div>
      
      <!-- 搜索区域 -->
      <div class="search-container">
        <!-- 设备号搜索框 -->
        <a-input
          v-model="deviceNumber"
          placeholder="请输入牛只设备号搜索"
          class="search-input"
          @pressEnter="handleSearch"
          @input="handleDeviceInput"
          @focus="handleDeviceFocus"
          @blur="handleDeviceBlur"
          :disabled="searchLoading"
          autocomplete="off"
          :allow-clear="false"
          :show-count="false"
          :bordered="true"
        >
          <template #suffix>
            <SearchOutlined 
              @click="handleSearch" 
              :style="{ color: searchLoading ? '#1890ff' : '#999' }"
            />
          </template>
        </a-input>
        
        <!-- 栏舍选择框 -->
        <a-select
          v-model="selectedPenId"
          placeholder="请选择栏舍"
          class="pen-select"
          :disabled="searchLoading"
          :loading="pensLoading"
          allowClear
          @change="handlePenChange"
          @focus="handlePenFocus"
          @blur="handlePenBlur"
        >
          <a-select-option 
            v-for="pen in pens" 
            :key="pen.id" 
            :value="pen.id"
          >
            {{ pen.name }}
          </a-select-option>
        </a-select>
        
        <!-- 操作按钮 -->
        <a-button 
          type="primary" 
          @click="handleSearch" 
          :loading="searchLoading"
          class="search-btn"
        >
          查询
        </a-button>
        
        <a-button 
          v-if="isSearching" 
          @click="resetSearch" 
          class="reset-btn"
        >
          重置
        </a-button>
        
        <a-spin v-if="searchLoading" size="small" class="loading-spin" />
      </div>
    </div>

    <!-- 搜索状态提示 -->
    <div v-if="isSearching" class="search-status">
      <a-alert
        :message="getSearchStatusMessage()"
        type="info"
        show-icon
        closable
        @close="resetSearch"
        style="margin-bottom: 16px;"
      />
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <a-table
        :columns="columns"
        :data-source="displayData"
        :pagination="pagination"
        :loading="loading || searchLoading"
        :scroll="{ x: 2000 }"
        class="cattle-table"
        size="middle"
      >
        <!-- 操作列 -->
        <template #bodyCell="{ column, record }">
          <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" danger @click="handleDelete(record)">
                删除
              </a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </div>

    <!-- 新增/编辑弹窗 -->
    <a-modal
      :open="modalVisible"
      @update:open="modalVisible = $event"
      :title="modalTitle"
      width="800px"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
    >
      <a-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="耳号" name="earTag">
              <a-input v-model="formData.earTag" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="智能佩戴设备" name="deviceId">
              <a-input v-model="formData.deviceId" />
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="出生日期" name="birthDate">
              <a-date-picker v-model="formData.birthDate" style="width: 100%" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="月龄" name="ageInMonths">
              <a-input-number v-model="formData.ageInMonths" :precision="2" style="width: 100%" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="品类" name="category">
              <a-select v-model="formData.category" placeholder="请选择品类">
                <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="breed">
              <a-input v-model="formData.breed" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="生理阶段" name="physiologicalStage">
              <a-select v-model="formData.physiologicalStage" 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-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="formData.gender">
                <a-radio value="母">母</a-radio>
                <a-radio value="公">公</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="出生体重/KG" name="birthWeight">
              <a-input-number v-model="formData.birthWeight" :precision="2" style="width: 100%" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="现估值/KG" name="currentValue">
              <a-input-number v-model="formData.currentValue" :precision="2" style="width: 100%" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="代数" name="generation">
              <a-select v-model="formData.generation" 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="bloodlinePurity">
              <a-input v-model="formData.bloodlinePurity" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="入场日期" name="entryDate">
              <a-date-picker v-model="formData.entryDate" style="width: 100%" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="栏舍" name="pen">
              <a-select v-model="formData.pen" placeholder="请选择栏舍">
                <a-select-option value="杭嘉新村栏舍01">杭嘉新村栏舍01</a-select-option>
                <a-select-option value="杭嘉新村栏舍02">杭嘉新村栏舍02</a-select-option>
                <a-select-option value="杭嘉新村栏舍03">杭嘉新村栏舍03</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="已产胎次" name="calvings">
              <a-input-number v-model="formData.calvings" :min="0" style="width: 100%" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="来源" name="source">
              <a-select v-model="formData.source" placeholder="请选择来源">
                <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-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="冻精编号" name="frozenSemenNumber">
              <a-input v-model="formData.frozenSemenNumber" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>
  </div>
</template>

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

// 响应式数据
const loading = ref(false)
const searchLoading = ref(false)
const deviceNumber = ref('')
const modalVisible = ref(false)
const modalTitle = ref('新增档案')
const formRef = ref()
const isSearching = ref(false)
const searchResults = ref([])

// 栏舍相关数据
const pens = ref([])
const pensLoading = ref(false)
const selectedPenId = ref(null)

// 搜索参数日志
const searchLogs = ref([])

// 表格数据
const tableData = ref([
  {
    key: '1',
    earTag: '24075002455',
    deviceId: '24075002455',
    birthDate: '2017-08-08',
    ageInMonths: 97.07,
    category: '乳肉兼用',
    breed: '西藏高山牦牛',
    physiologicalStage: '育成母牛',
    gender: '母',
    birthWeight: 0.00,
    currentValue: 0.00,
    generation: '第一代',
    bloodlinePurity: '',
    entryDate: '2025-08-08 18:07:10',
    pen: '杭嘉新村栏舍01',
    calvings: 0,
    source: '合作社',
    frozenSemenNumber: ''
  },
  {
    key: '2',
    earTag: '24075002041',
    deviceId: '24075002041',
    birthDate: '2017-08-08',
    ageInMonths: 97.07,
    category: '乳肉兼用',
    breed: '西藏高山牦牛',
    physiologicalStage: '育成母牛',
    gender: '母',
    birthWeight: 0.00,
    currentValue: 0.00,
    generation: '第一代',
    bloodlinePurity: '',
    entryDate: '2025-08-08 18:07:10',
    pen: '杭嘉新村栏舍01',
    calvings: 0,
    source: '合作社',
    frozenSemenNumber: ''
  },
  {
    key: '3',
    earTag: '24075001812',
    deviceId: '24075001812',
    birthDate: '2017-08-08',
    ageInMonths: 97.03,
    category: '乳肉兼用',
    breed: '西藏高山牦牛',
    physiologicalStage: '育成母牛',
    gender: '母',
    birthWeight: 0.00,
    currentValue: 0.00,
    generation: '第一代',
    bloodlinePurity: '',
    entryDate: '2025-08-08 18:07:10',
    pen: '杭嘉新村栏舍01',
    calvings: 0,
    source: '合作社',
    frozenSemenNumber: ''
  }
])

// 类别映射函数（与后端保持一致）
const getCategoryName = (cate) => {
  const categoryMap = {
    1: '犊牛',
    2: '育成母牛',
    3: '架子牛',
    4: '青年牛',
    5: '基础母牛',
    6: '育肥牛'
  };
  return categoryMap[cate] || '未知';
};

// 表格列配置
const columns = [
  {
    title: '耳号',
    dataIndex: 'earTag',
    key: 'earTag',
    width: 120,
    fixed: 'left'
  },
  {
    title: '智能佩戴设备',
    dataIndex: 'deviceId',
    key: 'deviceId',
    width: 120
  },
  {
    title: '出生日期',
    dataIndex: 'birthDate',
    key: 'birthDate',
    width: 100
  },
  {
    title: '月龄',
    dataIndex: 'ageInMonths',
    key: 'ageInMonths',
    width: 80
  },
  {
    title: '品类',
    dataIndex: 'category',
    key: 'category',
    width: 100,
    customRender: ({ text }) => {
      return getCategoryName(text)
    }
  },
  {
    title: '品种',
    dataIndex: 'breed',
    key: 'breed',
    width: 120
  },
  {
    title: '生理阶段',
    dataIndex: 'physiologicalStage',
    key: 'physiologicalStage',
    width: 100
  },
  {
    title: '性别',
    dataIndex: 'gender',
    key: 'gender',
    width: 80
  },
  {
    title: '出生体重/KG',
    dataIndex: 'birthWeight',
    key: 'birthWeight',
    width: 120
  },
  {
    title: '现估值/KG',
    dataIndex: 'currentValue',
    key: 'currentValue',
    width: 120
  },
  {
    title: '代数',
    dataIndex: 'generation',
    key: 'generation',
    width: 80
  },
  {
    title: '血统纯度',
    dataIndex: 'bloodlinePurity',
    key: 'bloodlinePurity',
    width: 100
  },
  {
    title: '入场日期',
    dataIndex: 'entryDate',
    key: 'entryDate',
    width: 150
  },
  {
    title: '栏舍',
    dataIndex: 'pen',
    key: 'pen',
    width: 120
  },
  {
    title: '已产胎次',
    dataIndex: 'calvings',
    key: 'calvings',
    width: 100
  },
  {
    title: '来源',
    dataIndex: 'source',
    key: 'source',
    width: 80
  },
  {
    title: '冻精编号',
    dataIndex: 'frozenSemenNumber',
    key: 'frozenSemenNumber',
    width: 120
  },
  {
    title: '操作',
    key: 'action',
    width: 120,
    fixed: 'right'
  }
]

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

// 表单数据
const formData = reactive({
  earTag: '',
  deviceId: '',
  birthDate: null,
  ageInMonths: null,
  category: '',
  breed: '',
  physiologicalStage: '',
  gender: '',
  birthWeight: null,
  currentValue: null,
  generation: '',
  bloodlinePurity: '',
  entryDate: null,
  pen: '',
  calvings: null,
  source: '',
  frozenSemenNumber: ''
})

// 表单验证规则
const formRules = {
  earTag: [
    { required: true, message: '请输入耳号', trigger: 'blur' }
  ],
  deviceId: [
    { required: true, message: '请输入智能佩戴设备', trigger: 'blur' }
  ],
  birthDate: [
    { required: true, message: '请选择出生日期', trigger: 'change' }
  ],
  category: [
    { required: true, message: '请选择品类', trigger: 'change' }
  ],
  breed: [
    { required: true, message: '请输入品种', trigger: 'blur' }
  ],
  physiologicalStage: [
    { required: true, message: '请选择生理阶段', trigger: 'change' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  generation: [
    { required: true, message: '请选择代数', trigger: 'change' }
  ],
  entryDate: [
    { required: true, message: '请选择入场日期', trigger: 'change' }
  ],
  pen: [
    { required: true, message: '请选择栏舍', trigger: 'change' }
  ],
  source: [
    { required: true, message: '请选择来源', trigger: 'change' }
  ]
}

// 计算属性 - 显示数据
const displayData = computed(() => {
  return isSearching.value ? searchResults.value : tableData.value
})

// 方法
const handleSearch = async () => {
  const timestamp = new Date().toISOString()
  
  console.log('=== 开始搜索 ===')
  console.log('时间:', timestamp)
  console.log('设备号:', deviceNumber.value)
  console.log('栏舍ID:', selectedPenId.value)
  
  // 检查搜索条件
  if (!deviceNumber.value.trim() && !selectedPenId.value) {
    console.log('搜索条件检查: 未输入任何搜索条件')
    message.warning('请输入设备号或选择栏舍进行搜索')
    return
  }
  
  try {
    searchLoading.value = true
    isSearching.value = true
    
    // 构建搜索参数
    const searchParams = {
      page: 1,
      pageSize: 100 // 搜索时显示更多结果
    }
    
    // 添加设备号搜索条件
    if (deviceNumber.value.trim()) {
      searchParams.search = deviceNumber.value.trim()
    }
    
    // 添加栏舍搜索条件
    if (selectedPenId.value) {
      searchParams.penId = selectedPenId.value
    }
    
    console.log('=== 前端发送搜索参数 ===')
    console.log('搜索参数:', searchParams)
    console.log('API端点:', '/iot-cattle/public')
    
    // 记录搜索日志
    searchLogs.value.push({
      type: 'search_start',
      timestamp,
      deviceNumber: deviceNumber.value,
      penId: selectedPenId.value,
      searchParams: { ...searchParams }
    })
    
    // 调用后端API搜索牛只档案
    const response = await api.get('/iot-cattle/public', {
      params: searchParams
    })
    
    console.log('=== 后端API响应 ===')
    console.log('响应时间:', new Date().toISOString())
    console.log('响应状态:', response.success)
    console.log('响应数据:', response.data)
    console.log('响应消息:', response.message)
    
    // 记录API响应日志
    searchLogs.value.push({
      type: 'api_response',
      timestamp: new Date().toISOString(),
      success: response.success,
      dataCount: response.data?.list?.length || 0,
      message: response.message,
      fullResponse: response
    })
    
    if (response && response.data && response.data.list) {
      console.log('=== 开始格式化搜索结果 ===')
      console.log('原始数据条数:', response.data.list.length)
      
      // 格式化搜索结果
      const formattedResults = response.data.list.map((cattle, index) => {
        const formatted = {
          key: `search-${index}`,
          id: cattle.id,
          earTag: cattle.earNumber || cattle.earTag,
          deviceId: cattle.deviceId || '',
          birthDate: cattle.birthday || cattle.birthDate,
          ageInMonths: cattle.ageInMonths || 0,
          category: cattle.cate || cattle.category,
          breed: cattle.varieties || cattle.breed,
          physiologicalStage: cattle.physiologicalStage || cattle.level || '',
          gender: cattle.sex === 1 ? '公' : cattle.sex === 2 ? '母' : '未知',
          birthWeight: cattle.birthWeight || 0,
          currentValue: cattle.currentWeight || cattle.weight || 0,
          generation: cattle.algebra || cattle.generation,
          bloodlinePurity: cattle.descent || cattle.bloodlinePurity,
          entryDate: cattle.intoTime || cattle.entryDate,
          pen: cattle.penName || cattle.pen,
          calvings: cattle.parity || cattle.calvings,
          source: cattle.source || '',
          frozenSemenNumber: cattle.semenNum || cattle.frozenSemenNumber
        }
        
        console.log(`格式化记录 ${index + 1}:`, {
          原始ID: cattle.id,
          耳标号: formatted.earTag,
          品种: formatted.breed,
          性别: formatted.gender
        })
        
        return formatted
      })
      
      console.log('=== 搜索结果处理完成 ===')
      console.log('格式化后数据条数:', formattedResults.length)
      
      searchResults.value = formattedResults
      pagination.total = formattedResults.length
      pagination.current = 1
      
      // 构建搜索条件描述
      let searchDesc = []
      if (deviceNumber.value.trim()) {
        searchDesc.push(`设备号: ${deviceNumber.value.trim()}`)
      }
      if (selectedPenId.value) {
        const selectedPen = pens.value.find(pen => pen.id === selectedPenId.value)
        searchDesc.push(`栏舍: ${selectedPen ? selectedPen.name : '未知'}`)
      }
      
      console.log('=== 搜索成功 ===')
      console.log('找到记录数:', formattedResults.length)
      console.log('搜索条件:', searchDesc.join(', '))
      
      message.success(`找到 ${formattedResults.length} 条匹配的牛只档案 (${searchDesc.join(', ')})`)
    } else {
      console.log('=== 搜索无结果 ===')
      console.log('响应数据为空或格式不正确')
      
      searchResults.value = []
      pagination.total = 0
      message.info('未找到匹配的牛只档案')
    }
  } catch (error) {
    const errorTimestamp = new Date().toISOString()
    
    console.log('=== 搜索发生错误 ===')
    console.log('错误时间:', errorTimestamp)
    console.log('错误类型:', error.name)
    console.log('错误消息:', error.message)
    console.log('错误堆栈:', error.stack)
    console.log('完整错误对象:', error)
    
    // 记录错误日志
    searchLogs.value.push({
      type: 'search_error',
      timestamp: errorTimestamp,
      errorName: error.name,
      errorMessage: error.message,
      errorStack: error.stack,
      fullError: error
    })
    
    // 根据错误类型提供不同的错误信息
    let errorMessage = '搜索失败'
    if (error.message.includes('网络连接失败')) {
      errorMessage = '网络连接失败，请检查网络连接'
    } else if (error.message.includes('认证已过期')) {
      errorMessage = '登录已过期，请重新登录'
    } else if (error.message.includes('服务器内部错误')) {
      errorMessage = '服务器繁忙，请稍后重试'
    } else if (error.message) {
      errorMessage = `搜索失败: ${error.message}`
    }
    
    console.log('=== 显示错误信息 ===')
    console.log('错误信息:', errorMessage)
    
    message.error(errorMessage)
    searchResults.value = []
    pagination.total = 0
  } finally {
    console.log('=== 搜索完成 ===')
    console.log('完成时间:', new Date().toISOString())
    console.log('搜索状态:', isSearching.value)
    console.log('结果数量:', searchResults.value.length)
    
    searchLoading.value = false
  }
}

// 重置搜索
const resetSearch = () => {
  const timestamp = new Date().toISOString()
  
  console.log('=== 重置搜索 ===')
  console.log('重置时间:', timestamp)
  console.log('重置前设备号:', deviceNumber.value)
  console.log('重置前栏舍ID:', selectedPenId.value)
  
  deviceNumber.value = ''
  selectedPenId.value = null
  isSearching.value = false
  searchResults.value = []
  pagination.total = tableData.value.length
  pagination.current = 1
  
  // 记录重置日志
  searchLogs.value.push({
    type: 'search_reset',
    timestamp,
    previousDeviceNumber: deviceNumber.value,
    previousPenId: selectedPenId.value
  })
  
  console.log('=== 重置完成 ===')
  console.log('重置后设备号:', deviceNumber.value)
  console.log('重置后栏舍ID:', selectedPenId.value)
  
  message.info('已重置搜索')
}

// 设备号输入监听事件
const handleDeviceInput = (event) => {
  const value = event.target.value
  const timestamp = new Date().toISOString()
  
  console.log('=== 设备号输入监听 ===')
  console.log('时间:', timestamp)
  console.log('输入值:', value)
  console.log('输入长度:', value.length)
  console.log('是否为空:', !value.trim())
  
  // 记录输入日志
  searchLogs.value.push({
    type: 'device_input',
    timestamp,
    value,
    length: value.length,
    isEmpty: !value.trim()
  })
  
  // 如果输入为空，自动重置搜索
  if (!value.trim()) {
    console.log('输入为空，自动重置搜索')
    resetSearch()
  }
}

// 设备号输入框获得焦点
const handleDeviceFocus = (event) => {
  const timestamp = new Date().toISOString()
  console.log('=== 设备号输入框获得焦点 ===')
  console.log('时间:', timestamp)
  console.log('当前值:', deviceNumber.value)
  
  searchLogs.value.push({
    type: 'device_focus',
    timestamp,
    currentValue: deviceNumber.value
  })
}

// 设备号输入框失去焦点
const handleDeviceBlur = (event) => {
  const timestamp = new Date().toISOString()
  console.log('=== 设备号输入框失去焦点 ===')
  console.log('时间:', timestamp)
  console.log('最终值:', deviceNumber.value)
  
  searchLogs.value.push({
    type: 'device_blur',
    timestamp,
    finalValue: deviceNumber.value
  })
}

// 栏舍选择变化事件
const handlePenChange = (value) => {
  const timestamp = new Date().toISOString()
  const selectedPen = pens.value.find(pen => pen.id === value)
  
  console.log('=== 栏舍选择变化 ===')
  console.log('时间:', timestamp)
  console.log('选择的栏舍ID:', value)
  console.log('选择的栏舍名称:', selectedPen ? selectedPen.name : '未知')
  console.log('是否清空选择:', value === null || value === undefined)
  
  selectedPenId.value = value
  
  // 记录选择日志
  searchLogs.value.push({
    type: 'pen_change',
    timestamp,
    penId: value,
    penName: selectedPen ? selectedPen.name : '未知',
    isCleared: value === null || value === undefined
  })
}

// 栏舍下拉框获得焦点
const handlePenFocus = (event) => {
  const timestamp = new Date().toISOString()
  console.log('=== 栏舍下拉框获得焦点 ===')
  console.log('时间:', timestamp)
  console.log('当前选择:', selectedPenId.value)
  console.log('可用栏舍数量:', pens.value.length)
  
  searchLogs.value.push({
    type: 'pen_focus',
    timestamp,
    currentSelection: selectedPenId.value,
    availablePensCount: pens.value.length
  })
}

// 栏舍下拉框失去焦点
const handlePenBlur = (event) => {
  const timestamp = new Date().toISOString()
  console.log('=== 栏舍下拉框失去焦点 ===')
  console.log('时间:', timestamp)
  console.log('最终选择:', selectedPenId.value)
  
  searchLogs.value.push({
    type: 'pen_blur',
    timestamp,
    finalSelection: selectedPenId.value
  })
}

// 获取栏舍列表
const fetchPens = async () => {
  try {
    pensLoading.value = true
    const response = await api.get('/pens/public') 
    
    if (response.success) {
      pens.value = response.data.list || [] 
      console.log('获取栏舍列表成功:', pens.value.length, '个栏舍')
    } else {
      console.error('获取栏舍列表失败:', response.message)
    }
  } catch (error) {
    console.error('获取栏舍列表失败:', error)
    message.error('获取栏舍列表失败: ' + (error.message || '未知错误'))
  } finally {
    pensLoading.value = false
  }
}

// 获取搜索状态消息
const getSearchStatusMessage = () => {
  let searchDesc = []
  if (deviceNumber.value.trim()) {
    searchDesc.push(`设备号: ${deviceNumber.value.trim()}`)
  }
  if (selectedPenId.value) {
    const selectedPen = pens.value.find(pen => pen.id === selectedPenId.value)
    searchDesc.push(`栏舍: ${selectedPen ? selectedPen.name : '未知'}`)
  }
  
  if (searchDesc.length === 0) {
    return '正在搜索...'
  }
  
  return `正在搜索: ${searchDesc.join(', ')}`
}

const handleEdit = (record) => {
  modalTitle.value = '编辑档案'
  Object.assign(formData, {
    ...record,
    birthDate: record.birthDate ? dayjs(record.birthDate) : null,
    entryDate: record.entryDate ? dayjs(record.entryDate) : null
  })
  modalVisible.value = true
}

const handleDelete = (record) => {
  message.success('删除成功')
  // 实现删除逻辑
}

const handleModalOk = async () => {
  try {
    await formRef.value.validate()
    message.success(modalTitle.value + '成功')
    modalVisible.value = false
    resetForm()
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

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

const resetForm = () => {
  Object.keys(formData).forEach(key => {
    if (key === 'birthDate' || key === 'entryDate') {
      formData[key] = null
    } else if (key === 'ageInMonths' || key === 'birthWeight' || key === 'currentValue' || key === 'calvings') {
      formData[key] = null
    } else {
      formData[key] = ''
    }
  })
  formRef.value?.resetFields()
}

// 获取所有牛只档案数据
const fetchAllCattleData = async () => {
  try {
    const response = await api.get('/iot-cattle/public', {
      params: {
        page: 1,
        pageSize: 1000 // 获取大量数据
      }
    })
    
    if (response && response.data && response.data.list) {
      // 格式化数据，使用与搜索函数相同的逻辑
      const formattedResults = response.data.list.map((cattle, index) => {
        const formatted = {
          key: `all-${index}`,
          id: cattle.id,
          earTag: cattle.earNumber || cattle.earTag,
          deviceId: cattle.deviceId || '',
          birthDate: cattle.birthday || cattle.birthDate,
          ageInMonths: cattle.ageInMonths || 0,
          category: cattle.cate || cattle.category,
          breed: cattle.varieties || cattle.breed,
          physiologicalStage: cattle.physiologicalStage || cattle.level || '',
          gender: cattle.sex === 1 ? '公' : cattle.sex === 2 ? '母' : '未知',
          birthWeight: cattle.birthWeight || 0,
          currentValue: cattle.currentWeight || cattle.weight || 0,
          generation: cattle.algebra || cattle.generation,
          bloodlinePurity: cattle.descent || cattle.bloodlinePurity,
          entryDate: cattle.intoTime || cattle.entryDate,
          pen: cattle.penName || cattle.pen,
          calvings: cattle.parity || cattle.calvings,
          source: cattle.source || '',
          frozenSemenNumber: cattle.semenNum || cattle.frozenSemenNumber
        }
        
        return formatted
      })
      
      return formattedResults
    }
    return []
  } catch (error) {
    console.error('获取所有牛只档案失败:', error)
    return []
  }
}

// 测试导出函数
const testClick = () => {
  console.log('=== 按钮被点击 ===')
  message.info('按钮被点击了！')
  exportData()
}

const testExport = () => {
  console.log('测试导出函数被调用')
  message.info('测试导出函数被调用')
}

// 导出数据
const exportData = async () => {
  console.log('=== 导出函数被调用 ===')
  message.info('导出函数被调用')
  
  try {
    // 使用displayData计算属性，它会根据搜索状态返回正确的数据
    const dataToExport = displayData.value
    
    console.log('=== 导出数据调试 ===')
    console.log('isSearching:', isSearching.value)
    console.log('searchResults.length:', searchResults.value.length)
    console.log('tableData.length:', tableData.value.length)
    console.log('displayData.length:', dataToExport.length)
    console.log('原始数据示例:', dataToExport[0])
    
    if (!dataToExport || dataToExport.length === 0) {
      message.warning('没有数据可导出')
      return
    }
    
    message.loading('正在导出数据...', 0)
    
    // 转换数据格式以匹配导出工具类的列配置
    const exportData = dataToExport.map(item => {
      console.log('转换前数据项:', item)
      return {
        id: item.id || item.key,
        ear_tag: item.earTag || '',
        device_id: item.deviceId || '',
        birth_date: item.birthDate || '',
        age_in_months: item.ageInMonths || 0,
        category: item.category || '',
        breed: item.breed || '',
        physiological_stage: item.physiologicalStage || '',
        gender: item.gender || '',
        birth_weight: item.birthWeight || 0,
        current_weight: item.currentValue || 0,
        generation: item.generation || '',
        bloodline_purity: item.bloodlinePurity || '',
        entry_date: item.entryDate || '',
        pen_name: item.pen || '',
        calvings: item.calvings || 0,
        source: item.source || '',
        frozen_semen_number: item.frozenSemenNumber || ''
      }
    })
    
    console.log('转换后数据示例:', exportData[0])
    console.log('转换后数据总数:', exportData.length)
    
    const result = ExportUtils.exportCattleData(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('导出失败，请重试')
  }
}

// 生命周期
onMounted(() => {
  console.log('=== CattleArchives组件已挂载 ===')
  console.log('tableData长度:', tableData.value.length)
  console.log('displayData长度:', displayData.value.length)
  pagination.total = tableData.value.length
  // 获取栏舍列表
  fetchPens()
})
</script>

<style scoped>
.cattle-archives {
  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;
}

.action-btn {
  height: 40px;
  padding: 0 20px;
  border-radius: 6px;
  font-weight: 500;
}

.search-container {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.search-container .search-input {
  width: 250px;
  min-width: 200px;
}

.pen-select {
  width: 200px;
  min-width: 150px;
}

.search-btn {
  height: 40px;
  padding: 0 20px;
  border-radius: 6px;
  font-weight: 500;
}

.reset-btn {
  height: 40px;
  padding: 0 16px;
  border-radius: 6px;
}

.loading-spin {
  margin-left: 8px;
}

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

/* 强制隐藏任何搜索建议下拉框 */
.search-input :deep(.ant-input) {
  autocomplete: off;
}

.search-input :deep(.ant-input-suffix) {
  pointer-events: auto;
}

/* 隐藏任何可能的下拉建议 */
.search-input :deep(.ant-dropdown) {
  display: none !important;
}

.search-input :deep(.ant-select-dropdown) {
  display: none !important;
}

.search-input :deep(.ant-cascader-dropdown) {
  display: none !important;
}

/* 强制隐藏输入框的所有下拉建议 */
.search-input :deep(.ant-input-affix-wrapper) {
  position: relative;
}

.search-input :deep(.ant-input-affix-wrapper::after) {
  display: none !important;
}

/* 确保栏舍选择框可见 */
.pen-select {
  width: 200px;
  min-width: 150px;
  display: block !important;
  visibility: visible !important;
}

/* 强制显示搜索容器中的所有元素 */
.search-container {
  display: flex !important;
  align-items: center !important;
  gap: 12px !important;
  flex-wrap: wrap !important;
}

.search-container .search-input {
  width: 250px !important;
  min-width: 200px !important;
  display: block !important;
  visibility: visible !important;
}

.search-container .pen-select {
  width: 200px !important;
  min-width: 150px !important;
  display: block !important;
  visibility: visible !important;
}

/* 强制隐藏任何可能的搜索建议 */
.search-container :deep(.ant-dropdown) {
  display: none !important;
}

.search-container :deep(.ant-select-dropdown) {
  display: none !important;
}

.search-container :deep(.ant-cascader-dropdown) {
  display: none !important;
}

/* 确保只有栏舍选择框显示下拉选项 */
.pen-select :deep(.ant-select-dropdown) {
  display: block !important;
}

/* 强制隐藏输入框的所有下拉建议 */
.search-input :deep(.ant-input-affix-wrapper) {
  position: relative;
  overflow: hidden;
}

.search-input :deep(.ant-input-affix-wrapper::before) {
  display: none !important;
}

.search-input :deep(.ant-input-affix-wrapper::after) {
  display: none !important;
}

/* 确保输入框不显示任何下拉建议 */
.search-input :deep(.ant-input) {
  autocomplete: off;
  autocorrect: off;
  autocapitalize: off;
  spellcheck: false;
}

/* 强制隐藏所有可能的下拉建议 */
.search-input :deep(.ant-dropdown-menu) {
  display: none !important;
}

.search-input :deep(.ant-menu) {
  display: none !important;
}

.search-input :deep(.ant-list) {
  display: none !important;
}

/* 确保栏舍选择框正常工作 */
.pen-select :deep(.ant-select) {
  display: block !important;
  visibility: visible !important;
}

.pen-select :deep(.ant-select-selector) {
  display: block !important;
  visibility: visible !important;
}

.search-status {
  margin-bottom: 16px;
}

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

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

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

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

.cattle-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%;
    justify-content: flex-start;
  }
  
  .search-container .search-input {
    width: 100%;
    max-width: 300px;
  }
  
  .pen-select {
    width: 100%;
    max-width: 250px;
  }
}

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