<template>
  <div ref="chartElement" class="budget-trend-chart" role="img" :aria-label="ariaLabel"></div>
</template>

<script setup>
import { computed, shallowRef } from 'vue'
import { BarChart as EChartsBarChart } from 'echarts/charts'
import { GridComponent, LegendComponent, 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, LegendComponent, TooltipComponent, EChartsBarChart, CanvasRenderer])

const props = defineProps({
  labels: { type: Array, required: true },
  budget: { type: Array, required: true },
  used: { type: Array, required: true },
  occupied: { type: Array, default: () => [] },
  available: { type: Array, default: () => [] }
})

const chartElement = shallowRef(null)
const themeColors = useThemeColors()
const prefersReducedMotion = () =>
  typeof window !== 'undefined' && window.matchMedia?.('(prefers-reduced-motion: reduce)').matches

const currency = (value) =>
  Number(value || 0).toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  })

const percent = (value, total) => {
  const denominator = Number(total || 0)
  if (!denominator) return 0
  return Number(((Number(value || 0) / denominator) * 100).toFixed(2))
}

const percentSeries = (series) =>
  props.budget.map((total, index) => percent(series[index], total))

const usedPercent = computed(() => percentSeries(props.used))
const occupiedPercent = computed(() => percentSeries(props.occupied))
const availableAmountSeries = computed(() =>
  props.budget.map((total, index) => {
    const explicitValue = Number(props.available[index])
    if (Number.isFinite(explicitValue) && explicitValue > 0) {
      return explicitValue
    }

    const usedValue = Number(props.used[index] || 0)
    const occupiedValue = Number(props.occupied[index] || 0)
    return Math.max(Number(total || 0) - usedValue - occupiedValue, 0)
  })
)
const availablePercent = computed(() =>
  props.budget.map((total, index) => percent(availableAmountSeries.value[index], total))
)

const usagePercent = computed(() =>
  usedPercent.value.map((value, index) => Number((value + Number(occupiedPercent.value[index] || 0)).toFixed(2)))
)

const ariaLabel = computed(() =>
  props.labels.map((label, index) => (
    `${label}预算${currency(props.budget[index])}，已发生${usedPercent.value[index] || 0}%，已占用${occupiedPercent.value[index] || 0}%，剩余${availablePercent.value[index] || 0}%`
  )).join('；')
)

function buildSeriesData(percentValues, amountValues) {
  return percentValues.map((value, index) => ({
    value,
    amount: Number(amountValues[index] || 0)
  }))
}

const chartOptions = computed(() => ({
  backgroundColor: 'transparent',
  animation: {
    duration: prefersReducedMotion() ? 0 : 820,
    easing: 'cubicOut'
  },
  legend: {
    top: 0,
    left: 0,
    itemWidth: 9,
    itemHeight: 9,
    itemGap: 16,
    textStyle: {
      color: '#475569',
      fontSize: 12,
      fontWeight: 700
    }
  },
  grid: {
    top: 38,
    right: 88,
    bottom: 14,
    left: 58
  },
  tooltip: {
    trigger: 'axis',
    confine: true,
    appendToBody: true,
    axisPointer: {
      type: 'shadow',
      shadowStyle: {
        color: 'rgba(58, 124, 165, 0.06)'
      }
    },
    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);',
    formatter(params = []) {
      const items = Array.isArray(params) ? params : [params]
      const index = Number(items[0]?.dataIndex || 0)
      const lines = items.map((item) => {
        const percentValue = Number(item?.value || 0).toFixed(2)
        const amount = currency(item?.data?.amount || 0)
        return `${item.marker}${item.seriesName}: ${percentValue}%（¥${amount}）`
      })
      return [
        `${items[0]?.axisValue || ''}`,
        ...lines,
        `总占用率: ${usagePercent.value[index] || 0}%`,
        `预算总额: ¥${currency(props.budget[index])}`
      ].join('<br/>')
    }
  },
  xAxis: {
    type: 'value',
    min: 0,
    max: 100,
    axisLine: { show: false },
    axisTick: { show: false },
    axisLabel: {
      color: '#64748b',
      fontSize: 11,
      fontWeight: 700,
      formatter: (value) => `${Number(value)}%`
    },
    splitLine: { lineStyle: { color: 'rgba(226, 232, 240, 0.72)' } }
  },
  yAxis: {
    type: 'category',
    data: props.labels,
    inverse: true,
    axisTick: { show: false },
    axisLine: { show: false },
    axisLabel: {
      color: '#334155',
      fontSize: 12,
      fontWeight: 800
    }
  },
  series: [
    {
      name: '已发生',
      type: 'bar',
      stack: 'budgetUsage',
      data: buildSeriesData(usedPercent.value, props.used),
      barWidth: 20,
      emphasis: { focus: 'series' },
      label: {
        show: true,
        position: 'inside',
        color: '#ffffff',
        fontSize: 11,
        fontWeight: 800,
        formatter: ({ value }) => Number(value) >= 10 ? `${Number(value).toFixed(1)}%` : ''
      },
      itemStyle: {
        color: themeColors.value.chartPrimary,
        borderRadius: [4, 0, 0, 4]
      }
    },
    {
      name: '已占用',
      type: 'bar',
      stack: 'budgetUsage',
      data: buildSeriesData(occupiedPercent.value, props.occupied),
      barWidth: 20,
      emphasis: { focus: 'series' },
      label: {
        show: true,
        position: 'inside',
        color: '#ffffff',
        fontSize: 11,
        fontWeight: 800,
        formatter: ({ value }) => Number(value) >= 10 ? `${Number(value).toFixed(1)}%` : ''
      },
      itemStyle: {
        color: themeColors.value.chartAmber || themeColors.value.warning,
        borderColor: '#ffffff',
        borderWidth: 1
      }
    },
    {
      name: '剩余可用',
      type: 'bar',
      stack: 'budgetUsage',
      data: buildSeriesData(availablePercent.value, availableAmountSeries.value),
      barWidth: 20,
      emphasis: { focus: 'series' },
      label: {
        show: true,
        position: 'right',
        distance: 10,
        color: '#334155',
        fontSize: 12,
        fontWeight: 850,
        formatter: ({ dataIndex }) => `${usagePercent.value[dataIndex] || 0}%`
      },
      itemStyle: {
        color: '#e8eef5',
        borderColor: '#ffffff',
        borderWidth: 1,
        borderRadius: [0, 4, 4, 0]
      }
    }
  ]
}))

useEcharts(chartElement, chartOptions)
</script>

<style scoped>
.budget-trend-chart {
  position: relative;
  width: 100%;
  height: 252px;
}
</style>
