<template>
  <div class="system-trend-chart">
    <div class="chart-legend">
      <span><i :style="{ background: chartColors.primary }"></i>工具调用（次）</span>
      <span><i :style="{ background: chartColors.blue }"></i>Token 消耗（K）</span>
      <span><i :style="{ background: chartColors.purple }"></i>在线人数</span>
      <span><i :style="{ background: chartColors.amber }"></i>平均在线时长（分钟）</span>
    </div>
    <div ref="chartElement" class="chart-body" role="img" :aria-label="ariaLabel"></div>
  </div>
</template>

<script setup>
import { computed, shallowRef } from 'vue'
import { BarChart as EChartsBarChart, LineChart as EChartsLineChart } from 'echarts/charts'
import { GridComponent, TooltipComponent } from 'echarts/components'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'

import { useEcharts } from '../../composables/useEcharts.js'
import { useThemeColors } from '../../composables/useThemeColors.js'

use([GridComponent, TooltipComponent, EChartsBarChart, EChartsLineChart, CanvasRenderer])

const props = defineProps({
  labels: { type: Array, required: true },
  toolCalls: { type: Array, required: true },
  tokens: { type: Array, required: true },
  onlineUsers: { type: Array, required: true },
  onlineMinutes: { type: Array, required: true }
})

const chartElement = shallowRef(null)
const themeColors = useThemeColors()
const chartColors = computed(() => ({
  primary: themeColors.value.chartPrimary,
  blue: themeColors.value.chartBlue,
  purple: themeColors.value.chartPurple,
  amber: themeColors.value.chartAmber
}))

const tokenInK = computed(() => props.tokens.map((value) => Math.round(Number(value || 0) / 100) / 10))
const ariaLabel = computed(() =>
  props.labels.map((label, index) => (
    `${label}工具调用${props.toolCalls[index] || 0}次，Token消耗${tokenInK.value[index] || 0}K，在线${props.onlineUsers[index] || 0}人，平均在线${props.onlineMinutes[index] || 0}分钟`
  )).join('；')
)

const chartOptions = computed(() => ({
  backgroundColor: 'transparent',
  animation: true,
  animationDuration: 1200,
  animationDurationUpdate: 1200,
  animationEasing: 'linear',
  animationEasingUpdate: 'linear',
  grid: {
    top: 18,
    right: 42,
    bottom: 22,
    left: 38,
    containLabel: true
  },
  tooltip: {
    trigger: 'axis',
    confine: true,
    appendToBody: true,
    backgroundColor: 'rgba(255, 255, 255, 0.98)',
    borderColor: 'rgba(148, 163, 184, 0.24)',
    borderWidth: 1,
    padding: [9, 10],
    textStyle: {
      color: '#334155',
      fontSize: 12,
      fontWeight: 700
    },
    extraCssText: 'border-radius:4px;box-shadow:0 12px 28px rgba(15,23,42,.12);'
  },
  xAxis: {
    type: 'category',
    data: props.labels,
    boundaryGap: true,
    axisTick: { show: false },
    axisLine: { lineStyle: { color: 'rgba(148, 163, 184, 0.28)' } },
    axisLabel: {
      color: '#64748b',
      fontSize: 11,
      fontWeight: 700
    }
  },
  yAxis: [
    {
      type: 'value',
      min: 0,
      max: 360,
      splitNumber: 6,
      axisLabel: {
        color: '#64748b',
        fontSize: 11,
        fontWeight: 700
      },
      splitLine: { lineStyle: { color: 'rgba(226, 232, 240, 0.75)' } }
    },
    {
      type: 'value',
      min: 0,
      max: 90,
      splitNumber: 6,
      axisLabel: {
        color: '#64748b',
        fontSize: 11,
        fontWeight: 700
      },
      splitLine: { show: false }
    }
  ],
  series: [
    {
      name: '工具调用（次）',
      type: 'bar',
      data: props.toolCalls,
      barWidth: 14,
      itemStyle: {
        color: chartColors.value.primary,
        borderRadius: [4, 4, 0, 0]
      }
    },
    {
      name: 'Token 消耗（K）',
      type: 'line',
      yAxisIndex: 1,
      data: tokenInK.value,
      smooth: true,
      symbol: 'circle',
      symbolSize: 7,
      lineStyle: {
        width: 2.5,
        color: chartColors.value.blue
      },
      itemStyle: {
        color: '#ffffff',
        borderColor: chartColors.value.blue,
        borderWidth: 2.5
      },
      areaStyle: {
        color: buildAreaColor(chartColors.value.blue, 0.11)
      }
    },
    {
      name: '在线人数',
      type: 'line',
      data: props.onlineUsers,
      smooth: true,
      symbol: 'circle',
      symbolSize: 7,
      lineStyle: {
        width: 2.5,
        color: chartColors.value.purple
      },
      itemStyle: {
        color: '#ffffff',
        borderColor: chartColors.value.purple,
        borderWidth: 2.5
      }
    },
    {
      name: '平均在线时长（分钟）',
      type: 'line',
      yAxisIndex: 1,
      data: props.onlineMinutes,
      smooth: true,
      symbol: 'circle',
      symbolSize: 7,
      lineStyle: {
        width: 2.5,
        color: chartColors.value.amber
      },
      itemStyle: {
        color: '#ffffff',
        borderColor: chartColors.value.amber,
        borderWidth: 2.5
      }
    }
  ]
}))

useEcharts(chartElement, chartOptions)

function buildAreaColor(color, alpha) {
  return {
    type: 'linear',
    x: 0,
    y: 0,
    x2: 0,
    y2: 1,
    colorStops: [
      { offset: 0, color: toRgba(color, alpha) },
      { offset: 1, color: toRgba(color, 0.02) }
    ]
  }
}

function toRgba(color, alpha) {
  const normalized = String(color || '').trim()
  const hex = normalized.replace('#', '')
  if (/^[\da-f]{6}$/i.test(hex)) {
    const r = parseInt(hex.slice(0, 2), 16)
    const g = parseInt(hex.slice(2, 4), 16)
    const b = parseInt(hex.slice(4, 6), 16)
    return `rgba(${r}, ${g}, ${b}, ${alpha})`
  }
  return `rgba(58, 124, 165, ${alpha})`
}
</script>

<style scoped>
.system-trend-chart {
  height: 280px;
  display: flex;
  flex-direction: column;
}

.chart-legend {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px 16px;
  color: #475569;
  font-size: 12px;
  margin-bottom: 12px;
}

.chart-legend i {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 2px;
  margin-right: 4px;
  vertical-align: middle;
}

.chart-body {
  flex: 1;
  min-height: 0;
}
</style>
