<template>
  <div v-if="!configured" class="not-configured">未配置</div>
  <div v-else class="chart-container">
    <Chart :options="chartOptions" :height="height" :width="width" />
  </div>
</template>

<script lang="ts" setup>
import { computed } from 'vue'
import Chart from '@/components/chart/index.vue'

interface Props {
  recordId: number | string
  configured?: boolean
  height?: string
  width?: string
}

const props = withDefaults(defineProps<Props>(), {
  configured: true,
  height: '60px',
  width: '160px',
})

// 生成随机 QPS 数据
const generateQpsData = (id: number | string) => {
  const numericId = typeof id === 'string' ? parseInt(id, 10) || 1 : id
  const baseValue = ((numericId * 17) % 100) + 50
  const data: number[] = []
  for (let i = 0; i < 12; i++) {
    const variation = Math.sin(i + numericId) * 30
    data.push(Math.max(0, Math.min(200, baseValue + variation + Math.random() * 20)))
  }
  return data
}

// 获取图表配置
const chartOptions = computed(() => {
  const data = generateQpsData(props.recordId)
  const avgValue = data.reduce((a, b) => a + b, 0) / data.length

  return {
    tooltip: {
      trigger: 'axis',
      formatter: (params: any) => {
        if (params && params.length > 0) {
          return `QPS: ${params[0].value.toFixed(1)}`
        }
        return ''
      },
    },
    grid: {
      left: 0,
      right: 0,
      top: 5,
      bottom: 5,
    },
    xAxis: {
      type: 'category',
      show: false,
      data: data.map((_, i) => i),
    },
    yAxis: {
      type: 'value',
      show: false,
      min: 0,
      max: 200,
    },
    series: [
      {
        type: 'line',
        data,
        smooth: true,
        symbol: 'circle',
        symbolSize: 4,
        showSymbol: false,
        lineStyle: {
          width: 2,
          color: '#165DFF',
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(22, 93, 255, 0.3)' },
              { offset: 1, color: 'rgba(22, 93, 255, 0.05)' },
            ],
          },
        },
        markLine: {
          silent: true,
          symbol: 'none',
          label: {
            show: false,
          },
          lineStyle: {
            type: 'dashed',
            color: '#86909C',
            width: 1,
          },
          data: [
            {
              yAxis: avgValue,
            },
          ],
        },
      },
    ],
  }
})
</script>

<style scoped lang="less">
.not-configured {
  color: rgb(var(--text-3));
  font-size: 12px;
  text-align: center;
  padding: 8px 0;
}

.chart-container {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 4px 0;
}
</style>
