<template>
  <div class="monitor-page">
    <a-page-header
      title="实时监控"
      sub-title="宁夏智慧养殖监管平台实时监控"
    >
      <template #extra>
        <a-space>
          <a-select
            v-model="selectedFarm"
            style="width: 200px"
            placeholder="选择养殖场"
            @change="handleFarmChange"
          >
            <a-select-option value="all">全部养殖场</a-select-option>
            <a-select-option v-for="farm in dataStore.farms" :key="farm.id" :value="farm.id">
              {{ farm.name }}
            </a-select-option>
          </a-select>
          <a-button type="primary" @click="refreshAllData">
            <template #icon><reload-outlined /></template>
            刷新数据
          </a-button>
        </a-space>
      </template>
    </a-page-header>
    
    <!-- 性能监控组件 -->
    <chart-performance-monitor style="display: none;" />
    
    <div class="monitor-content">
      <!-- 实时数据概览 -->
      <div class="monitor-stats">
        <a-card :bordered="false">
          <template #title>
            <span>温度监控</span>
            <a-tag color="orange" style="margin-left: 8px">{{ getLatestValue(temperatureData) }}°C</a-tag>
          </template>
          <monitor-chart 
            title="温度变化趋势" 
            type="line" 
            :data="temperatureData" 
            height="250px" 
            :refresh-interval="30000"
            cache-key="temperature-chart"
            :enable-cache="true"
            :cache-ttl="60000"
            @refresh="refreshTemperatureData"
          />
        </a-card>
        
        <a-card :bordered="false">
          <template #title>
            <span>湿度监控</span>
            <a-tag color="blue" style="margin-left: 8px">{{ getLatestValue(humidityData) }}%</a-tag>
          </template>
          <monitor-chart 
            title="湿度变化趋势" 
            type="line" 
            :data="humidityData" 
            height="250px" 
            :refresh-interval="30000"
            cache-key="humidity-chart"
            :enable-cache="true"
            :cache-ttl="60000"
            @refresh="refreshHumidityData"
          />
        </a-card>
      </div>
      
      <div class="monitor-stats">
        <a-card :bordered="false">
          <template #title>
            <span>设备状态</span>
            <a-tag color="green" style="margin-left: 8px">在线率: {{ deviceOnlineRate }}%</a-tag>
          </template>
          <monitor-chart 
            title="设备状态分布" 
            type="pie" 
            :data="deviceStatusData" 
            height="250px" 
            :refresh-interval="60000"
            cache-key="device-status-chart"
            :enable-cache="true"
            :cache-ttl="120000"
            @refresh="refreshDeviceData"
          />
        </a-card>
        
        <a-card :bordered="false">
          <template #title>
            <span>预警监控</span>
            <a-tag color="red" style="margin-left: 8px">{{ alertCount }}个预警</a-tag>
          </template>
          <monitor-chart 
            title="预警类型分布" 
            type="pie" 
            :data="alertTypeData" 
            height="250px" 
            :refresh-interval="60000"
            cache-key="alert-type-chart"
            :enable-cache="true"
            :cache-ttl="120000"
            @refresh="refreshAlertData"
          />
        </a-card>
      </div>
      
      <!-- 实时预警列表 -->
      <a-card title="实时预警信息" :bordered="false" class="alert-card">
        <a-table 
          :dataSource="alertTableData" 
          :columns="alertColumns" 
          :pagination="{ pageSize: 5 }" 
          :loading="dataStore.loading.alerts"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'type'">
              {{ getAlertTypeText(record.type) }}
            </template>
            <template v-if="column.key === 'level'">
              <a-tag :color="getAlertLevelColor(record.level)">
                {{ getAlertLevelText(record.level) }}
              </a-tag>
            </template>
            <template v-if="column.key === 'created_at'">
              {{ formatTime(record.created_at) }}
            </template>
            <template v-if="column.key === 'action'">
              <a-button type="link" size="small" @click="handleAlert(record.id)">
                处理
              </a-button>
            </template>
          </template>
        </a-table>
      </a-card>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, reactive } from 'vue'
import { ReloadOutlined } from '@ant-design/icons-vue'
import { useDataStore } from '../stores'
import MonitorChart from '../components/MonitorChart.vue'
import { message } from 'ant-design-vue'
import { api } from '../utils/api'
import ChartPerformanceMonitor from '../components/ChartPerformanceMonitor.vue'
import { DataCache } from '../utils/chartService'

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

// 选中的养殖场
const selectedFarm = ref('all')

// 处理养殖场变化
function handleFarmChange(farmId) {
  refreshAllData()
}

// 刷新所有数据（优化版本）
async function refreshAllData() {
  // 清理相关缓存以强制刷新
  DataCache.delete(`temperature_data_${selectedFarm.value}`)
  DataCache.delete(`humidity_data_${selectedFarm.value}`)
  
  await dataStore.fetchAllData()
  refreshTemperatureData()
  refreshHumidityData()
  refreshDeviceData()
  refreshAlertData()
  
  message.success('数据刷新完成')
}

// 温度数据
const temperatureData = reactive({
  xAxis: [],
  series: [{
    name: '温度',
    data: [],
    itemStyle: { color: '#ff7a45' },
    areaStyle: { opacity: 0.2 }
  }]
})

// 湿度数据
const humidityData = reactive({
  xAxis: [],
  series: [{
    name: '湿度',
    data: [],
    itemStyle: { color: '#1890ff' },
    areaStyle: { opacity: 0.2 }
  }]
})

// 设备状态数据
const deviceStatusData = computed(() => {
  const devices = selectedFarm.value === 'all' 
    ? dataStore.devices 
    : dataStore.devices.filter(d => (d.farm_id || d.farmId) == selectedFarm.value)
  
  const online = devices.filter(d => d.status === 'online').length
  const offline = devices.length - online
  
  return [
    { value: online, name: '在线设备', itemStyle: { color: '#52c41a' } },
    { value: offline, name: '离线设备', itemStyle: { color: '#d9d9d9' } }
  ]
})

// 设备在线率
const deviceOnlineRate = computed(() => {
  const devices = selectedFarm.value === 'all' 
    ? dataStore.devices 
    : dataStore.devices.filter(d => (d.farm_id || d.farmId) == selectedFarm.value)
  
  if (devices.length === 0) return 0
  
  const online = devices.filter(d => d.status === 'online').length
  return ((online / devices.length) * 100).toFixed(1)
})

// 预警类型数据
const alertTypeData = computed(() => {
  const alerts = selectedFarm.value === 'all' 
    ? dataStore.alerts 
    : dataStore.alerts.filter(a => a.farm_id == selectedFarm.value)
  
  // 按类型分组统计（使用中文类型名）
  const typeCount = {}
  alerts.forEach(alert => {
    const chineseType = getAlertTypeText(alert.type)
    typeCount[chineseType] = (typeCount[chineseType] || 0) + 1
  })
  
  // 转换为图表数据格式
  return Object.keys(typeCount).map(type => ({
    value: typeCount[type],
    name: type,
    itemStyle: { 
      color: type.includes('温度') ? '#ff4d4f' : 
             type.includes('湿度') ? '#1890ff' : 
             type.includes('设备') ? '#faad14' : '#52c41a'
    }
  }))
})

// 预警数量
const alertCount = computed(() => {
  return selectedFarm.value === 'all' 
    ? dataStore.alertCount 
    : dataStore.alerts.filter(a => a.farm_id == selectedFarm.value).length
})

// 预警表格数据
const alertTableData = computed(() => {
  const alerts = selectedFarm.value === 'all' 
    ? dataStore.alerts 
    : dataStore.alerts.filter(a => a.farm_id == selectedFarm.value)
  
  return alerts.map(alert => ({
    key: alert.id,
    id: alert.id,
    type: getAlertTypeText(alert.type),
    level: alert.level,
    farmId: alert.farm_id,
    farmName: dataStore.farms.find(f => f.id == alert.farm_id)?.name || '',
    created_at: alert.created_at
  }))
})

// 预警表格列定义
const alertColumns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: 80
  },
  {
    title: '预警类型',
    dataIndex: 'type',
    key: 'type'
  },
  {
    title: '预警级别',
    dataIndex: 'level',
    key: 'level'
  },
  {
    title: '养殖场',
    dataIndex: 'farmName',
    key: 'farmName'
  },
  {
    title: '时间',
    dataIndex: 'created_at',
    key: 'created_at',
    sorter: (a, b) => new Date(a.created_at) - new Date(b.created_at),
    defaultSortOrder: 'descend'
  },
  {
    title: '操作',
    key: 'action'
  }
]

// 获取预警级别颜色
function getAlertLevelColor(level) {
  switch (level) {
    case 'high': return 'red'
    case 'medium': return 'orange'
    case 'low': return 'blue'
    default: return 'default'
  }
}

// 获取预警级别文本
function getAlertLevelText(level) {
  switch (level) {
    case 'high': return '高'
    case 'medium': return '中'
    case 'low': return '低'
    default: return '未知'
  }
}

// 获取预警类型文本（英文转中文）
function getAlertTypeText(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 formatTime(timestamp) {
  const date = new Date(timestamp)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  
  // 如果是今天
  if (date.toDateString() === now.toDateString()) {
    return date.toLocaleTimeString('zh-CN', { 
      hour: '2-digit', 
      minute: '2-digit',
      second: '2-digit'
    })
  }
  
  // 如果是昨天
  const yesterday = new Date(now.getTime() - 24 * 60 * 60 * 1000)
  if (date.toDateString() === yesterday.toDateString()) {
    return '昨天 ' + date.toLocaleTimeString('zh-CN', { 
      hour: '2-digit', 
      minute: '2-digit'
    })
  }
  
  // 如果是一周内
  if (diff < 7 * 24 * 60 * 60 * 1000) {
    const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
    return weekdays[date.getDay()] + ' ' + date.toLocaleTimeString('zh-CN', { 
      hour: '2-digit', 
      minute: '2-digit'
    })
  }
  
  // 其他情况显示完整日期
  return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN', { 
    hour: '2-digit', 
    minute: '2-digit'
  })
}

// 处理预警
function handleAlert(alertId) {
  message.success(`已处理预警 #${alertId}`)
}

// 刷新温度数据（优化版本）
async function refreshTemperatureData() {
  const cacheKey = `temperature_data_${selectedFarm.value}`
  
  try {
    // 检查缓存
    let data = DataCache.get(cacheKey)
    
    if (!data) {
      // 调用后端监控数据API
      data = await api.get('/stats/public/monitoring')
      
      // 缓存数据（2分钟）
      if (data) {
        DataCache.set(cacheKey, data, 2 * 60 * 1000)
      }
    } else {
      console.log('使用缓存的温度数据')
    }
    
    // api.get返回的是result.data，直接检查数据结构
    if (data && data.environmentData && data.environmentData.temperature && data.environmentData.temperature.history) {
      const temperatureInfo = data.environmentData.temperature
      
      // 使用后端返回的温度历史数据，格式化时间标签
      const timeLabels = temperatureInfo.history.map(item => formatTime(item.time))
      const tempValues = temperatureInfo.history.map(item => item.value)
      
      console.log('温度数据处理成功:', { timeLabels, tempValues })
      
      temperatureData.xAxis = timeLabels
      temperatureData.series[0].data = tempValues
      return
    }
    
    // 如果API调用失败，显示错误信息
    console.error('无法获取温度数据，请检查后端服务')
  } catch (error) {
    console.error('获取温度数据出错:', error)
    // 显示错误状态
    temperatureData.xAxis = ['无数据']
    temperatureData.series[0].data = [0]
  }
}

// 刷新湿度数据（优化版本）
async function refreshHumidityData() {
  const cacheKey = `humidity_data_${selectedFarm.value}`
  
  try {
    // 检查缓存
    let data = DataCache.get(cacheKey)
    
    if (!data) {
      // 调用后端监控数据API
      data = await api.get('/stats/public/monitoring')
      
      // 缓存数据（2分钟）
      if (data) {
        DataCache.set(cacheKey, data, 2 * 60 * 1000)
      }
    } else {
      console.log('使用缓存的湿度数据')
    }
    
    if (data && data.environmentData && data.environmentData.humidity && data.environmentData.humidity.history) {
      const timeLabels = data.environmentData.humidity.history.map(item => {
        const date = new Date(item.time);
        return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
      });
      const humidityValues = data.environmentData.humidity.history.map(item => item.value);
      
      humidityData.xAxis = timeLabels;
      humidityData.series[0].data = humidityValues;
    } else {
      console.error('无法获取湿度数据，请检查后端服务');
      humidityData.series[0].data = [];
      humidityData.xAxis = ['无数据'];
    }
  } catch (error) {
    console.error('获取湿度数据出错:', error)
    // 显示错误状态
    humidityData.xAxis = ['无数据']
    humidityData.series[0].data = [0]
  }
}

// 刷新设备数据
function refreshDeviceData() {
  // 设备状态数据是计算属性，会自动更新
}

// 刷新预警数据
function refreshAlertData() {
  // 预警数据是计算属性，会自动更新
}

// 获取最新值
function getLatestValue(data) {
  const seriesData = data.series?.[0]?.data
  return seriesData?.length > 0 ? seriesData[seriesData.length - 1] : '0'
}

// 组件挂载时加载数据
onMounted(async () => {
  // 加载数据
  await dataStore.fetchAllData()
  
  // 初始化图表数据
  refreshTemperatureData()
  refreshHumidityData()
})
</script>

<style scoped>
.monitor-page {
  padding: 0 16px;
}

.monitor-content {
  margin-top: 16px;
}

.monitor-stats {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
  margin-bottom: 16px;
}

.alert-card {
  margin-bottom: 16px;
}

@media (max-width: 1200px) {
  .monitor-stats {
    grid-template-columns: 1fr;
  }
}
</style>