<template>
  <div :ref="el => containerRef = el" style="width:100%;height:100%;min-height:200px;"></div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from 'vue'
import * as echarts from 'echarts'

const props = withDefaults(defineProps<{
  /** 数据：{ name, value }[] */
  data: { name: string; value: number }[]
  totalLabel?: string
  totalUnit?: string
}>(), {
  totalLabel: '总计',
  totalUnit: '',
})

const containerRef = ref<HTMLElement | null>(null)
let chart: echarts.ECharts | null = null

function render() {
  if (!containerRef.value) return
  if (!chart) chart = echarts.init(containerRef.value)

  const total = props.data.reduce((s, d) => s + Math.abs(d.value), 0)
  // 构建瀑布图数据
  let accumulate = 0
  const seriesData = props.data.map((d, i) => {
    const isLast = i === props.data.length - 1
    const isPos = d.value >= 0
    const item: any = {
      value: isPos ? d.value : -d.value,
      itemStyle: {
        color: isPos ? '#52c41a' : '#ff4d4f',
        borderColor: isPos ? '#52c41a' : '#ff4d4f',
      },
    }
    if (!isLast) {
      if (isPos) {
        // 正数：从accumulate开始
        item.offset = accumulate
        accumulate += d.value
      } else {
        // 负数：向下
        accumulate += d.value
        item.offset = Math.max(0, accumulate)
      }
    } else {
      // 最后一项是总计
      item.offset = 0
      item.value = total
      item.itemStyle = { color: '#409eff' }
    }
    return item
  })

  // 简化瀑布图：用堆积柱状图模拟
  const posData = props.data.map(d => d.value > 0 ? d.value : 0)
  const negData = props.data.map(d => d.value < 0 ? -d.value : 0)

  chart.setOption({
    tooltip: {
      trigger: 'axis',
      formatter: (params: any[]) => {
        const idx = params[0]?.dataIndex
        const d = props.data[idx]
        if (!d) return ''
        return `${d.name}: <b>${d.value?.toLocaleString()}${props.totalUnit}</b>`
      },
    },
    grid: { left: 60, right: 30, top: 20, bottom: 40 },
    xAxis: {
      type: 'category',
      data: [...props.data.map(d => d.name), props.totalLabel],
      axisLabel: { rotate: 0, fontSize: 11, color: '#666', interval: 0 },
      axisLine: { show: false },
      axisTick: { show: false },
    },
    yAxis: {
      type: 'value',
      name: props.totalUnit,
      splitLine: { lineStyle: { color: '#f0f0f0', type: 'dashed' } },
      axisLabel: { fontSize: 10, color: '#999' },
    },
    series: [
      {
        type: 'bar',
        stack: 'total',
        data: posData,
        barWidth: 24,
        itemStyle: { color: '#52c41a', borderRadius: [4, 4, 0, 0] },
        label: {
          show: true,
          position: 'top',
          formatter: (p: any) => {
            const v = props.data[p.dataIndex]?.value
            return v && v > 0 ? v?.toLocaleString() : ''
          },
          fontSize: 10, color: '#52c41a',
        },
      },
      {
        type: 'bar',
        stack: 'total',
        data: negData,
        barWidth: 24,
        itemStyle: { color: '#ff4d4f', borderRadius: [4, 4, 0, 0] },
        label: {
          show: true,
          position: 'bottom',
          formatter: (p: any) => {
            const v = props.data[p.dataIndex]?.value
            return v && v < 0 ? v?.toLocaleString() : ''
          },
          fontSize: 10, color: '#ff4d4f',
        },
      },
      {
        type: 'bar',
        stack: 'total',
        data: props.data.map(() => null).concat(total),
        barWidth: 24,
        itemStyle: { color: '#409eff', borderRadius: [4, 4, 0, 0] },
        label: {
          show: true,
          position: 'top',
          formatter: total?.toLocaleString(),
          fontSize: 13, fontWeight: 700, color: '#409eff',
        },
      },
    ],
  }, true)
}

watch(() => props.data, render, { deep: true })
onMounted(render)
onUnmounted(() => { chart?.dispose(); chart = null })
</script>
