<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-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-card
          ><template #header>{{ trendData.multiDevice ? '设备对比趋势图' : '多指标趋势图' }}</template
          ><Chart ref="trendChart" class="chart-xl"
        /></el-card>
        <el-card class="mt-4"><template #header>小时均值图</template><Chart ref="hourlyChart" class="chart-lg" /></el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import Chart from '@/components/Charts/Chart.vue';
import { getVibrationTrendData, type VibrationTrendPageVO } from '@/api/ems/report/vibrationBoard';
import VibrationBoardFilter from '../components/VibrationBoardFilter.vue';
import VibrationBoardDeviceTree from '../components/VibrationBoardDeviceTree.vue';
import { useVibrationBoardQueryState } from '../components/useVibrationBoardQueryState';
import { vibrationMetricOptions } from '../components/vibrationBoardShared';

defineOptions({ name: 'VibrationBoardTrend' });

const trendChart = ref<any>();
const hourlyChart = ref<any>();
const {
  loading,
  treeLoading,
  monitorTreeOptions,
  treeProps,
  daterangeRecordTime,
  queryForm,
  loadTree,
  handleTreeNodeClick,
  setTimeRange,
  setSamplingInterval,
  setVibrationParam,
  buildQuery
} = useVibrationBoardQueryState();
const trendData = ref<VibrationTrendPageVO>({ series: [], hourlyItems: [] });
const metricColorMap = Object.fromEntries(vibrationMetricOptions.map((item) => [item.field, item.color]));
const toNumber = (value: number | string | undefined) => Number(value ?? 0);

const renderCharts = () => {
  const series = trendData.value.series || [];
  trendChart.value?.setData({
    color: series.map((item) => metricColorMap[item.field || queryForm.value.vibrationParam] || '#5b8ff9'),
    tooltip: { trigger: 'axis' },
    legend: { top: 8, data: series.map((item) => item.name) },
    xAxis: { type: 'time' },
    yAxis: { type: 'value', name: trendData.value.unit || '' },
    series: series.map((item) => ({
      name: item.name,
      type: 'line',
      smooth: true,
      connectNulls: true,
      showSymbol: false,
      data: (item.points || []).map((point) => [point.time, toNumber(point.value)])
    }))
  });
  hourlyChart.value?.setData({
    xAxis: { type: 'category', data: (trendData.value.hourlyItems || []).map((item) => item.hour) },
    yAxis: { type: 'value', name: trendData.value.unit || '' },
    series: [
      {
        type: 'bar',
        data: (trendData.value.hourlyItems || []).map((item) => toNumber(item.avgValue)),
        itemStyle: { color: metricColorMap[queryForm.value.vibrationParam] || '#5b8ff9' }
      }
    ]
  });
};

const handleQuery = async () => {
  loading.value = true;
  try {
    const { data } = await getVibrationTrendData(buildQuery());
    trendData.value = data || { series: [], hourlyItems: [] };
    await nextTick();
    renderCharts();
  } finally {
    loading.value = false;
  }
};

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

<style scoped>
.chart-xl {
  height: 460px;
}
.chart-lg {
  height: 320px;
}
</style>
