<template>
  <div class="performance-monitor">
    <a-card title="系统性能监控" :bordered="false">
      <a-tabs default-active-key="1">
        <!-- 系统资源监控 -->
        <a-tab-pane key="1" tab="系统资源">
          <div class="resource-panels">
            <!-- CPU使用率 -->
            <a-card class="resource-card" :body-style="{ padding: '10px' }">
              <template #title>
                <div class="card-title">
                  <span>CPU使用率</span>
                  <a-tag :color="getCpuStatusColor()">{{ getCpuStatusText() }}</a-tag>
                </div>
              </template>
              <a-progress
                type="dashboard"
                :percent="cpuUsage"
                :stroke-color="getCpuStrokeColor()"
                :format="percent => `${percent.toFixed(1)}%`"
              />
              <div class="resource-details">
                <p>核心数: {{ cpuInfo.cores }}</p>
                <p>型号: {{ cpuInfo.model }}</p>
              </div>
            </a-card>
            
            <!-- 内存使用率 -->
            <a-card class="resource-card" :body-style="{ padding: '10px' }">
              <template #title>
                <div class="card-title">
                  <span>内存使用率</span>
                  <a-tag :color="getMemoryStatusColor()">{{ getMemoryStatusText() }}</a-tag>
                </div>
              </template>
              <a-progress
                type="dashboard"
                :percent="memoryUsage"
                :stroke-color="getMemoryStrokeColor()"
                :format="percent => `${percent.toFixed(1)}%`"
              />
              <div class="resource-details">
                <p>总内存: {{ formatBytes(memoryInfo.total) }}</p>
                <p>已用: {{ formatBytes(memoryInfo.used) }}</p>
                <p>可用: {{ formatBytes(memoryInfo.free) }}</p>
              </div>
            </a-card>
            
            <!-- 磁盘使用率 -->
            <a-card class="resource-card" :body-style="{ padding: '10px' }">
              <template #title>
                <div class="card-title">
                  <span>磁盘使用率</span>
                  <a-tag :color="getDiskStatusColor()">{{ getDiskStatusText() }}</a-tag>
                </div>
              </template>
              <a-progress
                type="dashboard"
                :percent="diskUsage"
                :stroke-color="getDiskStrokeColor()"
                :format="percent => `${percent.toFixed(1)}%`"
              />
              <div class="resource-details">
                <p>总空间: {{ formatBytes(diskInfo.total) }}</p>
                <p>已用: {{ formatBytes(diskInfo.used) }}</p>
                <p>可用: {{ formatBytes(diskInfo.free) }}</p>
              </div>
            </a-card>
          </div>
          
          <!-- 系统资源历史图表 -->
          <div class="chart-container">
            <a-card title="资源使用历史" :bordered="false">
              <div ref="resourceChart" style="height: 300px;"></div>
            </a-card>
          </div>
        </a-tab-pane>
        
        <!-- 数据库监控 -->
        <a-tab-pane key="2" tab="数据库性能">
          <div class="db-panels">
            <!-- 连接池状态 -->
            <a-card title="数据库连接池" :bordered="false">
              <a-row :gutter="16">
                <a-col :span="8">
                  <a-statistic 
                    title="活跃连接" 
                    :value="dbPoolStatus.acquired || 0" 
                    :value-style="{ color: '#3f8600' }" 
                  />
                </a-col>
                <a-col :span="8">
                  <a-statistic 
                    title="空闲连接" 
                    :value="dbPoolStatus.idle || 0" 
                    :value-style="{ color: '#1890ff' }" 
                  />
                </a-col>
                <a-col :span="8">
                  <a-statistic 
                    title="等待连接" 
                    :value="dbPoolStatus.pending || 0" 
                    :value-style="{ color: dbPoolStatus.pending > 0 ? '#cf1322' : '#8c8c8c' }" 
                  />
                </a-col>
              </a-row>
              <a-divider />
              <a-progress 
                :percent="dbPoolUtilization" 
                :stroke-color="getDbPoolStrokeColor()" 
                :format="percent => `利用率: ${percent.toFixed(1)}%`" 
              />
            </a-card>
            
            <!-- 慢查询列表 -->
            <a-card title="慢查询" :bordered="false" style="margin-top: 16px;">
              <a-table 
                :columns="slowQueryColumns" 
                :data-source="slowQueries" 
                :pagination="{ pageSize: 5 }" 
                :scroll="{ x: 800 }"
              >
                <template #bodyCell="{ column, record }">
                  <template v-if="column.key === 'duration'">
                    <span :style="{ color: getDurationColor(record.duration) }">
                      {{ record.duration }}ms
                    </span>
                  </template>
                  <template v-if="column.key === 'query'">
                    <a-tooltip :title="record.query">
                      <div class="query-text">{{ record.query }}</div>
                    </a-tooltip>
                  </template>
                </template>
              </a-table>
            </a-card>
            
            <!-- 查询模式统计 -->
            <a-card title="查询模式统计" :bordered="false" style="margin-top: 16px;">
              <a-table 
                :columns="queryPatternColumns" 
                :data-source="queryPatterns" 
                :pagination="{ pageSize: 5 }" 
                :scroll="{ x: 800 }"
              >
                <template #bodyCell="{ column, record }">
                  <template v-if="column.key === 'avgDuration'">
                    <span :style="{ color: getDurationColor(record.avgDuration) }">
                      {{ record.avgDuration.toFixed(2) }}ms
                    </span>
                  </template>
                  <template v-if="column.key === 'pattern'">
                    <a-tooltip :title="record.pattern">
                      <div class="query-text">{{ record.pattern }}</div>
                    </a-tooltip>
                  </template>
                </template>
              </a-table>
            </a-card>
          </div>
        </a-tab-pane>
        
        <!-- API性能监控 -->
        <a-tab-pane key="3" tab="API性能">
          <div class="api-panels">
            <!-- API总体统计 -->
            <a-card title="API请求统计" :bordered="false">
              <a-row :gutter="16">
                <a-col :span="6">
                  <a-statistic 
                    title="总请求数" 
                    :value="apiStats.totalRequests || 0" 
                  />
                </a-col>
                <a-col :span="6">
                  <a-statistic 
                    title="平均响应时间" 
                    :value="apiStats.avgResponseTime || 0" 
                    :precision="2"
                    suffix="ms"
                    :value-style="{ color: getApiResponseTimeColor() }" 
                  />
                </a-col>
                <a-col :span="6">
                  <a-statistic 
                    title="错误率" 
                    :value="apiStats.errorRate || 0" 
                    :precision="2"
                    suffix="%"
                    :value-style="{ color: getApiErrorRateColor() }" 
                  />
                </a-col>
                <a-col :span="6">
                  <a-statistic 
                    title="请求/分钟" 
                    :value="apiStats.requestsPerMinute || 0" 
                    :precision="2"
                  />
                </a-col>
              </a-row>
            </a-card>
            
            <!-- API端点性能 -->
            <a-card title="API端点性能" :bordered="false" style="margin-top: 16px;">
              <a-table 
                :columns="apiEndpointColumns" 
                :data-source="apiEndpoints" 
                :pagination="{ pageSize: 5 }" 
                :scroll="{ x: 800 }"
              >
                <template #bodyCell="{ column, record }">
                  <template v-if="column.key === 'avgDuration'">
                    <span :style="{ color: getDurationColor(record.avgDuration) }">
                      {{ record.avgDuration.toFixed(2) }}ms
                    </span>
                  </template>
                  <template v-if="column.key === 'errorRate'">
                    <span :style="{ color: getErrorRateColor(record.errorRate) }">
                      {{ record.errorRate.toFixed(2) }}%
                    </span>
                  </template>
                </template>
              </a-table>
            </a-card>
            
            <!-- API响应时间图表 -->
            <a-card title="API响应时间趋势" :bordered="false" style="margin-top: 16px;">
              <div ref="apiResponseChart" style="height: 300px;"></div>
            </a-card>
          </div>
        </a-tab-pane>
        
        <!-- 警报配置 -->
        <a-tab-pane key="4" tab="警报配置">
          <a-card :bordered="false">
            <a-form :model="alertThresholds" layout="vertical">
              <a-divider orientation="left">系统资源警报阈值</a-divider>
              <a-row :gutter="16">
                <a-col :span="8">
                  <a-form-item label="CPU使用率 (%)">
                    <a-input-number 
                      v-model="alertThresholds.system.cpuUsage" 
                      :min="0" 
                      :max="100" 
                      style="width: 100%" 
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item label="内存使用率 (%)">
                    <a-input-number 
                      v-model="alertThresholds.system.memoryUsage" 
                      :min="0" 
                      :max="100" 
                      style="width: 100%" 
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item label="磁盘使用率 (%)">
                    <a-input-number 
                      v-model="alertThresholds.system.diskUsage" 
                      :min="0" 
                      :max="100" 
                      style="width: 100%" 
                    />
                  </a-form-item>
                </a-col>
              </a-row>
              
              <a-divider orientation="left">数据库警报阈值</a-divider>
              <a-row :gutter="16">
                <a-col :span="8">
                  <a-form-item label="连接池利用率 (%)">
                    <a-input-number 
                      v-model="alertThresholds.database.connectionPoolUtilization" 
                      :min="0" 
                      :max="100" 
                      style="width: 100%" 
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item label="慢查询数量">
                    <a-input-number 
                      v-model="alertThresholds.database.slowQueryCount" 
                      :min="0" 
                      style="width: 100%" 
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item label="错误率 (%)">
                    <a-input-number 
                      v-model="alertThresholds.database.errorRate" 
                      :min="0" 
                      :max="100" 
                      style="width: 100%" 
                    />
                  </a-form-item>
                </a-col>
              </a-row>
              
              <a-divider orientation="left">API警报阈值</a-divider>
              <a-row :gutter="16">
                <a-col :span="8">
                  <a-form-item label="响应时间 (ms)">
                    <a-input-number 
                      v-model="alertThresholds.api.responseTime" 
                      :min="0" 
                      style="width: 100%" 
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item label="错误率 (%)">
                    <a-input-number 
                      v-model="alertThresholds.api.errorRate" 
                      :min="0" 
                      :max="100" 
                      style="width: 100%" 
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item label="请求率 (每分钟)">
                    <a-input-number 
                      v-model="alertThresholds.api.requestRate" 
                      :min="0" 
                      style="width: 100%" 
                    />
                  </a-form-item>
                </a-col>
              </a-row>
              
              <a-form-item>
                <a-button type="primary" @click="saveAlertThresholds">保存配置</a-button>
                <a-button style="margin-left: 8px" @click="resetAlertThresholds">重置</a-button>
              </a-form-item>
            </a-form>
          </a-card>
        </a-tab-pane>
      </a-tabs>
    </a-card>
  </div>
</template>

<script>
import { defineComponent, ref, onMounted, onUnmounted, reactive, toRefs } from 'vue';
import { message } from 'ant-design-vue';
import * as echarts from 'echarts';
import axios from 'axios';

export default defineComponent({
  name: 'PerformanceMonitor',
  setup() {
    // 系统资源状态
    const state = reactive({
      // CPU信息
      cpuUsage: 0,
      cpuInfo: {
        cores: 0,
        model: '未知',
        speed: 0
      },
      
      // 内存信息
      memoryUsage: 0,
      memoryInfo: {
        total: 0,
        free: 0,
        used: 0
      },
      
      // 磁盘信息
      diskUsage: 0,
      diskInfo: {
        total: 0,
        free: 0,
        used: 0
      },
      
      // 数据库连接池状态
      dbPoolStatus: {
        acquired: 0,
        idle: 0,
        pending: 0,
        max: 10
      },
      dbPoolUtilization: 0,
      
      // 慢查询
      slowQueries: [],
      
      // 查询模式统计
      queryPatterns: [],
      
      // API统计
      apiStats: {
        totalRequests: 0,
        totalErrors: 0,
        errorRate: 0,
        avgResponseTime: 0,
        requestsPerMinute: 0
      },
      
      // API端点性能
      apiEndpoints: [],
      
      // 历史数据
      historyData: {
        timestamps: [],
        cpu: [],
        memory: [],
        disk: [],
        apiResponseTime: []
      },
      
      // 警报阈值
      alertThresholds: reactive({
        system: {
          cpuUsage: 80,
          memoryUsage: 80,
          diskUsage: 80
        },
        database: {
          connectionPoolUtilization: 80,
          slowQueryCount: 5,
          errorRate: 5
        },
        api: {
          responseTime: 500,
          errorRate: 5,
          requestRate: 1000
        }
      }),
      
      // 默认警报阈值（用于重置）
      defaultAlertThresholds: reactive({
        system: {
          cpuUsage: 80,
          memoryUsage: 80,
          diskUsage: 80
        },
        database: {
          connectionPoolUtilization: 80,
          slowQueryCount: 5,
          errorRate: 5
        },
        api: {
          responseTime: 500,
          errorRate: 5,
          requestRate: 1000
        }
      })
    });
    
    // 图表引用
    const resourceChart = ref(null);
    const apiResponseChart = ref(null);
    
    // 图表实例
    let resourceChartInstance = null;
    let apiResponseChartInstance = null;
    
    // 定时器
    let refreshTimer = null;
    
    // 表格列定义
    const slowQueryColumns = [
      {
        title: '查询',
        dataIndex: 'query',
        key: 'query',
        ellipsis: true,
        width: '50%'
      },
      {
        title: '执行时间',
        dataIndex: 'duration',
        key: 'duration',
        sorter: (a, b) => a.duration - b.duration,
        width: '15%'
      },
      {
        title: '执行时间',
        dataIndex: 'timestamp',
        key: 'timestamp',
        width: '20%'
      },
      {
        title: '参数',
        dataIndex: 'params',
        key: 'params',
        ellipsis: true,
        width: '15%'
      }
    ];
    
    const queryPatternColumns = [
      {
        title: '查询模式',
        dataIndex: 'pattern',
        key: 'pattern',
        ellipsis: true,
        width: '40%'
      },
      {
        title: '执行次数',
        dataIndex: 'count',
        key: 'count',
        sorter: (a, b) => a.count - b.count,
        width: '15%'
      },
      {
        title: '平均执行时间',
        dataIndex: 'avgDuration',
        key: 'avgDuration',
        sorter: (a, b) => a.avgDuration - b.avgDuration,
        width: '15%'
      },
      {
        title: '最大执行时间',
        dataIndex: 'maxDuration',
        key: 'maxDuration',
        width: '15%'
      },
      {
        title: '最后执行',
        dataIndex: 'lastExecuted',
        key: 'lastExecuted',
        width: '15%'
      }
    ];
    
    const apiEndpointColumns = [
      {
        title: '端点',
        dataIndex: 'endpoint',
        key: 'endpoint',
        width: '30%'
      },
      {
        title: '请求数',
        dataIndex: 'count',
        key: 'count',
        sorter: (a, b) => a.count - b.count,
        width: '15%'
      },
      {
        title: '平均响应时间',
        dataIndex: 'avgDuration',
        key: 'avgDuration',
        sorter: (a, b) => a.avgDuration - b.avgDuration,
        width: '15%'
      },
      {
        title: '错误率',
        dataIndex: 'errorRate',
        key: 'errorRate',
        sorter: (a, b) => a.errorRate - b.errorRate,
        width: '15%'
      },
      {
        title: '最大响应时间',
        dataIndex: 'maxDuration',
        key: 'maxDuration',
        width: '15%'
      }
    ];
    
    // 初始化图表
    const initCharts = () => {
      // 初始化资源使用图表
      if (resourceChart.value) {
        resourceChartInstance = echarts.init(resourceChart.value);
        const option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'cross',
              label: {
                backgroundColor: '#6a7985'
              }
            }
          },
          legend: {
            data: ['CPU使用率', '内存使用率', '磁盘使用率']
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            boundaryGap: false,
            data: state.historyData.timestamps
          },
          yAxis: {
            type: 'value',
            max: 100,
            min: 0,
            axisLabel: {
              formatter: '{value}%'
            }
          },
          series: [
            {
              name: 'CPU使用率',
              type: 'line',
              stack: 'Total',
              areaStyle: {},
              emphasis: {
                focus: 'series'
              },
              data: state.historyData.cpu
            },
            {
              name: '内存使用率',
              type: 'line',
              stack: 'Total',
              areaStyle: {},
              emphasis: {
                focus: 'series'
              },
              data: state.historyData.memory
            },
            {
              name: '磁盘使用率',
              type: 'line',
              stack: 'Total',
              areaStyle: {},
              emphasis: {
                focus: 'series'
              },
              data: state.historyData.disk
            }
          ]
        };
        resourceChartInstance.setOption(option);
      }
      
      // 初始化API响应时间图表
      if (apiResponseChart.value) {
        apiResponseChartInstance = echarts.init(apiResponseChart.value);
        const option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'cross',
              label: {
                backgroundColor: '#6a7985'
              }
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            boundaryGap: false,
            data: state.historyData.timestamps
          },
          yAxis: {
            type: 'value',
            axisLabel: {
              formatter: '{value}ms'
            }
          },
          series: [
            {
              name: 'API响应时间',
              type: 'line',
              data: state.historyData.apiResponseTime,
              markLine: {
                data: [
                  {
                    name: '警报阈值',
                    yAxis: state.alertThresholds.api.responseTime,
                    lineStyle: {
                      color: '#ff4d4f'
                    }
                  }
                ]
              }
            }
          ]
        };
        apiResponseChartInstance.setOption(option);
      }
    };
    
    // 更新图表数据
    const updateCharts = () => {
      if (resourceChartInstance) {
        resourceChartInstance.setOption({
          xAxis: {
            data: state.historyData.timestamps
          },
          series: [
            {
              data: state.historyData.cpu
            },
            {
              data: state.historyData.memory
            },
            {
              data: state.historyData.disk
            }
          ]
        });
      }
      
      if (apiResponseChartInstance) {
        apiResponseChartInstance.setOption({
          xAxis: {
            data: state.historyData.timestamps
          },
          series: [
            {
              data: state.historyData.apiResponseTime,
              markLine: {
                data: [
                  {
                    name: '警报阈值',
                    yAxis: state.alertThresholds.api.responseTime
                  }
                ]
              }
            }
          ]
        });
      }
    };
    
    // 获取性能数据
    const fetchPerformanceData = async () => {
      try {
        const response = await axios.get('/api/performance/metrics');
        const data = response.data;
        
        // 更新系统资源数据
        if (data.system && data.system.current) {
          state.cpuUsage = data.system.current.cpu.usage;
          state.cpuInfo = {
            cores: data.system.current.cpu.cores,
            model: data.system.current.cpu.model,
            speed: data.system.current.cpu.speed
          };
          
          state.memoryUsage = data.system.current.memory.usage;
          state.memoryInfo = {
            total: data.system.current.memory.total,
            free: data.system.current.memory.free,
            used: data.system.current.memory.used
          };
          
          state.diskUsage = data.system.current.disk.usage;
          state.diskInfo = {
            total: data.system.current.disk.total,
            free: data.system.current.disk.free,
            used: data.system.current.disk.used
          };
        }
        
        // 更新数据库数据
        if (data.database) {
          if (data.database.poolStatus) {
            state.dbPoolStatus = data.database.poolStatus;
            state.dbPoolUtilization = data.database.poolStatus.acquired / 
              (data.database.poolStatus.acquired + data.database.poolStatus.idle) * 100 || 0;
          }
          
          if (data.database.slowQueries) {
            state.slowQueries = data.database.slowQueries.map((query, index) => ({
              ...query,
              key: index
            }));
          }
          
          if (data.database.queryPatterns) {
            state.queryPatterns = Object.entries(data.database.queryPatterns).map(([pattern, stats], index) => ({
              key: index,
              pattern,
              ...stats
            }));
          }
        }
        
        // 更新API数据
        if (data.api) {
          state.apiStats = data.api;
          
          if (data.api.endpoints) {
            state.apiEndpoints = data.api.endpoints.map((endpoint, index) => ({
              ...endpoint,
              key: index
            }));
          }
        }
        
        // 更新历史数据
        const timestamp = new Date().toLocaleTimeString();
        state.historyData.timestamps.push(timestamp);
        state.historyData.cpu.push(state.cpuUsage);
        state.historyData.memory.push(state.memoryUsage);
        state.historyData.disk.push(state.diskUsage);
        state.historyData.apiResponseTime.push(state.apiStats.avgResponseTime || 0);
        
        // 限制历史数据长度
        const maxHistoryPoints = 20;
        if (state.historyData.timestamps.length > maxHistoryPoints) {
          state.historyData.timestamps.shift();
          state.historyData.cpu.shift();
          state.historyData.memory.shift();
          state.historyData.disk.shift();
          state.historyData.apiResponseTime.shift();
        }
        
        // 更新图表
        updateCharts();
        
        // 获取警报阈值
        if (data.alertThresholds) {
          state.alertThresholds = data.alertThresholds;
        }
      } catch (error) {
        console.error('获取性能数据失败:', error);
      }
    };
    
    // 保存警报阈值
    const saveAlertThresholds = async () => {
      try {
        await axios.post('/api/performance/thresholds', state.alertThresholds);
        message.success('警报阈值已保存');
      } catch (error) {
        console.error('保存警报阈值失败:', error);
        message.error('保存警报阈值失败');
      }
    };
    
    // 重置警报阈值
    const resetAlertThresholds = () => {
      Object.keys(state.defaultAlertThresholds).forEach(category => {
        Object.keys(state.defaultAlertThresholds[category]).forEach(key => {
          state.alertThresholds[category][key] = state.defaultAlertThresholds[category][key];
        });
      });
      message.success('警报阈值已重置');
    };
    
    // 格式化字节数
    const formatBytes = (bytes, decimals = 2) => {
      if (bytes === 0) return '0 Bytes';
      
      const k = 1024;
      const dm = decimals < 0 ? 0 : decimals;
      const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
      
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      
      return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
    };
    
    // 获取CPU状态颜色
    const getCpuStatusColor = () => {
      if (state.cpuUsage >= state.alertThresholds.system.cpuUsage) return 'red';
      if (state.cpuUsage >= state.alertThresholds.system.cpuUsage * 0.8) return 'orange';
      return 'green';
    };
    
    // 获取CPU状态文本
    const getCpuStatusText = () => {
      if (state.cpuUsage >= state.alertThresholds.system.cpuUsage) return '警告';
      if (state.cpuUsage >= state.alertThresholds.system.cpuUsage * 0.8) return '注意';
      return '正常';
    };
    
    // 获取CPU进度条颜色
    const getCpuStrokeColor = () => {
      if (state.cpuUsage >= state.alertThresholds.system.cpuUsage) return '#ff4d4f';
      if (state.cpuUsage >= state.alertThresholds.system.cpuUsage * 0.8) return '#faad14';
      return '#52c41a';
    };
    
    // 获取内存状态颜色
    const getMemoryStatusColor = () => {
      if (state.memoryUsage >= state.alertThresholds.system.memoryUsage) return 'red';
      if (state.memoryUsage >= state.alertThresholds.system.memoryUsage * 0.8) return 'orange';
      return 'green';
    };
    
    // 获取内存状态文本
    const getMemoryStatusText = () => {
      if (state.memoryUsage >= state.alertThresholds.system.memoryUsage) return '警告';
      if (state.memoryUsage >= state.alertThresholds.system.memoryUsage * 0.8) return '注意';
      return '正常';
    };
    
    // 获取内存进度条颜色
    const getMemoryStrokeColor = () => {
      if (state.memoryUsage >= state.alertThresholds.system.memoryUsage) return '#ff4d4f';
      if (state.memoryUsage >= state.alertThresholds.system.memoryUsage * 0.8) return '#faad14';
      return '#52c41a';
    };
    
    // 获取磁盘状态颜色
    const getDiskStatusColor = () => {
      if (state.diskUsage >= state.alertThresholds.system.diskUsage) return 'red';
      if (state.diskUsage >= state.alertThresholds.system.diskUsage * 0.8) return 'orange';
      return 'green';
    };
    
    // 获取磁盘状态文本
    const getDiskStatusText = () => {
      if (state.diskUsage >= state.alertThresholds.system.diskUsage) return '警告';
      if (state.diskUsage >= state.alertThresholds.system.diskUsage * 0.8) return '注意';
      return '正常';
    };
    
    // 获取磁盘进度条颜色
    const getDiskStrokeColor = () => {
      if (state.diskUsage >= state.alertThresholds.system.diskUsage) return '#ff4d4f';
      if (state.diskUsage >= state.alertThresholds.system.diskUsage * 0.8) return '#faad14';
      return '#52c41a';
    };
    
    // 获取数据库连接池进度条颜色
    const getDbPoolStrokeColor = () => {
      if (state.dbPoolUtilization >= state.alertThresholds.database.connectionPoolUtilization) return '#ff4d4f';
      if (state.dbPoolUtilization >= state.alertThresholds.database.connectionPoolUtilization * 0.8) return '#faad14';
      return '#52c41a';
    };
    
    // 获取执行时间颜色
    const getDurationColor = (duration) => {
      if (duration >= state.alertThresholds.api.responseTime) return '#ff4d4f';
      if (duration >= state.alertThresholds.api.responseTime * 0.8) return '#faad14';
      return '#52c41a';
    };
    
    // 获取API响应时间颜色
    const getApiResponseTimeColor = () => {
      if (state.apiStats.avgResponseTime >= state.alertThresholds.api.responseTime) return '#ff4d4f';
      if (state.apiStats.avgResponseTime >= state.alertThresholds.api.responseTime * 0.8) return '#faad14';
      return '#52c41a';
    };
    
    // 获取API错误率颜色
    const getApiErrorRateColor = () => {
      if (state.apiStats.errorRate >= state.alertThresholds.api.errorRate) return '#ff4d4f';
      if (state.apiStats.errorRate >= state.alertThresholds.api.errorRate * 0.8) return '#faad14';
      return '#52c41a';
    };
    
    // 获取错误率颜色
    const getErrorRateColor = (rate) => {
      if (rate >= state.alertThresholds.api.errorRate) return '#ff4d4f';
      if (rate >= state.alertThresholds.api.errorRate * 0.8) return '#faad14';
      return '#52c41a';
    };
    
    // 组件挂载时
    onMounted(() => {
      // 初始化图表
      initCharts();
      
      // 获取初始数据
      fetchPerformanceData();
      
      // 设置定时刷新
      refreshTimer = setInterval(fetchPerformanceData, 10000); // 每10秒刷新一次
      
      // 监听窗口大小变化，调整图表大小
      window.addEventListener('resize', () => {
        if (resourceChartInstance) resourceChartInstance.resize();
        if (apiResponseChartInstance) apiResponseChartInstance.resize();
      });
    });
    
    // 组件卸载时
    onUnmounted(() => {
      // 清除定时器
      if (refreshTimer) clearInterval(refreshTimer);
      
      // 销毁图表实例
      if (resourceChartInstance) resourceChartInstance.dispose();
      if (apiResponseChartInstance) apiResponseChartInstance.dispose();
      
      // 移除事件监听
      window.removeEventListener('resize', () => {});
    });
    
    return {
      ...toRefs(state),
      resourceChart,
      apiResponseChart,
      slowQueryColumns,
      queryPatternColumns,
      apiEndpointColumns,
      saveAlertThresholds,
      resetAlertThresholds,
      formatBytes,
      getCpuStatusColor,
      getCpuStatusText,
      getCpuStrokeColor,
      getMemoryStatusColor,
      getMemoryStatusText,
      getMemoryStrokeColor,
      getDiskStatusColor,
      getDiskStatusText,
      getDiskStrokeColor,
      getDbPoolStrokeColor,
      getDurationColor,
      getApiResponseTimeColor,
      getApiErrorRateColor,
      getErrorRateColor
    };
  }
});
</script>

<style scoped>
.performance-monitor {
  margin: 16px;
}

.resource-panels {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin-bottom: 16px;
}

.resource-card {
  flex: 1;
  min-width: 250px;
  text-align: center;
}

.card-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.resource-details {
  margin-top: 16px;
  text-align: left;
}

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

.query-text {
  max-width: 300px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>