<template>
  <div class="smart-collar-alert-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title">智能项圈预警</h2>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <div class="stat-card">
        <div class="stat-icon battery">
          <PoweroffOutlined />
        </div>
        <div class="stat-content">
          <div class="stat-value">{{ stats.lowBattery }}</div>
          <div class="stat-label">低电量预警</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon offline">
          <DisconnectOutlined />
        </div>
        <div class="stat-content">
          <div class="stat-value">{{ stats.offline }}</div>
          <div class="stat-label">离线预警</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon temperature">
          <FireOutlined />
        </div>
        <div class="stat-content">
          <div class="stat-value">{{ stats.highTemperature }}</div>
          <div class="stat-label">温度预警</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon movement">
          <ThunderboltOutlined />
        </div>
        <div class="stat-content">
          <div class="stat-value">{{ stats.abnormalMovement }}</div>
          <div class="stat-label">异常运动预警</div>
        </div>
      </div>
    </div>

    <!-- 搜索和筛选栏 -->
    <div class="search-bar">
      <div class="search-group">
        <a-input
          :value="searchValue"
          @input="updateSearchValue"
          placeholder="请输入项圈编号"
          class="search-input"
          @pressEnter="handleSearch"
        />
        <a-select
          v-model="alertTypeFilter"
          placeholder="预警类型"
          class="filter-select"
          @change="handleFilterChange"
        >
          <a-select-option value="">全部预警</a-select-option>
          <a-select-option value="battery">低电量预警</a-select-option>
          <a-select-option value="offline">离线预警</a-select-option>
          <a-select-option value="temperature_low">温度过低预警</a-select-option>
          <a-select-option value="temperature_high">温度过高预警</a-select-option>
          <a-select-option value="movement">异常运动预警</a-select-option>
          <a-select-option value="wear">佩戴异常预警</a-select-option>
        </a-select>
        <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() || alertTypeFilter">
          清除
        </a-button>
      </div>
      <a-button @click="exportData" class="export-button">
        <template #icon>
          <ExportOutlined />
        </template>
        导出数据
      </a-button>
    </div>

    <!-- 预警列表表格 -->
    <div class="table-container">
      <a-table
        :columns="columns"
        :data-source="alerts"
        :loading="loading"
        :pagination="pagination"
        row-key="id"
        @change="handleTableChange"
        class="alert-table"
      >
        <template #bodyCell="{ column, record }">
          <!-- 项圈编号 -->
          <template v-if="column.dataIndex === 'collarNumber'">
            <span class="collar-number">{{ record.collarNumber }}</span>
          </template>
          
          <!-- 预警类型 -->
          <template v-else-if="column.dataIndex === 'alertType'">
            <a-tag 
              :color="getAlertTypeColor(record.alertType)"
              class="alert-type-tag"
            >
              {{ getAlertTypeText(record.alertType) }}
            </a-tag>
          </template>
          
          <!-- 预警级别 -->
          <template v-else-if="column.dataIndex === 'alertLevel'">
            <a-tag 
              :color="getAlertLevelColor(record.alertLevel)"
              class="alert-level-tag"
            >
              {{ getAlertLevelText(record.alertLevel) }}
            </a-tag>
          </template>
          
          <!-- 预警时间 -->
          <template v-else-if="column.dataIndex === 'alertTime'">
            <div class="alert-time-cell">
              <span class="alert-time-value">{{ record.alertTime }}</span>
            </div>
          </template>
          
          <!-- 操作 -->
          <template v-else-if="column.dataIndex === 'action'">
            <div class="action-cell">
              <a-button type="link" class="action-link" @click="viewDetails(record)">
                查看详情
              </a-button>
              <a-button type="link" class="action-link" @click="viewLocation(record)">
                查看位置
              </a-button>
              <a-button type="link" class="action-link" @click="handleAlert(record)">
                处理预警
              </a-button>
            </div>
          </template>
        </template>
      </a-table>
    </div>

    <!-- 预警详情模态框 -->
    <a-modal
      :open="detailVisible"
      title="预警详情"
      :footer="null"
      width="800px"
      @cancel="handleDetailCancel"
    >
      <div class="alert-detail-modal">
        <div class="detail-grid">
          <div class="detail-item">
            <span class="label">项圈编号:</span>
            <span class="value">{{ currentAlert?.collarNumber }}</span>
          </div>
          <div class="detail-item">
            <span class="label">预警类型:</span>
            <span class="value">
              <a-tag :color="getAlertTypeColor(currentAlert?.alertType)">
                {{ getAlertTypeText(currentAlert?.alertType) }}
              </a-tag>
            </span>
          </div>
          <div class="detail-item">
            <span class="label">预警级别:</span>
            <span class="value">
              <a-tag :color="getAlertLevelColor(currentAlert?.alertLevel)">
                {{ getAlertLevelText(currentAlert?.alertLevel) }}
              </a-tag>
            </span>
          </div>
          <div class="detail-item">
            <span class="label">预警时间:</span>
            <span class="value">{{ currentAlert?.alertTime }}</span>
          </div>
          <div class="detail-item">
            <span class="label">设备电量:</span>
            <span class="value">{{ currentAlert?.battery }}%</span>
          </div>
          <div class="detail-item">
            <span class="label">设备温度:</span>
            <span class="value">{{ currentAlert?.temperature }}°C</span>
          </div>
          <div class="detail-item">
            <span class="label">GPS信号:</span>
            <span class="value">{{ currentAlert?.gpsSignal }}</span>
          </div>
          <div class="detail-item">
            <span class="label">佩戴状态:</span>
            <span class="value">{{ currentAlert?.wearStatus }}</span>
          </div>
          <div class="detail-item">
            <span class="label">预警描述:</span>
            <span class="value">{{ currentAlert?.description }}</span>
          </div>
        </div>
        
        <!-- 底部按钮 -->
        <div class="modal-footer">
          <a-button @click="handleDetailCancel">关闭</a-button>
          <a-button type="primary" @click="viewLocation(currentAlert)">查看位置</a-button>
          <a-button type="primary" @click="handleAlert(currentAlert)">处理预警</a-button>
        </div>
      </div>
    </a-modal>

    <!-- 位置查看模态框 -->
    <a-modal
      :open="locationVisible"
      title="设备位置"
      :footer="null"
      width="90%"
      :style="{ top: '20px' }"
      @cancel="handleLocationCancel"
    >
      <div class="location-modal">
        <!-- 地图容器 -->
        <div class="map-container">
          <div id="locationMap" class="baidu-map"></div>
        </div>
        
        <!-- 底部取消按钮 -->
        <div class="location-footer">
          <a-button class="cancel-btn" @click="handleLocationCancel">取消</a-button>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import {
  SearchOutlined,
  PoweroffOutlined,
  DisconnectOutlined,
  FireOutlined,
  ThunderboltOutlined,
  ExportOutlined
} from '@ant-design/icons-vue'
import { ExportUtils } from '../utils/exportUtils'
import { loadBMapScript, createMap } from '@/utils/mapService'

// 响应式数据
const alerts = ref([])
const loading = ref(false)
const searchValue = ref('')
const alertTypeFilter = ref('')
const detailVisible = ref(false)
const locationVisible = ref(false)
const currentAlert = ref(null)
const baiduMap = ref(null)
const locationMarker = ref(null)

// 统计数据
const stats = reactive({
  lowBattery: 0,
  offline: 0,
  highTemperature: 0,
  abnormalMovement: 0,
  wearOff: 0
})

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
})

// 表格列配置
const columns = [
  {
    title: '项圈编号',
    dataIndex: 'collarNumber',
    key: 'collarNumber',
    width: 120,
    align: 'center',
  },
  {
    title: '预警类型',
    dataIndex: 'alertType',
    key: 'alertType',
    width: 120,
    align: 'center',
  },
  {
    title: '预警级别',
    dataIndex: 'alertLevel',
    key: 'alertLevel',
    width: 100,
    align: 'center',
  },
  {
    title: '预警时间',
    dataIndex: 'alertTime',
    key: 'alertTime',
    width: 180,
    align: 'center',
  },
  {
    title: '设备电量',
    dataIndex: 'battery',
    key: 'battery',
    width: 100,
    align: 'center',
  },
  {
    title: '设备温度',
    dataIndex: 'temperature',
    key: 'temperature',
    width: 100,
    align: 'center',
  },
  {
    title: '当日步数',
    dataIndex: 'dailySteps',
    key: 'dailySteps',
    width: 120,
    align: 'center',
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    width: 250,
    align: 'center',
  }
]

// 判断预警类型
const determineAlertType = (record) => {
  const alerts = []
  
  // 检查电量预警
  if (record.battery !== undefined && record.battery !== null && record.battery < 20) {
    alerts.push('battery')
  }
  
  // 检查脱落预警 (bandge_status为0)
  if (record.bandge_status !== undefined && record.bandge_status !== null && record.bandge_status === 0) {
    alerts.push('wear')
  }
  
  // 检查离线预警 (is_connect为0)
  if (record.is_connect !== undefined && record.is_connect !== null && record.is_connect === 0) {
    alerts.push('offline')
  }
  
  // 检查温度预警
  if (record.temperature !== undefined && record.temperature !== null) {
    if (record.temperature < 20) {
      alerts.push('temperature_low')
    } else if (record.temperature > 40) {
      alerts.push('temperature_high')
    }
  }
  
  // 检查运动异常预警 (steps - y_steps为0)
  if (record.steps !== undefined && record.y_steps !== undefined && 
      record.steps !== null && record.y_steps !== null) {
    const movementDiff = record.steps - record.y_steps
    if (movementDiff === 0) {
      alerts.push('movement')
    }
  }
  
  // 返回第一个预警类型，如果没有预警则返回null
  return alerts.length > 0 ? alerts[0] : null
}

// 获取预警类型文本
const getAlertTypeText = (type) => {
  const typeMap = {
    'battery': '低电量预警',
    'offline': '离线预警',
    'temperature_low': '温度过低预警',
    'temperature_high': '温度过高预警',
    'movement': '异常运动预警',
    'wear': '佩戴异常预警'
  }
  return typeMap[type] || '温度预警'
}

// 获取预警类型颜色
const getAlertTypeColor = (type) => {
  const colorMap = {
    'battery': 'orange',
    'offline': 'red',
    'temperature_low': 'blue',
    'temperature_high': 'red',
    'movement': 'purple',
    'wear': 'blue'
  }
  return colorMap[type] || 'default'
}

// 获取预警级别文本
const getAlertLevelText = (level) => {
  const levelMap = {
    'high': '高级',
    'medium': '中级',
    'low': '低级'
  }
  return levelMap[level] || '未知'
}

// 获取预警级别颜色
const getAlertLevelColor = (level) => {
  const colorMap = {
    'high': 'red',
    'medium': 'orange',
    'low': 'green'
  }
  return colorMap[level] || 'default'
}

// 计算统计数据
const calculateStats = (data) => {
  const newStats = {
    lowBattery: 0,
    offline: 0,
    highTemperature: 0,
    abnormalMovement: 0,
    wearOff: 0
  }
  
  data.forEach(item => {
    const alertType = determineAlertType(item)
    if (alertType === 'battery') {
      newStats.lowBattery++
    } else if (alertType === 'offline') {
      newStats.offline++
    } else if (alertType === 'temperature_high') {
      newStats.highTemperature++
    } else if (alertType === 'movement') {
      newStats.abnormalMovement++
    } else if (alertType === 'wear') {
      newStats.wearOff++
    }
  })
  
  return newStats
}

// 获取统计数据
const fetchStats = async () => {
  try {
    const { smartAlertService } = await import('../utils/dataService')
    const statsResult = await smartAlertService.getCollarAlertStats()
    
    if (statsResult && statsResult.success) {
      const statsData = statsResult.data || {}
      stats.lowBattery = statsData.lowBattery || 0
      stats.offline = statsData.offline || 0
      stats.highTemperature = statsData.highTemperature || 0
      stats.abnormalMovement = statsData.abnormalMovement || 0
      stats.wearOff = statsData.wearOff || 0
      console.log('统计数据更新:', stats)
    } else {
      console.warn('获取统计数据失败:', statsResult)
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

// 获取数据
const fetchData = async (showMessage = false, customAlertType = null) => {
  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())
    }
    
    // 添加预警类型筛选 - 使用传入的参数或默认值
    const alertType = customAlertType !== null ? customAlertType : alertTypeFilter.value
    if (alertType && alertType.trim() !== '') {
      params.append('alertType', alertType)
    }
    
    // 调用API获取预警数据
    const { smartAlertService } = await import('../utils/dataService')
    console.log('使用smartAlertService获取项圈预警数据')
    console.log('搜索参数:', {
      search: searchValue.value.trim(),
      alertType: alertTypeFilter.value,
      page: pagination.current,
      limit: pagination.pageSize
    })
    
    const requestParams = {
      search: searchValue.value.trim(),
      alertType: alertType,
      page: pagination.current,
      limit: pagination.pageSize
    }
    console.log('发送API请求，参数:', requestParams)
    
    const result = await smartAlertService.getCollarAlerts(requestParams)
    console.log('API响应结果:', result)
    console.log('API返回的数据类型:', typeof result.data)
    console.log('API返回的数据长度:', result.data ? result.data.length : 'undefined')
    console.log('API返回的数据内容:', result.data)
    
    if (result.success) {
      // 转换API返回的数据格式
      const rawData = result.data || []
      console.log('原始API数据:', rawData)
      
      // 预警级别中文映射
      const alertLevelMap = {
        'high': '高级',
        'medium': '中级',
        'low': '低级',
        'critical': '紧急'
      }
      
      // 转换数据格式
      const transformedData = rawData.map(item => {
        // 格式化时间
        let alertTime = ''
        if (item.alertTime) {
          if (typeof item.alertTime === 'number') {
            alertTime = new Date(item.alertTime * 1000).toLocaleString('zh-CN')
          } else if (typeof item.alertTime === 'string') {
            const date = new Date(item.alertTime)
            if (!isNaN(date.getTime())) {
              alertTime = date.toLocaleString('zh-CN')
            } else {
              alertTime = item.alertTime
            }
          }
        }
        
        // 使用API返回的预警类型，如果没有则使用判断函数
        let alertTypeText = '正常'
        let alertLevel = 'low'
        let determinedAlertType = null
        
        if (item.alertType) {
          // 使用API返回的预警类型
          const alertTypeMap = {
            'battery': '低电量预警',
            'offline': '离线预警',
            'temperature': '温度预警',
            'temperature_low': '温度过低预警',
            'temperature_high': '温度过高预警',
            'movement': '异常运动预警',
            'wear': '佩戴异常预警'
          }
          alertTypeText = alertTypeMap[item.alertType] || item.alertType
          determinedAlertType = item.alertType
          
          // 使用API返回的预警级别
          const alertLevelMap = {
            'high': '高级',
            'medium': '中级',
            'low': '低级',
            'critical': '紧急'
          }
          alertLevel = alertLevelMap[item.alertLevel] || item.alertLevel
        } else {
          // 如果没有预警类型，使用判断函数
          determinedAlertType = determineAlertType(item)
          alertTypeText = determinedAlertType ? getAlertTypeText(determinedAlertType) : '正常'
          
          // 根据预警类型确定预警级别
          if (determinedAlertType === 'battery' || determinedAlertType === 'offline' || determinedAlertType === 'temperature_high') {
            alertLevel = 'high'
          } else if (determinedAlertType === 'movement' || determinedAlertType === 'wear' || determinedAlertType === 'temperature_low') {
            alertLevel = 'medium'
          }
        }
        
        return {
          id: item.id || `${item.deviceId || item.sn}_${item.alertType || 'normal'}`,
          collarNumber: item.collarNumber || item.sn || item.deviceId || '',
          alertType: alertTypeText,
          alertLevel: alertLevel,
          alertTime: alertTime,
          battery: item.battery || item.batteryLevel || '',
          temperature: item.temperature || item.temp || '',
          dailySteps: item.dailySteps || item.steps || '',
          longitude: item.longitude || 0,
          latitude: item.latitude || 0,
          // 保留原始数据用于其他功能
          ...item,
          // 添加判断结果
          determinedAlertType: determinedAlertType
        }
      })
      
      // 更新预警列表数据
      alerts.value = transformedData
      pagination.total = result.total || 0
      
      // 使用API返回的统计数据
      if (result.stats) {
        stats.lowBattery = result.stats.lowBattery || 0
        stats.offline = result.stats.offline || 0
        stats.highTemperature = result.stats.highTemperature || 0
        stats.abnormalMovement = result.stats.abnormalMovement || 0
        stats.wearOff = result.stats.wearOff || 0
        console.log('使用API返回的统计数据:', result.stats)
      } else {
        // 如果没有统计数据，使用计算的方式
        const calculatedStats = calculateStats(rawData)
        stats.lowBattery = calculatedStats.lowBattery
        stats.offline = calculatedStats.offline
        stats.highTemperature = calculatedStats.highTemperature
        stats.abnormalMovement = calculatedStats.abnormalMovement
        stats.wearOff = calculatedStats.wearOff
        console.log('计算统计数据:', calculatedStats)
      }
      
      console.log('更新后的统计数据:', stats)
      
      console.log('转换后的预警列表:', alerts.value)
      console.log('总数:', pagination.total)
      console.log('统计数据:', result.stats)
      
      if (showMessage) {
        const searchText = searchValue.value.trim() ? `搜索"${searchValue.value.trim()}"` : '加载'
        message.success(`${searchText}完成，共找到 ${pagination.total} 条预警数据`)
      }
      
    } else {
      throw new Error(result.message || '获取数据失败')
    }
    
  } catch (error) {
    console.error('获取数据失败:', error)
    console.error('错误详情:', {
      message: error.message,
      stack: error.stack,
      name: error.name
    })
    if (showMessage) {
      message.error('获取数据失败: ' + error.message)
    }
    
    // 清空数据而不是显示模拟数据
    alerts.value = []
    pagination.total = 0
    stats.lowBattery = 0
    stats.offline = 0
    stats.highTemperature = 0
    stats.abnormalMovement = 0
    stats.wearOff = 0
  } finally {
    loading.value = false
  }
}

// 从API获取预警数据
const fetchAlertData = async () => {
  try {
    loading.value = true
    
    // 构建查询参数
    const params = new URLSearchParams({
      page: pagination.current.toString(),
      limit: pagination.pageSize.toString(),
      _t: Date.now().toString()
    })
    
    // 添加筛选条件
    if (searchValue.value.trim()) {
      params.append('search', searchValue.value.trim())
    }
    if (alertTypeFilter.value) {
      params.append('alertType', alertTypeFilter.value)
    }
    
    // 调用API获取预警数据
    const response = await fetch(`/api/smart-alerts/public/collar?${params}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    })
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    const result = await response.json()
    
    if (result.success) {
      alerts.value = result.data.list || []
      pagination.total = result.data.pagination?.total || 0
      
      // 更新统计数据
      if (result.data.stats) {
        stats.lowBattery = result.data.stats.lowBattery || 0
        stats.offline = result.data.stats.offline || 0
        stats.highTemperature = result.data.stats.highTemperature || 0
        stats.abnormalMovement = result.data.stats.abnormalMovement || 0
        stats.wearOff = result.data.stats.wearOff || 0
      } else {
        // 如果没有统计数据，从数据中计算
        stats.lowBattery = alerts.value.filter(alert => alert.alertType === 'battery').length
        stats.offline = alerts.value.filter(alert => alert.alertType === 'offline').length
        stats.highTemperature = alerts.value.filter(alert => alert.alertType === 'temperature').length
        stats.abnormalMovement = alerts.value.filter(alert => alert.alertType === 'movement').length
        stats.wearOff = alerts.value.filter(alert => alert.alertType === 'wear').length
      }
    } else {
      throw new Error(result.message || '获取预警数据失败')
    }
  } catch (error) {
    console.error('获取预警数据失败:', error)
    message.error('获取预警数据失败: ' + error.message)
    alerts.value = []
    pagination.total = 0
    resetStats()
  } finally {
    loading.value = false
  }
}

// 重置统计信息
const resetStats = () => {
  stats.lowBattery = 0
  stats.offline = 0
  stats.highTemperature = 0
  stats.abnormalMovement = 0
  stats.wearOff = 0
}

// 更新搜索值
const updateSearchValue = (e) => {
  searchValue.value = e.target.value
  console.log('搜索输入框值变化:', searchValue.value)
}

// 搜索处理
const handleSearch = async () => {
  pagination.current = 1
  await fetchData(true)
}

// 筛选变化处理
const handleFilterChange = async (value) => {
  console.log('=== 智能项圈预警类型筛选变化 ===')
  console.log('传入的 value 参数:', value)
  console.log('传入的 value 参数类型:', typeof value)
  console.log('传入的 value 参数长度:', value !== undefined ? value.length : 'undefined')
  console.log('传入的 value 参数是否为空:', value === '')
  console.log('传入的 value 参数是否为undefined:', value === undefined)
  console.log('传入的 value 参数是否为null:', value === null)
  console.log('传入的 value 参数是否有效:', value && value.trim() !== '')
  
  // 使用传入的 value 参数而不是 alertTypeFilter.value
  const alertType = value || ''
  console.log('使用的 alertType:', alertType)
  
  pagination.current = 1
  console.log('准备调用 fetchData，参数:', {
    search: searchValue.value,
    alertType: alertType,
    page: pagination.current,
    limit: pagination.pageSize
  })
  
  // 更新列表数据，统计数据会在数据转换时计算
  await fetchData(true, alertType)
}

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

// 查看详情
const viewDetails = (record) => {
  currentAlert.value = record
  detailVisible.value = true
}

// 查看位置
const viewLocation = (record) => {
  if (record.longitude && record.latitude && record.longitude !== 0 && record.latitude !== 0) {
    currentAlert.value = record
    locationVisible.value = true
    
    // 延迟初始化地图，确保DOM已渲染
    setTimeout(() => {
      initBaiduMap()
    }, 100)
  } else {
    message.warning('该设备暂无有效定位信息')
  }
}

// 处理预警
const handleAlert = async (record) => {
  try {
    console.log('处理预警:', record)
    
    // 调用API处理预警
    const { smartAlertService } = await import('../utils/dataService')
    const result = await smartAlertService.handleCollarAlert(record.id, {
      action: 'acknowledged',
      notes: '通过管理界面处理',
      handler: 'admin'
    })
    
    if (result.success) {
      message.success(`预警处理成功: ${record.collarNumber}`)
      // 刷新数据
      await fetchData()
    } else {
      message.error(`预警处理失败: ${result.message}`)
    }
  } catch (error) {
    console.error('处理预警失败:', error)
    message.error('处理预警失败: ' + error.message)
  }
}

// 取消详情
const handleDetailCancel = () => {
  detailVisible.value = false
  currentAlert.value = null
}

// 取消位置查看
const handleLocationCancel = () => {
  locationVisible.value = false
  currentAlert.value = null
  if (baiduMap.value) {
    baiduMap.value = null
  }
  if (locationMarker.value) {
    locationMarker.value = null
  }
}

// 初始化百度地图
const initBaiduMap = async () => {
  if (!currentAlert.value) return
  
  try {
    // 确保百度地图API已加载
    await loadBMapScript()
    
    // 获取地图容器
    const mapContainer = document.getElementById('locationMap')
    if (!mapContainer) {
      message.error('地图容器不存在')
      return
    }
    
    // 创建地图实例
    const map = await createMap(mapContainer, {
      center: new window.BMap.Point(currentAlert.value.longitude, currentAlert.value.latitude),
      zoom: 15
    })
    
    baiduMap.value = map
    
    // 添加设备位置标记
    const point = new window.BMap.Point(currentAlert.value.longitude, currentAlert.value.latitude)
    
    // 创建自定义标记图标
    const icon = new window.BMap.Icon(
      'data:image/svg+xml;base64,' + btoa(`
        <svg width="32" height="48" viewBox="0 0 32 48" xmlns="http://www.w3.org/2000/svg">
          <path d="M16 0C7.163 0 0 7.163 0 16c0 16 16 32 16 32s16-16 16-32C32 7.163 24.837 0 16 0z" fill="#ff0000"/>
          <circle cx="16" cy="16" r="8" fill="#ffffff"/>
        </svg>
      `),
      new window.BMap.Size(32, 48),
      {
        anchor: new window.BMap.Size(16, 48)
      }
    )
    
    const marker = new window.BMap.Marker(point, { icon: icon })
    map.addOverlay(marker)
    locationMarker.value = marker
    
    // 创建信息窗口
    const infoWindow = new window.BMap.InfoWindow(`
      <div style="padding: 10px; font-size: 14px;">
        <div style="font-weight: bold; margin-bottom: 5px;">项圈位置</div>
        <div>设备编号: ${currentAlert.value.collarNumber}</div>
        <div>经度: ${currentAlert.value.longitude}</div>
        <div>纬度: ${currentAlert.value.latitude}</div>
        <div style="margin-top: 5px; color: #666;">
          预警时间: ${currentAlert.value.alertTime}
        </div>
      </div>
    `, {
      width: 200,
      height: 120
    })
    
    // 点击标记显示信息窗口
    marker.addEventListener('click', () => {
      map.openInfoWindow(infoWindow, point)
    })
    
    // 启用地图控件
    map.addControl(new window.BMap.NavigationControl())
    map.addControl(new window.BMap.ScaleControl())
    map.addControl(new window.BMap.OverviewMapControl())
    map.addControl(new window.BMap.MapTypeControl())
    
    // 启用滚轮缩放
    map.enableScrollWheelZoom(true)
    
    console.log('定位地图初始化成功')
    
  } catch (error) {
    console.error('初始化百度地图失败:', error)
    message.error('地图初始化失败: ' + error.message)
  }
}

// 表格变化处理
const handleTableChange = async (pag) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  await fetchData()
}

// 导出数据
const exportData = async () => {
  try {
    console.log('🔄 开始导出智能项圈预警数据')
    message.loading('正在导出数据...', 0)
    
    // 调用API导出数据
    const { smartAlertService } = await import('../utils/dataService')
    const exportParams = {
      search: searchValue.value.trim(),
      alertType: alertTypeFilter.value,
      format: 'json'
    }
    
    const result = await smartAlertService.exportCollarAlerts(exportParams)
    
    if (result.success) {
      const exportData = result.data || []
      
      if (exportData.length === 0) {
        message.destroy()
        message.warning('没有数据可导出')
        return
      }
      
      // 转换数据格式用于Excel导出
      const transformedData = exportData.map(item => ({
        collarNumber: item.collarNumber || item.sn || '',
        alertType: item.alertType || '',
        alertLevel: item.alertLevel || '',
        alertTime: item.alertTime || '',
        battery: item.battery || item.batteryLevel || '',
        temperature: item.temperature || item.temp || '',
        dailySteps: item.dailySteps || item.steps || ''
      }))
      
      // 列配置
      const columns = [
        { title: '项圈编号', dataIndex: 'collarNumber', key: 'collarNumber' },
        { title: '预警类型', dataIndex: 'alertType', key: 'alertType' },
        { title: '预警级别', dataIndex: 'alertLevel', key: 'alertLevel' },
        { title: '预警时间', dataIndex: 'alertTime', key: 'alertTime', dataType: 'datetime' },
        { title: '设备电量', dataIndex: 'battery', key: 'battery' },
        { title: '设备温度', dataIndex: 'temperature', key: 'temperature' },
        { title: '当日步数', dataIndex: 'dailySteps', key: 'dailySteps' }
      ]
      
      // 调用导出方法
      const exportResult = ExportUtils.exportToExcel(transformedData, columns, '智能项圈预警数据')
      
      if (exportResult.success) {
        message.destroy()
        message.success(`导出成功！文件：${exportResult.filename}`)
      } else {
        message.destroy()
        message.error(exportResult.message)
      }
    } else {
      message.destroy()
      message.error(`导出失败: ${result.message}`)
    }
  } catch (error) {
    message.destroy()
    console.error('导出失败:', error)
    message.error('导出失败，请重试')
  }
}

// 组件挂载时获取数据
onMounted(async () => {
  // 获取列表数据，统计数据会在数据转换时计算
  await fetchData(true)
})
</script>

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

/* 页面标题样式 */
.page-header {
  margin-bottom: 24px;
}

.page-title {
  font-size: 24px;
  font-weight: bold;
  color: #52c41a;
  margin: 0;
  padding: 12px 20px;
  background: #f6ffed;
  border: 1px solid #b7eb8f;
  border-radius: 6px;
  display: inline-block;
}

/* 统计卡片样式 */
.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
  margin-bottom: 24px;
}

.stat-card {
  display: flex;
  align-items: center;
  padding: 20px;
  background: #fff;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: #fff;
  margin-right: 16px;
}

.stat-icon.battery {
  background: linear-gradient(135deg, #ff9a56, #ff6b6b);
}

.stat-icon.offline {
  background: linear-gradient(135deg, #ff6b6b, #ee5a52);
}

.stat-icon.temperature {
  background: linear-gradient(135deg, #ff6b6b, #ff4757);
}

.stat-icon.movement {
  background: linear-gradient(135deg, #a55eea, #8b5cf6);
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #262626;
  line-height: 1;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #8c8c8c;
}

/* 搜索栏样式 */
.search-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  gap: 16px;
}

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

.search-input {
  width: 200px;
  border-radius: 4px;
}

.filter-select {
  width: 150px;
  border-radius: 4px;
}

.search-button {
  border-radius: 4px;
}

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

/* 表格容器样式 */
.table-container {
  background: #fff;
  border-radius: 6px;
  overflow: hidden;
}

.alert-table {
  font-size: 12px;
}

/* 表格单元格样式 */
.collar-number {
  color: #1890ff;
  font-weight: 500;
}

.alert-type-tag,
.alert-level-tag {
  border-radius: 4px;
  font-size: 12px;
  padding: 2px 8px;
}

.alert-time-cell {
  text-align: center;
}

.alert-time-value {
  font-weight: bold;
  font-size: 14px;
}

.action-cell {
  display: flex;
  flex-direction: column;
  gap: 2px;
  align-items: center;
}

.action-link {
  color: #1890ff;
  font-size: 12px;
  padding: 0;
  height: auto;
  line-height: 1.2;
  text-decoration: underline;
}

.action-link:hover {
  color: #40a9ff;
}

/* 预警详情模态框样式 */
.alert-detail-modal {
  padding: 20px 0;
}

.detail-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px 24px;
  margin-bottom: 24px;
}

.detail-item {
  display: flex;
  align-items: center;
}

.detail-item .label {
  min-width: 100px;
  color: #666;
  font-size: 14px;
  margin-right: 12px;
}

.detail-item .value {
  color: #333;
  font-size: 14px;
  font-weight: 500;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
  margin-top: 20px;
}

/* 位置查看模态框样式 */
.location-modal {
  height: 80vh;
  display: flex;
  flex-direction: column;
}

.map-container {
  flex: 1;
  position: relative;
  min-height: 500px;
}

.baidu-map {
  width: 100%;
  height: 100%;
  border-radius: 8px;
}

.location-footer {
  display: flex;
  justify-content: flex-end;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
  margin-top: 16px;
}

.cancel-btn {
  background-color: #f5f5f5;
  border-color: #d9d9d9;
  color: #666;
}

.cancel-btn:hover {
  background-color: #e6e6e6;
  border-color: #bfbfbf;
  color: #333;
}

/* 表格样式优化 */
.alert-table :deep(.ant-table) {
  font-size: 12px;
}

.alert-table :deep(.ant-table-thead > tr > th) {
  padding: 8px 4px;
  font-size: 12px;
  font-weight: 600;
  text-align: center;
  white-space: nowrap;
  background: #fafafa;
}

.alert-table :deep(.ant-table-tbody > tr > td) {
  padding: 6px 4px;
  font-size: 12px;
}

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