<template>
  <div class="smart-eartag-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">温度预警</a-select-option>
          <a-select-option value="movement">异常运动预警</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 === 'eartagNumber'">
            <span class="eartag-number">{{ record.eartagNumber }}</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="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?.eartagNumber }}</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">运动量:</span>
            <span class="value">{{ currentAlert?.movement }}</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="handleAlert(currentAlert)">处理预警</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'

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

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

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

// 表格列配置
const columns = [
  {
    title: '耳标编号',
    dataIndex: 'eartagNumber',
    key: 'eartagNumber',
    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: 200,
    align: 'center',
  }
]

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

// 获取预警类型颜色
const getAlertTypeColor = (type) => {
  const colorMap = {
    'battery': 'orange',
    'offline': 'red',
    'temperature': 'red',
    'movement': 'purple'
  }
  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 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.getEartagAlerts(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)
    console.log('响应类型:', typeof result)
    console.log('是否有success字段:', 'success' in result)
    console.log('success值:', result.success)
    
    if (result.success) {
      // 更新预警列表数据
      alerts.value = result.data || []
      pagination.total = result.total || 0
      
      // 更新统计数据
      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
      }
      
      console.log('更新后的预警列表:', alerts.value)
      console.log('总数:', pagination.total)
      
      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
  } finally {
    loading.value = false
  }
}

// 从API获取预警数据
const fetchAlertData = async () => {
  try {
    loading.value = true
    
    // 构建查询参数
    const params = {
      page: pagination.current,
      limit: pagination.pageSize,
      alertType: alertTypeFilter.value,
      search: searchValue.value.trim()
    }
    
    // 调用API获取预警数据
    const response = await api.get('/smart-alerts/public/eartag', { params })
    
    if (response && response.success) {
      alerts.value = response.data || []
      pagination.total = response.total || 0
      
      // 更新统计数据
      updateStatsFromData(alerts.value)
    } else {
      console.error('获取预警数据失败:', response)
      alerts.value = []
      pagination.total = 0
      resetStats()
    }
  } catch (error) {
    console.error('获取预警数据失败:', error)
    message.error('获取预警数据失败: ' + error.message)
    alerts.value = []
    pagination.total = 0
    resetStats()
  } finally {
    loading.value = false
  }
}

// 从数据更新统计信息
const updateStatsFromData = (data) => {
  stats.lowBattery = data.filter(alert => alert.alertType === 'battery').length
  stats.offline = data.filter(alert => alert.alertType === 'offline').length
  stats.highTemperature = data.filter(alert => alert.alertType === 'temperature').length
  stats.abnormalMovement = data.filter(alert => alert.alertType === 'movement').length
}

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

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

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

// 筛选变化处理
const handleFilterChange = (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
  })
  
  // 直接调用 fetchData 并传递 alertType 参数
  fetchData(true, alertType)
}

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

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

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

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

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

// 导出数据
const exportData = async () => {
  try {
    console.log('=== 开始导出智能耳标预警数据 ===')
    
    message.loading('正在获取所有预警数据...', 0)
    
    // 使用smartAlertService获取所有预警数据，不受分页限制
    const { smartAlertService } = await import('../utils/dataService')
    
    const requestParams = {
      search: searchValue.value.trim(),
      alertType: alertTypeFilter.value,
      page: 1,
      limit: 1000 // 获取大量数据
    }
    
    console.log('导出请求参数:', requestParams)
    
    const apiResult = await smartAlertService.getEartagAlerts(requestParams)
    console.log('预警API响应:', apiResult)
    
    if (!apiResult.success || !apiResult.data) {
      message.destroy()
      message.warning('没有数据可导出')
      return
    }
    
    const allAlerts = apiResult.data || []
    console.log('获取到所有预警数据:', allAlerts.length, '条记录')
    console.log('原始数据示例:', allAlerts[0])
    
    // 预警类型中文映射
    const alertTypeMap = {
      'battery': '低电量预警',
      'offline': '离线预警', 
      'temperature': '温度异常预警',
      'movement': '运动异常预警',
      'location': '位置异常预警'
    }
    
    // 预警级别中文映射
    const alertLevelMap = {
      'high': '高',
      'medium': '中',
      'low': '低',
      'critical': '紧急'
    }
    
    // 转换数据格式以匹配导出工具类的列配置
    const exportData = allAlerts.map(item => {
      console.log('转换前预警数据项:', item)
      
      // 格式化时间
      let alertTime = ''
      if (item.alertTime || item.alert_time || item.created_at) {
        const timeValue = item.alertTime || item.alert_time || item.created_at
        if (typeof timeValue === 'number') {
          // Unix时间戳转换
          alertTime = new Date(timeValue * 1000).toLocaleString('zh-CN')
        } else if (typeof timeValue === 'string') {
          // 字符串时间转换
          const date = new Date(timeValue)
          if (!isNaN(date.getTime())) {
            alertTime = date.toLocaleString('zh-CN')
          } else {
            alertTime = timeValue
          }
        }
      }
      
      return {
        device_name: item.deviceName || item.eartagNumber || item.device_name || item.deviceId || '',
        alert_type: alertTypeMap[item.alertType || item.alert_type] || item.alertType || item.alert_type || '',
        alert_level: alertLevelMap[item.alertLevel || item.alert_level] || item.alertLevel || item.alert_level || '',
        alert_content: item.alertContent || item.alert_content || item.message || item.description || '系统预警',
        alert_time: alertTime,
        status: item.status || (item.processed ? '已处理' : '未处理'),
        handler: item.handler || item.processor || item.handler_name || item.operator || ''
      }
    })
    
    console.log('转换后预警数据示例:', exportData[0])
    console.log('转换后预警数据总数:', exportData.length)
    
    message.destroy()
    message.loading('正在导出数据...', 0)
    
    const result = ExportUtils.exportAlertData(exportData, 'eartag')
    
    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('导出失败，请重试')
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchData(true)
})
</script>

<style scoped>
.smart-eartag-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;
}

/* 表格单元格样式 */
.eartag-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;
}

/* 表格样式优化 */
.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>
