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

    <el-row :gutter="16" class="mt-4 vibration-grid">
      <el-col :xs="24" :lg="7" :xl="6">
        <VibrationBoardDeviceTree :loading="treeLoading" :tree-data="monitorTreeOptions" :tree-props="treeProps" @node-click="handleTreeNodeClick" />
      </el-col>
      <el-col :xs="24" :lg="17" :xl="18">
        <el-row :gutter="16" class="vibration-grid">
          <el-col :xs="12" :md="8">
            <el-card shadow="never" class="kpi-card">
              <div class="kpi-label">采样记录数</div>
              <div class="kpi-value">{{ toNumber(qualityData.sampleCount) }}</div>
              <div class="metric-foot">用于衡量本次质量统计的样本规模。</div>
            </el-card>
          </el-col>
          <el-col :xs="12" :md="8">
            <el-card shadow="never" class="kpi-card">
              <div class="kpi-label">有效样本数</div>
              <div class="kpi-value">{{ toNumber(qualityData.validCount) }}</div>
              <div class="metric-foot">位移有效样本越少，越要优先排查采集链路。</div>
            </el-card>
          </el-col>
          <el-col :xs="24" :md="8">
            <el-card shadow="never" class="kpi-card">
              <div class="kpi-label">有效率</div>
              <div class="kpi-value">{{ formatPercentValue(qualityData.validRate ?? qualityData.coverageRate) }}</div>
              <div class="metric-foot">位移有效率越低，越可能存在空值、零值占位或离线问题。</div>
            </el-card>
          </el-col>
        </el-row>

        <el-card shadow="never" class="chart-card mt-4">
          <template #header>
            <div class="card-header">
                <div class="card-title-group">
                <div class="card-title">位移采集质量</div>
                <div class="card-subtitle">柱图看样本量，折线看有效率与无效率，帮助区分“质量差”与“本来采样就少”的情况。</div>
              </div>
              <HelpButton title="位移采集质量" :content="QUALITY_HELP" />
            </div>
          </template>
          <div ref="qualityChartRef" class="chart-container-lg" />
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import * as echarts from 'echarts';
import { getDisplacementQualityData as getVibrationQualityData, type VibrationQualityPageVO } from '@/api/ems/report/displacementBoard';
import HelpButton from '../components/HelpButton.vue';
import VibrationBoardFilter from '../components/VibrationBoardFilter.vue';
import VibrationBoardDeviceTree from '../components/VibrationBoardDeviceTree.vue';
import { QUALITY_HELP } from '../components/helpContent';
import { useChartResize } from '../components/useChartResize';
import { useVibrationBoardQueryState } from '../components/useVibrationBoardQueryState';
import { buildCategoryDataZoom, formatPercentValue, toNumber } from '../components/vibrationBoardShared';

defineOptions({ name: 'VibrationBoardQuality' });

const qualityChartRef = ref<HTMLElement>();
const { getChart } = useChartResize(qualityChartRef);

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

const qualityData = ref<VibrationQualityPageVO>({ metricQualityItems: [] });

const renderChart = () => {
  const chart = getChart(qualityChartRef);
  if (!chart) {
    return;
  }
  const sampleCount = toNumber(qualityData.value.sampleCount);
  const validCount = toNumber(qualityData.value.validCount);
  const invalidCount = toNumber(qualityData.value.invalidCount);
  const validRate = Number((toNumber(qualityData.value.validRate ?? qualityData.value.coverageRate) * 100).toFixed(1));
  const invalidRate = Number((toNumber(qualityData.value.invalidRate) * 100).toFixed(1));
  if (!sampleCount) {
    chart.clear();
    return;
  }
  const categories = ['有效样本', '无效样本'];
  const sampleValues = [validCount, invalidCount];
  const rateValues = [validRate, invalidRate];
  chart.setOption(
    {
      color: ['#5b8ff9', '#f97316'],
      tooltip: {
        trigger: 'axis',
        axisPointer: { type: 'shadow' },
        formatter: (params: any[]) => {
          const itemIndex = params[0]?.dataIndex || 0;
          return [
            `<b>${categories[itemIndex]}</b>`,
            `${params[0].marker}样本量: <b>${sampleValues[itemIndex]}</b>`,
            `${params[1].marker}占比: <b>${rateValues[itemIndex]}%</b>`
          ].join('<br/>');
        }
      },
      legend: {
        top: 8,
        data: ['样本量', '占比'],
        textStyle: { color: '#475569' }
      },
      grid: { left: 56, right: 52, top: 56, bottom: 46 },
      dataZoom: buildCategoryDataZoom(categories.length, 'x'),
      xAxis: {
        type: 'category',
        data: categories,
        axisLabel: { color: '#334155' }
      },
      yAxis: [
        {
          type: 'value',
          name: '样本量',
          minInterval: 1,
          axisLabel: { color: '#64748b' },
          splitLine: { lineStyle: { type: 'dashed', color: 'rgba(148, 163, 184, 0.35)' } }
        },
        {
          type: 'value',
          name: '占比',
          min: 0,
          max: 100,
          axisLabel: { formatter: '{value}%', color: '#64748b' },
          splitLine: { show: false }
        }
      ],
      series: [
        {
          name: '样本量',
          type: 'bar',
          barMaxWidth: 28,
          data: sampleValues,
          itemStyle: {
            borderRadius: [8, 8, 0, 0],
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#5b8ff9' },
              { offset: 1, color: 'rgba(91, 143, 249, 0.22)' }
            ])
          },
        },
        {
          name: '占比',
          type: 'line',
          yAxisIndex: 1,
          smooth: true,
          symbolSize: 10,
          data: rateValues,
          lineStyle: { width: 2.4 },
          itemStyle: { color: '#f97316' }
        }
      ]
    },
    true
  );
};

const handleQuery = async () => {
  loading.value = true;
  try {
    const { data } = await getVibrationQualityData(buildQuery());
    qualityData.value = data || { metricQualityItems: [] };
    await nextTick();
    renderChart();
  } finally {
    loading.value = false;
  }
};

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

<style scoped lang="scss">
@import '../components/vibrationBoardReport.scss';
</style>
