<template>
  <div class="cattle-exit-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">
        <a-input
          v-model="searchValue"
          placeholder="请输入耳号搜索"
          class="search-input"
          @pressEnter="handleSearch"
          @input="handleInputChange"
          @focus="handleSearchFocus"
          @blur="handleSearchBlur"
        >
          <template #suffix>
            <a-space>
              <SearchOutlined @click="handleSearch" style="cursor: pointer;" />
              <ClearOutlined 
                v-if="searchValue && searchValue.trim()" 
                @click="handleResetSearch" 
                style="cursor: pointer; color: #999;" 
                title="重置搜索"
              />
            </a-space>
          </template>
        </a-input>

      </div>
    </div>

    <!-- 筛选区域 -->
    <div class="filter-bar">
      <a-row :gutter="16">
        <a-col :span="6">
          <a-select
            v-model="filters.exitReason"
            placeholder="离栏原因"
            allowClear
            style="width: 100%"
            @change="handleFilterChange"
            @select="(value, option) => handleFilterSelect(value, option, 'exitReason')"
          >
            <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-col>
        <a-col :span="6">
          <a-select
            v-model="filters.status"
            placeholder="记录状态"
            allowClear
            style="width: 100%"
            @change="handleFilterChange"
            @select="(value, option) => handleFilterSelect(value, option, 'status')"
          >
            <a-select-option value="已确认">已确认</a-select-option>
            <a-select-option value="待确认">待确认</a-select-option>
            <a-select-option value="已取消">已取消</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="exit-table"
        size="middle"
      >
        <!-- 状态列 -->
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <a-tag :color="getStatusColor(record.status)">
              {{ record.status }}
            </a-tag>
          </template>
          <template v-if="column.key === 'exitReason'">
            <a-tag :color="getReasonColor(record.exitReason)">
              {{ record.exitReason }}
            </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 
                v-if="record.status === '待确认'" 
                type="link" 
                size="small" 
                @click="handleConfirm(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="exitDate">
          <a-date-picker 
            v-model:value="formData.exitDate" 
            style="width: 100%" 
            placeholder="请选择离栏日期"
          />
        </a-form-item>
        
        <a-form-item label="离栏原因" name="exitReason">
          <a-select 
            v-model:value="formData.exitReason" 
            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="originalPenId">
          <a-select 
            v-model:value="formData.originalPenId" 
            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="destination">
          <a-input 
            v-model:value="formData.destination" 
            placeholder="请输入牛只去向"
          />
        </a-form-item>
        
        <a-form-item label="处理方式" name="disposalMethod">
          <a-select 
            v-model:value="formData.disposalMethod" 
            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="handler">
          <a-input 
            v-model:value="formData.handler" 
            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 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.exitDate }}</a-descriptions-item>
        <a-descriptions-item label="离栏原因">
          <a-tag :color="getReasonColor(currentRecord.exitReason)">
            {{ currentRecord.exitReason }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="原栏舍">{{ currentRecord.originalPenName }}</a-descriptions-item>
        <a-descriptions-item label="去向">{{ currentRecord.destination }}</a-descriptions-item>
        <a-descriptions-item label="处理方式">{{ currentRecord.disposalMethod }}</a-descriptions-item>
        <a-descriptions-item label="处理人员">{{ currentRecord.handler }}</a-descriptions-item>
        <a-descriptions-item label="状态">
          <a-tag :color="getStatusColor(currentRecord.status)">
            {{ 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,
  ClearOutlined
} 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 selectedRowKeys = ref([])

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

// 当前记录详情
const currentRecord = 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: 'exitDate',
    key: 'exitDate',
    width: 120
  },
  {
    title: '离栏原因',
    dataIndex: 'exitReason',
    key: 'exitReason',
    width: 120
  },
  {
    title: '原栏舍',
    dataIndex: 'originalPenName',
    key: 'originalPenName',
    width: 100
  },
  {
    title: '去向',
    dataIndex: 'destination',
    key: 'destination',
    width: 150
  },
  {
    title: '处理方式',
    dataIndex: 'disposalMethod',
    key: 'disposalMethod',
    width: 120
  },
  {
    title: '处理人员',
    dataIndex: 'handler',
    key: 'handler',
    width: 100
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100
  },
  {
    title: '创建时间',
    dataIndex: 'created_at',
    key: 'created_at',
    width: 150
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    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: '',
  exitDate: null,
  exitReason: '',
  originalPenId: null,
  destination: '',
  disposalMethod: '',
  handler: '',
  status: '待确认',
  remark: ''
})

// 表单验证规则
const formRules = {
  earNumber: [
    { required: true, message: '请输入牛只耳号', trigger: 'blur' }
  ],
  exitDate: [
    { required: true, message: '请选择离栏日期', trigger: 'change' }
  ],
  exitReason: [
    { required: true, message: '请选择离栏原因', trigger: 'change' }
  ],
  originalPenId: [
    { required: true, message: '请选择原栏舍', trigger: 'change' }
  ],
  destination: [
    { required: true, message: '请输入去向', trigger: 'blur' }
  ],
  disposalMethod: [
    { required: true, message: '请选择处理方式', trigger: 'change' }
  ],
  handler: [
    { required: true, message: '请输入处理人员', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 方法
const getStatusColor = (status) => {
  const colorMap = {
    '已确认': 'green',
    '待确认': 'orange',
    '已取消': 'red'
  }
  return colorMap[status] || 'default'
}

const getReasonColor = (reason) => {
  const colorMap = {
    '出售': 'green',
    '死亡': 'red',
    '淘汰': 'orange',
    '转场': 'blue',
    '其他': 'default'
  }
  return colorMap[reason] || 'default'
}

// 数据加载方法
const loadData = async () => {
  try {
    loading.value = true;
    const params = {
      page: pagination.current,
      pageSize: pagination.pageSize,
      search: searchValue.value,
      exitReason: filters.exitReason,
      status: filters.status,
      dateRange: filters.dateRange
    };
    
    // 详细的请求日志
    console.group('📡 [离栏记录] API请求详情');
    console.log('🕒 请求时间:', new Date().toISOString());
    console.log('🔍 搜索参数:', searchValue.value);
    console.log('📋 完整请求参数:', JSON.stringify(params, null, 2));
    console.log('🔗 请求路径:', '/api/cattle-exit-records');
    console.log('🔄 请求方法:', 'GET');
    console.groupEnd();
    
    // 性能监控开始
    const startTime = performance.now();
    const response = await api.cattleExitRecords.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: 'cattleExitRecords.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 || '',
        originalPenName: item.originalPen?.name || ''
      }));
      pagination.total = response.data.total;
    }
  } catch (error) {
    console.error('❌ [离栏记录] 加载数据失败:', error);
    message.error('加载数据失败');
  } finally {
    loading.value = false;
  }
}

// 不再需要加载牛只列表

const loadPenList = async () => {
  try {
    const response = await api.cattlePens.getList({ page: 1, pageSize: 1000 })
    if (response.success) {
      penList.value = response.data.list
    }
  } catch (error) {
    console.error('加载栏舍列表失败:', error)
  }
}

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

// 获取离栏记录详情（用于编辑）
const getExitRecordDetail = async (id) => {
  console.log('🔵 [离栏记录-编辑] ========== 开始获取详情 ==========')
  console.log('🔵 [离栏记录-编辑] 函数被调用，记录ID:', id)
  console.log('🔵 [离栏记录-编辑] 调用时间:', new Date().toISOString())
  
  try {
    console.log('🔄 [离栏记录-编辑] 开始获取详情')
    console.log('📋 [离栏记录-编辑] 记录ID:', id)
    
    // 调用后端接口获取详情
    console.log('📡 [离栏记录-编辑] 准备调用 API: /cattle-exit-records/' + id)
    const response = await api.cattleExitRecords.getById(id)
    console.log('📡 [离栏记录-编辑] API 调用完成，响应状态:', response.success)
    
    if (response.success && response.data) {
      console.log('✅ [离栏记录-编辑] 获取详情成功:', response.data)
      console.log('🔵 [离栏记录-编辑] ========== 获取详情成功 ==========')
      return response.data
    } else {
      console.error('❌ [离栏记录-编辑] 获取详情失败:', response.message)
      throw new Error(response.message || '获取离栏记录详情失败')
    }
  } catch (error) {
    console.error('❌ [离栏记录-编辑] 获取详情异常:', error)
    console.error('🔵 [离栏记录-编辑] ========== 获取详情失败 ==========')
    throw error
  }
}

// 编辑离栏记录
const handleEdit = async (record) => {
  // 立即输出日志，确认函数被调用
  console.log('🟢🟢🟢 [离栏记录-编辑] ========== handleEdit 函数被调用 ==========')
  console.log('🟢 [离栏记录-编辑] 调用时间:', new Date().toISOString())
  console.log('🟢 [离栏记录-编辑] 记录数据:', record)
  console.log('🟢 [离栏记录-编辑] 记录ID:', record?.id)
  
  // 验证 record 对象
  if (!record) {
    console.error('❌ [离栏记录-编辑] record 为空')
    message.error('记录数据为空')
    return
  }
  
  if (!record.id) {
    console.error('❌ [离栏记录-编辑] record.id 为空')
    message.error('记录ID为空')
    return
  }
  
  try {
    console.log('🔄 [离栏记录-编辑] 开始编辑操作')
    console.log('📋 [离栏记录-编辑] 编辑记录ID:', record.id)
    
    // 调用封装的获取详情接口
    console.log('📞 [离栏记录-编辑] 准备调用 getExitRecordDetail 函数，ID:', record.id)
    console.log('📞 [离栏记录-编辑] getExitRecordDetail 函数是否存在:', typeof getExitRecordDetail)
    
    const detailData = await getExitRecordDetail(record.id)
    console.log('📞 [离栏记录-编辑] getExitRecordDetail 函数调用完成，返回数据:', detailData)
    
    if (detailData) {
      console.log('📋 [离栏记录] 获取到的详情数据:', detailData)
      
      modalTitle.value = '编辑离栏记录'
      
      // 确保栏舍列表已加载
      if (penList.value.length === 0) {
        await loadPenList()
      }
      
      // 填充表单数据 - 直接赋值给 reactive 对象的属性
      
      // 处理日期转换
      let exitDateValue = null
      if (detailData.exitDate) {
        // 如果是字符串，转换为 dayjs 对象
        if (typeof detailData.exitDate === 'string') {
          exitDateValue = dayjs(detailData.exitDate)
        } else if (detailData.exitDate instanceof Date) {
          exitDateValue = dayjs(detailData.exitDate)
        } else if (detailData.exitDate && typeof detailData.exitDate === 'object' && detailData.exitDate.format) {
          // 如果已经是 dayjs 对象，直接使用
          exitDateValue = detailData.exitDate
        } else {
          exitDateValue = dayjs(detailData.exitDate)
        }
        console.log('📅 [离栏记录] 日期转换:', detailData.exitDate, '->', exitDateValue?.format('YYYY-MM-DD'))
        console.log('📅 [离栏记录] exitDateValue 类型:', typeof exitDateValue, '是否为 dayjs:', exitDateValue && typeof exitDateValue.format === 'function')
      }
      
      // 先填充表单数据（在打开模态框之前）
      console.log('📝 [离栏记录] 开始填充表单数据')
      
      // 直接赋值给 reactive 对象
      formData.id = detailData.id || null
      formData.earNumber = detailData.earNumber || ''
      formData.exitDate = exitDateValue  // 确保是 dayjs 对象
      formData.exitReason = detailData.exitReason || ''
      formData.originalPenId = detailData.originalPenId || null
      formData.destination = detailData.destination || ''
      formData.disposalMethod = detailData.disposalMethod || ''
      formData.handler = detailData.handler || ''
      formData.status = detailData.status || '待确认'
      formData.remark = detailData.remark || ''
      
      console.log('📝 [离栏记录] 表单数据已填充到 formData')
      console.log('📝 [离栏记录] formData.exitDate:', formData.exitDate)
      console.log('📝 [离栏记录] formData.exitDate 类型:', typeof formData.exitDate)
      console.log('📝 [离栏记录] formData.exitDate 是否为 dayjs:', formData.exitDate && typeof formData.exitDate.format === 'function')
      console.log('📝 [离栏记录] formData 完整数据:', {
        id: formData.id,
        earNumber: formData.earNumber,
        exitDate: formData.exitDate ? (formData.exitDate.format ? formData.exitDate.format('YYYY-MM-DD') : formData.exitDate) : null,
        exitReason: formData.exitReason,
        originalPenId: formData.originalPenId,
        destination: formData.destination,
        disposalMethod: formData.disposalMethod,
        handler: formData.handler,
        status: formData.status,
        remark: formData.remark
      })
      
      // 先打开模态框
      modalVisible.value = true
      console.log('📝 [离栏记录] 模态框已打开')
      
      // 等待模态框完全打开和表单渲染
      await nextTick()
      await new Promise(resolve => setTimeout(resolve, 300))
      
      // 确保日期字段是 dayjs 对象（防止被序列化）
      if (detailData.exitDate && (!formData.exitDate || typeof formData.exitDate.format !== 'function')) {
        formData.exitDate = exitDateValue
        console.log('🔄 [离栏记录] 重新设置 exitDate 为 dayjs 对象:', formData.exitDate)
      }
      
      console.log('🔍 [离栏记录] 检查 formData.exitDate 是否为 dayjs:', 
        formData.exitDate && typeof formData.exitDate.format === 'function' ? '是' : '否',
        formData.exitDate ? (formData.exitDate.format ? formData.exitDate.format('YYYY-MM-DD') : formData.exitDate) : 'null'
      )
      
      // 由于表单使用 v-model 绑定到 formData，直接修改 formData 即可更新表单
      // 但为了确保表单组件正确响应，我们尝试使用 setFieldsValue（如果可用）
      if (formRef.value) {
        // 检查表单实例是否有 setFieldsValue 方法
        if (typeof formRef.value.setFieldsValue === 'function') {
          try {
            const fieldsValue = {
              id: formData.id,
              earNumber: formData.earNumber,
              exitDate: formData.exitDate, // 确保是 dayjs 对象
              exitReason: formData.exitReason,
              originalPenId: formData.originalPenId,
              destination: formData.destination,
              disposalMethod: formData.disposalMethod,
              handler: formData.handler,
              status: formData.status,
              remark: formData.remark
            }
            console.log('🔧 [离栏记录] 使用 setFieldsValue 设置表单值')
            console.log('🔧 [离栏记录] exitDate 值:', fieldsValue.exitDate, '类型:', typeof fieldsValue.exitDate)
            formRef.value.setFieldsValue(fieldsValue)
            console.log('✅ [离栏记录] setFieldsValue 设置成功')
          } catch (error) {
            console.warn('⚠️ [离栏记录] setFieldsValue 失败，但 formData 已更新，表单应该会自动响应:', error)
          }
        } else {
          console.log('ℹ️ [离栏记录] 表单实例没有 setFieldsValue 方法，使用 v-model 绑定（formData 已更新）')
        }
      } else {
        console.warn('⚠️ [离栏记录] formRef.value 为空，但 formData 已更新，表单应该会自动响应')
      }
      
      // 再次使用 nextTick 确保值已更新
      await nextTick()
      await new Promise(resolve => setTimeout(resolve, 100))
      
      // 验证表单值
      console.log('✅ [离栏记录] 模态框已打开')
      console.log('✅ [离栏记录] formData.exitDate 最终值:', formData.exitDate)
      console.log('✅ [离栏记录] formData.exitDate 是否为 dayjs:', formData.exitDate && typeof formData.exitDate.format === 'function')
      
      // 如果表单实例有 getFieldsValue 方法，验证表单值
      if (formRef.value && typeof formRef.value.getFieldsValue === 'function') {
        try {
          const currentFormData = formRef.value.getFieldsValue()
          console.log('✅ [离栏记录] 表单当前值（通过 getFieldsValue）:', currentFormData)
          console.log('✅ [离栏记录] 表单 exitDate 值:', currentFormData.exitDate)
        } catch (error) {
          console.warn('⚠️ [离栏记录] 无法获取表单值:', error)
        }
      }
    } else {
      message.error('获取离栏记录详情失败')
    }
  } catch (error) {
    console.error('❌ [离栏记录] 编辑操作失败:', error)
    message.error(error.message || '获取离栏记录详情失败')
  }
}

const handleDelete = (record) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除离栏记录"${record.recordId}"吗？`,
    async onOk() {
      try {
        await api.cattleExitRecords.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.cattleExitRecords.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.cattleExitRecords.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])
    console.log('原始数据所有字段:', Object.keys(allRecords[0]))
    
    // 转换数据格式以匹配导出工具类的列配置
    const exportData = allRecords.map(item => {
      console.log('转换前离栏记录数据项:', item)
      
      // 解析原栏舍的JSON对象，只提取name字段
      let fromPenName = ''
      try {
        if (item.originalPen && item.originalPen.name) {
          fromPenName = item.originalPen.name
        } else 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 || item.originalPenName || ''
        }
      } catch (e) {
        fromPenName = item.fromPenName || item.originalPenName || item.fromPen || ''
      }
      
      return {
        id: item.id,
        ear_tag: item.earTag || item.earNumber || '',
        from_pen: fromPenName,
        exit_reason: item.exitReason || item.reason || '',
        exit_time: item.exitDate || item.exitTime || item.exit_time || '',
        destination: item.destination || item.dest || '',
        operator: item.handler || item.operator || item.operatorName || item.createdBy || item.creator || item.created_by || item.operator_name || '系统',
        notes: item.notes || item.remark || ''
      }
    })
    
    console.log('转换后离栏记录数据示例:', exportData[0])
    console.log('转换后离栏记录数据总数:', exportData.length)
    
    message.destroy()
    message.loading('正在导出数据...', 0)
    
    const result = ExportUtils.exportExitData(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 handleConfirm = async (record) => {
  Modal.confirm({
    title: '确认离栏记录',
    content: `确定要确认离栏记录"${record.recordId}"吗？`,
    async onOk() {
      try {
        await api.cattleExitRecords.confirm(record.id)
        message.success('确认成功')
        loadData()
      } catch (error) {
        console.error('确认失败:', error)
        message.error('确认失败')
      }
    }
  })
}

// 不再需要牛只变化处理，因为用户直接输入耳号

// 字段变化监听方法
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 handleSearch = () => {
  // 获取当前用户信息
  const userInfo = JSON.parse(localStorage.getItem('user') || '{}');
  
  // 使用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.exitReason,
      状态: filters.status,
      日期范围: 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_EXIT_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: {
        exitReason: filters.exitReason,
        status: filters.status,
        dateRange: filters.dateRange
      },
      networkStatus: navigator.onLine ? 'online' : 'offline'
    };

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

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

const handleResetSearch = () => {
  console.log('🔄 [离栏记录] 重置搜索操作');
  console.log('📝 重置前搜索值:', searchValue.value);
  
  // 清空搜索值
  searchValue.value = '';
  
  console.log('📝 重置后搜索值:', searchValue.value);
  console.log('✅ [离栏记录] 搜索值已清空');
  
  // 重置分页到第一页
  pagination.current = 1;
  
  // 重新加载数据
  loadData();
  
  // 显示重置成功提示
  message.success('搜索已重置');
}

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

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

const handleResetFilters = () => {
  filters.exitReason = null
  filters.status = null
  filters.dateRange = null
  handleFilterChange()
}

const handleModalOk = async () => {
  try {
    console.log('💾 [离栏记录] 开始保存操作')
    console.log('📝 [离栏记录] 用户输入的表单数据:', {
      id: formData.id,
      earNumber: formData.earNumber,
      exitDate: formData.exitDate,
      exitReason: formData.exitReason,
      originalPenId: formData.originalPenId,
      destination: formData.destination,
      disposalMethod: formData.disposalMethod,
      handler: formData.handler,
      status: formData.status,
      remark: formData.remark
    })
    
    await formRef.value.validate()
    console.log('✅ [离栏记录] 表单验证通过')
    
    // 准备发送给后端的数据，转换日期格式
    const submitData = {
      ...formData,
      exitDate: formData.exitDate ? formData.exitDate.format('YYYY-MM-DD') : null,
      originalPenId: formData.originalPenId ? Number(formData.originalPenId) : null
    }
    
    console.log('📤 [离栏记录] 准备发送的数据:', submitData)
    
    if (modalTitle.value === '新增离栏记录') {
      console.log('🆕 [离栏记录] 执行创建操作')
      await api.cattleExitRecords.create(submitData)
      console.log('✅ [离栏记录] 创建成功')
      message.success('创建成功')
    } else {
      console.log('🔄 [离栏记录] 执行更新操作，记录ID:', formData.id)
      const response = await api.cattleExitRecords.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.group('⌨️ [离栏记录] 手动输入处理');
  console.log('🕒 时间:', new Date().toLocaleString());
  console.log('📝 输入值:', value);
  console.log('📏 输入长度:', value.length);
  console.log('🔍 当前searchValue:', searchValue.value);
  console.log('🔍 值是否相等:', value === searchValue.value);
  console.groupEnd();
  
  // 手动更新searchValue
  searchValue.value = value;
  
  // 如果输入框有值，显示搜索提示
  if (value && value.trim()) {
    console.log('💡 [离栏记录] 搜索提示: 按回车键或点击搜索图标进行搜索');
  }
};

// 搜索框焦点事件
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 resetForm = () => {
  Object.keys(formData).forEach(key => {
    if (key === 'exitDate' || key === 'originalPenId') {
      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.groupEnd();
  
  // 如果输入框有值，显示搜索提示
  if (newValue && newValue.trim()) {
    console.log('💡 [离栏记录] 搜索提示: 按回车键或点击搜索图标进行搜索');
  }
}, { immediate: false });

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

<style scoped>
.cattle-exit-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: 300px;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 8px;
}

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

.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;
}

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

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

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

.exit-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-exit-records {
    padding: 16px;
  }
  
  .action-buttons {
    flex-direction: column;
    gap: 8px;
  }
}
</style>
