<template>
  <div class="cattle-transfer-records">
    <!-- 页面标题 -->
    <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">
        <div class="search-input-group">
          <div style="position: relative; flex: 1;">
            <input
              ref="searchInputRef"
              v-model="searchValue"
              placeholder="请输入耳号搜索"
              class="search-input"
              @keyup.enter="handleSearch"
              @input="handleInputChange"
              @change="handleInputChange"
              @focus="handleSearchFocus"
              @blur="handleSearchBlur"
              style="width: 100%; height: 40px; padding: 8px 40px 8px 12px; border: 1px solid #d9d9d9; border-radius: 6px; font-size: 14px; outline: none;"
            />
            <SearchOutlined 
              @click="handleSearch" 
              style="position: absolute; right: 12px; top: 50%; transform: translateY(-50%); cursor: pointer; color: #999;"
            />
          </div>
          <a-button 
            class="search-reset-btn" 
            @click="handleResetSearch"
            :disabled="!searchValue"
            type="default"
          >
            <template #icon><CloseCircleOutlined /></template>
            重置
          </a-button>
        </div>

      </div>
    </div>

    <!-- 筛选区域 -->
    <div class="filter-bar">
      <a-row :gutter="16">
        <a-col :span="6">
          <a-select
            v-model="filters.fromPen"
            placeholder="转出栏舍"
            allowClear
            style="width: 100%"
            @change="handleFilterChange"
            @select="(value, option) => handlePenSelect(value, option, 'fromPen')"
          >
            <a-select-option 
              v-for="pen in penList" 
              :key="pen.id" 
              :value="pen.name"
            >
              {{ pen.name }}
            </a-select-option>
          </a-select>
        </a-col>
        <a-col :span="6">
          <a-select
            v-model="filters.toPen"
            placeholder="转入栏舍"
            allowClear
            style="width: 100%"
            @change="handleFilterChange"
            @select="(value, option) => handlePenSelect(value, option, 'toPen')"
          >
            <a-select-option 
              v-for="pen in penList" 
              :key="pen.id" 
              :value="pen.name"
            >
              {{ pen.name }}
            </a-select-option>
          </a-select>
        </a-col>
        <!-- <a-col :span="6">
          <a-range-picker
            v-model="filters.dateRange"
            style="width: 100%"
            @change="handleFilterChange"
          />
        </a-col> -->
        <a-col :span="6">
          <a-button @click="handleResetFilters">重置筛选</a-button>
        </a-col>
      </a-row>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <a-table
        :columns="columns"
        :data-source="tableData"
        :pagination="pagination"
        :loading="loading"
        :row-selection="rowSelection"
        class="transfer-table"
        size="middle"
      >
        <!-- 状态列 -->
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <a-tag :color="record.status === '已完成' ? 'green' : 'orange'">
              {{ 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="handleViewDetails(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="700px"
      @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="earNumber">
          <a-input
            v-model:value="formData.earNumber"
            placeholder="请输入牛只耳号"
          />
        </a-form-item>
        
        <a-form-item label="转出栏舍" name="fromPenId">
          <a-select 
            v-model:value="formData.fromPenId" 
            placeholder="请选择转出栏舍"
          >
            <a-select-option 
              v-for="pen in penList" 
              :key="pen.id" 
              :value="pen.id"
            >
              {{ pen.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item label="转入栏舍" name="toPenId">
          <a-select 
            v-model:value="formData.toPenId" 
            placeholder="请选择转入栏舍"
          >
            <a-select-option 
              v-for="pen in penList" 
              :key="pen.id" 
              :value="pen.id"
            >
              {{ pen.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item label="转栏日期" name="transferDate">
          <a-date-picker 
            v-model:value="formData.transferDate" 
            style="width: 100%" 
            placeholder="请选择转栏日期"
          />
        </a-form-item>
        
        <a-form-item label="转栏原因" name="reason">
          <a-select 
            v-model:value="formData.reason" 
            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-form-item label="操作人员" name="operator">
          <a-input 
            v-model:value="formData.operator" 
            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="detailsModalVisible"
      @update:open="detailsModalVisible = $event"
      title="转栏记录详情"
      width="600px"
      :footer="null"
    >
      <a-descriptions :column="2" bordered>
        <a-descriptions-item label="记录编号">{{ currentRecord.id }}</a-descriptions-item>
        <a-descriptions-item label="牛只耳号">{{ currentRecord.earNumber }}</a-descriptions-item>
        <a-descriptions-item label="转出栏舍">{{ currentRecord.fromPenName }}</a-descriptions-item>
        <a-descriptions-item label="转入栏舍">{{ currentRecord.toPenName }}</a-descriptions-item>
        <a-descriptions-item label="转栏日期">{{ currentRecord.transferDate }}</a-descriptions-item>
        <a-descriptions-item label="转栏原因">{{ currentRecord.reason }}</a-descriptions-item>
        <a-descriptions-item label="操作人员">{{ currentRecord.operator }}</a-descriptions-item>
        <a-descriptions-item label="状态">
          <a-tag :color="currentRecord.status === '已完成' ? 'green' : 'orange'">
            {{ currentRecord.status }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="创建时间" :span="2">{{ currentRecord.created_at }}</a-descriptions-item>
        <a-descriptions-item label="备注" :span="2">{{ currentRecord.remark || '无' }}</a-descriptions-item>
      </a-descriptions>
    </a-modal>
  </div>
</template>

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

// 响应式数据
const loading = ref(false)
const searchValue = ref('')
const modalVisible = ref(false)
const detailsModalVisible = ref(false)
const modalTitle = ref('新增转栏记录')
const formRef = ref()
const searchInputRef = ref()
const selectedRowKeys = ref([])

// 筛选条件
const filters = reactive({
  fromPen: null,
  toPen: null,
  dateRange: null
})

// 当前记录详情
const currentRecord = ref({})

// 牛只列表
const cattleList = ref([])

// 栏舍列表
const penList = ref([])

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

// 表格列配置
const columns = [
  {
    title: '记录编号',
    dataIndex: 'id',
    key: 'id',
    width: 120
  },
  {
    title: '牛只耳号',
    dataIndex: 'earNumber',
    key: 'earNumber',
    width: 120
  },
  {
    title: '转出栏舍',
    dataIndex: 'fromPenName',
    key: 'fromPenName',
    width: 150
  },
  {
    title: '转入栏舍',
    dataIndex: 'toPenName',
    key: 'toPenName',
    width: 150
  },
  {
    title: '转栏日期',
    dataIndex: 'transferDate',
    key: 'transferDate',
    width: 120
  },
  {
    title: '转栏原因',
    dataIndex: 'reason',
    key: 'reason',
    width: 120
  },
  {
    title: '操作人员',
    dataIndex: 'operator',
    key: 'operator',
    width: 100
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100
  },
  {
    title: '创建时间',
    dataIndex: 'created_at',
    key: 'created_at',
    width: 150
  },
  {
    title: '操作',
    key: 'action',
    width: 180,
    fixed: 'right'
  }
]

// 分页配置
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({
  id: null,
  earNumber: '',
  fromPenId: null,
  toPenId: null,
  transferDate: null,
  reason: '',
  operator: '',
  status: '已完成',
  remark: ''
})

// 表单验证规则
const formRules = {
  earNumber: [
    { required: true, message: '请输入牛只耳号', trigger: 'blur' },
    { min: 1, max: 50, message: '耳号长度应在1-50个字符之间', trigger: 'blur' }
  ],
  fromPenId: [
    { required: true, message: '请选择转出栏舍', trigger: 'change' }
  ],
  toPenId: [
    { required: true, message: '请选择转入栏舍', trigger: 'change' }
  ],
  transferDate: [
    { required: true, message: '请选择转栏日期', trigger: 'change' }
  ],
  reason: [
    { required: true, message: '请选择转栏原因', trigger: 'change' }
  ],
  operator: [
    { required: true, message: '请输入操作人员', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 方法
const loadData = async () => {
  try {
    loading.value = true;
    // 将栏舍名称转换为栏舍ID
    const fromPenId = filters.fromPen ? penList.value.find(pen => pen.name === filters.fromPen)?.id : null;
    const toPenId = filters.toPen ? penList.value.find(pen => pen.name === filters.toPen)?.id : null;
    
    const params = {
      page: pagination.current,
      pageSize: pagination.pageSize,
      search: searchValue.value,
      fromPen: fromPenId,
      toPen: toPenId,
      dateRange: filters.dateRange
    };
    
    // 详细的请求日志
    console.group('📡 [转栏记录] API请求详情');
    console.log('🕒 请求时间:', new Date().toISOString());
    console.log('🔍 搜索参数:', searchValue.value);
    console.log('🏠 栏舍筛选转换:', {
      转出栏舍名称: filters.fromPen,
      转出栏舍ID: fromPenId,
      转入栏舍名称: filters.toPen,
      转入栏舍ID: toPenId
    });
    console.log('📋 完整请求参数:', JSON.stringify(params, null, 2));
    console.log('🔗 请求路径:', '/api/cattle-transfer-records');
    console.log('🔄 请求方法:', 'GET');
    console.groupEnd();
    
    // 性能监控开始
    const startTime = performance.now();
    const response = await api.cattleTransferRecords.getList(params);
    const endTime = performance.now();
    
    // 响应日志
    console.group('📡 [转栏记录] API响应摘要');
    console.log('⏱️ 请求耗时:', `${(endTime - startTime).toFixed(2)}ms`);
    console.log('🔄 响应状态:', response.success ? '成功' : '失败');
    console.log('🔍 搜索值:', searchValue.value);
    console.log('📊 结果数量:', response.data?.total || 0);
    console.groupEnd();
    
    // 安全地记录API调用指标
    if (api.metrics?.trackApiCall) {
      api.metrics.trackApiCall({
        endpoint: 'cattleTransferRecords.getList',
        duration: endTime - startTime,
        success: response.success,
        searchTerm: searchValue.value,
        resultCount: response.data?.total || 0
      }).catch(err => {
        console.error('📊 指标记录失败:', err);
      });
    } else {
      // 静默失败，不显示提示
    }

    if (response.success) {
      tableData.value = response.data.list.map(item => ({
        ...item,
        key: item.id,
        earNumber: item.earNumber || '',
        fromPenName: item.fromPen?.name || '',
        toPenName: item.toPen?.name || ''
      }));
      pagination.total = response.data.total;
    }
  } catch (error) {
    console.error('❌ [转栏记录] 加载数据失败:', error);
    message.error('加载数据失败');
  } finally {
    loading.value = false;
  }
}

// 不再需要加载牛只列表，因为用户直接输入耳号
// const loadCattleList = async () => {
//   // 已移除，因为牛只耳号改为用户直接输入
// }

const loadPenList = async () => {
  try {
    console.log('🔍 开始加载栏舍列表...')
    const response = await api.get('/cattle-pens/public', { 
      params: { page: 1, pageSize: 1000 } 
    })
    console.log('✅ 栏舍列表API响应:', response)
    
    if (response.success) {
      penList.value = response.data.list || []
      console.log(`📊 加载到 ${penList.value.length} 个栏舍`)
      if (penList.value.length > 0) {
        console.log('📋 栏舍列表示例:', penList.value.slice(0, 3))
      }
    } else {
      console.error('❌ 加载栏舍列表失败:', response.message)
      message.error('加载栏舍列表失败')
    }
  } catch (error) {
    console.error('❌ 加载栏舍列表异常:', error)
    message.error('加载栏舍列表失败')
  }
}

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

const handleEdit = async (record) => {
  console.log('🔄 [转栏记录] 开始编辑操作')
  console.log('📋 [转栏记录] 原始记录数据:', {
    id: record.id,
    earNumber: record.earNumber,
    fromPenId: record.fromPenId,
    toPenId: record.toPenId,
    transferDate: record.transferDate,
    reason: record.reason,
    operator: record.operator,
    status: record.status,
    remark: record.remark,
    fromPenName: record.fromPenName,
    toPenName: record.toPenName
  })
  
  modalTitle.value = '编辑转栏记录'
  
  // 确保栏舍列表已加载
  if (penList.value.length === 0) {
    await loadPenList()
  }
  
  // 处理日期转换
  let transferDateValue = null
  if (record.transferDate) {
    if (typeof record.transferDate === 'string') {
      transferDateValue = dayjs(record.transferDate)
    } else if (record.transferDate instanceof Date) {
      transferDateValue = dayjs(record.transferDate)
    } else if (record.transferDate && typeof record.transferDate === 'object' && record.transferDate.format) {
      // 如果已经是 dayjs 对象，直接使用
      transferDateValue = record.transferDate
    } else {
      transferDateValue = dayjs(record.transferDate)
    }
    console.log('📅 [转栏记录] 日期转换:', record.transferDate, '->', transferDateValue?.format('YYYY-MM-DD'))
  }
  
  // 填充表单数据
  formData.id = record.id
  formData.earNumber = record.earNumber || ''
  formData.fromPenId = record.fromPenId || null
  formData.toPenId = record.toPenId || null
  formData.transferDate = transferDateValue
  formData.reason = record.reason || ''
  formData.operator = record.operator || ''
  formData.status = record.status || '进行中'
  formData.remark = record.remark || ''
  
  console.log('📝 [转栏记录] 表单数据已填充:', formData)
  console.log('📝 [转栏记录] transferDate 是否为 dayjs:', formData.transferDate && typeof formData.transferDate.format === 'function')
  
  // 打开模态框
  modalVisible.value = true
  
  // 等待模态框和表单渲染完成
  await nextTick()
  await new Promise(resolve => setTimeout(resolve, 200))
  
  console.log('✅ [转栏记录] 模态框已打开，表单应该已填充')
}

const handleDelete = (record) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除转栏记录"${record.recordId}"吗？`,
    async onOk() {
      try {
        await api.cattleTransferRecords.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.cattleTransferRecords.batchDelete(selectedRowKeys.value)
        message.success('批量删除成功')
        selectedRowKeys.value = []
        loadData()
      } catch (error) {
        console.error('批量删除失败:', error)
        message.error('批量删除失败')
      }
    }
  })
}

const handleExport = async () => {
  try {
    console.log('=== 开始导出转栏记录数据 ===')
    
    message.loading('正在获取所有转栏记录数据...', 0)
    
    // 获取所有转栏记录数据，不受分页限制
    const response = await api.cattleTransferRecords.getList({
      page: 1,
      pageSize: 1000 // 获取大量数据
    })
    
    if (!response.success || !response.data || !response.data.list) {
      message.destroy()
      message.warning('没有数据可导出')
      return
    }
    
    const allRecords = response.data.list
    console.log('获取到所有转栏记录数据:', allRecords.length, '条记录')
    console.log('原始数据示例:', allRecords[0])
    
    // 转换数据格式以匹配导出工具类的列配置
    const exportData = allRecords.map(item => {
      console.log('转换前转栏记录数据项:', item)
      
      // 解析原栏舍和目标栏舍的JSON对象，只提取name字段
      let fromPenName = ''
      let toPenName = ''
      
      try {
        if (typeof item.fromPen === 'string') {
          const fromPenObj = JSON.parse(item.fromPen)
          fromPenName = fromPenObj.name || ''
        } else if (item.fromPen && item.fromPen.name) {
          fromPenName = item.fromPen.name
        } else {
          fromPenName = item.fromPenName || ''
        }
      } catch (e) {
        fromPenName = item.fromPenName || item.fromPen || ''
      }
      
      try {
        if (typeof item.toPen === 'string') {
          const toPenObj = JSON.parse(item.toPen)
          toPenName = toPenObj.name || ''
        } else if (item.toPen && item.toPen.name) {
          toPenName = item.toPen.name
        } else {
          toPenName = item.toPenName || ''
        }
      } catch (e) {
        toPenName = item.toPenName || item.toPen || ''
      }
      
      return {
        id: item.id,
        ear_tag: item.earTag || item.earNumber || '',
        from_pen: fromPenName,
        to_pen: toPenName,
        transfer_time: item.transferTime || item.transfer_time || item.created_at || '',
        reason: item.reason || item.transferReason || '',
        operator: item.operator || item.operatorName || ''
      }
    })
    
    console.log('转换后转栏记录数据示例:', exportData[0])
    console.log('转换后转栏记录数据总数:', exportData.length)
    
    message.destroy()
    message.loading('正在导出数据...', 0)
    
    const result = ExportUtils.exportTransferData(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 handleViewDetails = (record) => {
  currentRecord.value = record
  detailsModalVisible.value = true
}


const handleSearch = () => {
  // 获取当前用户信息
  const userInfo = JSON.parse(localStorage.getItem('user') || '{}');
  
  // 强制从DOM获取最新值
  const domValue = searchInputRef.value?.inputValue || searchInputRef.value?.value || '';
  if (domValue && domValue !== searchValue.value) {
    searchValue.value = domValue;
    console.log('🔄 [转栏记录] 从DOM同步搜索值:', domValue);
  }
  
  // 使用nextTick确保获取到最新的搜索值
  nextTick(() => {
    // 获取当前搜索值，确保获取到最新的值
    const currentSearchValue = searchValue.value ? searchValue.value.trim() : '';
  
    // 详细的搜索操作日志
    console.group('🔍 [转栏记录] 搜索操作详情');
    console.log('🕒 搜索时间:', new Date().toLocaleString());
    console.log('🔎 搜索关键词:', currentSearchValue || '空搜索');
    console.log('📝 原始搜索值:', searchValue.value);
    console.log('🔍 搜索值类型:', typeof searchValue.value);
    console.log('📏 搜索值长度:', searchValue.value ? searchValue.value.length : 0);
    console.log('📊 搜索参数:', {
      关键词: currentSearchValue,
      当前页: pagination.current,
      每页大小: pagination.pageSize,
      转出栏舍: filters.fromPen,
      转入栏舍: filters.toPen,
      日期范围: filters.dateRange
    });
    console.log('👤 用户信息:', {
      ID: userInfo.id || 'unknown',
      用户名: userInfo.username || 'unknown',
      角色: userInfo.role?.name || 'unknown'
    });
    console.log('🌐 环境信息:', {
      用户代理: navigator.userAgent,
      屏幕分辨率: `${window.screen.width}x${window.screen.height}`,
      网络状态: navigator.onLine ? '在线' : '离线',
      当前URL: window.location.href
    });
    console.groupEnd();
    
    // 合并搜索操作和日志记录
    const searchLog = {
      action: 'SEARCH_TRANSFER_RECORDS',
      searchValue: currentSearchValue,
      timestamp: new Date().toISOString(),
      page: pagination.current,
      pageSize: pagination.pageSize,
      userId: userInfo.id || 'unknown',
      username: userInfo.username || 'unknown',
      userAgent: navigator.userAgent,
      screenResolution: `${window.screen.width}x${window.screen.height}`,
      filters: {
        fromPen: filters.fromPen,
        toPen: filters.toPen,
        dateRange: filters.dateRange
      },
      networkStatus: navigator.onLine ? 'online' : 'offline'
    };

    // 安全地发送搜索日志到后端
    if (api.logs?.addSearchLog) {
      api.logs.addSearchLog({
        module: 'transfer-records',
        action: 'search',
        data: searchLog
      }).catch(err => {
        console.error('📡 日志发送失败:', err);
      });
    } else {
      console.log('ℹ️ [转栏记录] 搜索日志功能不可用');
    }

    pagination.current = 1;
    loadData();
  });
}

const handlePenSelect = (value, option, penType) => {
  console.group('🎯 [转栏记录] 栏舍选择事件');
  console.log('🕒 选择时间:', new Date().toLocaleString());
  console.log('📝 选择的值:', value);
  console.log('📋 选择的选项:', option);
  console.log('🏠 栏舍类型:', penType);
  console.log('🏠 选择前filters.fromPen:', filters.fromPen);
  console.log('🏠 选择前filters.toPen:', filters.toPen);
  
  // 手动更新filters对象
  if (penType === 'fromPen') {
    filters.fromPen = value;
    console.log('✅ 手动设置filters.fromPen为:', value);
  } else if (penType === 'toPen') {
    filters.toPen = value;
    console.log('✅ 手动设置filters.toPen为:', value);
  }
  
  console.log('🏠 选择后filters.fromPen:', filters.fromPen);
  console.log('🏠 选择后filters.toPen:', filters.toPen);
  console.groupEnd();
  
  // 触发筛选条件变化
  handleFilterChange();
}

const handleFilterChange = () => {
  console.group('🔄 [转栏记录] 筛选条件变化');
  console.log('🕒 变化时间:', new Date().toLocaleString());
  console.log('🏠 转出栏舍:', filters.fromPen);
  console.log('🏠 转入栏舍:', filters.toPen);
  console.log('📅 日期范围:', filters.dateRange);
  console.log('📊 完整filters对象:', JSON.stringify(filters, null, 2));
  console.groupEnd();
  
  pagination.current = 1
  loadData()
}

const handleResetFilters = () => {
  filters.fromPen = null
  filters.toPen = null
  filters.dateRange = null
  handleFilterChange()
}

// 重置搜索框
const handleResetSearch = () => {
  console.log('🔄 [转栏记录] 重置搜索框')
  searchValue.value = ''
  pagination.current = 1
  loadData()
  message.success('搜索条件已重置')
}

const handleModalOk = async () => {
  try {
    console.log('💾 [转栏记录] 开始保存操作')
    console.log('📝 [转栏记录] 用户输入的表单数据:', {
      id: formData.id,
      earNumber: formData.earNumber,
      fromPenId: formData.fromPenId,
      toPenId: formData.toPenId,
      transferDate: formData.transferDate,
      reason: formData.reason,
      operator: formData.operator,
      status: formData.status,
      remark: formData.remark
    })
    
    await formRef.value.validate()
    console.log('✅ [转栏记录] 表单验证通过')
    
    // 准备发送给后端的数据，转换日期格式
    const submitData = {
      ...formData,
      transferDate: formData.transferDate ? formData.transferDate.format('YYYY-MM-DD') : null,
      fromPenId: formData.fromPenId ? Number(formData.fromPenId) : null,
      toPenId: formData.toPenId ? Number(formData.toPenId) : null
    }
    
    console.log('📤 [转栏记录] 准备发送的数据:', submitData)
    
    if (modalTitle.value === '新增转栏记录') {
      console.log('🆕 [转栏记录] 执行创建操作')
      await api.cattleTransferRecords.create(submitData)
      console.log('✅ [转栏记录] 创建成功')
      message.success('创建成功')
    } else {
      console.log('🔄 [转栏记录] 执行更新操作，记录ID:', formData.id)
      const response = await api.cattleTransferRecords.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()
}

// 防抖计时器
let inputDebounceTimer = null;

// 处理输入变化
const handleInputChange = (e) => {
  const value = e.target.value;
  console.log('⌨️ [转栏记录] 原生input输入变化:', value);
  console.log('🔍 [转栏记录] 当前searchValue:', searchValue.value);
  console.log('✅ [转栏记录] v-model应该自动更新searchValue');
};

// 搜索框焦点事件
const handleSearchFocus = (e) => {
  console.log('🎯 [转栏记录] 搜索框获得焦点');
  console.log('📝 当前搜索值:', searchValue.value);
  console.log('🕒 焦点时间:', new Date().toLocaleString());
}

// 搜索框失焦事件
const handleSearchBlur = (e) => {
  // 使用nextTick确保Vue的响应式更新完成
  nextTick(() => {
    console.log('👋 [转栏记录] 搜索框失去焦点');
    console.log('📝 最终搜索值:', searchValue.value);
    console.log('🕒 失焦时间:', new Date().toLocaleString());
    
    // 如果搜索框有值，提示用户可以进行搜索
    if (searchValue.value && searchValue.value.trim()) {
      console.log('💡 [转栏记录] 搜索提示: 输入框有内容，可以按回车键或点击搜索图标进行搜索');
    } else {
      console.log('📭 [转栏记录] 搜索框为空');
    }
  });
}

const handleEarNumberChange = (event) => {
  const earNumber = event.target.value;
  // 当用户输入耳号时，可以在这里添加验证逻辑
  // 比如检查耳号是否存在，或者根据耳号自动填充其他信息
  console.log('用户输入耳号:', earNumber);
}

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

const filterOption = (input, option) => {
  return option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
}

const resetForm = () => {
  Object.keys(formData).forEach(key => {
    if (key === 'transferDate' || key === 'fromPenId' || key === 'toPenId') {
      formData[key] = null
    } else if (key === 'id') {
      formData[key] = null
    } else {
      formData[key] = ''
    }
  })
  formData.status = '已完成'
  formRef.value?.resetFields()
}

// 监听搜索值变化
watch(searchValue, (newValue, oldValue) => {
  console.group('👀 [转栏记录] 搜索值变化监听');
  console.log('🕒 时间:', new Date().toLocaleString());
  console.log('📝 新值:', newValue);
  console.log('📝 旧值:', oldValue);
  console.log('📏 新值长度:', newValue ? newValue.length : 0);
  console.log('📏 旧值长度:', oldValue ? oldValue.length : 0);
  console.log('🔄 变化类型:', (newValue?.length || 0) > (oldValue?.length || 0) ? '新增字符' : (newValue?.length || 0) < (oldValue?.length || 0) ? '删除字符' : '无变化');
  console.log('🔍 值是否相等:', newValue === oldValue);
  console.log('🎯 搜索框状态:', {
    hasValue: !!newValue,
    isEmpty: !newValue || newValue.trim() === '',
    isWhitespace: newValue && newValue.trim() === ''
  });
  console.groupEnd();
  
  // 如果输入框有值，显示搜索提示
  if (newValue && newValue.trim()) {
    console.log('💡 [转栏记录] 搜索提示: 按回车键或点击搜索图标进行搜索');
  } else {
    console.log('📭 [转栏记录] 搜索框为空');
  }
}, { immediate: true });

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

<style scoped>
.cattle-transfer-records {
  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: 16px;
  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: 380px;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 8px;
}

.search-input-group {
  display: flex;
  width: 100%;
  gap: 8px;
}

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

.search-reset-btn {
  height: 40px;
  border-radius: 6px;
  white-space: nowrap;
}

.search-hint {
  font-size: 12px;
  color: #1890ff;
  background: #f0f8ff;
  padding: 4px 8px;
  border-radius: 4px;
  border: 1px solid #d9f7be;
  margin-top: 4px;
  animation: fadeIn 0.3s ease-in;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(-5px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.filter-bar {
  margin-bottom: 24px;
  padding: 16px 24px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

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

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

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

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

.transfer-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%;
  }
  
  .filter-bar .ant-row .ant-col {
    margin-bottom: 8px;
  }
}

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