<template>
  <div class="gpu-monitor-wrapper">
    <div class="monitor-header">
      <div class="header-left">
        <h3 class="page-title"><i class="el-icon-odometer"></i> 算力资源实时监控</h3>
        <span class="refresh-tip">
          <i class="el-icon-loading" v-if="loading"></i>
          <i class="el-icon-time" v-else></i>
          自动刷新中（10s/次）
        </span>
      </div>
      <el-button type="primary" size="small" round icon="el-icon-refresh" :loading="loading" @click="fetchGpuData">立即同步</el-button>
    </div>

    <el-row :gutter="20">
      <el-col :span="14">
        <el-card shadow="never" class="info-card">
          <div slot="header" class="card-header">
            <span><i class="el-icon-processor"></i> 显卡硬件：{{ gpuData ? gpuData.gpu.model : '检测中...' }}</span>
            <el-tag type="success" size="mini" effect="dark">在线</el-tag>
          </div>

          <div v-if="gpuData" class="gpu-usage-flex">
            <div class="gauge-section">
              <el-progress
                type="dashboard"
                :percentage="calculatePercentage(gpuData.gpu.mem_used, gpuData.gpu.mem_total)"
                :stroke-width="12"
                :width="160"
                :color="customColors"
              ></el-progress>
              <div class="gauge-label">总显存占用率</div>
            </div>

            <div class="details-section">
              <div class="detail-item">
                <span class="label">已使用 (Used)</span>
                <span class="value used">{{ gpuData.gpu.mem_used }}</span>
              </div>
              <el-progress :percentage="calculatePercentage(gpuData.gpu.mem_used, gpuData.gpu.mem_total)" :show-text="false" :stroke-width="8" :color="customColors"></el-progress>

              <el-divider></el-divider>

              <div class="mini-stats">
                <div class="mini-item">
                  <div class="m-label">空闲 (Free)</div>
                  <div class="m-value">{{ gpuData.gpu.mem_free }}</div>
                </div>
                <div class="mini-item">
                  <div class="m-label">总量 (Total)</div>
                  <div class="m-value">{{ gpuData.gpu.mem_total }}</div>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="10">
        <el-card shadow="never" class="info-card">
          <div slot="header" class="card-header">
            <span><i class="el-icon-connection"></i> PyTorch 显存池</span>
          </div>
          <div v-if="gpuData" class="torch-container">
            <div class="torch-box reserved">
              <div class="t-label">Reserved (预留)</div>
              <div class="t-value">{{ gpuData.torch.reserved }}</div>
              <div class="t-desc">Torch 预先向系统申请的缓存</div>
            </div>
            <div class="torch-box allocated">
              <div class="t-label">Allocated (分配)</div>
              <div class="t-value">{{ gpuData.torch.allocated }}</div>
              <div class="t-desc">当前 AI 模型实际占用的显存</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-card shadow="never" class="m-t-20 table-card">
      <div slot="header" class="card-header">
        <span><i class="el-icon-collection"></i> Ollama 推理引擎：运行中模型</span>
      </div>
      <el-table :data="gpuData ? gpuData.ollama : []" size="medium" style="width: 100%">
        <el-table-column label="模型名称" min-width="150">
          <template slot-scope="scope">
            <div class="model-cell">
              <div class="model-icon"><i class="el-icon-box"></i></div>
              <span class="model-name-text">{{ scope.row.model_name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="size" label="磁盘大小" width="120"></el-table-column>
        <el-table-column prop="size_vram" label="显存占用 (VRAM)" width="150">
          <template slot-scope="scope">
            <span class="vram-text">{{ scope.row.size_vram }}</span>
          </template>
        </el-table-column>
        <el-table-column label="GPU 负载">
          <template slot-scope="scope">
            <el-progress
              :percentage="Number(scope.row.gpu_percentage)"
              :color="scope.row.gpu_percentage > 90 ? '#67c23a' : '#e6a23c'"
              :stroke-width="10"
              stroke-linecap="round"
            ></el-progress>
          </template>
        </el-table-column>
        <el-table-column prop="stat" label="活跃状态" width="120" align="center">
          <template slot-scope="scope">
            <span class="status-dot" :class="{ 'is-active': scope.row.stat.includes('OK') }"></span>
            {{ scope.row.stat }}
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'GpuDashboard',
  data() {
    return {
      gpuData: null,
      loading: false,
      timer: null,
      customColors: [
        {color: '#67c23a', percentage: 40},
        {color: '#e6a23c', percentage: 75},
        {color: '#f56c6c', percentage: 90}
      ]
    };
  },
  mounted() {
    this.fetchGpuData();
    this.timer = setInterval(this.fetchGpuData, 10000);
  },
  beforeDestroy() {
    if (this.timer) clearInterval(this.timer);
  },
  methods: {
    async fetchGpuData() {
      this.loading = true;
      try {
        const response = await axios.get('/api1/gpu/info');
        this.gpuData = response.data;
      } catch (error) {
        this.$message.error('获取 GPU 监控数据失败');
      } finally {
        setTimeout(() => { this.loading = false; }, 500);
      }
    },
    calculatePercentage(usedStr, totalStr) {
      const used = parseFloat(usedStr) || 0;
      const total = parseFloat(totalStr) || 1;
      return Math.min(Math.round((used / total) * 100), 100);
    }
  }
};
</script>

<style scoped>
.gpu-monitor-wrapper { padding: 0; }
.m-t-20 { margin-top: 20px; }

/* 头部样式 */
.monitor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.page-title { margin: 0; font-size: 18px; color: #303133; display: flex; align-items: center; }
.page-title i { margin-right: 8px; color: #409EFF; }
.refresh-tip { font-size: 12px; color: #909399; margin-left: 15px; }

/* 卡片通用 */
.info-card { border: none; border-radius: 8px; }
.card-header { display: flex; justify-content: space-between; align-items: center; font-weight: bold; }

/* GPU 显存布局 */
.gpu-usage-flex {
  display: flex;
  align-items: center;
  padding: 10px 0;
}
.gauge-section { width: 200px; text-align: center; border-right: 1px solid #f0f2f5; }
.gauge-label { font-size: 13px; color: #909399; margin-top: -15px; }

.details-section { flex: 1; padding-left: 30px; }
.detail-item { display: flex; justify-content: space-between; margin-bottom: 8px; align-items: flex-end; }
.detail-item .label { font-size: 13px; color: #606266; }
.detail-item .value { font-size: 20px; font-weight: bold; font-family: 'PingFang SC', sans-serif; }
.value.used { color: #f56c6c; }

.mini-stats { display: flex; gap: 40px; }
.m-label { font-size: 12px; color: #909399; margin-bottom: 4px; }
.m-value { font-size: 14px; font-weight: 600; color: #303133; }

/* PyTorch 盒子样式 */
.torch-container { display: flex; flex-direction: column; gap: 12px; }
.torch-box {
  padding: 15px;
  border-radius: 6px;
  position: relative;
  overflow: hidden;
}
.torch-box.reserved { background: #fdf6ec; border: 1px solid #faecd8; }
.torch-box.allocated { background: #ecf5ff; border: 1px solid #d9ecff; }
.t-label { font-size: 12px; color: #909399; }
.t-value { font-size: 20px; font-weight: bold; margin: 5px 0; color: #303133; }
.t-desc { font-size: 11px; color: #a8abb2; }

/* 表格样式 */
.table-card { border: none; }
.model-cell { display: flex; align-items: center; }
.model-icon {
  width: 32px;
  height: 32px;
  background: #f0f2f5;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 10px;
  color: #409EFF;
}
.model-name-text { font-weight: 600; color: #303133; }
.vram-text { color: #409EFF; font-family: monospace; font-weight: bold; }

/* 状态小点 */
.status-dot {
  display: inline-block;
  width: 8px;
  height: 8px;
  background: #909399;
  border-radius: 50%;
  margin-right: 6px;
}
.status-dot.is-active {
  background: #67c23a;
  box-shadow: 0 0 6px #67c23a;
}
</style>
