<!-- <template>
    <div ref="chartDiv" style="width: 100%; height: 100%"></div>
  </template>
  
  <script>
  import * as am5 from "@amcharts/amcharts5";
  import * as am5radar from "@amcharts/amcharts5/radar";
  import am5themes_Animated from "@amcharts/amcharts5/themes/Animated";
  
  export default {
    name: 'AmGaugeChart',
    props: {
      data: {
        type: Object,
        default: () => ({ value: 0 })
      }
    },
    data() {
      return {
        chart: null,
        root: null
      }
    },
    mounted() {
      this.initChart();
    },
    beforeDestroy() {
      if (this.root) {
        this.root.dispose();
      }
    },
    methods: {
      initChart() {
        // 创建根元素
        this.root = am5.Root.new(this.$refs.chartDiv);
  
        // 设置主题
        this.root.setThemes([am5themes_Animated.new(this.root)]);
  
        // 创建图表
        this.chart = this.root.container.children.push(
          am5radar.RadarChart.new(this.root, {
            panX: false,
            panY: false,
            startAngle: -180,
            endAngle: 0
          })
        );
  
        // 创建轴
        const axisRenderer = am5radar.AxisRendererCircular.new(this.root, {
          innerRadius: -10,
          strokeOpacity: 1,
          strokeWidth: 15,
          strokeGradient: am5.LinearGradient.new(this.root, {
            rotation: 0,
            stops: [
              { color: am5.color(0x19d228) },
              { color: am5.color(0xf4fb16) },
              { color: am5.color(0xf6d32b) },
              { color: am5.color(0xfb7116) }
            ]
          })
        });
  
        const xAxis = this.chart.xAxes.push(
            am5radar.ValueAxis.new(this.root, {
            maxDeviation: 0,
            min: 0,
            max: 100,
            strictMinMax: true,
            renderer: axisRenderer
          })
        );
  
        // 添加仪表盘指针
        const axisDataItem = xAxis.makeDataItem({});
        const clockHand = am5radar.ClockHand.new(this.root, {
          pinRadius: am5.percent(20),
          radius: am5.percent(100),
          bottomWidth: 40
        });
        clockHand.pin.setAll({
          fillOpacity: 0,
          strokeOpacity: 0.5,
          stroke: am5.color(0x000000),
          strokeWidth: 1,
          strokeDasharray: [2, 2]
        });
        clockHand.hand.setAll({
          fillOpacity: 0,
          strokeOpacity: 0.5,
          stroke: am5.color(0x000000),
          strokeWidth: 0.5
        });
  
        axisDataItem.set("value", 0);
        axisDataItem.set("clockHand", clockHand);
        xAxis.createAxisRange(axisDataItem);
  
        // 设置数据
        axisDataItem.set("value", this.data.value);
  
        // 添加标签
        const label = this.chart.radarContainer.children.push(
          am5.Label.new(this.root, {
            centerX: am5.percent(50),
            textAlign: "center",
            centerY: am5.percent(50),
            fontSize: "3em"
          })
        );
  
        // 更新标签文本
        label.set("text", Math.round(this.data.value).toString());
  
        // 动画效果
        this.chart.appear(1000, 100);
      }
    }
  }
  </script> -->
  <!-- <template>
    <div ref="chartDiv" style="width: 100%; height: 300px;"></div>
  </template>
  
  <script>
  import * as am5 from "@amcharts/amcharts5/index";
  import * as am5xy from "@amcharts/amcharts5/xy";
  import am5themes_Animated from "@amcharts/amcharts5/themes/Animated";
  
  export default {
    name: 'LineChart',
    data() {
      return {
        chart: null,
        root: null
      }
    },
    mounted() {
      this.initChart();
    },
    beforeDestroy() {
      if (this.root) {
        this.root.dispose();
      }
    },
    methods: {
      initChart() {
        // Create root element
        this.root = am5.Root.new(this.$refs.chartDiv);
  
        // Set themes
        this.root.setThemes([am5themes_Animated.new(this.root)]);
  
        // Create chart
        this.chart = this.root.container.children.push(
          am5xy.XYChart.new(this.root, {
            panX: false,
            panY: false,
            wheelX: "none",
            wheelY: "none"
          })
        );
  
        // Create axes
        let xAxis = this.chart.xAxes.push(
          am5xy.CategoryAxis.new(this.root, {
            renderer: am5xy.AxisRendererX.new(this.root, {}),
            categoryField: "category"
          })
        );
  
        let yAxis = this.chart.yAxes.push(
          am5xy.ValueAxis.new(this.root, {
            renderer: am5xy.AxisRendererY.new(this.root, {})
          })
        );
  
        // Create series
        let series = this.chart.series.push(
          am5xy.LineSeries.new(this.root, {
            name: "Series",
            xAxis: xAxis,
            yAxis: yAxis,
            valueYField: "value",
            categoryXField: "category",
            tooltip: am5.Tooltip.new(this.root, {
              labelText: "{valueY}"
            })
          })
        );
  
        series.strokes.template.setAll({
          strokeWidth: 3,
          strokeColor: am5.color(0x00BFFF)
        });
  
        series.bullets.push(function() {
          return am5.Bullet.new(this.root, {
            sprite: am5.Circle.new(this.root, {
              radius: 5,
              fill: am5.color(0x00BFFF)
            })
          });
        });
  
        // Set data
        let data = [
          { category: "A", value: 10 },
          { category: "B", value: 30 },
          { category: "C", value: 20 },
          { category: "D", value: 40 },
          { category: "E", value: 30 },
          { category: "F", value: 35 },
          { category: "G", value: 25 }
        ];
  
        xAxis.data.setAll(data);
        series.data.setAll(data);
  
        // Add cursor
        this.chart.set("cursor", am5xy.XYCursor.new(this.root, {
          behavior: "none"
        }));
  
        // Make stuff animate on load
        series.appear(1000);
        this.chart.appear(1000, 100);
      }
    }
  }
  </script> -->

  <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>