<template>
  <div class="alarm-report-container">
    <el-card class="operate-card">
      <!-- 顶部操作区 -->
      <div class="operate-area">
        <el-button-group>
          <el-date-picker v-model="currentMonth" type="month" placeholder="选择月" @change="handleMonthChange"
            value-format="yyyy-MM">
          </el-date-picker>
        </el-button-group>
        <el-button type="default" @click="handleRefresh">
          <i class="el-icon-refresh"></i> 刷新
        </el-button>
        <el-button type="default" @click="handleExport">
          <i class="el-icon-download"></i> 导出
        </el-button>
      </div>
    </el-card>
    <!-- 中部系统总览区 -->
    <el-card class="overall-card">
      <div slot="header" class="card-header">
        <span>系统概览</span>
      </div>
      <div class="overall-content">
        <div v-for="(item, index) in overviewData" :key="index" class="overall-item">
          <el-statistic :value="item.value" :precision="0" :value-style="{ color: '#409EFF' }">
            <template slot="prefix">
              <el-icon class="el-icon-info"></el-icon>
            </template>
            <template slot="suffix">条 </template>
          </el-statistic>
          <div class="overall-label">{{ item.label }}</div>
        </div>
      </div>
    </el-card>

    <!-- 底部各系统告警统计展示区 -->
    <el-card class="system-stats-card">
      <div slot="header" class="card-header">
        <span>各系统告警统计</span>
      </div>
      <div>
        <el-table :data="systemStatsData" header-align="center" style="width: 100%" stripe
          v-loading="loadingsystemStats">
          <el-table-column prop="systemName" label="系统名称" width="120" fixed="left" />
          <el-table-column prop="totalAlarms" label="告警总数" min-width="120" align="center" />
          <el-table-column prop="processedCount" label="已处理告警总数" min-width="120" align="center" />
          <el-table-column prop="untreatedCount" label="未处理告警总数" min-width="120" align="center" />
          <el-table-column prop="contentAlarms" label="内容类告警" min-width="120" align="center" />
          <el-table-column prop="thresholdAlarms" label="阈值类告警" min-width="120" align="center" />
          <el-table-column prop="existenceAlarms" label="存在性告警总数" min-width="120" align="center" />
          <el-table-column prop="permissionCount" label="用户权限变更监控数量" min-width="120" align="center" />
          <el-table-column prop="dbCount" label="数据库监控数量" min-width="120" align="center" />
          <el-table-column prop="connectCount" label="系统内部连接性监控数量" min-width="120" align="center" />
          <el-table-column prop="ipCount" label="异常IP访问监控数量" min-width="120" align="center" />
          <el-table-column prop="taskCount" label="定时任务异常情况监控数量" min-width="120" align="center" />
        </el-table>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getAlarmStats, exportAlarmData, getNewAlarmStats, exportNewAlarmData } from '@/api/newApi/alarm'

export default {
  data() {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const currentMonthValue = `${year}-${month}`;
    return {
      loadingsystemStats: false,
      currentMonth: currentMonthValue,
      months: [],
      alarmData: {//告警统计数据
        overall: {},
        indicatorStats: []
      }
    }
  },
  computed: {
    // 根据当前选择的月份获取系统总览数据
    overviewData() {
      const overall = this.alarmData.overall || {};
      return [
        { label: '告警总数', value: overall.totalAlarms },
        { label: '已处理告警总数', value: overall.totalProcessed },
        { label: '未处理告警总数', value: overall.totalUntreated },
        { label: '内容类告警', value: overall.toralContentAlarms },
        { label: '阈值类告警', value: overall.totalThresholdAlarms },
        { label: '存在性告警总数', value: overall.existenceAlarms },
      ];
    },
    // 根据当前选择的月份获取各系统告警统计数据
    systemStatsData() {
      return (this.alarmData.indicatorStats || []).map(item => ({
        systemName: item.systemName,
        totalAlarms: item.totalAlarms,
        processedCount: item.processedCount,
        untreatedCount: item.untreatedCount,
        contentAlarms: item.contentAlarms,
        thresholdAlarms: item.thresholdAlarms,
        existenceAlarms: item.existenceAlarms,
        permissionCount: item.permissionCount,
        dbCount: item.dbCount,
        connectCount: item.connectCount,
        ipCount: item.ipCount,
        taskCount: item.taskCount
      }));
    }
  },
  created() {
    this.getAlarmEven();
  },
  methods: {
    //获取告警统计数据
    getAlarmEven() {
      this.loadingsystemStats = true;
      getNewAlarmStats(this.currentMonth).then(res => {
        // getAlarmStats(this.currentMonth).then(res => {
        if (res.code === 200) {

          this.alarmData = {
            overall: {
              totalAlarms: res.data.totalAlarms,
              totalProcessed: res.data.totalProcessed,
              totalUntreated: res.data.totalUntreated,
              toralContentAlarms: res.data.toralContentAlarms,
              totalThresholdAlarms: res.data.totalThresholdAlarms,
              existenceAlarms: res.data.existenceAlarms
            },
            indicatorStats: res.data.systemStats || []
          };
          console.log(this.alarmData, ' this.alarmData')
          // 更新月份列表
          // if (res.data.months && Array.isArray(res.data.months)) {
          //   this.months = res.data.months.map(month => {
          //      res.data.months=['2026-01','2026-02','2026-03','2026-04','2026-05','2026-06','2026-07','2026-08','2026-09','2026-10','2026-11','2026-12']
          //     const [year, monthNum] = month.split('-');
          //     return {
          //       // label: `${monthNum}月`,
          //       label: month,
          //       value: month
          //     };
          //   });
          // }
          this.loadingsystemStats = false;
        } else {
          this.$message.error('获取告警统计数据失败');
        }
      })
    },
    // 处理月份切换
    handleMonthChange(month) {
      console.log('Selected month:', month);
      // 确保 month 是字符串格式的 YYYY-MM
      if (month) {
        this.currentMonth = month;
        // 切换月份后重新获取数据
        this.getAlarmEven();
      }
    },
    // 处理刷新
    handleRefresh() {
      // 刷新时重新获取数据
      this.getAlarmEven()
    },
    // 处理导出
    handleExport() {
      // 显示确认对话框
      this.$confirm(`确定要导出 ${this.currentMonth} 月份的告警数据吗？`, '导出确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: '正在下载...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });

        // exportAlarmData(this.currentMonth).then(res => {
        exportNewAlarmData(this.currentMonth).then(async (res) => {
          // 处理导出成功逻辑
          const blob = new Blob([res], { type: 'application/vnd.ms-excel' });
          try {
            // 检查是否支持 File System Access API (仅在安全上下文可用)
            if (typeof window.showSaveFilePicker === 'function') {
              const fileHandle = await window.showSaveFilePicker({
                suggestedName: `告警数据_${this.currentMonth}.xlsx`,
                types: [
                  {
                    description: 'Excel文件',
                    accept: {
                      'application/vnd.ms-excel': ['.xlsx']
                    }
                  }
                ]
              });
              const writable = await fileHandle.createWritable();
              await writable.write(blob);
              await writable.close();
              this.$message.success('导出成功');
            } else {
              // 降级方案：使用传统的下载方式
              // 注意：在非安全上下文（如HTTP或本地IP）中，浏览器不允许选择保存位置
              // 文件将下载到浏览器默认的下载目录
              const url = URL.createObjectURL(blob);
              const a = document.createElement('a');
              a.href = url;
              a.download = `告警数据_${this.currentMonth}.xlsx`;
              document.body.appendChild(a);
              a.click();
              document.body.removeChild(a);
              URL.revokeObjectURL(url);
              this.$message.success('导出成功（文件已保存到默认下载目录）');
            }
          } catch (error) {
            console.error('导出失败:', error);
            // 如果用户取消选择，不显示错误信息
            if (error.name !== 'AbortError') {
              this.$message.error('导出失败');
            }
          }
        }).finally(() => {
          loading.close();
        })
      }).catch(() => {
        // 用户取消导出
        this.$message.info('已取消导出');
      });
    }
  }
}
</script>

<style scoped>
.alarm-report-container {
  padding: 20px;
}

.operate-card {
  margin-bottom: 20px;
}

.operate-area {
  display: flex;
  align-items: center;
  gap: 10px;
}

.overall-card {
  margin-bottom: 20px;
}

.card-header {
  font-weight: bold;
  font-size: 16px;
}

.overall-content {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  padding: 20px 0;
}

.overall-item {
  text-align: center;
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #f9fafc;
}

.overall-label {
  margin-top: 10px;
  font-size: 14px;
  color: #666666;
}

.system-stats-card {
  margin-bottom: 20px;
}

.el-table {
  margin-top: 20px;
}
</style>