<template>
  <div v-loading="loading" class="app-container">
    <VibrationBoardFilter
      :selection-label="queryForm.selectionLabel"
      :time-range="daterangeRecordTime"
      :sampling-interval="queryForm.samplingInterval"
      :vibration-param="queryForm.vibrationParam"
      show-metric
      @update:time-range="setTimeRange"
      @update:sampling-interval="setSamplingInterval"
      @update:vibration-param="setVibrationParam"
      @query="handleQuery"
    />

    <el-card shadow="never" class="mt-4">
      <el-form :inline="true" size="small" label-width="110px">
        <el-form-item label="高阈值">
          <el-input-number v-model="queryForm.highThreshold" :min="0" :precision="2" style="width: 140px" />
        </el-form-item>
        <el-form-item label="预警阈值">
          <el-input-number v-model="queryForm.warningThreshold" :min="0" :precision="2" style="width: 140px" />
        </el-form-item>
        <el-form-item label="连续样本数">
          <el-input-number v-model="queryForm.minContinuousSamples" :min="2" :max="100" style="width: 140px" />
        </el-form-item>
        <el-form-item label="变化率阈值">
          <el-input-number v-model="queryForm.rapidRiseThreshold" :min="0.1" :precision="2" :step="0.1" style="width: 140px" />
        </el-form-item>
        <el-form-item label="抖动阈值">
          <el-input-number v-model="queryForm.stddevThreshold" :min="0.1" :precision="2" :step="0.1" style="width: 140px" />
        </el-form-item>
      </el-form>
    </el-card>

    <el-row :gutter="16" class="mt-4">
      <el-col :span="6"
        ><el-card
          ><div class="kpi-label">高风险事件</div>
          <div class="kpi-value danger">{{ anomalyData.highEventCount || 0 }}</div></el-card
        ></el-col
      >
      <el-col :span="6"
        ><el-card
          ><div class="kpi-label">连续超标段</div>
          <div class="kpi-value warning">{{ anomalyData.continuousEventCount || 0 }}</div></el-card
        ></el-col
      >
      <el-col :span="6"
        ><el-card
          ><div class="kpi-label">变化过快</div>
          <div class="kpi-value primary">{{ anomalyData.rapidRiseEventCount || 0 }}</div></el-card
        ></el-col
      >
      <el-col :span="6"
        ><el-card
          ><div class="kpi-label">抖动异常</div>
          <div class="kpi-value purple">{{ anomalyData.jitterEventCount || 0 }}</div></el-card
        ></el-col
      >
    </el-row>

    <el-row :gutter="16" class="mt-4">
      <el-col :span="6">
        <VibrationBoardDeviceTree :loading="treeLoading" :tree-data="monitorTreeOptions" :tree-props="treeProps" @node-click="handleTreeNodeClick" />
      </el-col>
      <el-col :span="18">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-card>
              <template #header>高风险事件明细</template>
              <el-table :data="anomalyData.highEvents || []" stripe size="small" max-height="320">
                <el-table-column prop="monitorName" label="设备" />
                <el-table-column prop="value" label="数值" width="120" />
                <el-table-column prop="recodeTime" label="时间" width="180" />
              </el-table>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card>
              <template #header>变化过快事件</template>
              <el-table :data="anomalyData.rapidRiseEvents || []" stripe size="small" max-height="320">
                <el-table-column prop="monitorName" label="设备" />
                <el-table-column prop="diff" label="变化量" width="120" />
                <el-table-column prop="recodeTime" label="时间" width="180" />
              </el-table>
            </el-card>
          </el-col>
        </el-row>

        <el-card class="mt-4">
          <template #header>连续超标时段</template>
          <el-table :data="anomalyData.continuousEvents || []" stripe size="small" max-height="320">
            <el-table-column prop="monitorName" label="设备" />
            <el-table-column prop="startTime" label="开始时间" width="180" />
            <el-table-column prop="endTime" label="结束时间" width="180" />
            <el-table-column prop="maxValue" label="峰值" width="120" />
            <el-table-column prop="sampleCount" label="样本数" width="100" />
          </el-table>
        </el-card>

        <el-card class="mt-4">
          <template #header>抖动异常</template>
          <el-table :data="anomalyData.jitterEvents || []" stripe size="small" max-height="320">
            <el-table-column prop="monitorName" label="设备" />
            <el-table-column prop="hourBucket" label="小时桶" width="180" />
            <el-table-column prop="stddev" label="标准差" width="120" />
            <el-table-column prop="sampleCount" label="样本数" width="100" />
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { getVibrationAnomalyData, type VibrationAnomalyPageVO } from '@/api/ems/report/vibrationBoard';
import VibrationBoardFilter from '../components/VibrationBoardFilter.vue';
import VibrationBoardDeviceTree from '../components/VibrationBoardDeviceTree.vue';
import { useVibrationBoardQueryState } from '../components/useVibrationBoardQueryState';

defineOptions({ name: 'VibrationBoardAnomaly' });

const {
  loading,
  treeLoading,
  monitorTreeOptions,
  treeProps,
  daterangeRecordTime,
  queryForm,
  loadTree,
  handleTreeNodeClick,
  setTimeRange,
  setSamplingInterval,
  setVibrationParam,
  buildQuery
} = useVibrationBoardQueryState();

const anomalyData = ref<VibrationAnomalyPageVO>({
  highEvents: [],
  continuousEvents: [],
  rapidRiseEvents: [],
  jitterEvents: []
});

const applyThresholdDefaults = (data?: VibrationAnomalyPageVO) => {
  if (!data) return;
  queryForm.value.highThreshold = Number(data.highThreshold ?? queryForm.value.highThreshold ?? 0);
  queryForm.value.warningThreshold = Number(data.warningThreshold ?? queryForm.value.warningThreshold ?? 0);
  queryForm.value.minContinuousSamples = Number(data.minContinuousSamples ?? queryForm.value.minContinuousSamples ?? 3);
  queryForm.value.rapidRiseThreshold = Number(data.rapidRiseThreshold ?? queryForm.value.rapidRiseThreshold ?? 0);
  queryForm.value.stddevThreshold = Number(data.stddevThreshold ?? queryForm.value.stddevThreshold ?? 0);
};

const handleQuery = async () => {
  loading.value = true;
  try {
    const { data } = await getVibrationAnomalyData(buildQuery());
    anomalyData.value = data || {
      highEvents: [],
      continuousEvents: [],
      rapidRiseEvents: [],
      jitterEvents: []
    };
    applyThresholdDefaults(data);
  } finally {
    loading.value = false;
  }
};

onMounted(async () => {
  await loadTree();
  await handleQuery();
});
</script>

<style scoped>
.kpi-label {
  color: #5b6573;
  font-size: 13px;
}

.kpi-value {
  margin-top: 12px;
  font-size: 26px;
  font-weight: 700;
}

.danger {
  color: #f56c6c;
}

.warning {
  color: #e6a23c;
}

.primary {
  color: #409eff;
}

.purple {
  color: #9b59b6;
}
</style>
