<template>
  <div class="trend-chart">
    <div class="chart-legend">
      <span><i :style="{ background: activeColor }"></i>{{ legendLabel }}</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 },
  mode: { type: String, default: 'amount' },
  claimCount: { type: Array, default: () => [] },
  claimAmount: { type: Array, default: () => [] },
  applications: { type: Array, default: () => [] },
  approved: { type: Array, default: () => [] },
  avgHours: { type: Array, default: () => [] }
})

const chartElement = shallowRef(null)
const themeColors = useThemeColors()
const chartColors = computed(() => ({
  primary: themeColors.value.chartPrimary,
  blue: themeColors.value.chartBlue
}))
const isCountMode = computed(() => props.mode === 'count')

const claimCountSeries = computed(() => (
  props.claimCount.length ? props.claimCount : props.applications
))
const claimAmountSeries = computed(() => (
  props.claimAmount.length ? props.claimAmount : props.approved
))
const activeSeries = computed(() => (
  isCountMode.value ? claimCountSeries.value : claimAmountSeries.value
))
const activeColor = computed(() => (
  isCountMode.value ? chartColors.value.primary : chartColors.value.blue
))
const legendLabel = computed(() => (
  isCountMode.value ? '报销数量（单）' : '报销金额（元）'
))
const maxValue = computed(() => Math.max(...activeSeries.value.map((value) => Number(value || 0)), 1))

const ariaLabel = computed(() =>
  props.labels.map((label, index) => (
    isCountMode.value
      ? `${label}报销${claimCountSeries.value[index] || 0}单`
      : `${label}报销金额${formatCurrency(claimAmountSeries.value[index] || 0)}`
  )).join('；')
)

const chartOptions = computed(() => ({
  backgroundColor: 'transparent',
  animation: true,
  animationDuration: 1200,
  animationDurationUpdate: 1200,
  animationEasing: 'linear',
  animationEasingUpdate: 'linear',
  grid: {
    top: 18,
    right: 24,
    bottom: 22,
    left: 36,
    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: Math.ceil(maxValue.value * 1.2),
    splitNumber: 5,
    name: isCountMode.value ? '单' : '元',
    nameTextStyle: {
      color: '#64748b',
      fontSize: 11,
      fontWeight: 700
    },
    axisLabel: {
      color: '#64748b',
      fontSize: 11,
      fontWeight: 700,
      formatter: (value) => (isCountMode.value ? `${Math.round(value)}` : formatAxisCurrency(value))
    },
    splitLine: { lineStyle: { color: 'rgba(226, 232, 240, 0.75)' } }
  },
  series: [
    {
      name: legendLabel.value,
      type: isCountMode.value ? 'line' : 'bar',
      data: activeSeries.value,
      barWidth: 16,
      smooth: isCountMode.value,
      symbol: isCountMode.value ? 'circle' : 'none',
      symbolSize: 7,
      lineStyle: {
        width: 2.5,
        color: activeColor.value
      },
      itemStyle: {
        color: isCountMode.value ? '#ffffff' : activeColor.value,
        borderColor: activeColor.value,
        borderWidth: isCountMode.value ? 2.5 : 0,
        borderRadius: [4, 4, 0, 0]
      },
      areaStyle: {
        opacity: isCountMode.value ? 1 : 0,
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: toRgba(activeColor.value, 0.14) },
            { offset: 1, color: toRgba(activeColor.value, 0.02) }
          ]
        }
      },
      tooltip: {
        valueFormatter: (value) => (
          isCountMode.value ? `${Number(value || 0)} 单` : formatCurrency(value)
        )
      }
    }
  ]
}))

useEcharts(chartElement, chartOptions)

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})`
}

function formatCurrency(value) {
  const number = Number(value || 0)
  if (number >= 1000000) return `¥${(number / 1000000).toFixed(1)}M`
  if (number >= 1000) return `¥${(number / 1000).toFixed(1)}K`
  return `¥${Math.round(number)}`
}

function formatAxisCurrency(value) {
  const number = Number(value || 0)
  if (number >= 1000000) return `${(number / 1000000).toFixed(1)}M`
  if (number >= 1000) return `${(number / 1000).toFixed(0)}K`
  return `${Math.round(number)}`
}
</script>

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

.chart-legend {
  display: flex;
  align-items: center;
  gap: 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>
