<template>
  <div>
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;">
      <h1>牛只档案</h1>
      <a-space>
        <a-button @click="importAnimals" :loading="importLoading">
          <template #icon><ImportOutlined /></template>
          导入数据
        </a-button>
        <a-button @click="exportAnimals" :loading="exportLoading">
          <template #icon><ExportOutlined /></template>
          导出数据
        </a-button>
        <a-button type="primary" @click="showAddModal">
          <template #icon><PlusOutlined /></template>
          添加动物
        </a-button>
      </a-space>
    </div>
    
    <!-- 搜索区域 -->
    <div style="margin-bottom: 16px; display: flex; gap: 8px; align-items: center;">
      <a-input
        v-model:value="searchEarNumber"
        placeholder="请输入牛只设备号搜索"
        style="width: 300px;"
        @press-enter="searchAnimals"
        @input="handleSearchEarNumberInput"
      />
      <a-select
        v-model:value="searchPenId"
        placeholder="请选择栏舍"
        style="width: 200px;"
        :loading="pensLoading"
        @change="handleSearchPenChange"
      >
        <a-select-option :value="null">全部栏舍</a-select-option>
        <a-select-option 
          v-for="pen in pens" 
          :key="pen.id" 
          :value="pen.id"
        >
          {{ pen.name }}
        </a-select-option>
      </a-select>
      <a-button type="primary" @click="searchAnimals" :loading="searchLoading">
        <template #icon><SearchOutlined /></template>
        查询
      </a-button>
      <a-button @click="resetSearch" :disabled="!isSearching">
        重置
      </a-button>
    </div>
    
    <a-table 
      :columns="columns" 
      :data-source="animals" 
      :loading="loading"
      :pagination="pagination"
      @change="handleTableChange"
      row-key="id"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'health_status'">
          <a-tag :color="getHealthStatusColor(record.health_status)">
            {{ getHealthStatusText(record.health_status) }}
          </a-tag>
        </template>
        <template v-else-if="column.dataIndex === 'farm_name'">
          {{ getFarmName(record.farm_id) }}
        </template>
        <template v-else-if="column.dataIndex === 'last_inspection'">
          {{ formatDate(record.last_inspection) }}
        </template>
        <template v-else-if="column.dataIndex === 'action'">
          <a-button type="link" @click="editAnimal(record)">编辑</a-button>
          <a-popconfirm
            title="确定要删除这个动物记录吗？"
            @confirm="deleteAnimal(record.id)"
            ok-text="确定"
            cancel-text="取消"
          >
            <a-button type="link" danger>删除</a-button>
          </a-popconfirm>
        </template>
      </template>
    </a-table>

    <!-- 添加/编辑牛只档案模态框 -->
    <a-modal
      v-model:open="modalVisible"
      :title="isEdit ? '编辑牛只档案' : '添加牛只档案'"
      @ok="handleSubmit"
      @cancel="handleCancel"
      :confirm-loading="submitLoading"
      width="800px"
    >
      <a-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        layout="vertical"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="耳标号" name="earNumber">
              <a-input 
                v-model:value="formData.earNumber" 
                placeholder="请输入耳标号"
                @input="handleFieldChange('earNumber', $event.target.value)"
                @change="handleFieldChange('earNumber', $event.target.value)"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="性别" name="sex">
              <a-select 
                v-model:value="formData.sex" 
                placeholder="请选择性别"
                @change="handleFieldChange('sex', $event)"
              >
                <a-select-option :value="1">公</a-select-option>
                <a-select-option :value="2">母</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item label="品类" name="strain">
              <a-select 
                v-model:value="formData.strain" 
                placeholder="请选择品类"
                :loading="cattleUsersLoading"
                @change="handleFieldChange('strain', $event)"
                show-search
                :filter-option="filterOption"
              >
                <a-select-option 
                  v-for="user in cattleUsers" 
                  :key="user.id" 
                  :value="user.id"
                >
                  {{ user.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="品种" name="varieties">
              <a-select 
                v-model:value="formData.varieties" 
                placeholder="请选择品种"
                :loading="cattleTypesLoading"
                @change="handleFieldChange('varieties', $event)"
                show-search
                :filter-option="filterOption"
              >
                <!-- 动态选项 -->
                <a-select-option 
                  v-for="type in cattleTypes" 
                  :key="type.id" 
                  :value="type.id"
                >
                  {{ type.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="生理阶段" name="cate">
              <a-select 
                v-model:value="formData.cate" 
                placeholder="请选择生理阶段"
                @change="handleFieldChange('cate', $event)"
                show-search
                :filter-option="filterCateOption"
              >
                <a-select-option 
                  v-for="(name, value) in cateOptions" 
                  :key="value" 
                  :value="parseInt(value)"
                >
                  {{ name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="出生体重(kg)" name="birthWeight">
              <a-input-number 
                v-model:value="formData.birthWeight" 
                placeholder="请输入出生体重"
                :min="0"
                :precision="2"
                style="width: 100%"
                @change="handleFieldChange('birthWeight', $event)"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="当前体重(kg)" name="currentWeight">
              <a-input-number 
                v-model:value="formData.currentWeight" 
                placeholder="请输入当前体重"
                :min="0"
                :precision="2"
                style="width: 100%"
                @change="handleFieldChange('currentWeight', $event)"
              />
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="出生日期" name="birthday">
              <a-date-picker 
                v-model:value="formData.birthday" 
                placeholder="请选择出生日期"
                style="width: 100%"
                @change="handleFieldChange('birthday', $event)"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="月龄" name="ageInMonths">
              <a-input-number 
                v-model:value="formData.ageInMonths" 
                placeholder="请输入月龄"
                :min="0"
                style="width: 100%"
                @change="handleFieldChange('ageInMonths', $event)"
              />
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-row :gutter="16">
          
          <a-col :span="12">
            <a-form-item label="胎次" name="parity">
              <a-input-number 
                v-model:value="formData.parity" 
                placeholder="请输入胎次"
                :min="0"
                style="width: 100%"
                @change="handleFieldChange('parity', $event)"
              />
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="所属农场" name="orgId">
              <a-select 
                v-model:value="formData.orgId" 
                placeholder="请选择所属农场"
                :loading="farmsLoading"
                @change="handleFieldChange('orgId', $event)"
              >
                <a-select-option 
                  v-for="farm in farms" 
                  :key="farm.id" 
                  :value="farm.id"
                >
                  {{ farm.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="所属栏舍" name="penId">
              <a-select 
                v-model:value="formData.penId" 
                placeholder="请选择所属栏舍"
                :loading="pensLoading"
                @change="handleFieldChange('penId', $event)"
              >
                <a-select-option 
                  v-for="pen in pens" 
                  :key="pen.id" 
                  :value="pen.id"
                >
                  {{ pen.name }}
                </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="batchId">
              <a-select 
                v-model:value="formData.batchId" 
                placeholder="请选择所属批次"
                :loading="batchesLoading"
                @change="handleFieldChange('batchId', $event)"
              >
                <a-select-option 
                  v-for="batch in batches" 
                  :key="batch.id" 
                  :value="batch.id"
                >
                  {{ batch.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="来源" name="source">
              <a-select 
                v-model:value="formData.source" 
                placeholder="请选择来源"
                @change="handleFieldChange('source', $event)"
                show-search
                :filter-option="filterOption"
              >
                <a-select-option :value="1">购买</a-select-option>
                <a-select-option :value="2">自繁</a-select-option>
                <a-select-option :value="3">放生</a-select-option>
                <a-select-option :value="4">合作社</a-select-option>
                <a-select-option :value="5">入股</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>

    <!-- 导入数据模态框 -->
    <a-modal
      v-model:open="importModalVisible"
      title="导入牛只档案数据"
      @ok="confirmImport"
      @cancel="cancelImport"
      :confirm-loading="importLoading"
      width="600px"
    >
      <div style="padding: 20px 0;">
        <a-alert
          message="导入说明"
          description="请选择Excel文件(.xlsx或.xls格式)，文件大小不超过10MB。导入的数据将按照模板格式进行解析。"
          type="info"
          show-icon
          style="margin-bottom: 20px;"
        />
        
        <div style="display: flex; gap: 12px; align-items: center;">
          <a-upload
            :file-list="importFile ? [importFile] : []"
            :before-upload="() => false"
            @change="handleFileChange"
            accept=".xlsx,.xls"
            :max-count="1"
          >
            <a-button>
              <template #icon><ImportOutlined /></template>
              选择Excel文件
            </a-button>
          </a-upload>
          
          <a-button @click="downloadTemplate" :loading="templateLoading">
            <template #icon><DownloadOutlined /></template>
            下载模板
          </a-button>
        </div>
        
        <div style="margin-top: 16px; color: #666; font-size: 12px;">
          <p>支持的文件格式：.xlsx, .xls</p>
          <p>文件大小限制：10MB</p>
          <p>建议先下载模板文件，按照模板格式填写数据后再导入</p>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined, SearchOutlined, ExportOutlined, ImportOutlined, DownloadOutlined } from '@ant-design/icons-vue'
import { api } from '@/utils/api'
import { ExportUtils } from '../utils/exportUtils'
import { getSexName, getCategoryName, getSourceTypeName, getStrainName } from '../utils/fieldMappings'
import dayjs from 'dayjs'

// 响应式数据
const animals = ref([])
const farms = ref([])
const pens = ref([])
const batches = ref([])
const cattleUsers = ref([]) // 品系数据（cattle_user表）
const cattleTypes = ref([]) // 品种数据（cattle_type表）
const loading = ref(false)
const farmsLoading = ref(false)
const pensLoading = ref(false)
const batchesLoading = ref(false)
const cattleUsersLoading = ref(false)
const cattleTypesLoading = ref(false)
const modalVisible = ref(false)
const submitLoading = ref(false)
const isEdit = ref(false)
const formRef = ref()

// 类别选项（预定义映射）
const cateOptions = ref({
  1: '犊牛',
  2: '育成母牛',
  3: '架子牛',
  4: '青年牛',
  5: '基础母牛',
  6: '育肥牛'
})

// 分页相关
const pagination = ref({
  current: 1,
  pageSize: 50,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条数据`
})

// 搜索相关的响应式数据
const searchEarNumber = ref('')
const searchPenId = ref(null)
const searchLoading = ref(false)
const isSearching = ref(false)

// 导出相关
const exportLoading = ref(false)

// 导入相关
const importLoading = ref(false)
const importModalVisible = ref(false)
const importFile = ref(null)
const templateLoading = ref(false)

// 表单数据（基于iot_cattle表字段映射）
const formData = reactive({
  id: null,
  earNumber: '', // 映射iot_cattle.ear_number
  sex: 1, // 映射iot_cattle.sex
  strain: '', // 映射iot_cattle.strain
  varieties: '', // 映射iot_cattle.varieties
  cate: '', // 映射iot_cattle.cate
  birthWeight: 0, // 映射iot_cattle.birth_weight
  birthday: null, // 映射iot_cattle.birthday
  penId: null, // 映射iot_cattle.pen_id
  intoTime: null,
  parity: 0,
  source: '', // 映射iot_cattle.source，改为空字符串以便验证
  sourceDay: 0,
  sourceWeight: 0,
  ageInMonths: 0, // 从iot_cattle.birthday计算得出
  physiologicalStage: '',
  currentWeight: 0,
  weightCalculateTime: null,
  dayOfBirthday: 0,
  orgId: null,
  penId: null, // 映射iot_cattle.pen_id
  batchId: null // 映射iot_cattle.batch_id
})

// 控制是否显示自定义输入框
const showCustomTypeInput = ref(false)

// 表单验证规则（基于iot_cattle表字段映射）
const rules = {
  earNumber: [{ required: true, message: '请输入耳标号', trigger: 'blur' }], // iot_cattle.ear_number
  sex: [{ required: true, message: '请选择性别', trigger: 'change' }], // iot_cattle.sex
  strain: [{ required: true, message: '请输入品系', trigger: 'blur' }], // iot_cattle.strain
  varieties: [{ required: true, message: '请输入品种', trigger: 'blur' }], // iot_cattle.varieties
  cate: [{ required: true, message: '请输入类别', trigger: 'blur' }], // iot_cattle.cate
  birthWeight: [{ required: true, message: '请输入出生体重', trigger: 'blur' }], // iot_cattle.birth_weight
  birthday: [{ required: true, message: '请选择出生日期', trigger: 'change' }], // iot_cattle.birthday
  orgId: [{ required: true, message: '请选择所属农场', trigger: 'change' }], // iot_cattle.org_id
  source: [{ required: true, message: '请选择来源', trigger: 'change' }] // iot_cattle.source
}

// 表格列配置（基于iot_cattle表字段映射）
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: 80
  },
  {
    title: '耳标号',
    dataIndex: 'earNumber', // 映射iot_cattle.ear_number
    key: 'earNumber',
    width: 120
  },
  {
    title: '性别',
    dataIndex: 'sex', // 映射iot_cattle.sex
    key: 'sex',
    width: 80,
    customRender: ({ text }) => {
      return getSexName(text)
    }
  },
  {
    title: '品系',
    dataIndex: 'strain', // 映射iot_cattle.strain，显示用途名称
    key: 'strain',
    width: 120,
    customRender: ({ text }) => {
      // 后端已经返回格式化好的名称，直接显示
      return text || '-'
    }
  },
  {
    title: '品种',
    dataIndex: 'varieties', // 映射iot_cattle.varieties
    key: 'varieties',
    width: 120,
    customRender: ({ text }) => {
      return text || '-' 
    } 
  },
  { 
    title: '类别', 
    dataIndex: 'cate', // 映射iot_cattle.cate
    key: 'cate', 
    width: 100, 
    customRender: ({ text }) => {
      // 添加调试日志查看实际的cate值
      console.log('类别值:', text, '类型:', typeof text)
      // 如果是数字类型，使用映射函数；如果是字符串但不为空，直接显示；否则显示未知
      if (typeof text === 'number' || !isNaN(parseInt(text))) {
        const categoryName = getCategoryName(typeof text === 'number' ? text : parseInt(text))
        // 如果映射结果为'未知'且有原始值，显示原始值
        return categoryName === '未知' && text ? `未定义(${text})` : categoryName
      } else if (text && text !== '') {
        return text
      }
      return '未知'
    } 
  },
  {
    title: '出生体重(kg)',
    dataIndex: 'birthWeight', // 映射iot_cattle.birth_weight
    key: 'birthWeight',
    width: 120
  },
  {
    title: '月龄',
    dataIndex: 'ageInMonths', // 映射iot_cattle.birthday计算得出
    key: 'ageInMonths',
    width: 80
  },
  {
    title: '所属栏舍',
    dataIndex: 'penName', // 映射iot_cattle.pen_id关联cattle_pens表
    key: 'penName',
    width: 120
  },
  {
    title: '所属批次',
    dataIndex: 'batchName', // 映射iot_cattle.batch_id关联cattle_batches表
    key: 'batchName',
    width: 120
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    width: 150
  }
]

// 获取牛只档案列表（从iot_cattle表）
const fetchAnimals = async (page = 1, pageSize = 10) => {
  try {
    loading.value = true
    const token = localStorage.getItem('token')
    const response = await api.get('/iot-cattle/public', {
      params: { page, pageSize }
    })
    
    if (response.success) {
      animals.value = response.data.list || []
      // 更新分页信息
      if (response.data.pagination) {
        pagination.value.current = response.data.pagination.current
        pagination.value.pageSize = response.data.pagination.pageSize
        pagination.value.total = response.data.pagination.total
      }
      console.log('获取牛只档案列表成功:', animals.value.length, '条记录')
      console.log('分页信息:', response.data.pagination)
    } else {
      message.error('获取牛只档案列表失败')
    }
  } catch (error) {
    console.error('获取牛只档案列表失败:', error)
    if (error.response && error.response.status === 401) {
      message.error('登录已过期，请重新登录')
      setTimeout(() => {
        window.location.href = '/login'
      }, 2000)
    } else {
      message.error('获取牛只档案列表失败: ' + (error.message || '未知错误'))
    }
  } finally {
    loading.value = false
  }
}

// 获取农场列表
const fetchFarms = async () => {
  try {
    farmsLoading.value = true
    const token = localStorage.getItem('token')
    const response = await api.get('/iot-cattle/farms/list')
    if (response.success) {
      farms.value = response.data
    }
  } catch (error) {
    console.error('获取农场列表失败:', error)
  } finally {
    farmsLoading.value = false
  }
}

// 获取栏舍列表
const fetchPens = async (farmId = null) => {
  try {
    pensLoading.value = true
    console.log('🔍 [牛只档案] 开始获取栏舍列表')
    
    // 调用 /cattle-pens 接口
    const params = {
      page: 1,
      pageSize: 10
    }
    
    // 如果有 farmId，可以添加到参数中（如果后端支持）
    if (farmId) {
      params.farmId = farmId
    }
    
    console.log('📤 [牛只档案] 栏舍列表请求参数:', params)
    const response = await api.cattlePens.getList(params)
    console.log('📥 [牛只档案] 栏舍列表响应:', response)
    
    if (response.success && response.data) {
      // 从 response.data.list 中提取栏舍列表
      const pensList = response.data.list || []
      pens.value = pensList
      console.log('✅ [牛只档案] 获取栏舍列表成功，共', pensList.length, '条')
      return pensList
    }
    return []
  } catch (error) {
    console.error('❌ [牛只档案] 获取栏舍列表失败:', error)
    return []
  } finally {
    pensLoading.value = false
  }
}

// 获取批次列表
const fetchBatches = async (farmId = null) => {
  try {
    batchesLoading.value = true
    console.log('🔍 [牛只档案] 开始获取批次列表')
    
    // 调用 /cattle-batches 接口
    const params = {
      page: 1,
      pageSize: 10,
      search: '',
      exactMatch: true,
      strictMatch: true
    }
    
    // 如果有 farmId，可以添加到参数中（如果后端支持）
    if (farmId) {
      params.farmId = farmId
    }
    
    console.log('📤 [牛只档案] 批次列表请求参数:', params)
    const response = await api.cattleBatches.getList(params)
    console.log('📥 [牛只档案] 批次列表响应:', response)
    
    if (response.success && response.data) {
      // 从 response.data.list 中提取批次列表
      const batchesList = response.data.list || []
      batches.value = batchesList
      console.log('✅ [牛只档案] 获取批次列表成功，共', batchesList.length, '条')
      return batchesList
    }
    return []
  } catch (error) {
    console.error('❌ [牛只档案] 获取批次列表失败:', error)
    return []
  } finally {
    batchesLoading.value = false
  }
}

// 获取品系列表（cattle_user表）
const fetchCattleUsers = async () => {
  try {
    cattleUsersLoading.value = true
    const response = await api.get('/cattle-user')
    if (response.success) {
      cattleUsers.value = response.data
      console.log('获取品系列表成功:', cattleUsers.value.length, '条记录')
    }
  } catch (error) {
    console.error('获取品系列表失败:', error)
  } finally {
    cattleUsersLoading.value = false
  }
}

// 获取品种和类别列表（cattle_type表）
const fetchCattleTypes = async () => {
  try {
    cattleTypesLoading.value = true
    const response = await api.get('/cattle-type')
    if (response.success) {
      cattleTypes.value = response.data
      console.log('获取品种列表成功:', cattleTypes.value.length, '条记录')
    }
  } catch (error) {
    console.error('获取品种列表失败:', error)
  } finally {
    cattleTypesLoading.value = false
  }
}

// 字段变化监听函数
const handleFieldChange = (fieldName, value) => {
  console.log(`字段 ${fieldName} 变化:`, value)
  
  // 当农场变化时，重新加载栏舍和批次
  if (fieldName === 'orgId' && value) {
    fetchPens(value)
    fetchBatches(value)
  }
  
  // 更新表单数据
  formData[fieldName] = value
}

// 下拉框过滤选项方法
const filterOption = (input, option) => {
  return option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
}

// 类别下拉框过滤选项方法
const filterCateOption = (input, option) => {
  return option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
}

// 绑定耳标到iot_jbq_client表
const bindEarTag = async (earNumber, cattleId) => {
  try {
    console.log('开始绑定耳标:', earNumber, '到牛只ID:', cattleId)
    
    // 查找对应的耳标设备
    const response = await api.get('/iot-jbq-client', {
      params: { cid: earNumber }
    })
    
    if (response.success && response.data && response.data.length > 0) {
      const device = response.data[0]
      console.log('找到耳标设备:', device)
      
      // 更新设备的绑定状态
      const updateResponse = await api.put(`/iot-jbq-client/${device.id}`, {
        bandge_status: 1, // 1表示已绑定
        bound_cattle_id: cattleId,
        bound_ear_number: earNumber
      })
      
      if (updateResponse.success) {
        console.log('耳标绑定成功')
        message.success('耳标绑定成功')
      } else {
        console.error('耳标绑定失败:', updateResponse.message)
        message.warning('牛只档案创建成功，但耳标绑定失败')
      }
    } else {
      console.warn('未找到对应的耳标设备:', earNumber)
      message.warning('牛只档案创建成功，但未找到对应的耳标设备')
    }
  } catch (error) {
    console.error('耳标绑定失败:', error)
    message.warning('牛只档案创建成功，但耳标绑定失败')
  }
}

// 处理动物类型选择变化
const handleTypeChange = (value) => {
  console.log('=== 动物类型变化 ===')
  console.log('选择的类型:', value)
  console.log('变化前 formData.type:', formData.type)
  console.log('变化前 formData.customType:', formData.customType)
  
  showCustomTypeInput.value = value === 'other'
  // 当切换到非'other'类型时，清空customType字段
  // 这确保提交时使用正确的类型值
  if (value !== 'other') {
    formData.customType = ''
  }
  
  console.log('变化后 showCustomTypeInput:', showCustomTypeInput.value)
  console.log('变化后 formData.customType:', formData.customType)
}

// ==================== 添加牛只档案功能 ====================
// 显示添加牛只档案模态框
const showAddModal = () => {
  console.log('=== 点击新增按钮 ===')
  initializeAddMode()
  openModal()
  loadRequiredData()
}

// 初始化添加模式
const initializeAddMode = () => {
  isEdit.value = false
  resetForm()
  console.log('初始化添加模式，表单已重置')
}

// ==================== 编辑牛只档案功能 ====================
// 编辑牛只档案
// 编辑牛只档案
const editAnimal = async (record) => {
  try {
    console.log('=== 点击编辑按钮 ===')
    console.log('编辑记录ID:', record.id)
    
    // 调用后端接口获取详情
    const response = await api.get(`/iot-cattle/${record.id}`)
    
    if (response.success && response.data) {
      console.log('获取到的详情数据:', response.data)
      initializeEditMode(response.data)
      openModal()
      loadRequiredData()
    } else {
      message.error('获取牛只档案详情失败')
    }
  } catch (error) {
    console.error('获取牛只档案详情失败:', error)
    message.error(error.message || '获取牛只档案详情失败')
  }
}

// 初始化编辑模式
const initializeEditMode = (record) => {
  isEdit.value = true
  populateFormWithRecord(record)
  configureEditModeSettings()
}

// 计算月龄（基于birthday字段）
const calculateAgeInMonths = (birthday) => {
  if (!birthday) return 0
  
  // 如果birthday是时间戳（秒）
  if (typeof birthday === 'number') {
    const birthDate = dayjs.unix(birthday)
    const now = dayjs()
    return now.diff(birthDate, 'month')
  }
  
  // 如果birthday是日期字符串
  const birthDate = dayjs(birthday)
  const now = dayjs()
  return now.diff(birthDate, 'month')
}

// 填充表单数据（基于iot_cattle字段映射）
const populateFormWithRecord = (record) => {
  console.log('=== 填充编辑表单数据 ===');
  console.log('原始记录数据:', record);
  
  // 填充iot_cattle表字段映射
  formData.id = record.id
  formData.earNumber = record.earNumber || '' // iot_cattle.ear_number
  formData.sex = record.sex || 1 // iot_cattle.sex
  // 使用原始ID（strainId），如果没有则使用strain（兼容旧数据）
  formData.strain = record.strainId !== undefined ? record.strainId : (record.strain || '') // iot_cattle.strain
  // 使用原始ID（varietiesId），如果没有则使用varieties（兼容旧数据）
  formData.varieties = record.varietiesId !== undefined ? record.varietiesId : (record.varieties || '') // iot_cattle.varieties
  // 使用原始ID（cateId），如果没有则使用cate（兼容旧数据）
  formData.cate = record.cateId !== undefined ? record.cateId : (record.cate || '') // iot_cattle.cate
  formData.birthWeight = record.birthWeight || 0 // iot_cattle.birth_weight
  // 处理出生日期：如果是时间戳（秒），使用dayjs.unix；如果是日期字符串，使用dayjs
  if (record.birthday) {
    if (typeof record.birthday === 'number') {
      // 时间戳（秒）转换为dayjs对象
      const birthdayDate = dayjs.unix(record.birthday)
      formData.birthday = birthdayDate.isValid() ? birthdayDate : null
      console.log('转换出生日期:', record.birthday, '->', formData.birthday?.format('YYYY-MM-DD'))
    } else {
      formData.birthday = dayjs(record.birthday) // 日期字符串转换为dayjs对象
    }
  } else {
    formData.birthday = null
  }
  // 处理所属栏舍：如果为0或null，则设为null
  formData.penId = (record.penId && record.penId !== 0) ? record.penId : null // iot_cattle.pen_id
  // 处理入场日期：如果是时间戳（秒），使用dayjs.unix；如果是日期字符串，使用dayjs
  if (record.intoTime) {
    if (typeof record.intoTime === 'number') {
      formData.intoTime = dayjs.unix(record.intoTime) // 时间戳（秒）转换为dayjs对象
    } else {
      formData.intoTime = dayjs(record.intoTime) // 日期字符串转换为dayjs对象
    }
  } else {
    formData.intoTime = null
  }
  formData.parity = record.parity || 0
  // 处理来源：如果是数字（包括0），直接使用；否则设为空字符串
  if (typeof record.source === 'number') {
    formData.source = record.source
  } else if (record.source !== undefined && record.source !== null && record.source !== '') {
    formData.source = record.source
  } else {
    formData.source = ''
  }
  formData.sourceDay = record.sourceDay || 0
  formData.sourceWeight = record.sourceWeight || 0
  // 优先使用JSON中的ageInMonths，如果没有则计算
  formData.ageInMonths = record.ageInMonths !== undefined ? record.ageInMonths : calculateAgeInMonths(record.birthday)
  formData.physiologicalStage = record.physiologicalStage || ''
  formData.currentWeight = record.currentWeight || 0
  // 处理体重计算时间：如果是时间戳（秒），使用dayjs.unix；如果是日期字符串，使用dayjs
  if (record.weightCalculateTime) {
    if (typeof record.weightCalculateTime === 'number') {
      formData.weightCalculateTime = dayjs.unix(record.weightCalculateTime) // 时间戳（秒）转换为dayjs对象
    } else {
      formData.weightCalculateTime = dayjs(record.weightCalculateTime) // 日期字符串转换为dayjs对象
    }
  } else {
    formData.weightCalculateTime = null
  }
  formData.dayOfBirthday = record.dayOfBirthday || 0
  formData.orgId = record.farmId || record.orgId || null // iot_cattle.org_id
  
  // 保存 penId 和 batchId 的值，等待选项加载完成后再设置
  const savedPenId = (record.penId && record.penId !== 0) ? record.penId : null
  const savedBatchId = (record.batchId && record.batchId !== 0) ? record.batchId : null
  
  console.log('填充后的 formData:', JSON.parse(JSON.stringify(formData)));
  console.log('保存的 penId:', savedPenId, 'batchId:', savedBatchId);
  console.log('出生日期转换结果:', formData.birthday);
  
  // 如果所属农场有值，先加载对应的栏舍和批次选项，然后再设置值
  if (formData.orgId) {
    Promise.all([
      fetchPens(formData.orgId),
      fetchBatches(formData.orgId)
    ]).then(() => {
      // 选项加载完成后再设置值，使用 nextTick 确保 DOM 更新
      setTimeout(() => {
        if (savedPenId !== null) {
          formData.penId = savedPenId
          console.log('设置 penId:', savedPenId, '当前栏舍选项:', pens.value)
        }
        if (savedBatchId !== null) {
          formData.batchId = savedBatchId
          console.log('设置 batchId:', savedBatchId, '当前批次选项:', batches.value)
        }
      }, 100) // 延迟100ms确保选项已加载到DOM
    }).catch(error => {
      console.error('加载栏舍或批次选项失败:', error)
    })
  } else {
    // 如果没有农场ID，直接设置值（虽然可能没有对应的选项）
    formData.penId = savedPenId
    formData.batchId = savedBatchId
  }
}

// 配置编辑模式设置
const configureEditModeSettings = () => {
  // 根据类型决定是否显示自定义输入框
  showCustomTypeInput.value = formData.type === 'other'
}

// ==================== 删除动物功能 ====================
// 删除动物
const deleteAnimal = async (id) => {
  try {
    await performDeleteRequest(id)
    handleDeleteSuccess()
  } catch (error) {
    handleDeleteError(error)
  }
}

// 执行删除请求（使用iot_cattle API）
const performDeleteRequest = async (id) => {
  const token = localStorage.getItem('token')
  const response = await api.delete(`/iot-cattle/${id}`)
  
  if (!response.success) {
    throw new Error('删除请求失败')
  }
  
  return response
}

// 处理删除成功
const handleDeleteSuccess = () => {
  message.success('删除成功')
  fetchAnimals()
}

// 处理删除错误
const handleDeleteError = (error) => {
  console.error('删除动物失败:', error)
  message.error('删除失败')
}

// ==================== 通用功能 ====================
// 打开模态框
const openModal = () => {
  modalVisible.value = true
}

// 加载必需数据
const loadRequiredData = () => {
  fetchFarms()
  fetchCattleUsers()
  fetchCattleTypes()
}

// 提交表单（使用iot_cattle API）
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    // 使用统一的API工具，不需要手动配置headers
    
    console.log('=== 前端提交牛只档案表单 ===');
    console.log('是否编辑模式:', isEdit.value);
    console.log('原始表单数据:', JSON.parse(JSON.stringify(formData)));
    
    // 检查必填字段
    const requiredFields = ['earNumber', 'sex', 'strain', 'varieties', 'cate', 'birthWeight', 'birthday', 'orgId', 'source'];
    const missingFields = requiredFields.filter(field => !formData[field] && formData[field] !== 0);
    if (missingFields.length > 0) {
      console.error('缺少必填字段:', missingFields);
      message.error(`缺少必填字段: ${missingFields.join(', ')}`);
      return;
    }
    
    // 处理日期格式 - 转换为时间戳（秒）
    const submitData = {
      ...formData,
      birthday: formData.birthday ? Math.floor(formData.birthday.valueOf() / 1000) : null,
      weightCalculateTime: formData.weightCalculateTime ? Math.floor(formData.weightCalculateTime.valueOf() / 1000) : null
    }
    
    // 如果是新增操作，移除id字段
    if (!isEdit.value) {
      delete submitData.id
    }
    
    console.log('处理后的提交数据:', JSON.parse(JSON.stringify(submitData)));
    
    let response
    if (isEdit.value) {
      console.log('发送PUT请求到:', `/api/iot-cattle/${formData.id}`);
      response = await api.put(`/iot-cattle/${formData.id}`, submitData)
    } else {
      console.log('发送POST请求到:', '/api/iot-cattle');
      response = await api.post('/iot-cattle', submitData)
    }
    
    console.log('服务器响应:', response);
    
    if (response.success) {
      // 如果创建成功且有耳标号，尝试绑定耳标
      if (!isEdit.value && formData.earNumber) {
        await bindEarTag(formData.earNumber, response.data.id)
      }
      
      message.success(isEdit.value ? '更新牛只档案成功' : '创建牛只档案成功')
      modalVisible.value = false
      await fetchAnimals()
    } else {
      message.error(isEdit.value ? '更新牛只档案失败' : '创建牛只档案失败')
    }
  } catch (error) {
    console.error('提交牛只档案失败:', error)
    console.error('错误详情:', error.response?.data);
    message.error('操作失败')
  } finally {
    submitLoading.value = false
  }
}

// 取消操作
const handleCancel = () => {
  modalVisible.value = false
  resetForm()
}

// 重置表单（基于iot_cattle字段）
const resetForm = () => {
  Object.assign(formData, {
    id: null,
    earNumber: '',
    sex: 1,
    strain: '',
    varieties: '',
    cate: '',
    birthWeight: 0,
    birthday: null,
    penId: null,
    intoTime: null,
    parity: 0,
    source: '',
    sourceDay: 0,
    sourceWeight: 0,
    ageInMonths: 0,
    physiologicalStage: '',
    currentWeight: 0,
    weightCalculateTime: null,
    dayOfBirthday: 0,
    orgId: null,
    penId: null,
    batchId: null
  })
  showCustomTypeInput.value = false
  formRef.value?.resetFields()
  console.log('表单已重置')
}

// 获取健康状态颜色
const getHealthStatusColor = (status) => {
  const colors = {
    healthy: 'green',
    sick: 'red',
    quarantine: 'orange',
    treatment: 'blue'
  }
  return colors[status] || 'default'
}

// 获取健康状态文本
const getHealthStatusText = (status) => {
  const texts = {
    healthy: '健康',
    sick: '生病',
    quarantine: '隔离',
    treatment: '治疗中'
  }
  return texts[status] || status
}

// 获取农场名称
const getFarmName = (farmId) => {
  const farm = farms.value.find(f => f.id === farmId)
  return farm ? farm.name : `农场ID: ${farmId}`
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '-'
  return dayjs(date).format('YYYY-MM-DD')
}

// 监听搜索设备号输入
const handleSearchEarNumberInput = (e) => {
  console.log('搜索设备号输入变化:', e.target.value)
}

// 监听栏舍选择变化
const handleSearchPenChange = (value) => {
  console.log('栏舍选择变化:', value)
  if (value) {
    const selectedPen = pens.value.find(pen => pen.id === value)
    console.log('选中的栏舍信息:', selectedPen)
  }
}

// 搜索动物
const searchAnimals = async () => {
  try {
    searchLoading.value = true
    
    // 构建搜索参数
    const params = {
      page: 1,
      pageSize: 50
    }
    
    if (searchEarNumber.value.trim()) {
      params.search = searchEarNumber.value.trim()
    }
    
    if (searchPenId.value) {
      params.penId = searchPenId.value
    }
    
    // 如果没有任何搜索条件，提示用户
    if (!params.search && !params.penId) {
      message.warning('请输入牛只设备号或选择栏舍进行搜索')
      searchLoading.value = false
      return
    }
    
    console.log('发送搜索请求，参数:', params)
    
    const response = await api.get('/iot-cattle/public', {
      params: params
    })
    
    console.log('搜索响应数据:', response)
    
    if (response.success) {
      console.log('原始搜索结果数据:', response.data)
      
      // 格式化搜索结果以匹配前端表格结构
      const formattedResults = response.data.list.map((cattle, index) => ({
        key: `search-${index}`,
        id: cattle.id,
        // 确保字段名与表格列配置一致
        earNumber: cattle.earNumber || cattle.earTag, // 表格使用earNumber
        sex: cattle.sex, // 表格使用sex
        strain: cattle.strain, // 表格使用strain
        varieties: cattle.varieties, // 表格使用varieties
        cate: cattle.cate, // 表格使用cate
        birthWeight: cattle.birthWeight || 0, // 表格使用birthWeight
        ageInMonths: cattle.ageInMonths || 0, // 表格使用ageInMonths
        penName: cattle.penName || '未知栏舍', // 表格使用penName
        batchName: cattle.batchName || '未知批次', // 表格使用batchName
        // 以下是额外信息，不在表格中显示但可能有用
        farmName: cattle.farmName || '未知农场',
        source: cattle.source,
        intoTime: cattle.intoTime,
        currentWeight: cattle.currentWeight || 0
      }))
      
      console.log('格式化后的搜索结果:', formattedResults)
      
      animals.value = formattedResults
      isSearching.value = true
      message.success(response.message || `找到 ${formattedResults.length} 个匹配的动物`)
    } else {
      animals.value = []
      message.info('未找到匹配的动物')
    }
  } catch (error) {
    console.error('搜索动物失败:', error)
    message.error('搜索动物失败: ' + (error.message || '未知错误'))
    animals.value = []
  } finally {
    searchLoading.value = false
  }
}

// 导出动物数据
const exportAnimals = async () => {
  try {
    console.log('=== 开始导出动物数据 ===')
    
    exportLoading.value = true
    message.loading('正在获取所有动物数据...', 0)
    
    // 获取所有动物数据，不受分页限制
    const response = await api.get('/iot-cattle/public', {
      params: { 
        page: 1, 
        pageSize: 1000 // 获取大量数据
      }
    })
    
    if (!response.success || !response.data || !response.data.list) {
      message.destroy()
      message.warning('没有数据可导出')
      return
    }
    
    const allAnimals = response.data.list
    console.log('获取到所有动物数据:', allAnimals.length, '条记录')
    console.log('原始数据示例:', allAnimals[0])
    
    // 转换数据格式以匹配导出工具类的列配置
    const exportData = allAnimals.map(item => {
      return {
        id: item.id || item.key,
        ear_tag: item.earNumber || item.earTag || '',
        device_id: item.deviceId || '',
        birth_date: item.birthday ? (typeof item.birthday === 'number' ? new Date(item.birthday * 1000).toISOString().split('T')[0] : item.birthday) : (item.birthDate || ''),
        age_in_months: item.ageInMonths || 0,
        category: item.cate || item.category || '',
        breed: item.varieties || item.breed || '',
        physiological_stage: item.physiologicalStage || item.level || '',
        gender: item.sex === 1 ? '公' : item.sex === 2 ? '母' : '未知',
        birth_weight: item.birthWeight || 0,
        current_weight: item.currentWeight || item.weight || 0,
        generation: item.algebra || item.generation || '',
        bloodline_purity: item.descent || item.bloodlinePurity || '',
        entry_date: item.intoTime ? (typeof item.intoTime === 'number' ? new Date(item.intoTime * 1000).toISOString().split('T')[0] : item.intoTime) : (item.entryDate || ''),
        pen_name: item.penName || item.pen || '',
        calvings: item.parity || item.calvings || 0,
        source: item.source || '',
        frozen_semen_number: item.semenNum || item.frozenSemenNumber || ''
      }
    })
    
    console.log('转换后数据示例:', exportData[0])
    console.log('转换后数据总数:', exportData.length)
    
    message.destroy()
    message.loading('正在导出数据...', 0)
    
    const result = ExportUtils.exportCattleData(exportData)
    
    if (result.success) {
      message.destroy()
      message.success(`导出成功！文件：${result.filename}`)
    } else {
      message.destroy()
      message.error(result.message)
    }
  } catch (error) {
    message.destroy()
    console.error('导出失败:', error)
    message.error('导出失败，请重试')
  } finally {
    exportLoading.value = false
  }
}

// 导入动物数据
const importAnimals = () => {
  importModalVisible.value = true
}

// 处理文件选择
const handleFileChange = (info) => {
  const file = info.file
  if (file) {
    // 检查文件类型
    const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || 
                   file.type === 'application/vnd.ms-excel' ||
                   file.name.endsWith('.xlsx') || 
                   file.name.endsWith('.xls')
    
    if (!isExcel) {
      message.error('请选择Excel文件(.xlsx或.xls格式)')
      return
    }
    
    // 检查文件大小 (限制为10MB)
    const isLt10M = file.size / 1024 / 1024 < 10
    if (!isLt10M) {
      message.error('文件大小不能超过10MB')
      return
    }
    
    importFile.value = file
    message.success(`已选择文件: ${file.name}`)
  }
}

// 确认导入
const confirmImport = async () => {
  if (!importFile.value) {
    message.warning('请先选择要导入的文件')
    return
  }
  
  try {
    importLoading.value = true
    message.loading('正在导入数据...', 0)
    
    // 创建FormData
    const formData = new FormData()
    formData.append('file', importFile.value)
    
    // 调用导入API（FormData会自动处理Content-Type，不需要手动设置）
    const response = await api.post('/iot-cattle/import', formData)
    
    if (response.data.success) {
      message.destroy()
      message.success(`导入成功！共导入 ${response.data.importedCount} 条记录`)
      
      // 关闭模态框并刷新数据
      importModalVisible.value = false
      importFile.value = null
      await fetchAnimals()
    } else {
      message.destroy()
      message.error(response.data.message || '导入失败')
    }
  } catch (error) {
    message.destroy()
    console.error('导入失败:', error)
    // 显示具体的错误信息
    const errorMessage = error.message || error.response?.data?.message || '导入失败，请检查文件格式是否正确'
    message.error(errorMessage)
    
    // 如果是认证错误，提示用户重新登录
    if (errorMessage.includes('认证') || errorMessage.includes('未授权') || errorMessage.includes('登录')) {
      setTimeout(() => {
        window.location.href = '/login'
      }, 2000)
    }
  } finally {
    importLoading.value = false
  }
}

// 取消导入
const cancelImport = () => {
  importModalVisible.value = false
  importFile.value = null
}

// 下载导入模板
const downloadTemplate = async () => {
  try {
    templateLoading.value = true
    message.loading('正在生成模板文件...', 0)
    
    // 调用后端API下载模板
    const response = await api.get('/iot-cattle/public/import/template', {
      responseType: 'blob' // 重要：设置响应类型为blob
    })
    
    // 创建下载链接
    const blob = new Blob([response], { 
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
    })
    const url = window.URL.createObjectURL(blob)
    
    // 创建临时下载链接
    const link = document.createElement('a')
    link.href = url
    link.download = '牛只档案导入模板.xlsx'
    document.body.appendChild(link)
    link.click()
    
    // 清理
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    message.destroy()
    message.success('模板下载成功')
    
  } catch (error) {
    message.destroy()
    console.error('下载模板失败:', error)
    message.error('下载模板失败，请重试')
  } finally {
    templateLoading.value = false
  }
}

// 重置搜索
const resetSearch = () => {
  console.log('重置搜索条件')
  searchEarNumber.value = ''
  searchPenId.value = null
  isSearching.value = false
  fetchAnimals() // 重新加载全部动物
}

// 分页变化处理
const handleTableChange = (pag) => {
  console.log('分页变化:', pag)
  pagination.value.current = pag.current
  pagination.value.pageSize = pag.pageSize
  fetchAnimals(pag.current, pag.pageSize)
}

// 组件挂载时获取数据
onMounted(() => {
  console.log('=== 组件挂载，开始加载数据 ===')
  fetchAnimals()
  fetchFarms()
  fetchPens()
  fetchBatches()
  fetchCattleUsers()
  fetchCattleTypes()
})
</script>

<style scoped>
/* 可以添加自定义样式 */
</style>