<template>
  <div class="alert-stats">
    <a-card :bordered="false" title="预警数据统计">
      <div class="stats-summary">
        <div class="stat-item">
          <div class="stat-value">{{ totalAlerts }}</div>
          <div class="stat-label">预警总数</div>
        </div>
        <div class="stat-item">
          <div class="stat-value">{{ criticalAlerts }}</div>
          <div class="stat-label">严重预警</div>
        </div>
        <div class="stat-item">
          <div class="stat-value">{{ resolvedRate }}%</div>
          <div class="stat-label">解决率</div>
        </div>
      </div>
      
      <a-divider />
      
      <div class="chart-container">
        <e-chart :options="alertTypeOptions" height="300px" />
      </div>
      
      <a-divider />
      
      <div class="alert-table">
        <a-table 
          :dataSource="alertTableData" 
          :columns="alertColumns" 
          :pagination="{ pageSize: 5 }"
          size="small"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'level'">
              <a-tag :color="getLevelColor(record.level)">
                {{ record.level }}
              </a-tag>
            </template>
            <template v-if="column.key === 'status'">
              <a-tag 
                :color="getStatusColor(record.status)" 
                style="cursor: pointer"
                @click="handleStatusUpdate(record)"
              >
                {{ getStatusLabel(record.status) }}
              </a-tag>
            </template>
          </template>
        </a-table>
      </div>
    </a-card>
  </div>
</template>

<script setup>
import { computed } from 'vue'
import { useDataStore } from '../stores'
import EChart from './EChart.vue'
import { message, Modal } from 'ant-design-vue'
import { api } from '../utils/api'

// 使用数据存储
const dataStore = useDataStore()

// 预警总数
const totalAlerts = computed(() => dataStore.alerts.length)

// 严重预警数量
const criticalAlerts = computed(() => {
  return dataStore.alerts.filter(alert => alert.level === '严重').length
})

// 已解决预警数量
const resolvedAlerts = computed(() => {
  return dataStore.alerts.filter(alert => alert.status === '已解决').length
})

// 解决率
const resolvedRate = computed(() => {
  if (totalAlerts.value === 0) return 0
  return Math.round((resolvedAlerts.value / totalAlerts.value) * 100)
})

// 预警类型分布图表选项
const alertTypeOptions = computed(() => {
  // 按类型分组统计
  const typeCount = {}
  dataStore.alerts.forEach(alert => {
    const chineseType = getTypeText(alert.type)
    typeCount[chineseType] = (typeCount[chineseType] || 0) + 1
  })
  
  // 转换为图表数据格式
  const data = Object.keys(typeCount).map(type => ({
    value: typeCount[type],
    name: type
  }))
  
  return {
    title: {
      text: '预警类型分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'horizontal',
      bottom: 0
    },
    series: [
      {
        name: '预警类型',
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: data
      }
    ]
  }
})

// 预警表格数据
const alertTableData = computed(() => {
  return dataStore.alerts.map(alert => {
    const farm = dataStore.farms.find(f => f.id === alert.farm_id)
    const device = dataStore.devices.find(d => d.id === alert.device_id)
    return {
      key: alert.id,
      id: alert.id,
      type: getTypeText(alert.type),
      level: alert.level,
      message: alert.message,
      farmId: alert.farm_id,
      farmName: farm ? farm.name : `养殖场 #${alert.farm_id}`,
      deviceId: alert.device_id,
      deviceName: device ? device.name : `设备 #${alert.device_id}`,
      status: alert.status,
      timestamp: alert.created_at
    }
  })
})

// 预警表格列定义
const alertColumns = [
  {
    title: '预警类型',
    dataIndex: 'type',
    key: 'type',
    filters: [
      { text: '温度异常', value: '温度异常' },
      { text: '湿度异常', value: '湿度异常' },
      { text: '设备故障', value: '设备故障' },
      { text: '电量不足', value: '电量不足' },
      { text: '网络异常', value: '网络异常' }
    ],
    onFilter: (value, record) => record.type === value
  },
  {
    title: '级别',
    dataIndex: 'level',
    key: 'level',
    filters: [
      { text: '轻微', value: '轻微' },
      { text: '一般', value: '一般' },
      { text: '严重', value: '严重' }
    ],
    onFilter: (value, record) => record.level === value
  },
  {
    title: '养殖场',
    dataIndex: 'farmName',
    key: 'farmName'
  },
  {
    title: '设备',
    dataIndex: 'deviceName',
    key: 'deviceName'
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    filters: [
      { text: '未处理', value: '未处理' },
      { text: '处理中', value: '处理中' },
      { text: '已解决', value: '已解决' }
    ],
    onFilter: (value, record) => record.status === value
  },
  {
    title: '时间',
    dataIndex: 'timestamp',
    key: 'timestamp',
    sorter: (a, b) => new Date(a.timestamp) - new Date(b.timestamp),
    defaultSortOrder: 'descend'
  }
]

// 获取级别颜色
function getLevelColor(level) {
  switch (level) {
    case '轻微': return 'blue'
    case '一般': return 'orange'
    case '严重': return 'red'
    default: return 'blue'
  }
}

// 获取状态颜色
function getStatusColor(status) {
  switch (status) {
    case 'active': return 'error'
    case 'acknowledged': return 'processing'
    case 'resolved': return 'success'
    case '未处理': return 'error'
    case '处理中': return 'processing'
    case '已解决': return 'success'
    default: return 'default'
  }
}

// 处理状态更新
function handleStatusUpdate(record) {
  const statusOptions = [
    { label: '活跃', value: 'active' },
    { label: '已确认', value: 'acknowledged' },
    { label: '已解决', value: 'resolved' }
  ]
  
  const currentIndex = statusOptions.findIndex(option => option.value === record.status)
  const nextIndex = (currentIndex + 1) % statusOptions.length
  const nextStatus = statusOptions[nextIndex]
  
  Modal.confirm({
    title: '更新预警状态',
    content: `确定要将预警状态从"${getStatusLabel(record.status)}"更新为"${nextStatus.label}"吗？`,
    onOk: async () => {
      try {
        // 调用API更新预警状态
         await api.put(`/alerts/public/${record.id}/status`, {
           status: nextStatus.value
         })
        
        // 更新本地数据
        const alertIndex = dataStore.alerts.findIndex(alert => alert.id === record.id)
        if (alertIndex !== -1) {
          dataStore.alerts[alertIndex].status = nextStatus.value
        }
        
        message.success(`预警状态已更新为"${nextStatus.label}"`)
      } catch (error) {
        console.error('更新预警状态失败:', error)
        message.error('更新预警状态失败，请重试')
      }
    }
  })
}

// 获取类型文本（英文转中文）
function getTypeText(type) {
  const texts = {
    temperature_alert: '温度异常',
    humidity_alert: '湿度异常',
    feed_alert: '饲料异常',
    health_alert: '健康异常',
    device_alert: '设备异常',
    temperature: '温度异常',
    humidity: '湿度异常',
    device_failure: '设备故障',
    animal_health: '动物健康',
    security: '安全警报',
    maintenance: '维护提醒',
    other: '其他'
  }
  return texts[type] || type
}

// 获取状态标签
function getStatusLabel(status) {
  switch (status) {
    case 'active': return '活跃'
    case 'acknowledged': return '已确认'
    case 'resolved': return '已解决'
    default: return status
  }
}
</script>

<style scoped>
.alert-stats {
  width: 100%;
}

.stats-summary {
  display: flex;
  justify-content: space-around;
  margin-bottom: 16px;
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #1890ff;
}

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

.chart-container {
  margin: 16px 0;
}

.alert-table {
  margin-top: 16px;
}
</style>