<template>
  <div class="chart-container">
    <el-row :gutter="20">
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>CPU使用率</span>
            </div>
          </template>
          <div ref="cpuChart" class="chart"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>内存使用率</span>
            </div>
          </template>
          <div ref="memoryChart" class="chart"></div>
        </el-card>
      </el-col>
    </el-row>
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>磁盘使用率</span>
            </div>
          </template>
          <div ref="diskChart" class="chart"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>网络流量</span>
            </div>
          </template>
          <div ref="networkChart" class="chart"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, defineProps } from 'vue';
import { useRoute } from 'vue-router';
import * as echarts from 'echarts';
import { getServerStatus, getTraffic, getDiskInfo } from '@/utils/acs/server';

const props = defineProps({
  Type: {
    type: String,
    required: true
  }
});

const route = useRoute();
const cpuChart = ref(null);
const memoryChart = ref(null);
const diskChart = ref(null);
const networkChart = ref(null);

let cpuChartInstance = null;
let memoryChartInstance = null;
let diskChartInstance = null;
let networkChartInstance = null;

// 定时器ID
let timer = null;

// 初始化图表
const initCharts = () => {
  // 初始化CPU图表
  cpuChartInstance = echarts.init(cpuChart.value);
  const cpuOption = {
    tooltip: {
      formatter: '{a} <br/>{b} : {c}%'
    },
    series: [
      {
        name: 'CPU',
        type: 'gauge',
        detail: { formatter: '{value}%' },
        data: [{ value: 0, name: '使用率' }],
        axisLine: {
          lineStyle: {
            width: 30,
            color: [
              [0.3, '#67C23A'],
              [0.7, '#E6A23C'],
              [1, '#F56C6C']
            ]
          }
        }
      }
    ]
  };
  cpuChartInstance.setOption(cpuOption);

  // 初始化内存图表
  memoryChartInstance = echarts.init(memoryChart.value);
  const memoryOption = {
    tooltip: {
      formatter: '{a} <br/>{b} : {c}%'
    },
    series: [
      {
        name: '内存',
        type: 'gauge',
        detail: { formatter: '{value}%' },
        data: [{ value: 0, name: '使用率' }],
        axisLine: {
          lineStyle: {
            width: 30,
            color: [
              [0.3, '#67C23A'],
              [0.7, '#E6A23C'],
              [1, '#F56C6C']
            ]
          }
        }
      }
    ]
  };
  memoryChartInstance.setOption(memoryOption);

  // 初始化磁盘图表
  diskChartInstance = echarts.init(diskChart.value);
  const diskOption = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b} : {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: ['已使用', '可用']
    },
    series: [
      {
        name: '磁盘空间',
        type: 'pie',
        radius: '55%',
        center: ['50%', '60%'],
        data: [
          { value: 0, name: '已使用' },
          { value: 100, name: '可用' }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  };
  diskChartInstance.setOption(diskOption);

  // 初始化网络流量图表
  networkChartInstance = echarts.init(networkChart.value);
  const networkOption = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['上传', '下载']
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: Array(10).fill('').map((_, i) => `${i}`)
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '{value} MB/s'
      }
    },
    series: [
      {
        name: '上传',
        type: 'line',
        data: Array(10).fill(0),
        areaStyle: {}
      },
      {
        name: '下载',
        type: 'line',
        data: Array(10).fill(0),
        areaStyle: {}
      }
    ]
  };
  networkChartInstance.setOption(networkOption);
};

// 更新图表数据
const updateCharts = async () => {
  try {
    // 获取服务器状态
    const statusRes = await getServerStatus(route.query.server_id);
    if (statusRes && statusRes.data && statusRes.data.code === 200) {
      const statusData = statusRes.data.data;
      
      // 更新CPU图表
      if (cpuChartInstance) {
        const cpuUsage = statusData.cpu_usage || 0;
        cpuChartInstance.setOption({
          series: [
            {
              data: [{ value: parseFloat(cpuUsage).toFixed(2), name: '使用率' }]
            }
          ]
        });
      }
      
      // 更新内存图表
      if (memoryChartInstance) {
        const memoryUsage = statusData.memory_usage || 0;
        memoryChartInstance.setOption({
          series: [
            {
              data: [{ value: parseFloat(memoryUsage).toFixed(2), name: '使用率' }]
            }
          ]
        });
      }
    }

    // 获取磁盘信息
    const diskRes = await getDiskInfo(route.query.server_id);
    if (diskRes && diskRes.data && diskRes.data.code === 200) {
      const diskData = diskRes.data.data;
      if (diskChartInstance && diskData) {
        const used = diskData.used || 0;
        const available = diskData.available || 100;
        diskChartInstance.setOption({
          series: [
            {
              data: [
                { value: used, name: '已使用' },
                { value: available, name: '可用' }
              ]
            }
          ]
        });
      }
    }

    // 获取网络流量
    const trafficRes = await getTraffic(route.query.server_id);
    if (trafficRes && trafficRes.data && trafficRes.data.code === 200) {
      const trafficData = trafficRes.data.data;
      if (networkChartInstance && trafficData) {
        // 假设API返回的是最近的流量数据点
        const uploadData = trafficData.upload || Array(10).fill(0);
        const downloadData = trafficData.download || Array(10).fill(0);
        
        networkChartInstance.setOption({
          series: [
            {
              data: uploadData.slice(-10)
            },
            {
              data: downloadData.slice(-10)
            }
          ]
        });
      }
    }
  } catch (error) {
    console.error('更新图表数据失败:', error);
  }
};

// 调整图表大小
const resizeCharts = () => {
  cpuChartInstance && cpuChartInstance.resize();
  memoryChartInstance && memoryChartInstance.resize();
  diskChartInstance && diskChartInstance.resize();
  networkChartInstance && networkChartInstance.resize();
};

onMounted(() => {
  // 初始化图表
  initCharts();
  
  // 定时更新数据
  updateCharts();
  timer = setInterval(updateCharts, 30000); // 每30秒更新一次
  
  // 监听窗口大小变化
  window.addEventListener('resize', resizeCharts);
});

onBeforeUnmount(() => {
  // 清除定时器
  if (timer) {
    clearInterval(timer);
    timer = null;
  }
  
  // 移除事件监听
  window.removeEventListener('resize', resizeCharts);
  
  // 销毁图表实例
  cpuChartInstance && cpuChartInstance.dispose();
  memoryChartInstance && memoryChartInstance.dispose();
  diskChartInstance && diskChartInstance.dispose();
  networkChartInstance && networkChartInstance.dispose();
});
</script>

<style scoped>
.chart-container {
  margin-top: 20px;
}

.chart-card {
  margin-bottom: 20px;
}

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

.chart {
  height: 300px;
}
</style> 