<template>
  <div id="chartdiv"></div>
</template>
  
  <script>
import * as am5 from "@amcharts/amcharts5";
import * as am5percent from "@amcharts/amcharts5/percent";
import am5themes_Animated from "@amcharts/amcharts5/themes/Animated";

import { gpu_info } from "@/api/knowledge";

export default {
  name: "DoublePieChart",
  props: {
    percentage: {
        type: Number,
        default: 0
      }
  },
  data() {
    return {
      root: null,
      chart: null,
      series: null,
      centerLabel: null,
      currentPercentage: 0,
      isOnDashboard: false,
      timer: null, // 添加定时器变量
      isRequesting: false, // 添加请求状态标记
    };
  },
  watch: {
    percentage: {
      handler(newValue) {
        this.updateChart(newValue);
      },
    },
    $route: {
      immediate: true,
      handler(newRoute) {
        this.isOnDashboard = newRoute.path === "/dashboard";
       /*  if (this.isOnDashboard) {
          this.startPolling();
        } else {
          this.stopPolling();
        } */
      },
    },
  },
  methods: {
    initChart() {
      // 确保在重新初始化前清理旧实例
      if (this.root) {
        this.root.dispose();
      }

      // Create root element
      this.root = am5.Root.new("chartdiv");

      // Set themes
      this.root.setThemes([am5themes_Animated.new(this.root)]);

      // Create chart
      this.chart = this.root.container.children.push(
        am5percent.PieChart.new(this.root, {
          startAngle: 180,
          endAngle: 360,
          layout: this.root.verticalLayout,
          innerRadius: am5.percent(80),
        })
      );

      // 确保 chart 创建完成后再创建 series
      if (this.chart) {
        // Create series
        this.series = this.chart.series.push(
          am5percent.PieSeries.new(this.root, {
            valueField: "value",
            categoryField: "category",
            startAngle: 180,
            endAngle: 360,
            radius: am5.percent(80),
            innerRadius: am5.percent(30),
          })
        );

        // Set custom colors
        this.series.set(
          "colors",
          am5.ColorSet.new(this.root, {
            colors: [am5.color("#19bcbf"), am5.color("#F5F5F5")],
          })
        );

        // Disable labels and ticks
        this.series.labels.template.set("forceHidden", true);
        this.series.ticks.template.set("forceHidden", true);

        // Create center label
        this.centerLabel = am5.Label.new(this.root, {
          textAlign: "center",
          centerY: am5.p50,
          centerX: am5.p50,
          /*   y: am5.percent(-35), // 负值会使文字向上移动 */
          text: "[fontSize:24px]0%[/]\n[fontSize:14px]Compiled Ticket[/]",
        });

        this.chart.seriesContainer.children.push(this.centerLabel);

        // 初始化完成后更新数据
        this.$nextTick(() => {
          this.updateChart(this.percentage);
        });
      }
    },

    updateChart(percentage) {
      // 确保所有必要的组件都已创建
      if (!this.series || !this.centerLabel) {
        return;
      }

      try {
        // Update data
        this.series.data.setAll([
          { category: "memory", value: percentage },
          { category: "Remaining", value: 100 - percentage },
        ]);

        // Update center label
        this.centerLabel.set(
          "text",
          `[fontSize:24px]${percentage}%[/]\n[fontSize:14px]Compiled Ticket[/]`
        );
      } catch (error) {
        console.error("Error updating chart:", error);
      }
    },
    startPolling() {
      if (!this.isRequesting) {
        this.fetchGpuInfo();
      }
    },

    stopPolling() {
      this.isRequesting = false;
      if (this.timer) {
        clearTimeout(this.timer);
        this.timer = null;
      }
    },

    fetchGpuInfo() {
      if (!this.isOnDashboard) return;
      
      this.isRequesting = true;
      gpu_info()
        .then((res) => {
          const total = res.data.data.cpu.memory.total;
          const used = res.data.data.cpu.memory.used;
          this.currentPercentage = Number(((used / total) * 100).toFixed(2));
          
          // 请求成功后，等待3秒再发起下一次请求
          this.timer = setTimeout(() => {
            this.isRequesting = false;
            this.fetchGpuInfo();
          }, 3000);
        })
        .catch((error) => {
          console.error('Failed to fetch GPU info:', error);
          // 请求失败后，等待3秒重试
          this.timer = setTimeout(() => {
            this.isRequesting = false;
            this.fetchGpuInfo();
          }, 3000);
        });
    },
  },
  mounted() {
    // 使用 nextTick 确保 DOM 已经更新
    this.$nextTick(() => {
      this.initChart();
    });
  },
  beforeDestroy() {
    this.stopPolling();
    if (this.root) {
      this.root.dispose();
    }
  },
};
</script>
  
  <style scoped>
#chartdiv {
  width: 100%;
  height: 150px;
}
</style>