<template>
  <div>
    <el-card class="stats-card">
      <div class="stats-header">告警数量和类型分布</div>
      <el-row :gutter="20" class="stats-row">
        <el-col :span="24">
          <div ref="chart" class="chart"></div>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import { login, getAlgorithms,getEvents} from '@/utils/superbox.js';

const username = 'turingvideo';
const password = '1234qwer!';


export default {
  name: 'Statistics',
  data() {
    return {
      chart: null,
      seriesData: [

      ],
    };
  },
  // mounted() {
  //   this.initChart();
  // },
  async created(){
    try{
      const token = await login(username, password);
      await this.fetchTypeMapping(token);
      await this.updateSeriesData(token);
      this.initChart();
    }catch(error){
      console.error("Error fetching algorithms:", error);
    }
  },
  methods: {
    async fetchTypeMapping(token) {
      const algorithms = await getAlgorithms(token);
      let mapping = algorithms.map(algorithm => ({
        value: 0, // 初始化为10，可以根据实际数据进行调整
        code_name: algorithm.code_name,
        name: algorithm.name
      }));
      const newMapping = [
        {code_name: "minizawu:532",name: "杂物堆积",value: 0},
      ]

      mapping = mapping.concat(newMapping);
      this.seriesData = mapping;
    },
    async updateSeriesData(token){
      const events = await getEvents(token);
      events.forEach(event => {
        const matchAlgorithm = this.seriesData.find(item => item.code_name === event.types);
        if (matchAlgorithm){
          matchAlgorithm.value += 1;
        }
      })
    },
    initChart() {
      this.chart = echarts.init(this.$refs.chart);
      const option = {
        tooltip: {
          trigger: 'item',
        },
        legend: {
          orient: 'horizontal',
          bottom: 10,
          textStyle: {
            color: '#fff',
          },
          itemGap: 20,
          data: this.seriesData.map(item => item.name),
        },
        series: [
          {
            name: '告警类型',
            type: 'pie',
            radius: '50%',
            center: ['50%', '150px'],
            data: this.seriesData,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            },
            label: {
              show: true    
            },
            stillShowZeroSum: false,
          }
        ]
      };
      this.chart.setOption(option);
    }
  }
};
</script>

<style scoped>
.stats-card {
  background-color: #2a3f54;
  color: #fff;
  padding: 20px;
  border-radius: 8px;
}

.stats-header {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 20px;
  border-bottom: 1px solid #3a4b5c;
  padding-bottom: 10px;
}

.stats-row {
  /* margin-top: 20px; */
  margin-bottom: 10px;
}

.chart {
  width: 100%;
  height: 500px;
}
</style>
