<template>
  <div class="farm-info-management-container">
    <!-- 页面标题和操作栏 -->
    <div class="page-header">
      <h2 class="page-title">养殖场信息管理</h2>
      <div class="header-actions">
        <a-button @click="exportData" class="add-button">
          <template #icon>
            <ExportOutlined />
          </template>
          导出数据
        </a-button>
        <a-button type="primary" @click="showAddModal" class="add-button">
          <template #icon>
            <PlusOutlined />
          </template>
          新增养殖场
        </a-button>
        <div class="search-container">
          <a-input
            v-model="searchKeyword"
            placeholder="请输入养殖场名称、类型、联系人等关键词"
            class="search-input"
            @pressEnter="handleSearch"
            @input="handleSearchInput"
            @focus="handleSearchFocus"
            @blur="handleSearchBlur"
            @change="handleSearchChange"
          />
          <a-button type="primary" @click="handleSearch" class="search-button">
            <template #icon>
              <SearchOutlined />
            </template>
            搜索
          </a-button>
          
       
        </div>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <a-table
        :columns="columns"
        :data-source="filteredData"
        :loading="loading"
        :pagination="pagination"
        row-key="id"
        class="farm-table"
      >
        <!-- 状态列 -->
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <a-tag :color="record.status ? 'green' : 'red'">
              {{ record.status ? '启用' : '禁用' }}
            </a-tag>
          </template>
          <!-- 操作列 -->
          <template v-else-if="column.key === 'actions'">
            <a-space>
              <a-button type="link" @click="handleEdit(record)" class="action-btn">
                编辑
              </a-button>
              <a-button type="link" @click="handleView(record)" class="action-btn">
                查看
              </a-button>
              <a-button type="link" danger @click="handleDelete(record)" class="action-btn">
                删除
              </a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </div>

    <!-- 新增/编辑养殖场模态框 -->
    <a-modal
      :open="modalVisible"
      @update:open="(val) => modalVisible = val"
      :title="isEdit ? '编辑养殖场' : '新增养殖场'"
      @ok="handleSubmit"
      @cancel="handleCancel"
      :confirm-loading="submitting"
      width="800px"
    >
      <a-form
        :model="formData"
        ref="formRef"
        layout="vertical"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="养殖场名称" name="name">
              <a-input 
                v-model="formData.name" 
                placeholder="请输入养殖场名称"
                @input="(e) => handleFieldChange('name', e.target.value, formData.name)"
                @change="(e) => handleFieldChange('name', e.target.value, formData.name)"
                @blur="(e) => handleFieldChange('name', e.target.value, formData.name)"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="养殖场类型" name="type">
              <a-select 
                v-model="formData.type" 
                placeholder="请选择养殖场类型"
                @change="(value) => handleFieldChange('type', value, formData.type)"
              >
                <a-select-option value="dairy">奶牛场</a-select-option>
                <a-select-option value="beef">肉牛场</a-select-option>
                <a-select-option value="sheep">羊场</a-select-option>
                <a-select-option value="horse">马场</a-select-option>
                <a-select-option value="poultry">家禽场</a-select-option>
                <a-select-option value="mixed">综合养殖场</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="联系人" name="contact">
              <a-input 
                v-model="formData.contact" 
                placeholder="请输入联系人"
                @input="(e) => handleFieldChange('contact', e.target.value, formData.contact)"
                @change="(e) => handleFieldChange('contact', e.target.value, formData.contact)"
                @blur="(e) => handleFieldChange('contact', e.target.value, formData.contact)"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="联系电话" name="phone">
              <a-input 
                v-model="formData.phone" 
                placeholder="请输入联系电话"
                @input="(e) => handleFieldChange('phone', e.target.value, formData.phone)"
                @change="(e) => handleFieldChange('phone', e.target.value, formData.phone)"
                @blur="(e) => handleFieldChange('phone', e.target.value, formData.phone)"
              />
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-form-item label="详细地址" name="address">
          <a-input 
            v-model="formData.address" 
            placeholder="请输入详细地址"
            @input="(e) => handleFieldChange('address', e.target.value, formData.address)"
            @change="(e) => handleFieldChange('address', e.target.value, formData.address)"
            @blur="(e) => handleFieldChange('address', e.target.value, formData.address)"
          />
        </a-form-item>
        
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="经度" name="longitude">
              <a-input-number
                v-model="formData.longitude"
                :min="-180"
                :max="180"
                :precision="6"
                placeholder="请输入经度"
                style="width: 100%"
                @change="(value) => handleFieldChange('longitude', value, formData.longitude)"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="纬度" name="latitude">
              <a-input-number
                v-model="formData.latitude"
                :min="-90"
                :max="90"
                :precision="6"
                placeholder="请输入纬度"
                style="width: 100%"
                @change="(value) => handleFieldChange('latitude', value, formData.latitude)"
              />
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="状态" name="status">
              <a-select 
                v-model="formData.status" 
                placeholder="请选择状态"
                @change="(value) => handleFieldChange('status', value, formData.status)"
              >
                <a-select-option value="active">启用</a-select-option>
                <a-select-option value="inactive">禁用</a-select-option>
                <a-select-option value="maintenance">维护中</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        
        <!-- 调试按钮 - 开发环境使用 -->
        <a-form-item>
          <a-button @click="debugFormValidation" type="dashed" block>
            🔍 调试表单验证
          </a-button>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

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

// 响应式数据
const submitting = ref(false)
const modalVisible = ref(false)
const isEdit = ref(false)
const searchKeyword = ref('')
const formRef = ref(null)

// 表格列配置
const columns = [
  {
    title: '养殖场名称',
    dataIndex: 'name',
    key: 'name',
    width: 150,
  },
  {
    title: '养殖场类型',
    dataIndex: 'typeLabel',
    key: 'typeLabel',
    width: 120,
  },
  {
    title: '联系人',
    dataIndex: 'contact',
    key: 'contact',
    width: 100,
  },
  {
    title: '联系电话',
    dataIndex: 'phone',
    key: 'phone',
    width: 120,
  },
  {
    title: '详细地址',
    dataIndex: 'address',
    key: 'address',
    width: 200,
  },
  {
    title: '状态',
    dataIndex: 'statusLabel',
    key: 'statusLabel',
    width: 100,
    customRender: ({ record }) => {
      const statusColorMap = {
        'active': 'green',
        'inactive': 'red',
        'maintenance': 'orange'
      }
      const color = statusColorMap[record.status] || 'default'
      return h('a-tag', {
        color: color
      }, record.statusLabel || record.status)
    }
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt',
    key: 'createdAt',
    width: 150,
  },
  {
    title: '操作',
    key: 'actions',
    width: 150,
    fixed: 'right',
  },
]

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

// 表单数据
const formData = reactive({
  id: null,
  name: '',
  type: '',
  contact: '',
  phone: '',
  address: '',
  longitude: null,
  latitude: null,
  status: 'active'
})

// 表单验证规则 - 完全禁用验证
const formRules = {}

// 养殖场数据
const farmsData = ref([])
const loading = ref(false)

// 计算属性 - 直接使用后端搜索后的数据
const filteredData = computed(() => {
  return farmsData.value
})

// 类型映射
const typeMap = {
  'dairy': '奶牛场',
  'beef': '肉牛场', 
  'sheep': '羊场',
  'horse': '马场',
  'poultry': '家禽场',
  'mixed': '综合养殖场'
}

const typeMapReverse = {
  '奶牛场': 'dairy',
  '肉牛场': 'beef',
  '羊场': 'sheep', 
  '马场': 'horse',
  '家禽场': 'poultry',
  '综合养殖场': 'mixed'
}

// 状态映射
const statusMap = {
  'active': '启用',
  'inactive': '禁用',
  'maintenance': '维护中'
}

// 数据转换函数
const convertFarmFromDB = (farm) => {
  return {
    id: farm.id,
    name: farm.name,
    type: farm.type, // 保持英文值用于表单
    typeLabel: typeMap[farm.type] || farm.type, // 添加中文标签
    contact: farm.contact,
    phone: farm.phone,
    address: farm.address,
    longitude: farm.location?.lng || null,
    latitude: farm.location?.lat || null,
    status: farm.status, // 保持英文值用于表单
    statusLabel: statusMap[farm.status] || farm.status, // 添加中文标签
    createdAt: farm.created_at
  }
}

const convertFarmToDB = (farm) => {
  return {
    name: farm.name,
    type: farm.type,
    contact: farm.contact,
    phone: farm.phone,
    address: farm.address,
    location: {
      lng: farm.longitude,
      lat: farm.latitude
    },
    status: farm.status
  }
}

// 加载养殖场数据
const loadFarmsData = async () => {
  try {
    loading.value = true
    console.log('🔄 开始加载养殖场数据...')
    
    const response = await api.farms.getList()
    
    if (response.success) {
      farmsData.value = response.data.map(convertFarmFromDB)
      pagination.total = farmsData.value.length
      console.log('✅ 养殖场数据加载成功:', farmsData.value.length, '条记录')
    } else {
      message.error('加载养殖场数据失败: ' + (response.message || '未知错误'))
    }
  } catch (error) {
    console.error('❌ 加载养殖场数据失败:', error)
    message.error('加载养殖场数据失败: ' + (error.message || '网络错误'))
  } finally {
    loading.value = false
  }
}

// 方法
const showAddModal = async () => {
  console.log('🔄 开始打开新增养殖场模态框...')
  
  isEdit.value = false
  
  // 完全重置表单数据
  resetForm()
  
  modalVisible.value = true
  
  // 强制清除表单验证状态
  nextTick(() => {
    if (formRef.value) {
      formRef.value.clearValidate()
      // 延迟再次清除，确保完全清除
      setTimeout(() => {
        if (formRef.value) {
          formRef.value.clearValidate()
          console.log('✅ 已清除所有表单验证状态')
        }
      }, 100)
    }
  })
  
  // 记录打开新增模态框
  await logFormAction('modal_open', {
    action: 'add',
    formData: { ...formData }
  })
  
  console.log('✅ 新增养殖场模态框已打开，表单数据已重置')
}

const handleEdit = async (record) => {
  console.log('🔄 开始打开编辑养殖场模态框...', record)
  
  isEdit.value = true
  
  // 完全重置表单数据，然后设置编辑数据
  resetForm()
  
  // 设置编辑数据
  formData.id = record.id
  formData.name = record.name || ''
  formData.type = record.type || '' // 使用英文值用于表单选择
  formData.contact = record.contact || ''
  formData.phone = record.phone || ''
  formData.address = record.address || ''
  formData.longitude = record.longitude || null
  formData.latitude = record.latitude || null
  formData.status = record.status || 'active'
  
  modalVisible.value = true
  
  // 强制清除表单验证状态
  nextTick(() => {
    if (formRef.value) {
      formRef.value.clearValidate()
      // 延迟再次清除，确保完全清除
      setTimeout(() => {
        if (formRef.value) {
          formRef.value.clearValidate()
          console.log('✅ 已清除所有表单验证状态')
        }
      }, 100)
    }
  })
  
  // 记录打开编辑模态框
  await logFormAction('modal_open', {
    action: 'edit',
    recordId: record.id,
    formData: { ...formData }
  })
  
  console.log('✅ 编辑养殖场模态框已打开，表单数据已设置:', { ...formData })
}

const handleView = async (record) => {
  message.info(`查看养殖场: ${record.name}`)
  
  // 记录查看操作
  await logFormAction('record_view', {
    recordId: record.id,
    recordName: record.name
  })
  
  // 这里可以跳转到详情页面
}

const handleDelete = (record) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除养殖场"${record.name}"吗？`,
    async onOk() {
      try {
        console.log('🔄 开始删除养殖场:', record.id)
        
        const response = await api.farms.delete(record.id)
        
        if (response.success) {
          // 从本地数据中移除
          const index = farmsData.value.findIndex(item => item.id === record.id)
      if (index > -1) {
            farmsData.value.splice(index, 1)
            pagination.total = farmsData.value.length
          }
          
          // 记录删除成功
          await logFormAction('record_delete', {
            recordId: record.id,
            recordName: record.name,
            deletedData: { ...record }
          })
          
        message.success('删除成功')
          console.log('✅ 养殖场删除成功')
        } else {
          message.error('删除失败: ' + (response.message || '未知错误'))
        }
      } catch (error) {
        console.error('❌ 删除养殖场失败:', error)
        message.error('删除失败: ' + (error.message || '网络错误'))
        
        // 记录删除失败
        await logFormAction('record_delete_failed', {
          recordId: record.id,
          recordName: record.name,
          error: error.message
        })
      }
    }
  })
}

// 搜索输入框事件处理
let searchTimeout = null
let searchFocusTime = null

// 监听searchKeyword变化
watch(searchKeyword, (newValue, oldValue) => {
  console.log('👀 [Watch监听] searchKeyword变化:', {
    oldValue: oldValue,
    newValue: newValue,
    timestamp: new Date().toISOString(),
    type: typeof newValue,
    length: newValue ? newValue.length : 0
  })
}, { immediate: true })

// 输入框获得焦点
const handleSearchFocus = async (e) => {
  searchFocusTime = Date.now()
  console.log('🎯 [输入监听] 搜索框获得焦点:', {
    timestamp: new Date().toISOString(),
    currentValue: searchKeyword.value,
    eventValue: e.target.value,
    focusTime: searchFocusTime,
    valuesMatch: searchKeyword.value === e.target.value
  })
  
  await logFormAction('search_focus', {
    field: 'searchKeyword',
    currentValue: searchKeyword.value,
    eventValue: e.target.value,
    timestamp: new Date().toISOString()
  })
}

// 输入框失去焦点
const handleSearchBlur = async (e) => {
  const blurTime = Date.now()
  const focusDuration = searchFocusTime ? blurTime - searchFocusTime : 0
  
  console.log('👋 [输入监听] 搜索框失去焦点:', {
    timestamp: new Date().toISOString(),
    finalValue: searchKeyword.value,
    focusDuration: focusDuration + 'ms',
    blurTime: blurTime
  })
  
  await logFormAction('search_blur', {
    field: 'searchKeyword',
    finalValue: searchKeyword.value,
    focusDuration: focusDuration,
    timestamp: new Date().toISOString()
  })
  
  searchFocusTime = null
}

// 输入框值改变（与input不同，change在失焦时触发）
const handleSearchChange = async (e) => {
  const value = e.target.value
  console.log('🔄 [输入监听] 搜索框值改变:', {
    newValue: value,
    timestamp: new Date().toISOString(),
    eventType: 'change'
  })
  
  await logFormAction('search_change', {
    field: 'searchKeyword',
    newValue: value,
    eventType: 'change',
    timestamp: new Date().toISOString()
  })
}

// 实时搜索输入处理
const handleSearchInput = async (e) => {
  const value = e.target.value
  const oldValue = searchKeyword.value
  
  // 更新searchKeyword的值
  searchKeyword.value = value
  
  console.log('🔍 [输入监听] 搜索输入变化:', {
    oldValue: oldValue,
    newValue: value,
    timestamp: new Date().toISOString(),
    inputLength: value ? value.length : 0,
    searchKeywordValue: searchKeyword.value
  })
  
  // 记录输入变化日志
  await logFormAction('search_input_change', {
    field: 'searchKeyword',
    oldValue: oldValue,
    newValue: value,
    inputLength: value ? value.length : 0,
    isEmpty: !value || value.trim() === ''
  })
  
  // 清除之前的定时器
  if (searchTimeout) {
    clearTimeout(searchTimeout)
    console.log('⏰ [输入监听] 清除之前的搜索定时器')
  }
  
  // 如果输入为空，立即重新加载所有数据
  if (!value || value.trim() === '') {
    console.log('🔄 [输入监听] 输入为空，重新加载所有数据')
    await loadFarmsData()
    return
  }
  
  // 延迟500ms执行搜索，避免频繁请求
  searchTimeout = setTimeout(async () => {
    console.log('⏰ [输入监听] 延迟搜索触发，关键词:', value, 'searchKeyword.value:', searchKeyword.value)
    await handleSearch()
  }, 500)
}

const handleSearch = async () => {
  const searchKeywordValue = searchKeyword.value
  const searchStartTime = Date.now()
  
  console.log('🔍 [搜索监听] 开始搜索:', {
    keyword: searchKeywordValue,
    keywordType: typeof searchKeywordValue,
    keywordLength: searchKeywordValue ? searchKeywordValue.length : 0,
    keywordTrimmed: searchKeywordValue ? searchKeywordValue.trim() : '',
    timestamp: new Date().toISOString(),
    searchStartTime: searchStartTime
  })
  
  // 记录搜索开始日志
  await logFormAction('search_start', {
    keyword: searchKeywordValue,
    searchMethod: 'fetch_direct',
    timestamp: new Date().toISOString()
  })
  
  if (!searchKeywordValue || searchKeywordValue.trim() === '') {
    console.log('🔄 [搜索监听] 搜索关键词为空，重新加载所有数据', {
      searchKeywordValue: searchKeywordValue,
      isFalsy: !searchKeywordValue,
      isEmpty: searchKeywordValue === '',
      isWhitespace: searchKeywordValue && searchKeywordValue.trim() === ''
    })
    await loadFarmsData()
    return
  }
  
  try {
    console.log('🔄 [搜索监听] 发送搜索请求到后端:', searchKeywordValue)
    loading.value = true
    
    const searchUrl = `/api/farms/search?name=${encodeURIComponent(searchKeywordValue.trim())}`
    console.log('🌐 [搜索监听] 请求URL:', searchUrl)
    
    // 获取认证token
    const userInfo = JSON.parse(localStorage.getItem('user') || '{}')
    const token = userInfo.token || localStorage.getItem('token')
    
    console.log('🔐 [搜索监听] 认证信息:', {
      hasUserInfo: !!userInfo,
      hasToken: !!token,
      tokenLength: token ? token.length : 0,
      tokenPreview: token ? token.substring(0, 20) + '...' : 'none'
    })
    
    if (!token) {
      console.error('❌ [搜索监听] 未找到认证token')
      message.error('未找到认证token，请重新登录')
      throw new Error('未找到认证token，请重新登录')
    }
    
    // 检查token是否过期（简单检查）
    try {
      const tokenPayload = JSON.parse(atob(token.split('.')[1]))
      const currentTime = Math.floor(Date.now() / 1000)
      if (tokenPayload.exp && tokenPayload.exp < currentTime) {
        console.error('❌ [搜索监听] Token已过期')
        message.error('登录已过期，请重新登录')
        throw new Error('Token已过期，请重新登录')
      }
    } catch (e) {
      console.warn('⚠️ [搜索监听] Token解析失败:', e.message)
    }
    
    // 使用fetch直接查询后端API
    const response = await fetch(searchUrl, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      }
    })
    
    const responseTime = Date.now() - searchStartTime
    console.log('⏱️ [搜索监听] 后端响应时间:', responseTime + 'ms')
    console.log('📡 [搜索监听] 响应状态:', response.status, response.statusText)
    
    if (!response.ok) {
      if (response.status === 401) {
        console.error('❌ [搜索监听] 认证失败，token可能已过期')
        message.error('认证失败，请重新登录')
        throw new Error('认证失败，请重新登录')
      }
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    const result = await response.json()
    console.log('📊 [搜索监听] 后端返回数据:', {
      success: result.success,
      dataCount: result.data ? result.data.length : 0,
      message: result.message
    })
    
    if (result.success) {
      // 转换数据格式
      farmsData.value = result.data.map(convertFarmFromDB)
      pagination.total = farmsData.value.length
      
      console.log(`✅ [搜索监听] 搜索成功，找到 ${farmsData.value.length} 条记录`)
      message.success(`搜索完成，找到 ${farmsData.value.length} 条记录`)
      
      // 记录搜索成功日志
      await logFormAction('search_success', {
        keyword: searchKeywordValue,
        resultCount: farmsData.value.length,
        searchMethod: 'fetch_direct',
        responseTime: responseTime,
        backendData: result.data
      })
    } else {
      throw new Error(result.message || '搜索失败')
    }
  } catch (error) {
    const errorTime = Date.now() - searchStartTime
    console.error('❌ [搜索监听] 搜索失败:', {
      error: error.message,
      keyword: searchKeywordValue,
      errorTime: errorTime
    })
    message.error('搜索失败: ' + (error.message || '网络错误'))
    
    // 记录搜索失败日志
    await logFormAction('search_failed', {
      keyword: searchKeywordValue,
      error: error.message,
      errorTime: errorTime,
      searchMethod: 'fetch_direct'
    })
  } finally {
    loading.value = false
    const totalTime = Date.now() - searchStartTime
    console.log('⏱️ [搜索监听] 搜索总耗时:', totalTime + 'ms')
  }
}

// 高级搜索功能
const handleAdvancedSearch = async () => {
  try {
    console.log('🔄 开始高级搜索...')
    loading.value = true
    
    // 构建搜索参数
    const searchParams = new URLSearchParams()
    if (searchKeyword.value && searchKeyword.value.trim()) {
      searchParams.append('name', searchKeyword.value.trim())
    }
    
    // 使用API工具查询多个字段
    const result = await api.get(`/farms/search?${searchParams.toString()}`)
    
    if (result.success) {
      farmsData.value = result.data.map(convertFarmFromDB)
      pagination.total = farmsData.value.length
      
      console.log(`✅ 高级搜索成功，找到 ${farmsData.value.length} 条记录`)
      message.success(`高级搜索完成，找到 ${farmsData.value.length} 条记录`)
      
      // 记录高级搜索操作
      await logFormAction('advanced_search', {
        keyword: searchKeyword.value,
        resultCount: farmsData.value.length,
        searchMethod: 'fetch_advanced'
      })
    } else {
      throw new Error(result.message || '高级搜索失败')
    }
  } catch (error) {
    console.error('❌ 高级搜索失败:', error)
    message.error('高级搜索失败: ' + (error.message || '网络错误'))
  } finally {
    loading.value = false
  }
}

// 调试搜索关键词
const debugSearchKeyword = () => {
  console.log('🐛 [调试] 搜索关键词调试信息:', {
    searchKeyword: searchKeyword.value,
    searchKeywordType: typeof searchKeyword.value,
    searchKeywordLength: searchKeyword.value ? searchKeyword.value.length : 0,
    searchKeywordTrimmed: searchKeyword.value ? searchKeyword.value.trim() : '',
    searchKeywordIsEmpty: !searchKeyword.value,
    searchKeywordIsWhitespace: searchKeyword.value && searchKeyword.value.trim() === '',
    timestamp: new Date().toISOString()
  })
  
  message.info(`搜索关键词: "${searchKeyword.value}" (长度: ${searchKeyword.value ? searchKeyword.value.length : 0})`)
}

// 表单操作日志记录
const logFormAction = async (action, data = {}) => {
  try {
    const userInfo = JSON.parse(localStorage.getItem('user') || '{}')
    const logData = {
      module: 'farm-management',
      action: action,
      timestamp: new Date().toISOString(),
      userId: userInfo.id || 'unknown',
      username: userInfo.username || 'unknown',
      userAgent: navigator.userAgent,
      screenResolution: `${window.screen.width}x${window.screen.height}`,
      currentUrl: window.location.href,
      formData: { ...formData },
      additionalData: data,
      sessionId: sessionStorage.getItem('sessionId') || 'unknown'
    }
    
    console.group(`📝 [表单日志] ${action}`)
    console.log('🕒 时间:', new Date().toLocaleString())
    console.log('👤 用户:', userInfo.username || 'unknown')
    console.log('📋 操作:', action)
    console.log('📊 数据:', logData)
    console.groupEnd()
    
    // 发送日志到后端
    if (api.logs?.addFormLog) {
      await api.logs.addFormLog(logData)
    } else {
      console.log('ℹ️ 日志API不可用，仅记录到控制台')
    }
  } catch (error) {
    console.error('❌ 记录表单日志失败:', error)
  }
}

// 字段变化监听
const handleFieldChange = (fieldName, value, oldValue) => {
  console.group(`🔄 [字段变化] ${fieldName}`)
  console.log('🕒 时间:', new Date().toLocaleString())
  console.log('📝 字段名:', fieldName)
  console.log('📝 旧值:', oldValue)
  console.log('📝 新值:', value)
  console.log('📏 值类型:', typeof value)
  console.log('📏 值长度:', value ? value.length : 0)
  console.groupEnd()
  
  // 更新formData中的字段值
  if (fieldName in formData) {
    formData[fieldName] = value
    console.log(`✅ 已更新 formData.${fieldName} =`, value)
  }
  
  // 记录字段变化日志
  logFormAction('field_change', {
    fieldName,
    oldValue,
    newValue: value,
    changeType: oldValue !== value ? 'changed' : 'unchanged'
  })
  
  // 强制清除所有验证状态
  nextTick(() => {
    if (formRef.value) {
      formRef.value.clearValidate()
      console.log(`✅ 已清除所有验证状态`)
    }
  })
}

// 表单验证监听
const handleFormValidation = (isValid, errors = []) => {
  console.group(`✅ [表单验证] ${isValid ? '通过' : '失败'}`)
  console.log('🕒 时间:', new Date().toLocaleString())
  console.log('📊 验证结果:', isValid ? '✅ 通过' : '❌ 失败')
  if (!isValid && errors.length > 0) {
    console.log('❌ 错误详情:')
    errors.forEach((error, index) => {
      console.log(`  ${index + 1}. ${error.field}: ${error.message}`)
    })
  }
  console.groupEnd()
  
  // 记录验证日志
  logFormAction('form_validation', {
    isValid,
    errorCount: errors.length,
    errors: errors
  })
}

// 调试表单验证的辅助方法
const debugFormValidation = () => {
  console.group('🔍 表单验证调试信息')
  console.log('📝 当前表单数据:', JSON.stringify(formData, null, 2))
  console.log('📋 表单验证规则:', formRules)
  
  // 检查每个必填字段
  const requiredFields = ['name', 'type', 'contact', 'phone', 'address']
  requiredFields.forEach(field => {
    const value = formData[field]
    const isEmpty = !value || (typeof value === 'string' && value.trim() === '')
    console.log(`  ${field}: "${value}" ${isEmpty ? '❌ 为空' : '✅ 有值'}`)
  })
  
  // 检查手机号格式
  if (formData.phone) {
    const phonePattern = /^1[3-9]\d{9}$/
    const isValidPhone = phonePattern.test(formData.phone)
    console.log(`  手机号格式: ${isValidPhone ? '✅ 正确' : '❌ 错误'}`)
  }
  
  console.groupEnd()
  
  // 强制清除所有验证状态
  if (formRef.value) {
    formRef.value.clearValidate()
    console.log('✅ 已手动清除所有验证状态')
    message.success('已清除所有验证状态')
    
    // 延迟再次清除，确保完全清除
    setTimeout(() => {
      if (formRef.value) {
        formRef.value.clearValidate()
        console.log('✅ 延迟清除验证状态完成')
      }
    }, 100)
  }
  
  // 记录调试日志
  logFormAction('debug_form_validation', {
    formData: { ...formData },
    requiredFields: requiredFields
  })
}

const handleSubmit = async () => {
  try {
    // 记录表单提交开始
    await logFormAction('form_submit_start', {
      isEdit: isEdit.value,
      formData: { ...formData }
    })
    
    // 调试表单数据
    debugFormValidation()
    
    // 手动验证必填字段
    const validationErrors = []
    
    // 验证养殖场名称 (name)
    if (!formData.name || formData.name.trim() === '') {
      validationErrors.push('请输入养殖场名称')
    }
    
    // 验证养殖场类型 (type)
    if (!formData.type || formData.type.trim() === '') {
      validationErrors.push('请选择养殖场类型')
    }
    
    // 验证联系人 (contact)
    if (!formData.contact || formData.contact.trim() === '') {
      validationErrors.push('请输入联系人')
    }
    
    // 验证联系电话 (phone)
    if (!formData.phone || formData.phone.trim() === '') {
      validationErrors.push('请输入联系电话')
    } else {
      // 验证手机号格式
      const phonePattern = /^1[3-9]\d{9}$/
      if (!phonePattern.test(formData.phone.trim())) {
        validationErrors.push('请输入正确的11位手机号码')
      }
    }
    
    // 验证详细地址 (address)
    if (!formData.address || formData.address.trim() === '') {
      validationErrors.push('请输入详细地址')
    } else if (formData.address.trim().length < 5) {
      validationErrors.push('详细地址至少需要5个字符')
    }
    
    // 验证经纬度 (location)
    if (formData.longitude === null || formData.longitude === undefined || formData.longitude === '') {
      validationErrors.push('请输入经度')
    } else if (isNaN(parseFloat(formData.longitude)) || parseFloat(formData.longitude) < -180 || parseFloat(formData.longitude) > 180) {
      validationErrors.push('经度必须在-180到180之间')
    }
    
    if (formData.latitude === null || formData.latitude === undefined || formData.latitude === '') {
      validationErrors.push('请输入纬度')
    } else if (isNaN(parseFloat(formData.latitude)) || parseFloat(formData.latitude) < -90 || parseFloat(formData.latitude) > 90) {
      validationErrors.push('纬度必须在-90到90之间')
    }
    
    // 验证状态 (status)
    if (!formData.status || formData.status.trim() === '') {
      validationErrors.push('请选择状态')
    }
    
    if (validationErrors.length > 0) {
      message.error(validationErrors[0])
      message.warning(`还有${validationErrors.length}个字段需要修正`)
      
      // 记录表单验证失败
      await logFormAction('form_validation_failed', {
        formData: { ...formData },
        errors: validationErrors
      })
      return
    }
    
    // 清除所有验证状态
    if (formRef.value) {
      formRef.value.clearValidate()
    }
    
    // 记录验证通过
    await logFormAction('form_validation_success', {
      formData: { ...formData }
    })
    
    submitting.value = true
    
    // 转换数据格式
    const farmData = convertFarmToDB(formData)
    
    if (isEdit.value) {
      // 编辑养殖场
      console.log('🔄 开始更新养殖场:', formData.id)
      
      const response = await api.farms.update(formData.id, farmData)
      
      if (response.success) {
        // 更新本地数据
        const index = farmsData.value.findIndex(item => item.id === formData.id)
      if (index > -1) {
          const oldData = { ...farmsData.value[index] }
          farmsData.value[index] = convertFarmFromDB(response.data)
          
          // 记录编辑成功
          await logFormAction('form_edit_success', {
            recordId: formData.id,
            oldData,
            newData: { ...formData },
            changes: getFormChanges(oldData, formData)
          })
        }
        
        message.success('编辑成功')
        console.log('✅ 养殖场更新成功')
      } else {
        message.error('编辑失败: ' + (response.message || '未知错误'))
      }
    } else {
      // 新增养殖场
      console.log('🔄 开始创建养殖场')
      
      const response = await api.farms.create(farmData)
      
      if (response.success) {
        // 添加到本地数据
        const newRecord = convertFarmFromDB(response.data)
        farmsData.value.unshift(newRecord)
        pagination.total = farmsData.value.length
        
        // 记录新增成功
        await logFormAction('form_create_success', {
          recordId: newRecord.id,
          newData: { ...newRecord }
        })
        
      message.success('新增成功')
        console.log('✅ 养殖场创建成功')
      } else {
        message.error('新增失败: ' + (response.message || '未知错误'))
      }
    }
    
    modalVisible.value = false
    
    // 记录表单提交完成
    await logFormAction('form_submit_complete', {
      isEdit: isEdit.value,
      success: true
    })
    
  } catch (error) {
    console.error('❌ 表单提交失败:', error)
    message.error('操作失败: ' + (error.message || '网络错误'))
    
    // 记录表单提交失败
    await logFormAction('form_submit_failed', {
      isEdit: isEdit.value,
      formData: { ...formData },
      error: error.message
    })
  } finally {
    submitting.value = false
  }
}

// 获取表单变化对比
const getFormChanges = (oldData, newData) => {
  const changes = {}
  Object.keys(newData).forEach(key => {
    if (oldData[key] !== newData[key]) {
      changes[key] = {
        oldValue: oldData[key],
        newValue: newData[key]
      }
    }
  })
  return changes
}

const handleCancel = async () => {
  // 记录取消操作
  await logFormAction('modal_cancel', {
    isEdit: isEdit.value,
    formData: { ...formData }
  })
  
  modalVisible.value = false
  resetForm()
}

const resetForm = () => {
  // 完全重置表单数据，确保没有旧值残留
  formData.id = null
  formData.name = ''
  formData.type = ''
  formData.contact = ''
  formData.phone = ''
  formData.address = ''
  formData.longitude = null
  formData.latitude = null
  formData.status = 'active'
  
  // 清除表单验证状态
  if (formRef.value) {
    formRef.value.resetFields()
    formRef.value.clearValidate()
  }
  
  console.log('🔄 表单数据已完全重置:', { ...formData })
}

// 生命周期
onMounted(() => {
  loadFarmsData()
})

// 导出数据
const exportData = async () => {
  try {
    if (!farmsData.value || farmsData.value.length === 0) {
      message.warning('没有数据可导出')
      return
    }
    
    message.loading('正在导出数据...', 0)
    
    // 获取所有农场数据（取消分页限制）
    const response = await api.farms.getList()
    
    if (response.success) {
      const allFarms = response.data.map(convertFarmFromDB)
      console.log('获取到所有农场数据:', allFarms.length, '条记录')
      
      const result = ExportUtils.exportFarmData(allFarms)
      
      if (result.success) {
        message.destroy()
        message.success(`导出成功！文件：${result.filename}`)
      } else {
        message.destroy()
        message.error(result.message)
      }
    } else {
      message.destroy()
      message.error('获取数据失败')
    }
  } catch (error) {
    message.destroy()
    console.error('导出失败:', error)
    message.error('导出失败，请重试')
  }
}
</script>

<style scoped>
.farm-info-management-container {
  padding: 24px;
  background: #fff;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

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

.header-actions {
  display: flex;
  align-items: center;
  gap: 16px;
}

.add-button {
  height: 40px;
  font-size: 14px;
  font-weight: 500;
}

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

.search-input {
  width: 200px;
  height: 40px;
}

.search-button {
  height: 40px;
}

.table-container {
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
}

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

.action-btn {
  padding: 4px 8px;
  height: auto;
  font-size: 14px;
}

.action-btn:hover {
  background: #f5f5f5;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .header-actions {
    width: 100%;
    justify-content: space-between;
  }
  
  .search-container {
    flex: 1;
  }
  
  .search-input {
    width: 100%;
  }
}

/* 表格样式优化 */
:deep(.ant-table-thead > tr > th) {
  background: #fafafa;
  font-weight: 600;
  color: #262626;
}

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

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

/* 状态标签样式 */
:deep(.ant-tag) {
  border-radius: 4px;
  font-size: 12px;
  padding: 2px 8px;
}

/* 表单样式 */
:deep(.ant-form-item-label > label) {
  font-weight: 500;
  color: #262626;
}

:deep(.ant-input),
:deep(.ant-select),
:deep(.ant-input-number) {
  border-radius: 6px;
}

:deep(.ant-btn) {
  border-radius: 6px;
}

/* 表单验证状态优化 */
:deep(.ant-form-item-has-error .ant-input) {
  border-color: #ff4d4f;
}

:deep(.ant-form-item-has-error .ant-select-selector) {
  border-color: #ff4d4f;
}

:deep(.ant-form-item-has-success .ant-input) {
  border-color: #52c41a;
}

:deep(.ant-form-item-has-success .ant-select-selector) {
  border-color: #52c41a;
}

/* 清除验证错误时的过渡效果 */
:deep(.ant-input),
:deep(.ant-select-selector) {
  transition: border-color 0.3s ease;
}

/* 调试按钮样式 */
:deep(.ant-btn-dashed) {
  border-style: dashed;
  border-color: #d9d9d9;
  color: #666;
}

:deep(.ant-btn-dashed:hover) {
  border-color: #40a9ff;
  color: #40a9ff;
}
</style>
