<template>
  <div class="cattle-batches">
    <!-- 页面标题 -->
    <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
          :value="searchValue"
          placeholder="请输入批次名称或编号"
          class="search-input"
          @pressEnter="handleSearch"
          @input="(e) => {
            searchValue = e.target.value;
            handleInputChange(e);
          }"
        >
          <template #suffix>
            <SearchOutlined @click="handleSearch" />
          </template>
        </a-input>
        <a-button 
          @click="handleReset" 
          class="reset-button"
          :disabled="!searchValue.trim()"
        >
          <template #icon>
            <ReloadOutlined />
          </template>
          重置
        </a-button>
      </div>
    </div>

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

    <!-- 新增/编辑弹窗 -->
    <a-modal
      :open="modalVisible"
      @update:open="modalVisible = $event"
      :title="modalTitle"
      width="600px"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
    >
      <a-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
      >
        <a-form-item label="批次名称" name="name">
          <a-input 
            v-model:value="formData.name" 
            placeholder="请输入批次名称"
          />
        </a-form-item>
        
        <a-form-item label="批次编号" name="code">
          <a-input 
            v-model:value="formData.code" 
            placeholder="请输入批次编号"
          />
        </a-form-item>
        
        <a-form-item label="批次类型" name="type">
          <a-select 
            v-model:value="formData.type" 
            placeholder="请选择批次类型"
          >
            <a-select-option value="育成批次">育成批次</a-select-option>
            <a-select-option value="繁殖批次">繁殖批次</a-select-option>
            <a-select-option value="育肥批次">育肥批次</a-select-option>
            <a-select-option value="隔离批次">隔离批次</a-select-option>
            <a-select-option value="治疗批次">治疗批次</a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item label="开始日期" name="startDate">
          <a-date-picker 
            v-model:value="formData.startDate" 
            style="width: 100%" 
            placeholder="请选择开始日期"
          />
        </a-form-item>
        
        <a-form-item label="预计结束日期" name="expectedEndDate">
          <a-date-picker 
            v-model:value="formData.expectedEndDate" 
            style="width: 100%" 
            placeholder="请选择预计结束日期"
          />
        </a-form-item>
        
        <a-form-item label="实际结束日期" name="actualEndDate">
          <a-date-picker 
            v-model:value="formData.actualEndDate" 
            style="width: 100%" 
            placeholder="请选择实际结束日期"
          />
        </a-form-item>
        
        <a-form-item label="目标牛只数量" name="targetCount">
          <a-input-number 
            v-model:value="formData.targetCount" 
            :min="1" 
            :max="1000"
            style="width: 100%" 
            placeholder="请输入目标牛只数量"
          />
        </a-form-item>
        
        <a-form-item label="当前牛只数量" name="currentCount">
          <a-input-number 
            v-model:value="formData.currentCount" 
            :min="0" 
            :max="formData.targetCount || 1000"
            style="width: 100%" 
            placeholder="当前牛只数量"
          />
        </a-form-item>
        
        <a-form-item label="负责人" name="manager">
          <a-input 
            v-model:value="formData.manager" 
            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="cattleModalVisible"
      @update:open="cattleModalVisible = $event"
      title="批次牛只信息"
      width="1000px"
      :footer="null"
    >
      <a-table
        :columns="cattleColumns"
        :data-source="currentBatchCattle"
        :pagination="{
          current: cattlePagination.current,
          pageSize: cattlePagination.pageSize,
          total: cattlePagination.total,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
        }"
        @change="handleCattleTableChange"
        size="small"
      />
    </a-modal>

    <!-- 添加牛只到批次弹窗 -->
    <a-modal
      :open="addCattleModalVisible"
      @update:open="addCattleModalVisible = $event"
      title="添加牛只到批次"
      width="800px"
      @ok="handleAddCattleOk"
      @cancel="handleAddCattleCancel"
    >
      <div class="add-cattle-content">
        <a-input
          v-model="cattleSearchValue"
          placeholder="请输入耳号搜索牛只"
          class="cattle-search"
          @pressEnter="handleCattleSearch"
        >
          <template #suffix>
            <SearchOutlined @click="handleCattleSearch" />
          </template>
        </a-input>
        
        <a-table
          :columns="availableCattleColumns"
          :data-source="availableCattle"
          :pagination="{ pageSize: 5 }"
          :row-selection="cattleRowSelection"
          size="small"
          class="available-cattle-table"
        />
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import { message, Modal } from 'ant-design-vue'
import { 
  PlusOutlined, 
  DeleteOutlined, 
  ExportOutlined,
  SearchOutlined,
  ReloadOutlined 
} 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 cattleModalVisible = ref(false)
const addCattleModalVisible = ref(false)
const modalTitle = ref('新增批次')
const formRef = ref()
const selectedRowKeys = ref([])
const cattleSearchValue = ref('')
const selectedCattleKeys = ref([])

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

// 当前批次的牛只数据
const currentBatchCattle = ref([])
const currentBatchId = ref(null)
const cattlePagination = ref({
  current: 1,
  pageSize: 10,
  total: 0
})

// 可添加的牛只数据
const availableCattle = ref([
  {
    key: '1',
    earTag: '24075002455',
    breed: '西藏高山牦牛',
    gender: '母',
    ageInMonths: 97.07,
    physiologicalStage: '育成母牛',
    pen: '杭嘉新村栏舍01'
  },
  {
    key: '2',
    earTag: '24075002041',
    breed: '西藏高山牦牛',
    gender: '母',
    ageInMonths: 97.07,
    physiologicalStage: '育成母牛',
    pen: '杭嘉新村栏舍01'
  }
])

// 表格列配置
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: 80,
    align: 'center'
  },
  {
    title: '批次名称',
    dataIndex: 'name',
    key: 'name',
    width: 200
  },
  {
    title: '批次编号',
    dataIndex: 'code',
    key: 'code',
    width: 150
  },
  {
    title: '批次类型',
    dataIndex: 'type',
    key: 'type',
    width: 120
  },
  {
    title: '开始日期',
    dataIndex: 'startDate',
    key: 'startDate',
    width: 120
  },
  {
    title: '预计结束日期',
    dataIndex: 'expectedEndDate',
    key: 'expectedEndDate',
    width: 150
  },
  {
    title: '实际结束日期',
    dataIndex: 'actualEndDate',
    key: 'actualEndDate',
    width: 150
  },
  {
    title: '目标数量',
    dataIndex: 'targetCount',
    key: 'targetCount',
    width: 100
  },
  {
    title: '当前数量',
    dataIndex: 'currentCount',
    key: 'currentCount',
    width: 100
  },
  {
    title: '负责人',
    dataIndex: 'manager',
    key: 'manager',
    width: 100
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    width: 150
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right'
  }
]

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

// 可添加牛只表格列配置
const availableCattleColumns = [
  {
    title: '耳号',
    dataIndex: 'earTag',
    key: 'earTag'
  },
  {
    title: '品种',
    dataIndex: 'breed',
    key: 'breed'
  },
  {
    title: '性别',
    dataIndex: 'gender',
    key: 'gender'
  },
  {
    title: '月龄',
    dataIndex: 'ageInMonths',
    key: 'ageInMonths'
  },
  {
    title: '生理阶段',
    dataIndex: 'physiologicalStage',
    key: 'physiologicalStage'
  },
  {
    title: '当前栏舍',
    dataIndex: 'pen',
    key: 'pen'
  }
]

// 分页配置
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 cattleRowSelection = {
  selectedRowKeys: selectedCattleKeys,
  onChange: (keys) => {
    selectedCattleKeys.value = keys
  }
}

// 表单数据
const formData = reactive({
  name: '',
  code: '',
  type: '',
  startDate: null,
  expectedEndDate: null,
  actualEndDate: null,
  targetCount: null,
  currentCount: null,
  manager: '',
  status: '进行中',
  remark: '',
  farmId: 1 // 默认农场ID
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入批次名称', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入批次编号', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择批次类型', trigger: 'change' }
  ],
  startDate: [
    { required: true, message: '请选择开始日期', trigger: 'change' }
  ],
  targetCount: [
    { required: true, message: '请输入目标牛只数量', trigger: 'blur' }
  ],
  manager: [
    { required: true, message: '请输入负责人', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 方法
const loadData = async () => {
  try {
    loading.value = true;
    // 确保获取最新的searchValue值
    await nextTick();
    const currentSearchValue = searchValue.value.trim();
    const params = {
      page: 1,
      pageSize: pagination.pageSize,
      search: currentSearchValue,
      exactMatch: true,
      strictMatch: true
    };
    
    // 详细的请求日志
    console.group('📡 [批次设置] API请求详情');
    console.log('🕒 请求时间:', new Date().toISOString());
    console.log('🔍 搜索参数:', currentSearchValue);
    console.log('📋 完整请求参数:', JSON.stringify(params, null, 2));
    console.log('🔗 请求URL:', api.cattleBatches.getList.url);
    console.log('🔄 请求方法:', api.cattleBatches.getList.method);
    console.groupEnd();
    
    // 性能监控开始
    const startTime = performance.now();
    const apiResponse = await api.cattleBatches.getList(params);
    const endTime = performance.now();
    
    // 响应日志
    console.group('📡 [批次设置] API响应详情');
    console.log('⏱️ 请求耗时:', `${(endTime - startTime).toFixed(2)}ms`);
    console.log('🔄 响应状态:', apiResponse.success ? '成功' : '失败');
    console.log('📋 响应数据:', JSON.stringify({
      data: apiResponse.data,
      message: apiResponse.message || '',
      code: apiResponse.code || 0
    }, null, 2));
    console.log('📊 数据统计:', {
      totalItems: apiResponse.data?.total || 0,
      currentPage: apiResponse.data?.page || 1,
      pageSize: apiResponse.data?.pageSize || 10
    });
    console.groupEnd();
    
    // 记录API调用指标（如果metrics对象存在）
    if (api.metrics && typeof api.metrics.trackApiCall === 'function') {
      api.metrics.trackApiCall({
        endpoint: 'cattleBatches.getList',
        duration: endTime - startTime,
        success: apiResponse.success,
        searchTerm: currentSearchValue,
        resultCount: apiResponse.data?.total || 0
      }).catch(err => {
        console.error('📊 指标记录失败:', err);
      });
    } else {
      // 简单的性能日志记录
      console.log('📊 API性能指标:', {
        endpoint: 'cattleBatches.getList',
        duration: `${(endTime - startTime).toFixed(2)}ms`,
        success: apiResponse.success,
        searchTerm: currentSearchValue,
        resultCount: apiResponse.data?.total || 0
      });
    }
    
    if (apiResponse.success) {
      tableData.value = apiResponse.data.list.map(item => ({
        ...item,
        key: item.id,
        createTime: item.created_at ? dayjs(item.created_at).format('YYYY-MM-DD HH:mm:ss') : '-'
      }));
      pagination.total = apiResponse.data.total;
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    message.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

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

const handleEdit = async (record) => {
  console.log('🔄 [批次设置] 开始编辑操作')
  console.log('📋 [批次设置] 原始记录数据:', {
    id: record.id,
    name: record.name,
    type: record.type,
    status: record.status,
    startDate: record.startDate,
    expectedEndDate: record.expectedEndDate,
    actualEndDate: record.actualEndDate,
    manager: record.manager,
    remark: record.remark,
    farmId: record.farmId,
    farmName: record.farm?.name
  })
  
  modalTitle.value = '编辑批次'
  
  // 处理日期转换
  let startDateValue = null
  let expectedEndDateValue = null
  let actualEndDateValue = null
  
  if (record.startDate) {
    if (typeof record.startDate === 'string') {
      startDateValue = dayjs(record.startDate)
    } else if (record.startDate instanceof Date) {
      startDateValue = dayjs(record.startDate)
    } else if (record.startDate && typeof record.startDate === 'object' && record.startDate.format) {
      startDateValue = record.startDate
    } else {
      startDateValue = dayjs(record.startDate)
    }
  }
  
  if (record.expectedEndDate) {
    if (typeof record.expectedEndDate === 'string') {
      expectedEndDateValue = dayjs(record.expectedEndDate)
    } else if (record.expectedEndDate instanceof Date) {
      expectedEndDateValue = dayjs(record.expectedEndDate)
    } else if (record.expectedEndDate && typeof record.expectedEndDate === 'object' && record.expectedEndDate.format) {
      expectedEndDateValue = record.expectedEndDate
    } else {
      expectedEndDateValue = dayjs(record.expectedEndDate)
    }
  }
  
  if (record.actualEndDate) {
    if (typeof record.actualEndDate === 'string') {
      actualEndDateValue = dayjs(record.actualEndDate)
    } else if (record.actualEndDate instanceof Date) {
      actualEndDateValue = dayjs(record.actualEndDate)
    } else if (record.actualEndDate && typeof record.actualEndDate === 'object' && record.actualEndDate.format) {
      actualEndDateValue = record.actualEndDate
    } else {
      actualEndDateValue = dayjs(record.actualEndDate)
    }
  }
  
  // 填充表单数据 - 使用直接赋值确保响应式更新
  formData.id = record.id
  formData.name = record.name || ''
  formData.code = record.code || ''
  formData.type = record.type || ''
  formData.startDate = startDateValue
  formData.expectedEndDate = expectedEndDateValue
  formData.actualEndDate = actualEndDateValue
  formData.targetCount = record.targetCount || 0
  formData.currentCount = record.currentCount || 0
  formData.manager = record.manager || ''
  formData.status = record.status || '进行中'
  formData.remark = record.remark || ''
  formData.farmId = record.farmId || record.farm_id || null
  
  console.log('📝 [批次设置] 表单数据已填充:', formData)
  console.log('📝 [批次设置] startDate 是否为 dayjs:', formData.startDate && typeof formData.startDate.format === 'function')
  console.log('📝 [批次设置] expectedEndDate 是否为 dayjs:', formData.expectedEndDate && typeof formData.expectedEndDate.format === 'function')
  console.log('📝 [批次设置] actualEndDate 是否为 dayjs:', formData.actualEndDate && typeof formData.actualEndDate.format === 'function')
  
  // 打开模态框
  modalVisible.value = true
  
  // 等待模态框和表单渲染完成
  await nextTick()
  await new Promise(resolve => setTimeout(resolve, 200))
  
  console.log('✅ [批次设置] 模态框已打开，表单应该已填充')
}

const handleDelete = (record) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除批次"${record.name}"吗？`,
    async onOk() {
      try {
        await api.cattleBatches.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.cattleBatches.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.cattleBatches.getList({
      page: 1,
      pageSize: 1000 // 获取大量数据
    })
    
    if (!response.success || !response.data || !response.data.list) {
      message.destroy()
      message.warning('没有数据可导出')
      return
    }
    
    const allBatches = response.data.list
    console.log('获取到所有批次数据:', allBatches.length, '条记录')
    console.log('原始数据示例:', allBatches[0])
    
    // 转换数据格式以匹配导出工具类的列配置
    const exportData = allBatches.map(item => {
      console.log('转换前批次数据项:', item)
      return {
        id: item.id,
        batch_name: item.batchName || item.name || '',
        batch_type: item.batchType || item.type || '',
        target_count: item.targetCount || item.target_count || 0,
        current_count: item.currentCount || item.current_count || item.animalCount || item.cattleCount || 0,
        created_at: item.createdAt || item.created_at || '',
        manager: item.manager || item.managerName || '',
        status: item.status || '启用'
      }
    })
    
    console.log('转换后批次数据示例:', exportData[0])
    console.log('转换后批次数据总数:', exportData.length)
    
    message.destroy()
    message.loading('正在导出数据...', 0)
    
    const result = ExportUtils.exportBatchData(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 handleViewCattle = async (record) => {
  try {
    console.log('🔍 开始获取批次牛只数据');
    console.log('📋 批次信息:', {
      id: record.id,
      name: record.name,
      currentCount: record.currentCount
    });
    
    currentBatchId.value = record.id
    cattlePagination.value.current = 1
    cattlePagination.value.total = 0
    
    await loadBatchCattle(record.id, 1, 10)
    cattleModalVisible.value = true
  } catch (error) {
    console.error('获取批次牛只失败:', error)
    message.error('获取批次牛只失败')
  }
}

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

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

const handleAddCattle = (record) => {
  addCattleModalVisible.value = true
  selectedCattleKeys.value = []
}

const handleCattleSearch = () => {
  console.log('搜索牛只:', cattleSearchValue.value)
  // 实现牛只搜索逻辑
}

const handleAddCattleOk = async () => {
  if (selectedCattleKeys.value.length === 0) {
    message.warning('请选择要添加的牛只')
    return
  }
  
  try {
    await api.cattleBatches.addAnimals(formData.id, selectedCattleKeys.value)
    message.success(`成功添加 ${selectedCattleKeys.value.length} 头牛只到批次`)
    addCattleModalVisible.value = false
    selectedCattleKeys.value = []
    loadData()
  } catch (error) {
    console.error('添加牛只失败:', error)
    message.error('添加牛只失败')
  }
}

const handleAddCattleCancel = () => {
  addCattleModalVisible.value = false
  selectedCattleKeys.value = []
}

// 用于记录输入历史
const inputHistory = ref([]);

const handleInputChange = (e) => {
  const value = e.target.value;
  const changeLog = {
    currentValue: value,
    length: value.length,
    timestamp: new Date().toISOString(),
    previousValue: searchValue.value,
    changeType: value.length > searchValue.value.length ? '新增' : '删除',
    eventType: e.type,
    inputMethod: e.inputType || 'unknown',
    cursorPosition: e.target.selectionStart,
    isComposing: e.isComposing || false
  };
  
  // 记录输入历史
  inputHistory.value.push(changeLog);
  
  console.group('⌨️ [批次设置] 输入事件详情');
  console.log('🔍 事件类型:', e.type);
  console.log('📝 输入方法:', e.inputType || 'unknown');
  console.log('🔄 变化详情:', JSON.stringify(changeLog, null, 2));
  console.log('📜 输入历史:', JSON.stringify(inputHistory.value, null, 2));
  console.groupEnd();
}

const handleSearch = () => {
  // 获取当前用户信息
  const userInfo = JSON.parse(localStorage.getItem('user') || '{}');
  
  // 获取当前搜索值
  const currentSearchValue = searchValue.value.trim();
  
  // 合并搜索操作和日志记录
  const searchLog = {
    action: 'SEARCH_BATCHES',
    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}`,
    searchParams: {
      name: currentSearchValue,
      code: currentSearchValue,
      exactMatch: true,
      strictMatch: true
    },
    inputHistory: inputHistory.value,
    inputLength: currentSearchValue.length,
    lastInputChange: inputHistory.value[inputHistory.value.length - 1],
    networkStatus: navigator.onLine ? 'online' : 'offline'
  };

  console.group('🔍 [批次设置] 搜索操作详情');
  console.log('🕒 时间:', new Date().toLocaleString());
  console.log('👤 用户:', userInfo.username || 'unknown');
  console.log('🔎 搜索值:', currentSearchValue);
  console.log('📋 完整日志:', JSON.stringify(searchLog, null, 2));
  console.groupEnd();

  // 发送搜索日志到后端
  api.logs.addSearchLog({
    module: 'cattle-batches',
    action: 'search',
    data: searchLog
  }).catch(err => {
    console.error('📡 日志发送失败:', err);
  });

  // 重置分页并加载数据
  pagination.current = 1;
  loadData();
  
  // 清空输入历史
  inputHistory.value = [];
}

// 重置搜索方法
const handleReset = () => {
  console.log('🔄 [批次设置] 重置搜索');
  
  // 清空搜索值
  searchValue.value = '';
  
  // 重置分页到第一页
  pagination.current = 1;
  
  // 清空输入历史
  inputHistory.value = [];
  
  // 重新加载数据（显示所有数据）
  loadData();
  
  message.success('搜索已重置');
}

// 字段变化监听方法
const handleFieldChange = (fieldName, value) => {
  console.log(`📋 [批次设置] 字段变化监听: ${fieldName} = ${value}`)
  console.log(`📋 [批次设置] 字段类型: ${typeof value}`)
  
  // 特殊处理不同类型的数据
  let processedValue = value
  
  // 处理数字类型字段
  if (fieldName === 'targetCount' || fieldName === 'currentCount') {
    processedValue = value ? Number(value) : null
    console.log(`🔢 [批次设置] 数字字段 ${fieldName} 处理后: ${processedValue}`)
  }
  
  // 处理日期类型字段
  if (fieldName === 'startDate' || fieldName === 'expectedEndDate' || fieldName === 'actualEndDate') {
    processedValue = value // dayjs 对象直接使用
    console.log(`📅 [批次设置] 日期字段 ${fieldName} 处理后: ${processedValue}`)
  }
  
  // 处理字符串类型字段
  if (fieldName === 'name' || fieldName === 'code' || fieldName === 'manager' || fieldName === 'remark') {
    processedValue = value ? String(value).trim() : ''
    console.log(`📝 [批次设置] 字符串字段 ${fieldName} 处理后: "${processedValue}"`)
  }
  
  // 处理枚举类型字段
  if (fieldName === 'type' || fieldName === 'status') {
    processedValue = value ? String(value) : ''
    console.log(`🏷️ [批次设置] 枚举字段 ${fieldName} 处理后: "${processedValue}"`)
  }
  
  // 确保数据同步到 formData
  if (formData[fieldName] !== processedValue) {
    formData[fieldName] = processedValue
    console.log(`✅ [批次设置] 字段 ${fieldName} 已更新为: ${processedValue}`)
  } else {
    console.log(`ℹ️ [批次设置] 字段 ${fieldName} 值未变化: ${processedValue}`)
  }
  
  // 输出当前完整的表单数据
  console.log(`📊 [批次设置] 当前完整表单数据:`, {
    id: formData.id,
    name: formData.name,
    code: formData.code,
    type: formData.type,
    startDate: formData.startDate,
    expectedEndDate: formData.expectedEndDate,
    actualEndDate: formData.actualEndDate,
    targetCount: formData.targetCount,
    currentCount: formData.currentCount,
    manager: formData.manager,
    status: formData.status,
    remark: formData.remark,
    farmId: formData.farmId
  })
}

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

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

const resetForm = () => {
  Object.keys(formData).forEach(key => {
    if (key === 'startDate' || key === 'expectedEndDate' || key === 'actualEndDate') {
      formData[key] = null
    } else if (key === 'targetCount' || key === 'currentCount') {
      formData[key] = null
    } else {
      formData[key] = ''
    }
  })
  formData.status = '进行中'
  formData.farmId = 1 // 确保默认农场ID
  formRef.value?.resetFields()
}

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

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

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

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

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

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

.search-container {
  display: flex;
  align-items: center;
  gap: 8px;
  width: 400px;
}

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

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

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

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

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

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

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

.add-cattle-content {
  padding: 16px 0;
}

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

.available-cattle-table {
  margin-top: 16px;
}

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

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