<template>
  <div class="smart-eartag-container">
    <!-- 页面标题 -->
    <!-- <div class="page-header">
      <h2>智能耳标管理</h2>
      <p>实时监控耳标设备状态和动物健康数据</p>
    </div> -->

    <!-- 搜索栏 -->
    <div class="search-bar">
      <div class="search-group">
        <a-input
          :value="searchValue"
          @input="updateSearchValue"
          placeholder="请输入耳标编号"
          class="search-input"
          @pressEnter="handleSearch"
        />
        <a-button type="primary" class="search-button" @click="handleSearch">
          <template #icon>
            <SearchOutlined />
          </template>
          搜索
        </a-button>
        <a-button class="search-button" @click="handleClearSearch" v-if="searchValue.trim()">
          清除
        </a-button>
      </div>
      <a-button @click="exportData" class="export-button">
        <template #icon>
          <ExportOutlined />
        </template>
        导出数据
      </a-button>
    </div>

    <!-- 设备列表 -->
    <div class="device-list">
      <a-table
        :columns="columns"
        :data-source="deviceList"
        :pagination="pagination"
        :loading="loading"
        :row-key="record => record.id"
        :row-class-name="getRowClassName"
        @change="handleTableChange"
        size="middle"
        bordered
      >
        <!-- 耳标编号列 -->
        <template #eartagNumber="{ record }">
          <div class="eartag-number">
            <a-tag color="pink" size="small">{{ record.eartagNumber }}</a-tag>
          </div>
        </template>

        <!-- 设备电量列 -->
        <template #battery="{ record }">
          <div class="battery-info">
            <a-progress 
              :percent="record.battery" 
              :status="record.battery < 20 ? 'exception' : record.battery < 50 ? 'active' : 'success'"
              size="small"
              :show-info="false"
            />
            <span class="battery-text">{{ record.battery }}%</span>
          </div>
        </template>

        <!-- 设备温度列 -->
        <template #temperature="{ record }">
          <div class="temperature-info">
            <a-tag :color="getTemperatureColor(record.temperature)">
              {{ record.temperature }}°C
            </a-tag>
          </div>
        </template>

        <!-- 被采集主机列 -->
        <template #collectedHost="{ record }">
          <div class="host-info">
            <a-tag color="blue">{{ record.collectedHost }}</a-tag>
          </div>
        </template>

        <!-- 总运动量列 -->
        <template #totalMovement="{ record }">
          <div class="movement-info">
            <a-statistic 
              :value="record.totalMovement" 
              :value-style="{ fontSize: '14px', color: '#1890ff' }"
            />
          </div>
        </template>

        <!-- 当日运动量列 -->
        <template #dailyMovement="{ record }">
          <div class="movement-info">
            <a-statistic 
              :value="record.dailyMovement" 
              :value-style="{ fontSize: '14px', color: '#52c41a' }"
            />
          </div>
        </template>

        <!-- 定位信息列 -->
        <template #location="{ record }">
          <div class="location-info">
            <a-button 
              type="link" 
              size="small"
              @click="showLocation(record)"
              :disabled="!record.lat || !record.lon || record.lat === '0' || record.lon === '0'"
            >
              <template #icon>
                <EnvironmentOutlined />
              </template>
              {{ record.location }}
            </a-button>
          </div>
        </template>

        <!-- 数据最后更新时间列 -->
        <template #lastUpdate="{ record }">
          <div class="update-time">
            <a-tag color="default">{{ record.lastUpdate }}</a-tag>
          </div>
        </template>

        <!-- 绑定牲畜列 -->
        <template #bindingStatus="{ record }">
          <div class="binding-status">
            <a-tag 
              :color="record.bindingStatus === '已绑定' ? 'green' : 'default'"
              size="small"
            >
              {{ record.bindingStatus }}
            </a-tag>
          </div>
        </template>

        <!-- 设备状态列 -->
        <template #deviceStatus="{ record }">
          <div class="device-status">
            <a-tag 
              :color="getStatusColor(record.deviceStatus)"
              size="small"
            >
              {{ record.deviceStatus }}
            </a-tag>
          </div>
        </template>

        <!-- 操作列 -->
        <template #action="{ record }">
          <div class="action-buttons">
            <!-- <a-button type="link" size="small" @click="bindLivestock(record)">
              绑定牲畜
            </a-button> -->
            <a-button type="link" size="small" @click="showQRCode(record)">
              溯源二维码
            </a-button>
            <a-button type="link" size="small" @click="showBindingInfo(record)">
              绑定信息
            </a-button>
            <!-- <a-button type="link" size="small" @click="showLog(record)">
              日志
            </a-button> -->
          </div>
        </template>
      </a-table>
    </div>

    <!-- 定位信息模态框 -->
    <a-modal
      :open="locationVisible"
      title="耳标定位信息"
      width="800px"
      :footer="null"
      @cancel="handleLocationCancel"
    >
      <div class="location-modal">
        <div class="location-info-panel">
          <a-descriptions :column="2" bordered>
            <a-descriptions-item label="耳标编号">
              {{ currentLocationData?.eartagNumber }}
            </a-descriptions-item>
            <a-descriptions-item label="设备状态">
              <a-tag :color="getStatusColor(currentLocationData?.deviceStatus)">
                {{ currentLocationData?.deviceStatus }}
              </a-tag>
            </a-descriptions-item>
            <a-descriptions-item label="经度">
              {{ currentLocationData?.lon }}
            </a-descriptions-item>
            <a-descriptions-item label="纬度">
              {{ currentLocationData?.lat }}
            </a-descriptions-item>
            <a-descriptions-item label="GPS状态">
              <a-tag :color="currentLocationData?.gps_state === 'A' ? 'green' : 'red'">
                {{ currentLocationData?.gps_state === 'A' ? '有效' : '无效' }}
              </a-tag>
            </a-descriptions-item>
            <a-descriptions-item label="最后更新时间">
              {{ currentLocationData?.lastUpdate }}
            </a-descriptions-item>
          </a-descriptions>
        </div>
        
        <div class="map-container">
          <div class="map-controls">
            <a-radio-group v-model="mapType" @change="handleMapTypeChange">
              <a-radio-button value="map">地图</a-radio-button>
              <a-radio-button value="hybrid">混合</a-radio-button>
            </a-radio-group>
          </div>
          <div id="baidu-map" class="baidu-map"></div>
        </div>
      </div>
    </a-modal>

    <!-- 溯源二维码模态框 -->
    <a-modal
      :open="qrcodeVisible"
      title="溯源二维码"
      :footer="null"
      width="450px"
      @cancel="handleQRCodeCancel"
    >
      <div class="qrcode-modal-content">
        <div class="qrcode-container">
          <img v-if="qrcodeUrl" :src="qrcodeUrl" alt="溯源二维码" class="qrcode-image" />
        </div>
        <div class="device-sn-display">
          {{ currentDeviceSn }}
        </div>
      </div>
    </a-modal>

    <!-- 绑定信息模态框 -->
    <a-modal
      :open="bindInfoVisible"
      title="绑定信息"
      width="800px"
      :footer="null"
      @cancel="handleBindingInfoCancel"
    >
      <div v-if="!bindInfoData.basicInfo?.collarNumber || bindInfoData.basicInfo?.collarNumber === '-'" class="unbound-notice">
        <a-alert
          message="该耳标尚未绑定动物"
          description="当前耳标编号未与任何动物建立绑定关系，如需绑定请联系管理员。"
          type="info"
          show-icon
          style="margin-bottom: 20px;"
        />
      </div>
      
      <div v-else class="binding-info-content">
        <a-tabs v-model="activeTab" type="card">
          <a-tab-pane key="basic" tab="基本信息">
            <a-descriptions :column="2" bordered>
              <a-descriptions-item label="耳标编号">{{ bindInfoData.basicInfo?.collarNumber || bindInfoData.basicInfo?.earTag }}</a-descriptions-item>
              <a-descriptions-item label="动物类型">{{ bindInfoData.basicInfo?.animalType }}</a-descriptions-item>
              <a-descriptions-item label="品种">{{ bindInfoData.basicInfo?.breed }}</a-descriptions-item>
              <a-descriptions-item label="类别">{{ bindInfoData.basicInfo?.category }}</a-descriptions-item>
              <a-descriptions-item label="产犊次数">{{ bindInfoData.basicInfo?.calvingCount }}</a-descriptions-item>
              <a-descriptions-item label="来源类型">{{ bindInfoData.basicInfo?.sourceType }}</a-descriptions-item>
            </a-descriptions>
          </a-tab-pane>
          
          <a-tab-pane key="birth" tab="出生信息">
            <a-descriptions :column="2" bordered>
              <a-descriptions-item label="出生日期">{{ bindInfoData.birthInfo?.birthDate }}</a-descriptions-item>
              <a-descriptions-item label="出生体重">{{ bindInfoData.birthInfo?.birthWeight }}kg</a-descriptions-item>
              <a-descriptions-item label="断奶体重">{{ bindInfoData.birthInfo?.weaningWeight }}kg</a-descriptions-item>
              <a-descriptions-item label="入栏日期">{{ bindInfoData.birthInfo?.entryDate }}</a-descriptions-item>
              <a-descriptions-item label="断奶日龄">{{ bindInfoData.birthInfo?.weaningAge }}天</a-descriptions-item>
              <a-descriptions-item label="左乳头数">{{ bindInfoData.birthInfo?.leftTeatCount }}</a-descriptions-item>
              <a-descriptions-item label="右乳头数">{{ bindInfoData.birthInfo?.rightTeatCount }}</a-descriptions-item>
            </a-descriptions>
          </a-tab-pane>
          
          <a-tab-pane key="pedigree" tab="系谱信息">
            <a-descriptions :column="2" bordered>
              <a-descriptions-item label="父畜编号">{{ bindInfoData.pedigreeInfo?.fatherId }}</a-descriptions-item>
              <a-descriptions-item label="母畜编号">{{ bindInfoData.pedigreeInfo?.motherId }}</a-descriptions-item>
              <a-descriptions-item label="祖父编号">{{ bindInfoData.pedigreeInfo?.grandfatherId }}</a-descriptions-item>
              <a-descriptions-item label="祖母编号">{{ bindInfoData.pedigreeInfo?.grandmotherId }}</a-descriptions-item>
              <a-descriptions-item label="血统">{{ bindInfoData.pedigreeInfo?.bloodline }}</a-descriptions-item>
              <a-descriptions-item label="代数">{{ bindInfoData.pedigreeInfo?.generation }}</a-descriptions-item>
            </a-descriptions>
          </a-tab-pane>
          
          <a-tab-pane key="device" tab="设备信息">
            <a-descriptions :column="2" bordered>
              <a-descriptions-item label="设备ID">{{ bindInfoData.deviceInfo?.deviceId }}</a-descriptions-item>
              <a-descriptions-item label="电量">{{ bindInfoData.deviceInfo?.batteryLevel }}%</a-descriptions-item>
              <a-descriptions-item label="温度">{{ bindInfoData.deviceInfo?.temperature }}°C</a-descriptions-item>
              <a-descriptions-item label="状态">
                <span :class="bindInfoData.deviceInfo?.status === '在线' ? 'device-online' : 'device-offline'">
                  {{ bindInfoData.deviceInfo?.status }}
                </span>
              </a-descriptions-item>
              <a-descriptions-item label="最后更新">{{ bindInfoData.deviceInfo?.lastUpdate }}</a-descriptions-item>
              <a-descriptions-item label="位置">{{ bindInfoData.deviceInfo?.location }}</a-descriptions-item>
            </a-descriptions>
          </a-tab-pane>
          
          <a-tab-pane key="farm" tab="农场信息">
            <a-descriptions :column="2" bordered>
              <a-descriptions-item label="农场名称">{{ bindInfoData.farmInfo?.farmName }}</a-descriptions-item>
              <a-descriptions-item label="农场地址">{{ bindInfoData.farmInfo?.farmAddress }}</a-descriptions-item>
              <a-descriptions-item label="栏舍名称">{{ bindInfoData.farmInfo?.penName }}</a-descriptions-item>
              <a-descriptions-item label="批次名称">{{ bindInfoData.farmInfo?.batchName }}</a-descriptions-item>
            </a-descriptions>
          </a-tab-pane>
          
          <a-tab-pane key="insurance" tab="保险信息">
            <a-descriptions :column="2" bordered>
              <a-descriptions-item label="保险公司">{{ bindInfoData.insuranceInfo?.company }}</a-descriptions-item>
              <a-descriptions-item label="保单号">{{ bindInfoData.insuranceInfo?.policyNumber }}</a-descriptions-item>
              <a-descriptions-item label="保险金额">{{ bindInfoData.insuranceInfo?.amount }}元</a-descriptions-item>
              <a-descriptions-item label="保险期限">{{ bindInfoData.insuranceInfo?.period }}</a-descriptions-item>
              <a-descriptions-item label="状态">
                <span :class="bindInfoData.insuranceInfo?.status === '有效' ? 'status-valid' : 'status-invalid'">
                  {{ bindInfoData.insuranceInfo?.status }}
                </span>
              </a-descriptions-item>
            </a-descriptions>
          </a-tab-pane>
          
          <a-tab-pane key="loan" tab="贷款信息">
            <a-descriptions :column="2" bordered>
              <a-descriptions-item label="贷款银行">{{ bindInfoData.loanInfo?.bank }}</a-descriptions-item>
              <a-descriptions-item label="贷款金额">{{ bindInfoData.loanInfo?.amount }}元</a-descriptions-item>
              <a-descriptions-item label="贷款期限">{{ bindInfoData.loanInfo?.period }}</a-descriptions-item>
              <a-descriptions-item label="贷款利率">{{ bindInfoData.loanInfo?.rate }}%</a-descriptions-item>
              <a-descriptions-item label="状态">
                <span :class="bindInfoData.loanInfo?.status === '正常' ? 'status-normal' : 'status-no-loan'">
                  {{ bindInfoData.loanInfo?.status }}
                </span>
              </a-descriptions-item>
            </a-descriptions>
          </a-tab-pane>
        </a-tabs>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, nextTick } from 'vue'
import { message } from 'ant-design-vue'
import { EnvironmentOutlined, SearchOutlined, ExportOutlined } from '@ant-design/icons-vue'
import { api, directApi } from '../utils/api'
import { ExportUtils } from '../utils/exportUtils'
import { formatBindingInfo } from '../utils/fieldMappings'
import QRCode from 'qrcode'

// 响应式数据
const loading = ref(false)
const deviceList = ref([])
const searchValue = ref('')
const searchResult = ref(null)
const searchLoading = ref(false)
const highlightedEartagId = ref(null)
const locationVisible = ref(false)
const currentLocationData = ref(null)
const mapType = ref('map')
const bindInfoVisible = ref(false)
const bindInfoData = ref({
  basicInfo: {
    collarNumber: '',
    animalType: '',
    breed: '',
    category: '',
    calvingCount: '',
    sourceType: ''
  }
})
const activeTab = ref('basic')
const currentEartagNumber = ref('')

// 二维码相关数据
const qrcodeVisible = ref(false)
const qrcodeUrl = ref('')
const currentDeviceSn = ref('')

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

// 表格行样式类名
const getRowClassName = (record, index) => {
  // 可以根据需要添加不同的行样式
  if (record.battery < 20) {
    return 'low-battery-row'
  }
  if (record.temperature > 40 || record.temperature < 35) {
    return 'abnormal-temp-row'
  }
  return ''
}

// 表格列配置
const columns = [
  {
    title: '',
    dataIndex: 'checkbox',
    width: 50,
    // customRender: () => '<input type="checkbox">'
  },
  {
    title: '耳标编号',
    dataIndex: 'eartagNumber',
    key: 'eartagNumber',
    width: 120,
    slots: { customRender: 'eartagNumber' },
    sorter: true
  },
  {
    title: '设备电量/%',
    dataIndex: 'battery',
    key: 'battery',
    width: 120,
    slots: { customRender: 'battery' },
    sorter: true
  },
  {
    title: '设备温度/°C',
    dataIndex: 'temperature',
    key: 'temperature',
    width: 120,
    slots: { customRender: 'temperature' },
    sorter: true
  },
  {
    title: '被采集主机',
    dataIndex: 'collectedHost',
    key: 'collectedHost',
    width: 120,
    slots: { customRender: 'collectedHost' }
  },
  {
    title: '总运动量',
    dataIndex: 'totalMovement',
    key: 'totalMovement',
    width: 120,
    slots: { customRender: 'totalMovement' },
    sorter: true
  },
  {
    title: '当日运动量',
    dataIndex: 'dailyMovement',
    key: 'dailyMovement',
    width: 120,
    slots: { customRender: 'dailyMovement' },
    sorter: true
  },
  {
    title: '定位信息',
    dataIndex: 'location',
    key: 'location',
    width: 100,
    slots: { customRender: 'location' }
  },
  {
    title: '数据最后更新时间',
    dataIndex: 'lastUpdate',
    key: 'lastUpdate',
    width: 180,
    slots: { customRender: 'lastUpdate' },
    sorter: true
  },
  {
    title: '绑定牲畜',
    dataIndex: 'bindingStatus',
    key: 'bindingStatus',
    width: 100,
    slots: { customRender: 'bindingStatus' }
  },
  {
    title: '设备状态',
    dataIndex: 'deviceStatus',
    key: 'deviceStatus',
    width: 100,
    slots: { customRender: 'deviceStatus' }
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    slots: { customRender: 'action' }
  }
]

// 百度地图实例
let map = null
let marker = null

// 获取数据
const fetchData = async (showMessage = false) => {
  try {
    loading.value = true
    
    // 构建查询参数
    const params = new URLSearchParams({
      page: pagination.current.toString(),
      limit: pagination.pageSize.toString(),
      _t: Date.now().toString(), // 防止缓存
      refresh: 'true'
    })
    
    // 如果有搜索条件，添加到参数中
    if (searchValue.value.trim()) {
      params.append('search', searchValue.value.trim())
      console.log('搜索条件:', searchValue.value.trim())
    }
    
    // 调用API获取智能耳标数据
    const apiUrl = `/smart-devices/eartags?${params}`
    console.log('API请求URL:', apiUrl)
    
    const result = await api.get(apiUrl)
    
    if (result.success) {
      deviceList.value = result.data || []
      pagination.total = result.total || 0
      
      if (showMessage) {
        if (searchValue.value.trim()) {
          message.success(`搜索完成，找到 ${result.data.length} 条记录`)
        } else {
          message.success(`数据加载成功，共 ${result.total} 条记录`)
        }
      }
    } else {
      message.error(result.message || '获取数据失败')
    }
  } catch (error) {
    console.error('获取数据失败:', error)
    message.error('获取数据失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 更新搜索值
const updateSearchValue = (e) => {
  searchValue.value = e.target.value
}

// 搜索功能
const handleSearch = () => {
  console.log('执行搜索，当前搜索值:', searchValue.value)
  pagination.current = 1
  fetchData(true)
}

// 清除搜索
const handleClearSearch = () => {
  searchValue.value = ''
  pagination.current = 1
  fetchData(true)
}

// 表格变化处理
const handleTableChange = (pag, filters, sorter) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  fetchData(false)
}

// 获取温度颜色
const getTemperatureColor = (temperature) => {
  const temp = parseFloat(temperature)
  if (temp < 35) return 'blue'
  if (temp > 40) return 'red'
  return 'green'
}

// 获取状态颜色
const getStatusColor = (status) => {
  const colorMap = {
    '在线': 'green',
    '离线': 'red',
    '报警': 'orange',
    '维护': 'blue'
  }
  return colorMap[status] || 'default'
}

// 显示定位信息
const showLocation = async (record) => {
  console.log('显示定位信息，记录:', record)
  currentLocationData.value = record
  locationVisible.value = true
  
  console.log('模态框状态设置为true，locationVisible:', locationVisible.value)
  
  // 等待Vue的响应式更新完成
  await nextTick()
  console.log('nextTick完成，检查模态框DOM...')
  
  // 检查模态框是否真的显示了
  const modal = document.querySelector('.ant-modal')
  console.log('模态框元素:', modal)
  
  // 延迟初始化地图，确保模态框已显示且DOM已渲染
  setTimeout(() => {
    console.log('开始初始化地图...')
    initBaiduMap()
  }, 300)
}

// 取消定位信息
const handleLocationCancel = () => {
  locationVisible.value = false
  currentLocationData.value = null
  if (map) {
    map = null
  }
  if (marker) {
    marker = null
  }
}

// 初始化百度地图
const initBaiduMap = async () => {
  try {
    console.log('开始初始化百度地图...')
    
    const { lat, lon } = currentLocationData.value
    if (!lat || !lon || lat === '0' || lon === '0') {
      message.warning('该设备无有效定位信息')
      return
    }
    
    // 等待地图容器出现
    const waitForContainer = () => {
      return new Promise((resolve, reject) => {
        let attempts = 0
        const maxAttempts = 30 // 最多等待3秒
        
        const checkContainer = () => {
          const container = document.getElementById('baidu-map')
          console.log(`检查容器 (${attempts + 1}/${maxAttempts}):`, container)
          
          if (container) {
            // 检查容器是否可见且有尺寸
            const rect = container.getBoundingClientRect()
            const isVisible = rect.width > 0 && rect.height > 0
            console.log('容器尺寸:', rect.width, 'x', rect.height, '可见:', isVisible)
            
            if (isVisible) {
              console.log('地图容器找到且可见:', container)
              resolve(container)
            } else if (attempts < maxAttempts) {
              attempts++
              console.log(`容器存在但不可见，继续等待... (${attempts}/${maxAttempts})`)
              setTimeout(checkContainer, 100)
            } else {
              reject(new Error('地图容器存在但不可见，请检查模态框显示状态'))
            }
          } else if (attempts < maxAttempts) {
            attempts++
            console.log(`等待地图容器... (${attempts}/${maxAttempts})`)
            setTimeout(checkContainer, 100)
          } else {
            reject(new Error('地图容器未找到，请确保模态框已正确显示'))
          }
        }
        
        checkContainer()
      })
    }
    
    // 等待容器出现
    await waitForContainer()
    
    // 使用新的地图加载器
    const { createBaiduMap } = await import('../utils/baiduMapLoader')
    
    // 创建地图实例
    map = await createBaiduMap('baidu-map', {
      center: new window.BMap.Point(parseFloat(lon), parseFloat(lat)),
      zoom: 15
    })
    
    console.log('地图实例创建成功:', map)
    
    // 设置中心点
    const point = new window.BMap.Point(parseFloat(lon), parseFloat(lat))
    map.centerAndZoom(point, 15)
    console.log('地图中心点设置完成:', point)
    
    // 添加标记
    marker = new window.BMap.Marker(point)
    map.addOverlay(marker)
    console.log('标记添加完成')
    
    // 添加信息窗口
    const infoWindow = new window.BMap.InfoWindow(`
      <div style="padding: 10px; min-width: 200px;">
        <h4 style="margin: 0 0 10px 0; color: #1890ff;">耳标设备位置</h4>
        <p style="margin: 5px 0;"><strong>耳标编号:</strong> ${currentLocationData.value.eartagNumber}</p>
        <p style="margin: 5px 0;"><strong>经度:</strong> ${lon}</p>
        <p style="margin: 5px 0;"><strong>纬度:</strong> ${lat}</p>
        <p style="margin: 5px 0;"><strong>设备状态:</strong> ${currentLocationData.value.deviceStatus}</p>
        <p style="margin: 5px 0;"><strong>更新时间:</strong> ${currentLocationData.value.lastUpdate}</p>
      </div>
    `)
    
    marker.addEventListener('click', () => {
      map.openInfoWindow(infoWindow, point)
    })
    
    // 设置地图类型
    handleMapTypeChange()
    
    console.log('百度地图初始化完成')
    
  } catch (error) {
    console.error('初始化百度地图失败:', error)
    message.error('地图初始化失败: ' + error.message)
    
    // 如果是容器问题，尝试重新显示模态框
    if (error.message.includes('地图容器')) {
      console.log('尝试重新显示模态框...')
      setTimeout(() => {
        showLocation(currentLocationData.value)
      }, 1000)
      return
    }
    
    // 尝试重试
    try {
      const { retryLoadBaiduMapAPI } = await import('../utils/baiduMapLoader')
      await retryLoadBaiduMapAPI()
      console.log('重试加载百度地图API成功，重新初始化地图...')
      // 重新初始化地图
      setTimeout(() => {
        initBaiduMap()
      }, 1000)
    } catch (retryError) {
      console.error('重试加载百度地图API失败:', retryError)
    }
  }
}

// 地图类型切换
const handleMapTypeChange = () => {
  if (!map) return
  
  try {
    if (mapType.value === 'hybrid') {
      // 混合地图（卫星图+路网）
      map.setMapType(window.BMAP_HYBRID_MAP)
    } else {
      // 普通地图
      map.setMapType(window.BMAP_NORMAL_MAP)
    }
  } catch (error) {
    console.error('地图类型切换失败:', error)
  }
}

// 绑定牲畜
const bindLivestock = (record) => {
  message.info('绑定牲畜功能开发中...')
}

// 显示溯源二维码
const showQRCode = async (record) => {
  try {
    const deviceSn = record.eartagNumber
    if (!deviceSn) {
      message.warning('设备编号不存在')
      return
    }
    
    currentDeviceSn.value = deviceSn
    const traceUrl = `https://farm.aiotagro.com/source/source-index.html?device_sn=${deviceSn}`
    
    // 生成二维码
    const qrCodeDataUrl = await QRCode.toDataURL(traceUrl, {
      width: 250,
      margin: 2
    })
    
    qrcodeUrl.value = qrCodeDataUrl
    qrcodeVisible.value = true
  } catch (error) {
    console.error('生成二维码失败:', error)
    message.error('生成二维码失败，请重试')
  }
}

// 关闭绑定信息模态框
const handleBindingInfoCancel = () => {
  bindInfoVisible.value = false
  bindInfoData.value = {
    basicInfo: {
      collarNumber: '',
      animalType: '',
      breed: '',
      category: '',
      calvingCount: '',
      sourceType: ''
    }
  }
  activeTab.value = 'basic'
}

// 关闭二维码模态框
const handleQRCodeCancel = () => {
  qrcodeVisible.value = false
  qrcodeUrl.value = ''
  currentDeviceSn.value = ''
}

// 显示绑定信息
const showBindingInfo = async (record) => {
  try {
    console.log('显示绑定信息，记录:', record)
    currentEartagNumber.value = record.eartagNumber
    bindInfoVisible.value = true
    console.log('模态框状态设置为true，bindInfoVisible:', bindInfoVisible.value)
    
    const bindInfo = await getBindInfo(record.eartagNumber)
    console.log('获取到的绑定信息:', bindInfo)
    bindInfoData.value = bindInfo
    console.log('绑定信息数据已设置:', bindInfoData.value)
    message.success('绑定信息加载成功')
  } catch (error) {
    console.error('获取绑定信息失败:', error)
    if (error.message.includes('未绑定动物')) {
      message.warning('该耳标尚未绑定动物')
      bindInfoData.value = {
        basicInfo: { 
          collarNumber: '-', 
          animalType: '-', 
          breed: '-', 
          category: '-', 
          calvingCount: '-', 
          sourceType: '-' 
        },
        birthInfo: { 
          birthDate: '-', 
          birthWeight: '-', 
          weaningWeight: '-', 
          entryDate: '-', 
          weaningAge: '-', 
          leftTeatCount: '-', 
          rightTeatCount: '-' 
        },
        pedigreeInfo: { 
          fatherId: '-', 
          motherId: '-', 
          grandfatherId: '-', 
          grandmotherId: '-', 
          bloodline: '-', 
          generation: '-' 
        },
        deviceInfo: { 
          deviceId: '-', 
          batteryLevel: '-', 
          temperature: '-', 
          status: '-', 
          lastUpdate: '-', 
          location: '-' 
        },
        farmInfo: { 
          farmName: '-', 
          farmAddress: '-', 
          penName: '-', 
          batchName: '-' 
        },
        insuranceInfo: { 
          company: '-', 
          policyNumber: '-', 
          amount: '-', 
          period: '-', 
          status: '-' 
        },
        loanInfo: { 
          bank: '-', 
          amount: '-', 
          period: '-', 
          rate: '-', 
          status: '-' 
        }
      }
    } else {
      message.error('获取绑定信息失败: ' + error.message)
      bindInfoVisible.value = false
    }
  }
}

// 获取绑定信息
const getBindInfo = async (eartagNumber) => {
  try {
    const result = await api.get(`/animals/binding-info/${eartagNumber}`)
    
    if (result.success) {
      // 如果后端返回的数据没有basicInfo，则使用前端的formatBindingInfo函数进行格式化
      if (result.data && result.data.cattle && !result.data.basicInfo) {
        return formatBindingInfo(result.data.cattle, result.data.device)
      }
      // 后端已经返回格式化好的数据，直接使用
      return result.data
    } else {
      if (result.message && result.message.includes('未找到')) {
        throw new Error('该耳标未绑定动物，暂无绑定信息')
      }
      throw new Error(result.message || '获取绑定信息失败')
    }
  } catch (error) {
    console.error('获取绑定信息失败:', error)
    throw error
  }
}

// 显示日志
const showLog = (record) => {
  message.info('日志功能开发中...')
}

// 导出数据
const exportData = async () => {
  try {
    console.log('=== 开始导出智能耳标数据 ===')
    
    message.loading('正在获取所有设备数据...', 0)
    
    // 构建查询参数，获取所有数据
    const params = new URLSearchParams({
      page: '1',
      limit: '10000', // 设置一个很大的限制值来获取所有数据
      _t: Date.now().toString()
    })
    
    // 如果有搜索条件，添加到参数中
    if (searchValue.value.trim()) {
      params.append('search', searchValue.value.trim())
      console.log('导出搜索条件:', searchValue.value.trim())
    }
    
    // 调用专门的导出API获取所有智能耳标数据
    const apiUrl = `/smart-devices/public/eartags/export?${params}`
    console.log('导出API请求URL:', apiUrl)
    
    const result = await api.get(apiUrl)
    
    if (!result.success || !result.data || result.data.length === 0) {
      message.destroy()
      message.warning('没有数据可导出')
      return
    }
    
    const allDevices = result.data || []
    console.log('获取到所有设备数据:', allDevices.length, '条记录')
    console.log('原始数据示例:', allDevices[0])
    
    // 后端已经处理了大部分格式化，直接使用
    const exportData = allDevices
    
    console.log('导出设备数据示例:', exportData[0])
    console.log('导出设备数据总数:', exportData.length)
    
    message.destroy()
    message.loading('正在导出数据...', 0)
    
    const result_export = ExportUtils.exportDeviceData(exportData, 'eartag')
    
    if (result_export.success) {
      message.destroy()
      message.success(`导出成功！文件：${result_export.filename}`)
    } else {
      message.destroy()
      message.error(result_export.message)
    }
  } catch (error) {
    message.destroy()
    console.error('导出失败:', error)
    message.error('导出失败，请重试')
  }
}

// 组件挂载
onMounted(() => {
  fetchData(true)
  
  // 加载百度地图API
  loadBaiduMapAPI()
})

// 加载百度地图API
const loadBaiduMapAPI = async () => {
  try {
    console.log('开始加载百度地图API...')
    const { loadBaiduMapAPI: loadAPI } = await import('../utils/baiduMapLoader')
    await loadAPI()
    console.log('百度地图API加载完成')
  } catch (error) {
    console.error('百度地图API加载失败:', error)
    message.error('地图服务加载失败，定位功能可能不可用')
    throw error
  }
}

// 组件卸载
onUnmounted(() => {
  if (map) {
    map = null
  }
  if (marker) {
    marker = null
  }
})
</script>

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

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

.page-header h2 {
  color: #1890ff;
  margin-bottom: 8px;
}

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

.search-group {
  display: flex;
  align-items: center;
  gap: 12px;
}

.search-input {
  width: 300px;
}

.search-button {
  margin-left: 0;
}

.export-button {
  margin-left: 16px;
}

.device-list {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.eartag-number {
  text-align: center;
}

.battery-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.battery-text {
  font-size: 12px;
  color: #666;
  min-width: 35px;
}

.temperature-info {
  text-align: center;
}

.host-info {
  text-align: center;
}

.movement-info {
  text-align: center;
}

.location-info {
  text-align: center;
}

.update-time {
  text-align: center;
  font-size: 12px;
}

.binding-status {
  text-align: center;
}

.device-status {
  text-align: center;
}

.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.action-buttons .ant-btn {
  padding: 0;
  height: auto;
  line-height: 1.2;
}

.highlighted-row {
  background-color: #fff7e6 !important;
  animation: highlight-pulse 2s ease-in-out;
}

@keyframes highlight-pulse {
  0% { background-color: #fff7e6; }
  50% { background-color: #ffd591; }
  100% { background-color: #fff7e6; }
}

.location-modal {
  padding: 16px 0;
}

.location-info-panel {
  margin-bottom: 24px;
}

.map-container {
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  overflow: hidden;
}

.map-controls {
  padding: 12px;
  background: #fafafa;
  border-bottom: 1px solid #d9d9d9;
}

.baidu-map {
  width: 100%;
  height: 400px;
}

.unbound-notice {
  text-align: center;
  padding: 20px;
}

.binding-info-content {
  padding: 16px 0;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .smart-eartag-container {
    padding: 16px;
  }
  
  .action-buttons {
    flex-direction: row;
    flex-wrap: wrap;
  }
  
  .action-buttons .ant-btn {
    flex: 1;
    min-width: 60px;
  }
}

/* 表格行样式 */
.low-battery-row {
  background-color: #fff2e8 !important;
}

.low-battery-row:hover {
  background-color: #ffe7ba !important;
}

.abnormal-temp-row {
  background-color: #fff1f0 !important;
}

.abnormal-temp-row:hover {
  background-color: #ffccc7 !important;
}

/* 绑定信息模态框样式 */
.binding-info-content {
  max-height: 600px;
  overflow-y: auto;
}

.binding-info-content .ant-tabs-content-holder {
  padding: 16px 0;
}

.binding-info-content .ant-descriptions {
  margin-bottom: 0;
}

.binding-info-content .ant-descriptions-item-label {
  font-weight: 500;
  color: #666;
  width: 120px;
}

.binding-info-content .ant-descriptions-item-content {
  color: #333;
}

.unbound-notice {
  text-align: center;
  padding: 20px 0;
}

.unbound-notice .ant-alert {
  border-radius: 8px;
}

/* 设备状态样式 */
.device-online {
  color: #52c41a;
  font-weight: 500;
}

.device-offline {
  color: #ff4d4f;
  font-weight: 500;
}

/* 农场信息样式 */
.farm-info-item {
  margin-bottom: 8px;
}

.farm-info-item:last-child {
  margin-bottom: 0;
}

/* 保险和贷款状态样式 */
.status-valid {
  color: #52c41a;
  font-weight: 500;
}

.status-invalid {
  color: #ff4d4f;
  font-weight: 500;
}

.status-normal {
  color: #1890ff;
  font-weight: 500;
}

.status-no-loan {
  color: #999;
  font-weight: 500;
}

/* 二维码模态框样式 */
.qrcode-modal-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
}

.qrcode-container {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 20px;
}

.qrcode-image {
  width: 250px;
  height: 250px;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
}

.device-sn-display {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  text-align: center;
  padding: 10px;
  background: #f5f5f5;
  border-radius: 4px;
  width: 100%;
}

@media (max-width: 768px) {
  .search-bar .ant-col {
    margin-bottom: 12px;
  }
  
  .device-list {
    overflow-x: auto;
  }
}
</style>