<template>
    <div class="alert-container">
      <el-row class="filter-row">
        <el-col :span="11">
          <el-form-item label="开始时间">
            <el-date-picker v-model="filterParams.timeAfter" type="datetime" placeholder="请选择开始时间"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="结束时间">
            <el-date-picker v-model="filterParams.timeBefore" type="datetime" placeholder="请选择结束时间"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="2" class="filter-buttons">
          <el-button type="primary" @click="handleFilter">查询</el-button>
        </el-col>
      </el-row>
  
      <el-row>
        <el-col :span="24">
          <div class="statistics-container">
            <p v-for="(name, code) in typeMapping" :key="code">
              {{ name }}: {{ typeCounts[code] || 0 }} 次
            </p>
          </div>
        </el-col>
      </el-row>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, onMounted } from 'vue';
  import { BoxApi } from '@/utils/boxApi.ts';
  
  const apiInstance = new BoxApi();
  const typeMapping = reactive({});
  const typeCounts = reactive({}); // 存储每种类型的数量
  
  const filterParams = reactive({
    timeAfter: null,
    timeBefore: null,
  });
  
  // 获取告警类型并初始化每种类型的count
  const fetchTypeMapping = async (token) => {
    try {
      const algorithms = await apiInstance.getAlgorithms(token);
      const additionalMappings = [{ code_name: 'minizawu:532', name: '杂物堆积' }];
      
      algorithms.forEach((algorithm) => {
        typeMapping[algorithm.code_name] = algorithm.name;
        typeCounts[algorithm.code_name] = 0; // 初始化count为0
      });
      
      additionalMappings.forEach((item) => {
        typeMapping[item.code_name] = item.name;
        typeCounts[item.code_name] = 0;
      });
    } catch (error) {
      console.error("Error fetching algorithms:", error);
    }
  };
  
  // 统计每种告警类型的数量
  const fetchTypeCounts = async (timeAfter = null, timeBefore = null) => {
    const token = localStorage.getItem('alertToken');
  
    console.log(">>>>>>>>>>>>>>>>",typeMapping)
  
    // 遍历每种类型，根据code_name查询数据数量
    for (const code in typeMapping) {
      try {
        const { count } = await apiInstance.getEventsByParams(token, 1, 1, timeBefore, timeAfter, code);
        typeCounts[code] = count; // 存储每种类型的数量
      } catch (error) {
        console.error(`Error fetching count for type ${code}:`, error);
      }
    }
  };
  
  // 点击查询按钮时，添加时间条件并重新统计
  const handleFilter = () => {
    const timeAfter = filterParams.timeAfter ? formatDateTime(new Date(filterParams.timeAfter)) : null;
    const timeBefore = filterParams.timeBefore ? formatDateTime(new Date(filterParams.timeBefore)) : null;
    fetchTypeCounts(timeAfter, timeBefore); // 重新统计数量，添加时间条件
  };
  
  const formatDateTime = (datetime) => {
    const date = new Date(datetime);
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    const seconds = date.getSeconds().toString().padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  };
  
  onMounted(async () => {
    const token = localStorage.getItem('alertToken');
    await fetchTypeMapping(token);
    fetchTypeCounts(); // 初次加载时不加时间条件
  });
  </script>
  
  <style>
  .statistics-container {
    margin-top: 20px;
  }
  </style>
  