<template>
  <div class="mes-report-container realtime-alarm-report">
    <!-- 查询条件卡片 -->
    <el-card class="query-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>设备故障实时报警（现场响应专用）</span>
          <div class="header-actions">
            <el-button type="primary" @click="handleSearch" :loading="loading">
              <el-icon><Search /></el-icon>
              查询
            </el-button>
            <el-button @click="resetQuery" :disabled="loading">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
            <el-button type="success" @click="handleExport" :disabled="loading || total===0">
              <el-icon><Download /></el-icon>
              导出Excel
            </el-button>
          </div>
        </div>
      </template>
      <el-form :model="queryParams" label-width="110px" inline>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="dateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            :disabled="loading"
          />
        </el-form-item>
<!--        <el-form-item label="设备编号">
          <el-input v-model="queryParams.machineCode" placeholder="支持模糊查询" clearable :disabled="loading" />
        </el-form-item>
        <el-form-item label="报警级别">
          <el-select v-model="queryParams.alarmLevelId" clearable filterable placeholder="全部" :disabled="loading">
            <el-option v-for="item in alarmLevels" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="报警类型">
          <el-select v-model="queryParams.alarmTypeId" clearable filterable placeholder="全部" :disabled="loading">
            <el-option v-for="item in alarmTypes" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="报警状态">
          <el-select v-model="queryParams.alarmStatus" clearable filterable placeholder="全部" :disabled="loading">
            <el-option v-for="item in alarm_status" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="报警方式">
          <el-select v-model="queryParams.alarmMode" clearable filterable placeholder="全部" :disabled="loading">
            <el-option v-for="item in alarm_mode" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="设备型号">
          <el-select v-model="queryParams.deviceModeId" clearable filterable placeholder="全部" :disabled="loading">
            <el-option v-for="dm in deviceModeOptions" :key="dm.deviceModeId" :label="dm.deviceModeName" :value="dm.deviceModeId" />
          </el-select>
        </el-form-item>-->
      </el-form>
    </el-card>

    <!-- 概览统计卡片 -->
    <div class="overview-grid">
      <el-card class="overview-card" shadow="never">
        <div class="stat">
          <div class="stat-value">{{ total }}</div>
          <div class="stat-label">报警总数</div>
        </div>
        <div ref="pieRef" class="chart" />
      </el-card>
      <el-card class="overview-card" shadow="never">
        <div ref="lineRef" class="chart" />
      </el-card>
      <el-card class="overview-card" shadow="never">
        <div class="legend">
          <div class="legend-item" v-for="lvl in alarmLevelStats" :key="lvl.name">
            <span class="dot" :style="{ background: lvl.color }"></span>
            <span class="name">{{ lvl.name }}</span>
            <span class="value">{{ lvl.value }}</span>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="never">
      <el-table v-loading="loading" :data="list" stripe height="480">
        <el-table-column type="index" label="序号" width="80" align="center" />
        <el-table-column prop="machineCode" label="设备编号" width="140" align="center" />
        <el-table-column prop="machineName" label="设备名称" width="160" align="center" />
        <el-table-column prop="deviceModeName" label="设备型号" width="140" align="center" />
        <el-table-column prop="alarmBeginTime" label="故障发生时间" width="180" align="center" />
        <el-table-column prop="alarmContent" label="故障现象描述" min-width="220" align="left" />
        <el-table-column prop="alarmLevelName" label="故障等级" width="120" align="center" />
        <el-table-column prop="alarmTypeName" label="报警类型" width="120" align="center" />
        <el-table-column label="当前状态" width="120" align="center">
          <template #default="scope">
            <dict-tag :options="alarm_status" :value="scope.row.alarmStatus" />
          </template>
        </el-table-column>
        <el-table-column label="报警方式" width="120" align="center">
          <template #default="scope">
            <dict-tag :options="alarm_mode" :value="scope.row.alarmMode" />
          </template>
        </el-table-column>
        <el-table-column prop="alarmEndTime" label="结束时间" width="180" align="center" />
        <el-table-column prop="durationMinutes" label="持续时长(分钟)" width="140" align="center" />
      </el-table>
      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
  </div>
</template>

<script setup lang="ts" name="RealtimeAlarmReport">
import { onMounted, ref, getCurrentInstance, nextTick, toRefs } from 'vue';
import * as echarts from 'echarts';
import { listRealtimeAlarm, exportRealtimeAlarm } from '@/api/dms/report';
import { RealtimeAlarmQuery, RealtimeAlarmVO } from '@/api/dms/report/types';
import { getDmsDeviceModeList } from '@/api/dms/deviceMode';

const { proxy } = getCurrentInstance() as any;
const loading = ref(false);
const list = ref<RealtimeAlarmVO[]>([]);
const total = ref(0);
const dateRange = ref<string[]>([]);

const queryParams = ref<RealtimeAlarmQuery>({
  pageNum: 1,
  pageSize: 10,
  startDate: undefined,
  endDate: undefined,
  deviceModeId: undefined,
  machineCode: undefined,
  machineId: undefined,
  alarmLevelId: undefined,
  alarmTypeId: undefined,
  alarmStatus: undefined,
  alarmMode: undefined,
  alarmInfoType: undefined,
});

// 字典
const { alarm_status } = toRefs<any>(proxy?.useDict('alarm_status'));
const { alarm_mode } = toRefs<any>(proxy?.useDict('alarm_mode'));

// 报警级别、类型（后端可能以字典或基础表提供，这里先用字典拉取，如果没有则可替换为接口）
const alarmLevels = ref<Array<{ label: string; value: string | number }>>([]);
const alarmTypes = ref<Array<{ label: string; value: string | number }>>([]);

// 设备型号下拉
const deviceModeOptions = ref<Array<{ deviceModeId: number; deviceModeName: string }>>([]);

// 图表
const pieRef = ref<HTMLDivElement | null>(null);
const lineRef = ref<HTMLDivElement | null>(null);
let pieChart: echarts.ECharts | null = null;
let lineChart: echarts.ECharts | null = null;

function initCharts() {
  nextTick(() => {
    if (pieRef.value) {
      pieChart = echarts.init(pieRef.value);
      const levelGroup = groupBy(list.value, x => x.alarmLevelName || '未设定');
      const pieData = Object.entries(levelGroup).map(([name, arr]) => ({ name, value: (arr as any[]).length }));
      pieChart.setOption({
        title: { text: '报警级别分布', left: 'center' },
        tooltip: { trigger: 'item' },
        series: [{ type: 'pie', radius: ['40%', '70%'], data: pieData }]
      });
    }
    if (lineRef.value) {
      lineChart = echarts.init(lineRef.value);
      const byHour = groupBy(list.value, x => (x.alarmBeginTime || '').substring(0, 13));
      const categories = Object.keys(byHour).sort();
      const values = categories.map(k => (byHour[k] as any[]).length);
      lineChart.setOption({
        title: { text: '小时报警趋势', left: 'center' },
        xAxis: { type: 'category', data: categories },
        yAxis: { type: 'value' },
        tooltip: { trigger: 'axis' },
        series: [{ type: 'line', data: values, smooth: true }]
      });
    }
  });
}

function groupBy<T>(arr: T[], keySelector: (x: T) => string) {
  return arr.reduce((acc: any, cur: any) => {
    const key = keySelector(cur) || '-';
    acc[key] = acc[key] || [];
    acc[key].push(cur);
    return acc;
  }, {} as Record<string, T[]>);
}

async function getDeviceModeOptions() {
  const res = await getDmsDeviceModeList({});
  deviceModeOptions.value = (res?.data || []).map((x: any) => ({ deviceModeId: x.deviceModeId, deviceModeName: x.deviceModeName }));
}

async function getList() {
  loading.value = true;
  try {
    if (dateRange.value?.length === 2) {
      queryParams.value.startDate = dateRange.value[0];
      queryParams.value.endDate = dateRange.value[1];
    } else {
      queryParams.value.startDate = undefined;
      queryParams.value.endDate = undefined;
    }
    const res = await listRealtimeAlarm(queryParams.value);
    list.value = res.rows || [];
    total.value = res.total || 0;
    initCharts();
  } finally {
    loading.value = false;
  }
}

function handleSearch() {
  queryParams.value.pageNum = 1;
  getList();
}

function resetQuery() {
  dateRange.value = [];
  queryParams.value = { pageNum: 1, pageSize: 10 };
  getList();
}

function handleExport() {
  proxy?.download('/dms/report/realtimeAlarm/export', { ...queryParams.value }, `realtime_alarm_${new Date().getTime()}.xlsx`);
}

onMounted(async () => {
  await getDeviceModeOptions();
  await getList();
});
</script>

<style scoped>
.realtime-alarm-report {
  display: flex;
  flex-direction: column;
  gap: 12px;
}
.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.header-actions {
  display: flex;
  gap: 8px;
}
.query-card {
  border-radius: 8px;
}
.overview-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 12px;
}
.overview-card {
  height: 240px;
}
.chart {
  width: 100%;
  height: 180px;
}
.legend {
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 12px;
}
.legend-item { display: flex; align-items: center; gap: 8px; }
.legend-item .dot { width: 8px; height: 8px; border-radius: 50%; background: var(--el-color-primary); }
.stat { display: flex; align-items: baseline; gap: 12px; padding: 4px 12px; }
.stat-value { font-size: 28px; font-weight: 700; }
.stat-label { color: var(--el-text-color-secondary); }
.table-card { border-radius: 8px; }
</style>
