<template>
  <div class="realtime-monitor">
    <a-card title="实时监控面板" :bordered="false">
      <!-- 系统状态概览 -->
      <div class="system-overview">
        <a-row :gutter="16">
          <a-col :span="6">
            <a-card size="small" :bordered="false" class="status-card">
              <div class="status-item">
                <div class="status-icon" :class="systemStatus.api.status">
                  <a-badge :status="systemStatus.api.status === 'online' ? 'success' : 'error'" />
                </div>
                <div class="status-info">
                  <div class="status-title">API服务</div>
                  <div class="status-value">{{ systemStatus.api.status === 'online' ? '正常' : '异常' }}</div>
                  <div class="status-detail">响应时间: {{ systemStatus.api.responseTime }}ms</div>
                </div>
              </div>
            </a-card>
          </a-col>
          <a-col :span="6">
            <a-card size="small" :bordered="false" class="status-card">
              <div class="status-item">
                <div class="status-icon" :class="systemStatus.database.status">
                  <a-badge :status="systemStatus.database.status === 'online' ? 'success' : 'error'" />
                </div>
                <div class="status-info">
                  <div class="status-title">数据库</div>
                  <div class="status-value">{{ systemStatus.database.status === 'online' ? '正常' : '异常' }}</div>
                  <div class="status-detail">连接数: {{ systemStatus.database.connections }}</div>
                </div>
              </div>
            </a-card>
          </a-col>
          <a-col :span="6">
            <a-card size="small" :bordered="false" class="status-card">
              <div class="status-item">
                <div class="status-icon" :class="systemStatus.cache.status">
                  <a-badge :status="systemStatus.cache.status === 'online' ? 'success' : 'error'" />
                </div>
                <div class="status-info">
                  <div class="status-title">缓存服务</div>
                  <div class="status-value">{{ systemStatus.cache.status === 'online' ? '正常' : '异常' }}</div>
                  <div class="status-detail">内存使用: {{ systemStatus.cache.memoryUsage }}%</div>
                </div>
              </div>
            </a-card>
          </a-col>
          <a-col :span="6">
            <a-card size="small" :bordered="false" class="status-card">
              <div class="status-item">
                <div class="status-icon" :class="systemStatus.server.status">
                  <a-badge :status="systemStatus.server.status === 'online' ? 'success' : 'error'" />
                </div>
                <div class="status-info">
                  <div class="status-title">服务器</div>
                  <div class="status-value">{{ systemStatus.server.status === 'online' ? '正常' : '异常' }}</div>
                  <div class="status-detail">CPU: {{ systemStatus.server.cpuUsage }}%</div>
                </div>
              </div>
            </a-card>
          </a-col>
        </a-row>
      </div>

      <!-- 实时数据流 -->
      <div class="realtime-data-stream">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-card title="实时交易监控" size="small" :bordered="false">
              <div ref="tradingChartContainer" class="mini-chart"></div>
              <div class="data-summary">
                <a-statistic-group>
                  <a-statistic title="今日交易" :value="realtimeData.trading.todayCount" suffix="笔" />
                  <a-statistic title="交易金额" :value="realtimeData.trading.todayAmount" :precision="2" prefix="¥" />
                </a-statistic-group>
              </div>
            </a-card>
          </a-col>
          <a-col :span="12">
            <a-card title="环境监测" size="small" :bordered="false">
              <div ref="environmentChartContainer" class="mini-chart"></div>
              <div class="data-summary">
                <a-statistic-group>
                  <a-statistic title="温度" :value="realtimeData.environment.temperature" suffix="°C" />
                  <a-statistic title="湿度" :value="realtimeData.environment.humidity" suffix="%" />
                </a-statistic-group>
              </div>
            </a-card>
          </a-col>
        </a-row>
      </div>

      <!-- 告警信息 -->
      <div class="alert-section">
        <a-card title="系统告警" size="small" :bordered="false">
          <a-list
            :data-source="alerts"
            :pagination="false"
            size="small"
          >
            <template #renderItem="{ item }">
              <a-list-item>
                <a-list-item-meta>
                  <template #avatar>
                    <a-badge :status="getAlertStatus(item.level)" />
                  </template>
                  <template #title>
                    <span :class="`alert-${item.level}`">{{ item.title }}</span>
                  </template>
                  <template #description>
                    <div class="alert-description">
                      <div>{{ item.message }}</div>
                      <div class="alert-time">{{ formatTime(item.timestamp) }}</div>
                    </div>
                  </template>
                </a-list-item-meta>
                <template #actions>
                  <a-button size="small" @click="handleAlert(item)">处理</a-button>
                </template>
              </a-list-item>
            </template>
          </a-list>
        </a-card>
      </div>

      <!-- 在线用户 -->
      <div class="online-users">
        <a-card title="在线用户" size="small" :bordered="false">
          <div class="user-stats">
            <a-row :gutter="16">
              <a-col :span="8">
                <a-statistic title="总在线用户" :value="onlineUsers.total" />
              </a-col>
              <a-col :span="8">
                <a-statistic title="管理员" :value="onlineUsers.admin" />
              </a-col>
              <a-col :span="8">
                <a-statistic title="普通用户" :value="onlineUsers.user" />
              </a-col>
            </a-row>
          </div>
          <div class="user-activity">
            <a-timeline size="small">
              <a-timeline-item
                v-for="activity in recentActivities"
                :key="activity.id"
                :color="getActivityColor(activity.type)"
              >
                <div class="activity-content">
                  <div class="activity-user">{{ activity.user }}</div>
                  <div class="activity-action">{{ activity.action }}</div>
                  <div class="activity-time">{{ formatTime(activity.timestamp) }}</div>
                </div>
              </a-timeline-item>
            </a-timeline>
          </div>
        </a-card>
      </div>
    </a-card>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, nextTick } from 'vue';
import * as echarts from 'echarts';
import { monitorAPI } from '../services/api.js';

const tradingChartContainer = ref(null);
const environmentChartContainer = ref(null);
let tradingChart = null;
let environmentChart = null;
let updateTimer = null;

// 系统状态
const systemStatus = ref({
  api: { status: 'online', responseTime: 45 },
  database: { status: 'online', connections: 12 },
  cache: { status: 'online', memoryUsage: 68 },
  server: { status: 'online', cpuUsage: 35 }
});

// 实时数据
const realtimeData = ref({
  trading: {
    todayCount: 156,
    todayAmount: 2456789.50
  },
  environment: {
    temperature: 22.5,
    humidity: 65
  }
});

// 告警信息
const alerts = ref([
  {
    id: 1,
    level: 'warning',
    title: '服务器CPU使用率过高',
    message: '服务器CPU使用率达到85%，建议检查系统负载',
    timestamp: new Date(Date.now() - 5 * 60 * 1000)
  },
  {
    id: 2,
    level: 'info',
    title: '数据备份完成',
    message: '今日数据备份已成功完成',
    timestamp: new Date(Date.now() - 30 * 60 * 1000)
  },
  {
    id: 3,
    level: 'error',
    title: '支付接口异常',
    message: '第三方支付接口响应超时，部分交易可能受影响',
    timestamp: new Date(Date.now() - 2 * 60 * 60 * 1000)
  }
]);

// 在线用户
const onlineUsers = ref({
  total: 245,
  admin: 8,
  user: 237
});

// 最近活动
const recentActivities = ref([
  {
    id: 1,
    user: '张三',
    action: '创建了新的牛只档案',
    type: 'create',
    timestamp: new Date(Date.now() - 2 * 60 * 1000)
  },
  {
    id: 2,
    user: '李四',
    action: '完成了交易订单 #12345',
    type: 'trade',
    timestamp: new Date(Date.now() - 5 * 60 * 1000)
  },
  {
    id: 3,
    user: '王五',
    action: '登录系统',
    type: 'login',
    timestamp: new Date(Date.now() - 8 * 60 * 1000)
  },
  {
    id: 4,
    user: '赵六',
    action: '更新了环境监测数据',
    type: 'update',
    timestamp: new Date(Date.now() - 12 * 60 * 1000)
  }
]);

// 初始化图表
const initCharts = () => {
  // 交易监控图表
  if (tradingChartContainer.value) {
    tradingChart = echarts.init(tradingChartContainer.value);
    updateTradingChart();
  }

  // 环境监测图表
  if (environmentChartContainer.value) {
    environmentChart = echarts.init(environmentChartContainer.value);
    updateEnvironmentChart();
  }
};

// 更新交易图表
const updateTradingChart = () => {
  if (!tradingChart) return;

  // 生成最近24小时的模拟数据
  const hours = [];
  const amounts = [];
  const counts = [];

  for (let i = 23; i >= 0; i--) {
    const hour = new Date();
    hour.setHours(hour.getHours() - i);
    hours.push(hour.getHours() + ':00');
    
    // 模拟交易数据，白天交易更活跃
    const hourOfDay = hour.getHours();
    const baseActivity = hourOfDay >= 9 && hourOfDay <= 18 ? 1 : 0.3;
    amounts.push(Math.floor(Math.random() * 50000 * baseActivity + 10000));
    counts.push(Math.floor(Math.random() * 20 * baseActivity + 5));
  }

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'cross' }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '10%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: hours,
      axisLabel: { fontSize: 10 }
    },
    yAxis: [
      {
        type: 'value',
        name: '金额',
        axisLabel: { fontSize: 10 }
      },
      {
        type: 'value',
        name: '笔数',
        axisLabel: { fontSize: 10 }
      }
    ],
    series: [
      {
        name: '交易金额',
        type: 'line',
        yAxisIndex: 0,
        data: amounts,
        itemStyle: { color: '#1890ff' },
        lineStyle: { width: 2 },
        symbol: 'none'
      },
      {
        name: '交易笔数',
        type: 'bar',
        yAxisIndex: 1,
        data: counts,
        itemStyle: { color: '#52c41a', opacity: 0.7 }
      }
    ]
  };

  tradingChart.setOption(option);
};

// 更新环境图表
const updateEnvironmentChart = () => {
  if (!environmentChart) return;

  // 生成最近24小时的环境数据
  const hours = [];
  const temperatures = [];
  const humidities = [];

  for (let i = 23; i >= 0; i--) {
    const hour = new Date();
    hour.setHours(hour.getHours() - i);
    hours.push(hour.getHours() + ':00');
    
    // 模拟温度和湿度数据
    const hourOfDay = hour.getHours();
    const baseTemp = 20 + 8 * Math.sin((hourOfDay / 24) * 2 * Math.PI);
    temperatures.push(Math.round((baseTemp + (Math.random() - 0.5) * 4) * 10) / 10);
    
    const baseHumidity = 60 + 15 * Math.sin(((hourOfDay + 12) / 24) * 2 * Math.PI);
    humidities.push(Math.round(baseHumidity + (Math.random() - 0.5) * 10));
  }

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'cross' }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '10%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: hours,
      axisLabel: { fontSize: 10 }
    },
    yAxis: [
      {
        type: 'value',
        name: '温度(°C)',
        axisLabel: { fontSize: 10 }
      },
      {
        type: 'value',
        name: '湿度(%)',
        axisLabel: { fontSize: 10 }
      }
    ],
    series: [
      {
        name: '温度',
        type: 'line',
        yAxisIndex: 0,
        data: temperatures,
        itemStyle: { color: '#ff4d4f' },
        lineStyle: { width: 2 },
        symbol: 'none',
        smooth: true
      },
      {
        name: '湿度',
        type: 'line',
        yAxisIndex: 1,
        data: humidities,
        itemStyle: { color: '#1890ff' },
        lineStyle: { width: 2 },
        symbol: 'none',
        smooth: true
      }
    ]
  };

  environmentChart.setOption(option);
};

// 获取告警状态
const getAlertStatus = (level) => {
  const statusMap = {
    error: 'error',
    warning: 'warning',
    info: 'success'
  };
  return statusMap[level] || 'default';
};

// 获取活动颜色
const getActivityColor = (type) => {
  const colorMap = {
    create: 'green',
    trade: 'blue',
    login: 'gray',
    update: 'orange'
  };
  return colorMap[type] || 'gray';
};

// 格式化时间
const formatTime = (timestamp) => {
  const now = new Date();
  const time = new Date(timestamp);
  const diff = now - time;
  
  if (diff < 60 * 1000) {
    return '刚刚';
  } else if (diff < 60 * 60 * 1000) {
    return Math.floor(diff / (60 * 1000)) + '分钟前';
  } else if (diff < 24 * 60 * 60 * 1000) {
    return Math.floor(diff / (60 * 60 * 1000)) + '小时前';
  } else {
    return time.toLocaleDateString();
  }
};

// 处理告警
const handleAlert = (alert) => {
  console.log('处理告警:', alert);
  // 这里可以添加处理告警的逻辑
};

// 更新实时数据
const updateRealtimeData = async () => {
  try {
    const response = await monitorAPI.getRealtimeData();
    if (response.success) {
      systemStatus.value = response.data.systemStatus;
      realtimeData.value = response.data.realtimeData;
      onlineUsers.value = response.data.onlineUsers;
    } else {
      // 模拟数据更新
      updateMockData();
    }
  } catch (error) {
    console.error('获取实时数据失败:', error);
    updateMockData();
  }
};

// 更新模拟数据
const updateMockData = () => {
  // 随机更新一些数据
  realtimeData.value.trading.todayCount += Math.floor(Math.random() * 3);
  realtimeData.value.trading.todayAmount += Math.random() * 10000;
  
  realtimeData.value.environment.temperature += (Math.random() - 0.5) * 0.5;
  realtimeData.value.environment.humidity += Math.floor((Math.random() - 0.5) * 2);
  
  systemStatus.value.server.cpuUsage = Math.max(20, Math.min(90, 
    systemStatus.value.server.cpuUsage + (Math.random() - 0.5) * 10));
  
  onlineUsers.value.total += Math.floor((Math.random() - 0.5) * 4);
};

// 处理窗口大小变化
const handleResize = () => {
  if (tradingChart) tradingChart.resize();
  if (environmentChart) environmentChart.resize();
};

onMounted(() => {
  nextTick(() => {
    initCharts();
    updateRealtimeData();
    
    // 设置定时更新
    updateTimer = setInterval(() => {
      updateRealtimeData();
      updateTradingChart();
      updateEnvironmentChart();
    }, 30000); // 30秒更新一次
    
    window.addEventListener('resize', handleResize);
  });
});

onBeforeUnmount(() => {
  if (updateTimer) {
    clearInterval(updateTimer);
  }
  if (tradingChart) {
    tradingChart.dispose();
  }
  if (environmentChart) {
    environmentChart.dispose();
  }
  window.removeEventListener('resize', handleResize);
});
</script>

<style scoped>
.realtime-monitor {
  width: 100%;
  height: 100%;
}

.system-overview {
  margin-bottom: 20px;
}

.status-card {
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.status-item {
  display: flex;
  align-items: center;
  padding: 8px 0;
}

.status-icon {
  margin-right: 12px;
}

.status-info {
  flex: 1;
}

.status-title {
  font-size: 12px;
  color: #666;
  margin-bottom: 4px;
}

.status-value {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 2px;
}

.status-detail {
  font-size: 11px;
  color: #999;
}

.realtime-data-stream {
  margin-bottom: 20px;
}

.mini-chart {
  width: 100%;
  height: 200px;
  margin-bottom: 12px;
}

.data-summary {
  text-align: center;
}

.alert-section {
  margin-bottom: 20px;
}

.alert-error {
  color: #ff4d4f;
  font-weight: 500;
}

.alert-warning {
  color: #faad14;
  font-weight: 500;
}

.alert-info {
  color: #1890ff;
  font-weight: 500;
}

.alert-description {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.alert-time {
  font-size: 11px;
  color: #999;
}

.online-users .user-stats {
  margin-bottom: 16px;
}

.activity-content {
  font-size: 12px;
}

.activity-user {
  font-weight: 500;
  color: #333;
}

.activity-action {
  color: #666;
  margin: 2px 0;
}

.activity-time {
  color: #999;
  font-size: 11px;
}

:deep(.ant-card-head-title) {
  font-size: 14px;
  font-weight: 500;
}

:deep(.ant-card-body) {
  padding: 16px;
}

:deep(.ant-list-item) {
  padding: 8px 0;
}

:deep(.ant-timeline-item-content) {
  margin-left: 20px;
}

:deep(.ant-statistic-title) {
  font-size: 11px;
}

:deep(.ant-statistic-content) {
  font-size: 16px;
}
</style>