<template>
  <div class="pie-chart-container">
    <dv-charts v-if="option" :option="option" />
    <div v-else>Loading chart...</div>
  </div>
</template>

<script>
import { concle_count } from "@/api/knowledge";
export default {
  name: "PieChart",
  data() {
    return {
      option: null,
      data: [
        { name: "文档", value: 70 },
        { name: "模版", value: 46 },
        { name: "知识库文档", value: 23 },
        { name: "公式", value: 15 },
        { name: "变量", value: 67 },    
      ],
      refreshInterval: null,
      isOnDashboard: false,
    };
  },
  watch: {
    $route: {
      immediate: true,
      handler(newRoute) {
        this.isOnDashboard = newRoute.path === '/dashboard';
        this.handleRouteChange();
      }
    }
  },
  mounted() {
    this.init();
    /* this.refreshInterval = setInterval(() => {
      this.init();
    }, 30000); */
  },
  beforeDestroy() {
    // 组件销毁前清除定时器
    if (this.refreshInterval) {
      clearInterval(this.refreshInterval);
    }
  },
  methods: {
    handleRouteChange() {
      if (this.isOnDashboard) {
        this.init();
      } 
    },
    initChart() {
      const filteredData = this.data.filter((item) => item.value > 0);
      this.option = {
        series: [
          {
            type: "pie",
            data: filteredData,
            radius: "55%",
            insideLabel: {
              show: true,
            },
            outsideLabel: {
              show: true,
              formatter: "{name}",/*  {percent}% */
            },
          },
        ],
        color: [
          "#FF9F43",
          "#5E60CE",
          "#FF6B6B",
          "#54A0FF",
          "#FF4DFF",
          "#FF9F43",
          "#1DD1A1",
        ],
      };
    },
    init() {
      concle_count().then((res) => {
        this.data[0].value = res.data.dc_document.non_templates;
        this.data[1].value = res.data.dc_document.templates;
         this.data[2].value = res.data.kbm_document;
        this.data[3].value = res.data.dc_formula;
        this.data[4].value = res.data.dc_params;
       
        this.$nextTick(() => {
          this.initChart();
        });
      });
    },
  },
};
</script>

<style scoped>
.pie-chart-container {
  width: 100%;
  height: 400px;
  max-width: 800px;
  margin: 0 auto;
}
</style>